Vanetza
 
Loading...
Searching...
No Matches
serialization.cpp
1#include <vanetza/security/v2/length_coding.hpp>
2#include <vanetza/security/v2/serialization.hpp>
3#include <cassert>
4#include <limits>
5#include <stdexcept>
6#include <type_traits>
7
8namespace vanetza
9{
10namespace security
11{
12namespace v2
13{
14
15template<typename T>
16std::size_t trim_size_impl(T in, typename std::enable_if<std::is_same<T, std::size_t>::value>::type* = nullptr)
17{
18 return in;
19}
20
21template<typename T>
22std::size_t trim_size_impl(T in, typename std::enable_if<!std::is_same<T, std::size_t>::value>::type* = nullptr)
23{
24 if (in > std::numeric_limits<std::size_t>::max()) {
25 throw std::overflow_error("given size exceeds limits of std::size_t");
26 }
27 return static_cast<std::size_t>(in);
28}
29
30std::size_t trim_size(std::uintmax_t in)
31{
32 return trim_size_impl(in);
33}
34
35
36void serialize_length(OutputArchive& ar, std::uintmax_t length)
37{
38 ByteBuffer buf;
39 buf = encode_length(length);
40 for (auto it = buf.begin(); it != buf.end(); it++) {
41 ar << *it;
42 }
43}
44
45std::uintmax_t deserialize_length(InputArchive& ar)
46{
47 ByteBuffer buf(1);
48 ar >> buf[0];
49 const size_t leading = count_leading_ones(buf[0]);
50 buf.resize(leading + 1);
51 for (size_t c = 1; c <= leading; ++c) {
52 ar >> buf[c];
53 }
54 auto tup = decode_length(buf);
55 assert(std::get<0>(tup) != buf.begin());
56 return std::get<1>(tup);
57}
58
59} // namespace v2
60} // namespace security
61} // namespace vanetza