Arduino KVComm  master
Key-Value pair communication library for Arduino
KV_Types.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <stdint.h> // uint#_t
4 #include <string.h> // memcpy
5 
8 
42 template <class T>
43 struct KV_Type {
44  constexpr static uint8_t getTypeID();
45  constexpr static size_t getLength();
46  static void writeToBuffer(const T &, uint8_t *buffer);
47  static T readFromBuffer(const uint8_t *buffer);
48 };
49 
51 
53 #define KV_ADD_TRIVIAL_TYPE(type, typeid) \
54  template <> \
55  struct KV_Type<type> { \
56  constexpr inline static uint8_t getTypeID() { return typeid; } \
57  constexpr inline static size_t getLength() { return sizeof(type); } \
58  inline static void writeToBuffer(const type &t, uint8_t *buffer) { \
59  memcpy(buffer, &t, getLength()); \
60  } \
61  inline static void readFromBuffer(type &t, const uint8_t *buffer) { \
62  memcpy(&t, buffer, getLength()); \
63  } \
64  }
65 
67 KV_ADD_TRIVIAL_TYPE(uint8_t, 2);
68 KV_ADD_TRIVIAL_TYPE(int16_t, 3);
69 KV_ADD_TRIVIAL_TYPE(uint16_t, 4);
70 KV_ADD_TRIVIAL_TYPE(int32_t, 5);
71 KV_ADD_TRIVIAL_TYPE(uint32_t, 6);
72 KV_ADD_TRIVIAL_TYPE(int64_t, 7);
73 KV_ADD_TRIVIAL_TYPE(uint64_t, 8);
75 KV_ADD_TRIVIAL_TYPE(double, sizeof(double) == sizeof(float) ? 9 : 10);
78 
79 #if defined(__arm__)
80 // TODO: integers are a separate data type on ARM
81 // are there more platforms with this quirk?
82 KV_ADD_TRIVIAL_TYPE(int, 5);
83 KV_ADD_TRIVIAL_TYPE(unsigned int, 6);
84 #endif
KV_Type
Template struct for making types serializable.
Definition: KV_Types.hpp:43
KV_Type::readFromBuffer
static T readFromBuffer(const uint8_t *buffer)
KV_Type::getTypeID
constexpr static uint8_t getTypeID()
KV_ADD_TRIVIAL_TYPE
#define KV_ADD_TRIVIAL_TYPE(type, typeid)
Add a KV_Type definition that can be (de)serialized by just memcpying.
Definition: KV_Types.hpp:53
KV_Type::writeToBuffer
static void writeToBuffer(const T &, uint8_t *buffer)
KV_Type::getLength
constexpr static size_t getLength()