CCF
Loading...
Searching...
No Matches
blit_serialiser.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 "ccf/ds/nonstd.h"
7
9{
10 // Converts values to their raw, in-memory representation. To add support for
11 // custom types, add a specialization of BlitSerialiser for them.
12 template <typename T>
14 {
15 static SerialisedEntry to_serialised(const T& t)
16 {
17 if constexpr (std::is_same_v<T, std::vector<uint8_t>>)
18 {
19 return SerialisedEntry(t.begin(), t.end());
20 }
21 else if constexpr (ccf::nonstd::is_std_array<T>::value)
22 {
23 return SerialisedEntry(t.begin(), t.end());
24 }
25 else if constexpr (std::is_integral_v<T>)
26 {
27 SerialisedEntry s(sizeof(t));
28 std::memcpy(s.data(), (uint8_t*)&t, sizeof(t));
29 return s;
30 }
31 else if constexpr (std::is_same_v<T, std::string>)
32 {
33 return SerialisedEntry(t.begin(), t.end());
34 }
35 else
36 {
37 static_assert(
38 ccf::nonstd::dependent_false<T>::value, "Can't serialise this type");
39 }
40 }
41
42 static T from_serialised(const SerialisedEntry& rep)
43 {
44 if constexpr (std::is_same_v<T, std::vector<uint8_t>>)
45 {
46 return T(rep.begin(), rep.end());
47 }
48 else if constexpr (ccf::nonstd::is_std_array<T>::value)
49 {
50 T t;
51 if (rep.size() != t.size())
52 {
53 throw std::logic_error(fmt::format(
54 "Wrong serialised size {} for deserialisation of array of size {}",
55 rep.size(),
56 t.size()));
57 }
58 std::copy_n(rep.begin(), t.size(), t.begin());
59 return t;
60 }
61 else if constexpr (std::is_integral_v<T>)
62 {
63 if (rep.size() != sizeof(T))
64 {
65 throw std::logic_error(fmt::format(
66 "Wrong serialised size {} for deserialisation of integral of size "
67 "{}",
68 rep.size(),
69 sizeof(T)));
70 }
71 return *(T*)rep.data();
72 }
73 else if constexpr (std::is_same_v<T, std::string>)
74 {
75 return T(rep.begin(), rep.end());
76 }
77 else
78 {
79 static_assert(
81 "Can't deserialise this type");
82 }
83 }
84 };
85}
Definition sha256_hash.h:80
ccf::ByteVector SerialisedEntry
Definition serialised_entry.h:8
Definition blit_serialiser.h:14
static T from_serialised(const SerialisedEntry &rep)
Definition blit_serialiser.h:42
static SerialisedEntry to_serialised(const T &t)
Definition blit_serialiser.h:15
Definition nonstd.h:63
Definition nonstd.h:40