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 // NOLINTBEGIN(bugprone-branch-clone)
18 if constexpr (std::is_same_v<T, std::vector<uint8_t>>)
19 {
20 return SerialisedEntry(t.begin(), t.end());
21 }
22 else if constexpr (ccf::nonstd::is_std_array<T>::value)
23 {
24 return SerialisedEntry(t.begin(), t.end());
25 }
26 else if constexpr (std::is_integral_v<T>)
27 {
28 SerialisedEntry s(sizeof(t));
29 std::memcpy(s.data(), (uint8_t*)&t, sizeof(t));
30 return s;
31 }
32 else if constexpr (std::is_same_v<T, std::string>)
33 {
34 return SerialisedEntry(t.begin(), t.end());
35 }
36 else
37 {
38 static_assert(
39 ccf::nonstd::dependent_false<T>::value, "Can't serialise this type");
40 }
41 // NOLINTEND(bugprone-branch-clone)
42 }
43
44 static T from_serialised(const SerialisedEntry& rep)
45 {
46 // NOLINTBEGIN(bugprone-branch-clone)
47 if constexpr (std::is_same_v<T, std::vector<uint8_t>>)
48 {
49 return T(rep.begin(), rep.end());
50 }
51 else if constexpr (ccf::nonstd::is_std_array<T>::value)
52 {
53 T t;
54 if (rep.size() != t.size())
55 {
56 throw std::logic_error(fmt::format(
57 "Wrong serialised size {} for deserialisation of array of size {}",
58 rep.size(),
59 t.size()));
60 }
61 std::copy_n(rep.begin(), t.size(), t.begin());
62 return t;
63 }
64 else if constexpr (std::is_integral_v<T>)
65 {
66 if (rep.size() != sizeof(T))
67 {
68 throw std::logic_error(fmt::format(
69 "Wrong serialised size {} for deserialisation of integral of size "
70 "{}",
71 rep.size(),
72 sizeof(T)));
73 }
74 return *(T*)rep.data();
75 }
76 else if constexpr (std::is_same_v<T, std::string>)
77 {
78 return T(rep.begin(), rep.end());
79 }
80 else
81 {
82 static_assert(
84 "Can't deserialise this type");
85 }
86 // NOLINTEND(bugprone-branch-clone)
87 }
88 };
89}
Definition sha256_hash.h:88
ccf::ByteVector SerialisedEntry
Definition serialised_entry.h:8
Definition blit_serialiser.h:14
static T from_serialised(const SerialisedEntry &rep)
Definition blit_serialiser.h:44
static SerialisedEntry to_serialised(const T &t)
Definition blit_serialiser.h:15
Definition nonstd.h:63
Definition nonstd.h:40