Line data Source code
1 : /*
2 : * Protobuf serialization library - protobuf wire encoding and field attributes.
3 : *
4 : * Copyright (c) 2024 Antonin Kriz <antonin.kriz@gmail.com>
5 : * Released under the MIT License. See LICENSE in the project root.
6 : */
7 :
8 : #pragma once
9 :
10 : #include <cstdint>
11 : #include <stdexcept>
12 :
13 : namespace spb::pb::detail
14 : {
15 : using enum_type = int32_t;
16 :
17 : enum class tag_type : uint32_t
18 : {
19 : invalid = 0
20 : };
21 :
22 : //- https://protobuf.dev/programming-guides/encoding/
23 : enum class wire_type : uint8_t
24 : {
25 : //- int32, int64, uint32, uint64, sint32, sint64, bool, enum
26 : varint = 0,
27 : //- fixed64, sfixed64, double
28 : fixed64 = 1,
29 : //- string, bytes, embedded messages, packed repeated fields
30 : length_delimited = 2,
31 : //- not used
32 : StartGroup = 3,
33 : //- not used
34 : EndGroup = 4,
35 : //- fixed32, sfixed32, float
36 : fixed32 = 5
37 : };
38 :
39 : //- type1, type2 and packed flag
40 : enum scalar_encoder : uint8_t
41 : {
42 : none = 0,
43 : //- int32, int64, uint32, uint64, bool
44 : varint = 0x01,
45 : //- zigzag int32 or int64
46 : svarint = 0x02,
47 : //- 4 bytes
48 : i32 = 0x03,
49 : //- 8 bytes
50 : i64 = 0x04,
51 : //- packed array
52 : packed = 0x08
53 : };
54 :
55 : struct serialize_mode
56 : {
57 : scalar_encoder encoder = {};
58 : scalar_encoder encoder2 = {};
59 : size_t max_count = 0;
60 : size_t max_size = 0;
61 : };
62 :
63 : constexpr auto make_packed(scalar_encoder a) noexcept -> scalar_encoder
64 : {
65 : return scalar_encoder(a | scalar_encoder::packed);
66 : }
67 :
68 : constexpr auto is_packed(scalar_encoder a) noexcept -> bool
69 : {
70 : return (a & scalar_encoder::packed) == scalar_encoder::packed;
71 : }
72 :
73 : constexpr auto reset_packed(serialize_mode a) noexcept -> serialize_mode
74 : {
75 : a.encoder = scalar_encoder(a.encoder & ~scalar_encoder::packed);
76 : return a;
77 : }
78 :
79 4516 : constexpr auto encoder_type(scalar_encoder a) noexcept -> scalar_encoder
80 : {
81 4516 : return scalar_encoder(a & 0x07);
82 : }
83 :
84 4516 : constexpr auto to_wire_type(scalar_encoder a) noexcept -> wire_type
85 : {
86 4516 : switch (encoder_type(a))
87 : {
88 1240 : case scalar_encoder::i32:
89 1240 : return wire_type::fixed32;
90 1017 : case scalar_encoder::i64:
91 1017 : return wire_type::fixed64;
92 2259 : default:
93 2259 : return wire_type::varint;
94 : }
95 : }
96 :
97 970 : inline void check_size(size_t size, size_t max_size)
98 : {
99 970 : if (size > max_size) [[unlikely]]
100 132 : throw std::length_error("field is too large");
101 838 : }
102 :
103 : } // namespace spb::pb::detail
|