Created
January 20, 2021 18:54
-
-
Save facontidavide/66bba6ab4a18cb883f875dfca2b7e116 to your computer and use it in GitHub Desktop.
Not much worse than boost::serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct SizeStream{ | |
unsigned size; | |
SizeStream(): size(0) {} | |
template <typename T> | |
typename std::enable_if<std::is_arithmetic<T>::value, SizeStream&>::type | |
operator <<(T& op) | |
{ | |
size += sizeof(op); | |
return *this; | |
} | |
}; | |
struct SerializeStream{ | |
uint8_t* ptr_; | |
SerializeStream(uint8_t* buffer): ptr_(buffer) {} | |
template <typename T> | |
typename std::enable_if<std::is_arithmetic<T>::value, SerializeStream&>::type | |
operator << (T& op) | |
{ | |
unsigned S = sizeof(op); | |
memcpy( ptr_, &op, S ); | |
ptr_ += S; | |
return *this; | |
} | |
}; | |
struct DeserializeStream{ | |
const uint8_t* ptr_; | |
DeserializeStream(const uint8_t* buffer): ptr_(buffer) {} | |
template <typename T> | |
typename std::enable_if<std::is_arithmetic<T>::value, DeserializeStream&>::type | |
operator << (T& op) | |
{ | |
unsigned S = sizeof(op); | |
memcpy( &op, ptr_, S ); | |
ptr_ += S; | |
return *this; | |
} | |
}; | |
/* Example usage | |
struct Point{ | |
int x, y, z; | |
}; | |
struct Quat{ | |
int x, y, z, w; | |
}; | |
struct Trans{ | |
Point point; | |
Quat quat; | |
}; | |
template<class Archive> | |
Archive& operator << (Archive& ar, Point& p) | |
{ | |
ar << p.x; | |
ar << p.y; | |
ar << p.z; | |
return ar; | |
} | |
template<class Archive> | |
Archive& operator << (Archive& ar, Quat& q) | |
{ | |
ar << q.x; | |
ar << q.y; | |
ar << q.z; | |
ar << q.w; | |
return ar; | |
} | |
template<class Archive> | |
Archive& operator << (Archive& ar, Trans& t) | |
{ | |
ar << t.point; | |
ar << t.quat; | |
return ar; | |
} | |
// use like this: | |
SizeStream sz; | |
Trans trans; | |
sz << trans; | |
std::vector<uint8_t> buffer( sz.size ); | |
SerializeStream ss(buffer.data()); | |
ss << trans; | |
Trans trans_out; | |
DeserializeStream ds(buffer.data()); | |
ds << trans_out; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment