Vanetza
Loading...
Searching...
No Matches
archives.hpp
1#ifndef ARCHIVES_HPP_TLVURDQK
2#define ARCHIVES_HPP_TLVURDQK
3
4#include <vanetza/common/byte_order.hpp>
5#include <exception>
6#include <istream>
7#include <ostream>
8#include <streambuf>
9
10namespace vanetza
11{
12
13/**
14 * This is a drop-in replacement for boost::archive::binary_iarchive
15 */
16class InputArchive
17{
18public:
19 using InputStream = std::basic_istream<char>;
20 using StreamBuffer = std::basic_streambuf<char>;
21 class Exception : public std::runtime_error {
22 using std::runtime_error::runtime_error;
23 };
24
25 enum class ErrorCode {
26 Ok,
27 IncompleteData,
28 ExcessiveLength,
29 ConstraintViolation,
30 };
31
32 InputArchive(InputStream& is);
33 InputArchive(StreamBuffer& buf);
34
35 template<typename T>
36 InputArchive& operator>>(T& t)
37 {
38 static_assert(std::is_integral<T>::value == true, "only integral types are supported");
39 char* ptr = reinterpret_cast<char*>(&t);
40 load_binary(ptr, sizeof(T));
41 return *this;
42 }
43
44 void load_binary(unsigned char* data, std::size_t len);
45 void load_binary(char* data, std::size_t len);
46 char peek_byte();
47 std::size_t remaining_bytes();
48
49 bool is_good() const;
50 ErrorCode error_code() const;
51 void fail(ErrorCode error_code);
52
53private:
54 StreamBuffer* m_stream_buffer;
55 ErrorCode m_error_code = ErrorCode::Ok;
56};
57
58/**
59 * This is a drop-in replacement for boost::archive::binary_oarchive
60 */
61class OutputArchive
62{
63public:
64 using OutputStream = std::basic_ostream<char>;
65 using StreamBuffer = std::basic_streambuf<char>;
66 class Exception : public std::runtime_error {
67 using std::runtime_error::runtime_error;
68 };
69
70 OutputArchive(OutputStream& os);
71 OutputArchive(StreamBuffer& buf);
72
73 template<typename T>
74 OutputArchive& operator<<(const T& t)
75 {
76 static_assert(std::is_integral<T>::value == true, "only integral types are supported");
77 const char* ptr = reinterpret_cast<const char*>(&t);
78 save_binary(ptr, sizeof(T));
79 return *this;
80 }
81
82 void save_binary(const unsigned char* data, std::size_t len);
83 void save_binary(const char* data, std::size_t len);
84
85private:
86 StreamBuffer* m_stream_buffer;
87};
88
89} // namespace vanetza
90
91#endif /* ARCHIVES_HPP_TLVURDQK */
92