Gaia-ECS v1.0.0
A simple and powerful entity component system
Loading...
Searching...
No Matches
ser_ct.h
Go to the documentation of this file.
1
7
8#pragma once
9#include "gaia/config/config.h"
10
11#include <type_traits>
12#include <utility>
13
14#include "gaia/core/utility.h"
15#include "gaia/ser/impl/ser_dispatch.h"
16#include "gaia/ser/ser_common.h"
17
18namespace gaia {
19 namespace ser {
20 namespace detail {
22 template <typename Writer, typename T>
23 void save_one(Writer& s, const T& arg) {
24 auto saveTrivial = [](auto& writer, const auto& value) {
25 writer.save(value);
26 };
27 save_dispatch(s, arg, saveTrivial);
28 }
29
30 template <typename Reader, typename T>
31 void load_one(Reader& s, T& arg) {
32 auto loadTrivial = [](auto& reader, auto& value) {
33 reader.load(value);
34 };
35 load_dispatch(s, arg, loadTrivial);
36 }
37
38#if GAIA_ASSERT_ENABLED
39 template <typename Writer, typename T>
40 void check_one(Writer& s, const T& arg) {
41 T tmp{};
42
43 // Make sure that we write just as many bytes as we read.
44 // If the positions are the same there is a good chance that save and load match.
45 const auto pos0 = s.tell();
46 save_one(s, arg);
47 const auto pos1 = s.tell();
48 s.seek(pos0);
49 load_one(s, tmp);
50 GAIA_ASSERT(s.tell() == pos1);
51
52 // Return back to the original position in the buffer.
53 s.seek(pos0);
54 }
55#endif
56
58 class size_counter {
59 uint32_t m_pos = 0;
60
61 public:
62 template <typename T>
63 void save(const T&) {
64 m_pos += (uint32_t)sizeof(T);
65 }
66
67 void save_raw(const void*, uint32_t size, [[maybe_unused]] ser::serialization_type_id id) {
68 m_pos += size;
69 }
70
71 void seek(uint32_t pos) {
72 m_pos = pos;
73 }
74
75 GAIA_NODISCARD uint32_t tell() const {
76 return m_pos;
77 }
78 };
80 } // namespace detail
81
87 template <typename T>
88 GAIA_NODISCARD uint32_t bytes(const T& data) {
89 detail::size_counter counter;
90 detail::save_one(counter, data);
91 return counter.tell();
92 }
93
100 template <typename Writer, typename T>
101 void save(Writer& writer, const T& data) {
102 detail::save_one(writer, data);
103 }
104
111 template <typename Reader, typename T>
112 void load(Reader& reader, T& data) {
113 detail::load_one(reader, data);
114 }
115
116#if GAIA_ASSERT_ENABLED
125 template <typename Writer, typename T>
126 void check(Writer& writer, const T& data) {
127 detail::check_one(writer, data);
128 }
129#endif
130 } // namespace ser
131} // namespace gaia
GAIA_NODISCARD uint32_t bytes(const T &data)
Calculates how many bytes data would need when serialized via ser::save. Useful when a destination st...
Definition ser_ct.h:88
void load(Reader &reader, T &data)
Read data using Reader at compile-time.
Definition ser_ct.h:112
void save(Writer &writer, const T &data)
Write data using Writer at compile-time.
Definition ser_ct.h:101