CCF
Loading...
Searching...
No Matches
map_serializers.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
5#include "ds/ccf_assert.h"
6#include "ds/serialized.h"
7
8#include <span>
9
10namespace map
11{
12 template <class T>
13 inline size_t get_size(const T& data)
14 {
15 return sizeof(uint64_t) + sizeof(data);
16 }
17
18 static uint32_t get_padding(uint32_t size)
19 {
20 uint32_t padding = size % sizeof(uintptr_t);
21 if (padding != 0)
22 {
23 padding = sizeof(uintptr_t) - padding;
24 }
25 return padding;
26 }
27
28 static uint32_t add_padding(uint32_t data_size, uint8_t*& data, size_t& size)
29 {
30 constexpr uintptr_t padding = 0;
31 uint32_t padding_size = get_padding(data_size);
32 if (padding_size != 0)
33 {
35 data, size, reinterpret_cast<const uint8_t*>(&padding), padding_size);
36 }
37 return padding_size;
38 }
39
40 template <class T>
41 static size_t get_serialized_size_with_padding(const T& t)
42 {
43 const uint32_t t_size = get_size(t);
44 return t_size + get_padding(t_size);
45 }
46
47 template <class T>
48 inline size_t serialize(const T& t, uint8_t*& data, size_t& size)
49 {
50 uint64_t data_size = sizeof(T);
52 data,
53 size,
54 reinterpret_cast<const uint8_t*>(&data_size),
55 sizeof(uint64_t));
57 data, size, reinterpret_cast<const uint8_t*>(&t), sizeof(T));
58 return sizeof(uint64_t) + sizeof(T);
59 }
60
61 template <class T>
62 inline T deserialize(const uint8_t*& data, size_t& size)
63 {
64 size_t result = serialized::read<size_t>(data, size);
65 (void)result;
67 result == sizeof(T), "result:{} == sizeof(T):{}", result, sizeof(T));
68 return serialized::read<T>(data, size);
69 }
70
71 template <class M>
72 static M deserialize_map(std::span<const uint8_t> serialized_state)
73 {
74 using KeyType = typename M::KeyType;
75 using ValueType = typename M::ValueType;
76
77 M map;
78 const uint8_t* data = serialized_state.data();
79 size_t size = serialized_state.size();
80
81 while (size != 0)
82 {
83 // Deserialize the key
84 size_t key_size = size;
85 KeyType key = deserialize<KeyType>(data, size);
86 key_size -= size;
87 serialized::skip(data, size, get_padding(key_size));
88
89 // Deserialize the value
90 size_t value_size = size;
91 ValueType value = deserialize<ValueType>(data, size);
92 value_size -= size;
93 serialized::skip(data, size, get_padding(value_size));
94 map = map.put(key, value);
95 }
96 return map;
97 }
98}
#define CCF_ASSERT_FMT(expr,...)
Definition ccf_assert.h:10
Definition map_serializers.h:11
T deserialize(const uint8_t *&data, size_t &size)
Definition map_serializers.h:62
size_t get_size(const T &data)
Definition map_serializers.h:13
size_t serialize(const T &t, uint8_t *&data, size_t &size)
Definition map_serializers.h:48
void write(uint8_t *&data, size_t &size, const T &v)
Definition serialized.h:106
void skip(const uint8_t *&data, size_t &size, size_t skip)
Definition serialized.h:166