Coverage Report

Created: 2026-10-19 14:15

src/zserio/SerializeUtil.h
Line
Count
Source
1
/**
2
 * \file
3
 * It provides help methods for serialization and deserialization of generated objects.
4
 *
5
 * These utilities are not used by generated code and they are provided only for user convenience.
6
 *
7
 * \note Please note that file operations allocate memory as needed and are not designed to use allocators.
8
 */
9
10
#ifndef ZSERIO_SERIALIZE_UTIL_H_INC
11
#define ZSERIO_SERIALIZE_UTIL_H_INC
12
13
#include "zserio/BitStreamReader.h"
14
#include "zserio/BitStreamWriter.h"
15
#include "zserio/FileUtil.h"
16
#include "zserio/Traits.h"
17
#include "zserio/Types.h"
18
#include "zserio/Vector.h"
19
20
namespace zserio
21
{
22
23
namespace detail
24
{
25
26
template <typename T>
27
void initializeChildrenImpl(std::true_type, T& object)
28
9
{
29
9
    object.initializeChildren();
30
9
}
31
32
template <typename T>
33
void initializeChildrenImpl(std::false_type, T&)
34
{}
35
36
template <typename T>
37
void initializeChildren(T& object)
38
9
{
39
9
    initializeChildrenImpl(has_initialize_children<T>(), object);
40
9
}
41
42
template <typename T, typename... ARGS>
43
void initializeImpl(std::true_type, T& object, ARGS&&... arguments)
44
6
{
45
6
    object.initialize(std::forward<ARGS>(arguments)...);
46
6
}
47
48
template <typename T>
49
void initializeImpl(std::false_type, T& object)
50
9
{
51
9
    initializeChildren(object);
52
9
}
53
54
template <typename T, typename... ARGS>
55
void initialize(T& object, ARGS&&... arguments)
56
15
{
57
15
    initializeImpl(has_initialize<T>(), object, std::forward<ARGS>(arguments)...);
58
15
}
59
60
template <typename T, typename = void>
61
struct allocator_chooser
62
{
63
    using type = std::allocator<uint8_t>;
64
};
65
66
template <typename T>
67
struct allocator_chooser<T, detail::void_t<typename T::allocator_type>>
68
{
69
    using type = typename T::allocator_type;
70
};
71
72
// This implementation needs to be in detail because old MSVC compiler 2015 has problems with calling overload.
73
template <typename T, typename ALLOC, typename... ARGS>
74
BasicBitBuffer<ALLOC> serialize(T& object, const ALLOC& allocator, ARGS&&... arguments)
75
15
{
76
15
    detail::initialize(object, std::forward<ARGS>(arguments)...);
77
15
    BasicBitBuffer<ALLOC> bitBuffer(object.initializeOffsets(), allocator);
78
15
    BitStreamWriter writer(bitBuffer);
79
15
    object.write(writer);
80
15
    return bitBuffer;
81
15
}
82
83
} // namespace detail
84
85
/**
86
 * Serializes given generated object to bit buffer using given allocator.
87
 *
88
 * Before serialization, the method properly calls on the given zserio object methods `initialize()`
89
 * (if exits), `initializeChildren()` (if exists) and `initializeOffsets()`.
90
 *
91
 * Example:
92
 * \code{.cpp}
93
 *     #include <zserio/SerializeUtil.h>
94
 *     #include <zserio/pmr/PolymorphicAllocator.h>
95
 *
96
 *     const zserio::pmr::PolymorphicAllocator<> allocator;
97
 *     SomeZserioObject object(allocator);
98
 *     const zserio::BasicBitBuffer<zserio::pmr::PolymorphicAllocator<>> bitBuffer =
99
 *             zserio::serialize(object, allocator);
100
 * \endcode
101
 *
102
 * \param object Generated object to serialize.
103
 * \param allocator Allocator to use to allocate bit buffer.
104
 * \param arguments Object's actual parameters for initialize() method (optional).
105
 *
106
 * \return Bit buffer containing the serialized object.
107
 *
108
 * \throw CppRuntimeException When serialization fails.
109
 */
110
template <typename T, typename ALLOC, typename... ARGS,
111
        typename std::enable_if<!std::is_enum<T>::value && is_allocator<ALLOC>::value, int>::type = 0>
112
BasicBitBuffer<ALLOC> serialize(T& object, const ALLOC& allocator, ARGS&&... arguments)
113
4
{
114
4
    return detail::serialize(object, allocator, std::forward<ARGS>(arguments)...);
115
4
}
116
117
/**
118
 * Serializes given generated object to bit buffer using default allocator 'std::allocator<uint8_t>'.
119
 *
120
 * Before serialization, the method properly calls on the given zserio object methods `initialize()`
121
 * (if exits), `initializeChildren()` (if exists) and `initializeOffsets()`.
122
 *
123
 * Example:
124
 * \code{.cpp}
125
 *     #include <zserio/SerializeUtil.h>
126
 *
127
 *     SomeZserioObject object;
128
 *     const zserio::BitBuffer bitBuffer = zserio::serialize(object);
129
 * \endcode
130
 *
131
 * \param object Generated object to serialize.
132
 * \param arguments Object's actual parameters for initialize() method (optional).
133
 *
134
 * \return Bit buffer containing the serialized object.
135
 *
136
 * \throw CppRuntimeException When serialization fails.
137
 */
138
template <typename T, typename ALLOC = typename detail::allocator_chooser<T>::type, typename... ARGS,
139
        typename std::enable_if<!std::is_enum<T>::value &&
140
                        !is_first_allocator<typename std::decay<ARGS>::type...>::value,
141
                int>::type = 0>
142
BasicBitBuffer<ALLOC> serialize(T& object, ARGS&&... arguments)
143
5
{
144
5
    return detail::serialize(object, ALLOC(), std::forward<ARGS>(arguments)...);
145
5
}
146
147
/**
148
 * Serializes given generated enum to bit buffer.
149
 *
150
 * Example:
151
 * \code{.cpp}
152
 *     #include <zserio/SerializeUtil.h>
153
 *
154
 *     const SomeZserioEnum enumValue = SomeZserioEnum::SomeEnumValue;
155
 *     const zserio::BitBuffer bitBuffer = zserio::serialize(enumValue);
156
 * \endcode
157
 *
158
 * \param enumValue Generated enum to serialize.
159
 * \param allocator Allocator to use to allocate bit buffer.
160
 *
161
 * \return Bit buffer containing the serialized enum.
162
 *
163
 * \throw CppRuntimeException When serialization fails.
164
 */
165
template <typename T, typename ALLOC = std::allocator<uint8_t>,
166
        typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
167
BasicBitBuffer<ALLOC> serialize(T enumValue, const ALLOC& allocator = ALLOC())
168
6
{
169
6
    BasicBitBuffer<ALLOC> bitBuffer(zserio::bitSizeOf(enumValue), allocator);
170
6
    BitStreamWriter writer(bitBuffer);
171
6
    zserio::write(writer, enumValue);
172
6
    return bitBuffer;
173
6
}
174
175
/**
176
 * Deserializes given bit buffer to instance of generated object.
177
 *
178
 * Example:
179
 * \code{.cpp}
180
 *     #include <zserio/SerializeUtil.h>
181
 *
182
 *     SomeZserioObject object;
183
 *     const zserio::BitBuffer bitBuffer = zserio::serialize(object);
184
 *     SomeZserioObject readObject = zserio::deserialize<SomeZserioObject>(bitBuffer);
185
 * \endcode
186
 *
187
 * \param bitBuffer Bit buffer to use.
188
 * \param arguments Object's actual parameters together with allocator for object's read constructor (optional).
189
 *
190
 * \return Generated object created from the given bit buffer.
191
 *
192
 * \throw CppRuntimeException When deserialization fails.
193
 */
194
template <typename T, typename ALLOC, typename... ARGS>
195
typename std::enable_if<!std::is_enum<T>::value && !is_first_array_preallocation<ARGS...>::value, T>::type
196
deserialize(const BasicBitBuffer<ALLOC>& bitBuffer, ARGS&&... arguments)
197
12
{
198
12
    BitStreamReader reader(bitBuffer);
199
12
    return T(reader, std::forward<ARGS>(arguments)...);
200
12
}
201
202
/**
203
 * Deserializes given bit buffer to instance of generated object.
204
 *
205
 * Example:
206
 * \code{.cpp}
207
 *     #include <zserio/SerializeUtil.h>
208
 *
209
 *     SomeZserioObject object;
210
 *     const zserio::BitBuffer bitBuffer = zserio::serialize(object);
211
 *     SomeZserioObject readObject = zserio::deserialize<SomeZserioObject>(bitBuffer,
212
 *             zserio::ArrayPreallocation(1024*1024));
213
 * \endcode
214
 *
215
 * \param bitBuffer Bit buffer to use.
216
 * \param maxArrayPrealloc maximum preallocated capacity for arrays.
217
 * \param arguments Object's actual parameters together with allocator for object's read constructor (optional).
218
 *
219
 * \return Generated object created from the given bit buffer.
220
 *
221
 * \throw CppRuntimeException When deserialization fails.
222
 */
223
template <typename T, typename ALLOC, typename... ARGS>
224
typename std::enable_if<!std::is_enum<T>::value, T>::type deserialize(
225
        const BasicBitBuffer<ALLOC>& bitBuffer, ArrayPreallocation maxArrayPrealloc, ARGS&&... arguments)
226
6
{
227
6
    BitStreamReader reader(bitBuffer, maxArrayPrealloc);
228
6
    return T(reader, std::forward<ARGS>(arguments)...);
229
6
}
230
231
/**
232
 * Deserializes given bit buffer to instance of generated enum.
233
 *
234
 * Example:
235
 * \code{.cpp}
236
 *     #include <zserio/SerializeUtil.h>
237
 *
238
 *     const SomeZserioEnum enumValue = SomeZserioEnum::SomeEnumValue;
239
 *     const zserio::BitBuffer bitBuffer = zserio::serialize(enumValue);
240
 *     const SomeZserioEnum readEnumValue = zserio::deserialize<DummyEnum>(bitBuffer);
241
 * \endcode
242
 *
243
 * \param bitBuffer Bit buffer to use.
244
 *
245
 * \return Generated enum created from the given bit buffer.
246
 *
247
 * \throw CppRuntimeException When deserialization fails.
248
 */
249
template <typename T, typename ALLOC>
250
typename std::enable_if<std::is_enum<T>::value, T>::type deserialize(const BasicBitBuffer<ALLOC>& bitBuffer)
251
3
{
252
3
    BitStreamReader reader(bitBuffer);
253
3
    return zserio::read<T>(reader);
254
3
}
255
256
/**
257
 * Serializes given generated object to vector of bytes using given allocator.
258
 *
259
 * Before serialization, the method properly calls on the given zserio object methods `initialize()`
260
 * (if exits), `initializeChildren()` (if exists) and `initializeOffsets()`.
261
 *
262
 * Example:
263
 * \code{.cpp}
264
 *     #include <zserio/SerializeUtil.h>
265
 *     #include <zserio/pmr/PolymorphicAllocator.h>
266
 *
267
 *     const zserio::pmr::PolymorphicAllocator<> allocator;
268
 *     SomeZserioObject object(allocator);
269
 *     const zserio::vector<uint8_t, zserio::pmr::PolymorphicAllocator<>> buffer =
270
 *             zserio::serializeToBytes(object, allocator);
271
 * \endcode
272
 *
273
 * \param object Generated object to serialize.
274
 * \param allocator Allocator to use to allocate vector.
275
 * \param arguments Object's actual parameters for initialize() method (optional).
276
 *
277
 * \return Vector of bytes containing the serialized object.
278
 *
279
 * \throw CppRuntimeException When serialization fails.
280
 */
281
template <typename T, typename ALLOC, typename... ARGS,
282
        typename std::enable_if<!std::is_enum<T>::value && is_allocator<ALLOC>::value, int>::type = 0>
283
vector<uint8_t, ALLOC> serializeToBytes(T& object, const ALLOC& allocator, ARGS&&... arguments)
284
4
{
285
4
    const BasicBitBuffer<ALLOC> bitBuffer =
286
4
            detail::serialize(object, allocator, std::forward<ARGS>(arguments)...);
287
288
4
    return bitBuffer.getBytes();
289
4
}
290
291
/**
292
 * Serializes given generated object to vector of bytes using default allocator 'std::allocator<uint8_t>'.
293
 *
294
 * Before serialization, the method properly calls on the given zserio object methods `initialize()`
295
 * (if exits), `initializeChildren()` (if exists) and `initializeOffsets()`.
296
 *
297
 * However, it's still possible that not all bits of the last byte are used. In this case, only most
298
 * significant bits of the corresponding size are used.
299
 *
300
 * Example:
301
 * \code{.cpp}
302
 *     #include <zserio/SerializeUtil.h>
303
 *
304
 *     SomeZserioObject object;
305
 *     const zserio::vector<uint8_t> buffer = zserio::serializeToBytes(object);
306
 * \endcode
307
 *
308
 * \param object Generated object to serialize.
309
 * \param arguments Object's actual parameters for initialize() method (optional).
310
 *
311
 * \return Vector of bytes containing the serialized object.
312
 *
313
 * \throw CppRuntimeException When serialization fails.
314
 */
315
template <typename T, typename ALLOC = typename detail::allocator_chooser<T>::type, typename... ARGS,
316
        typename std::enable_if<!std::is_enum<T>::value &&
317
                        !is_first_allocator<typename std::decay<ARGS>::type...>::value,
318
                int>::type = 0>
319
vector<uint8_t, ALLOC> serializeToBytes(T& object, ARGS&&... arguments)
320
2
{
321
2
    const BasicBitBuffer<ALLOC> bitBuffer =
322
2
            detail::serialize(object, ALLOC(), std::forward<ARGS>(arguments)...);
323
324
2
    return bitBuffer.getBytes();
325
2
}
326
327
/**
328
 * Serializes given generated enum to vector of bytes.
329
 *
330
 * Example:
331
 * \code{.cpp}
332
 *     #include <zserio/SerializeUtil.h>
333
 *
334
 *     const SomeZserioEnum enumValue = SomeZserioEnum::SomeEnumValue;
335
 *     const zserio::vector<uint8_t> buffer = zserio::serializeToBytes(enumValue);
336
 * \endcode
337
 *
338
 * \param enumValue Generated enum to serialize.
339
 * \param allocator Allocator to use to allocate vector.
340
 *
341
 * \return Vector of bytes containing the serialized enum.
342
 *
343
 * \throw CppRuntimeException When serialization fails.
344
 */
345
template <typename T, typename ALLOC = std::allocator<uint8_t>,
346
        typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
347
vector<uint8_t, ALLOC> serializeToBytes(T enumValue, const ALLOC& allocator = ALLOC())
348
3
{
349
3
    const BasicBitBuffer<ALLOC> bitBuffer = serialize(enumValue, allocator);
350
351
3
    return bitBuffer.getBytes();
352
3
}
353
354
/**
355
 * Deserializes given vector of bytes to instance of generated object.
356
 *
357
 * This method can potentially use all bits of the last byte even if not all of them were written during
358
 * serialization (because there is no way how to specify exact number of bits). Thus, it could allow reading
359
 * behind stream (possibly in case of damaged data).
360
 *
361
 * Example:
362
 * \code{.cpp}
363
 *     #include <zserio/SerializeUtil.h>
364
 *
365
 *     SomeZserioObject object;
366
 *     const zserio::vector<uint8_t> buffer = zserio::serializeToBytes(object);
367
 *     SomeZserioObject readObject = zserio::deserializeFromBytes<SomeZserioObject>(buffer);
368
 * \endcode
369
 *
370
 * \param bitBuffer Vector of bytes to use.
371
 * \param arguments Object's actual parameters together with allocator for object's read constructor (optional).
372
 *
373
 * \return Generated object created from the given vector of bytes.
374
 *
375
 * \throw CppRuntimeException When deserialization fails.
376
 */
377
template <typename T, typename... ARGS>
378
typename std::enable_if<!std::is_enum<T>::value && !is_first_array_preallocation<ARGS...>::value, T>::type
379
deserializeFromBytes(Span<const uint8_t> buffer, ARGS&&... arguments)
380
9
{
381
9
    BitStreamReader reader(buffer);
382
9
    return T(reader, std::forward<ARGS>(arguments)...);
383
9
}
384
385
/**
386
 * Deserializes given vector of bytes to instance of generated object.
387
 *
388
 * This method can potentially use all bits of the last byte even if not all of them were written during
389
 * serialization (because there is no way how to specify exact number of bits). Thus, it could allow reading
390
 * behind stream (possibly in case of damaged data).
391
 *
392
 * Example:
393
 * \code{.cpp}
394
 *     #include <zserio/SerializeUtil.h>
395
 *
396
 *     SomeZserioObject object;
397
 *     const zserio::vector<uint8_t> buffer = zserio::serializeToBytes(object);
398
 *     SomeZserioObject readObject = zserio::deserializeFromBytes<SomeZserioObject>(buffer,
399
 *             zserio::ArrayPreallocation(1024*1024));
400
 * \endcode
401
 *
402
 * \param bitBuffer Vector of bytes to use.
403
 * \param arguments Object's actual parameters together with allocator for object's read constructor (optional).
404
 *
405
 * \return Generated object created from the given vector of bytes.
406
 *
407
 * \throw CppRuntimeException When deserialization fails.
408
 */
409
template <typename T, typename... ARGS>
410
typename std::enable_if<!std::is_enum<T>::value, T>::type deserializeFromBytes(
411
        Span<const uint8_t> buffer, ArrayPreallocation maxArrayPrealloc, ARGS&&... arguments)
412
6
{
413
6
    BitStreamReader reader(buffer, maxArrayPrealloc);
414
6
    return T(reader, std::forward<ARGS>(arguments)...);
415
6
}
416
417
/**
418
 * Deserializes given vector of bytes to instance of generated enum.
419
 *
420
 * Example:
421
 * \code{.cpp}
422
 *     #include <zserio/SerializeUtil.h>
423
 *
424
 *     const SomeZserioEnum enumValue = SomeZserioEnum::SomeEnumValue;
425
 *     const zserio::vector<uint8_t> buffer = zserio::serializeToBytes(enumValue);
426
 *     const SomeZserioEnum readEnumValue = zserio::deserializeFromBytes<DummyEnum>(buffer);
427
 * \endcode
428
 *
429
 * \param bitBuffer Vector of bytes to use.
430
 *
431
 * \return Generated enum created from the given vector of bytes.
432
 *
433
 * \throw CppRuntimeException When deserialization fails.
434
 */
435
template <typename T>
436
typename std::enable_if<std::is_enum<T>::value, T>::type deserializeFromBytes(Span<const uint8_t> buffer)
437
3
{
438
3
    BitStreamReader reader(buffer);
439
3
    return zserio::read<T>(reader);
440
3
}
441
442
/**
443
 * Serializes given generated object to file.
444
 *
445
 * Example:
446
 * \code{.cpp}
447
 *     #include <zserio/SerializeUtil.h>
448
 *
449
 *     SomeZserioObject object;
450
 *     zserio::serializeToFile(object, "FileName.bin");
451
 * \endcode
452
 *
453
 * \param object Generated object to serialize.
454
 * \param fileName File name to write.
455
 *
456
 * \throw CppRuntimeException When serialization fails.
457
 */
458
template <typename T, typename... ARGS>
459
void serializeToFile(T& object, const std::string& fileName, ARGS&&... arguments)
460
3
{
461
3
    const auto bitBuffer = serialize(object, std::forward<ARGS>(arguments)...);
462
3
    writeBufferToFile(bitBuffer, fileName);
463
3
}
464
465
/**
466
 * Deserializes given file contents to instance of generated object.
467
 *
468
 * Example:
469
 * \code{.cpp}
470
 *     #include <zserio/SerializeUtil.h>
471
 *
472
 *     const std::string fileName = "FileName.bin";
473
 *     SomeZserioObject object;
474
 *     zserio::serializeToFile(object, fileName);
475
 *     SomeZserioObject readObject = zserio::deserializeFromFile<SomeZserioObject>(fileName);
476
 * \endcode
477
 *
478
 * \note Please note that BitBuffer is always allocated using 'std::allocator<uint8_t>'.
479
 *
480
 * \param fileName File to use.
481
 * \param arguments Object's arguments (optional).
482
 *
483
 * \return Generated object created from the given file contents.
484
 *
485
 * \throw CppRuntimeException When deserialization fails.
486
 */
487
template <typename T, typename... ARGS>
488
typename std::enable_if<!is_first_array_preallocation<ARGS...>::value, T>::type deserializeFromFile(
489
        const std::string& fileName, ARGS&&... arguments)
490
3
{
491
3
    const BitBuffer bitBuffer = readBufferFromFile(fileName);
492
3
    return deserialize<T>(bitBuffer, std::forward<ARGS>(arguments)...);
493
3
}
494
495
/**
496
 * Deserializes given file contents to instance of generated object.
497
 *
498
 * Example:
499
 * \code{.cpp}
500
 *     #include <zserio/SerializeUtil.h>
501
 *
502
 *     const std::string fileName = "FileName.bin";
503
 *     SomeZserioObject object;
504
 *     zserio::serializeToFile(object, fileName);
505
 *     SomeZserioObject readObject = zserio::deserializeFromFile<SomeZserioObject>(fileName,
506
 *             zserio::ArrayPreallocation(1024*1024));
507
 * \endcode
508
 *
509
 * \note Please note that BitBuffer is always allocated using 'std::allocator<uint8_t>'.
510
 *
511
 * \param fileName File to use.
512
 * \param arguments Object's arguments (optional).
513
 *
514
 * \return Generated object created from the given file contents.
515
 *
516
 * \throw CppRuntimeException When deserialization fails.
517
 */
518
template <typename T, typename... ARGS>
519
T deserializeFromFile(const std::string& fileName, ArrayPreallocation maxArrayPrealloc, ARGS&&... arguments)
520
{
521
    const BitBuffer bitBuffer = readBufferFromFile(fileName);
522
    return deserialize<T>(bitBuffer, maxArrayPrealloc, std::forward<ARGS>(arguments)...);
523
}
524
525
} // namespace zserio
526
527
#endif // ZSERIO_SERIALIZE_UTIL_H_INC