VLink  2.3.0
A high-performance communication middleware
someip_serializer.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file someip_serializer.h
26  * @brief SOME/IP payload codec helpers and template field traversal.
27  *
28  * @details
29  * Implements the AUTOSAR R25-11 payload deployment selected by
30  * @c VLINK_SOMEIP_FIELDS: configurable payload byte order, alignment from the
31  * SOME/IP message start, field and structure length widths, UTF-8 and UTF-16
32  * strings framed by a BOM and null terminator, associative maps, unions with
33  * a type selector, and TLV structures with optional members and
34  * self-describing unknown-member skipping. Length fields, TLV tags, and
35  * union type selectors keep network byte order. The SOME/IP message header
36  * is outside this codec and limits a payload to @c UINT32_MAX-8 bytes.
37  *
38  * Non-template cursor and primitive operations are implemented once in
39  * @c src/extension/someip_serializer.cc; only container traversal and structure
40  * expansion remain templates. Failures are reported through boolean return
41  * values, and unsupported field types are rejected at compile time. Mixed
42  * or opaque field byte order and C++ bit-fields are not supported; deployment
43  * maximum-length constraints may be declared by the corresponding field
44  * wrappers; the wire format details are documented in
45  * @c doc/03-serialization.md.
46  */
47 
48 #pragma once
49 
50 #include <array>
51 #include <cstddef>
52 #include <cstdint>
53 #include <limits>
54 #include <map>
55 #include <optional>
56 #include <string>
57 #include <tuple>
58 #include <type_traits>
59 #include <unordered_map>
60 #include <utility>
61 #include <variant>
62 #include <vector>
63 
64 #include "../base/bytes.h"
65 #include "../base/macros.h"
66 #include "../base/traits.h"
67 
68 namespace vlink {
69 
70 /**
71  * @namespace vlink::SomeipSerializer
72  * @brief AUTOSAR SOME/IP payload codec for macro-declared structures.
73  */
74 namespace SomeipSerializer { // NOLINT(readability-identifier-naming)
75 
76 /**
77  * @brief Maximum payload size representable by a SOME/IP message.
78  *
79  * @details
80  * The 32-bit SOME/IP Length field includes the eight bytes from Request ID
81  * through Return Code, leaving this many bytes for the payload.
82  */
83 static constexpr size_t kMaxPayloadSize = std::numeric_limits<uint32_t>::max() - 8U;
84 
85 /**
86  * @enum Endian
87  * @brief Byte order used for SOME/IP payload scalar values.
88  */
89 enum class Endian : uint8_t {
90  kBig = 0,
91  kLittle = 1,
92 };
93 
94 /**
95  * @class Writer
96  * @brief Bounds-checked SOME/IP payload writer.
97  *
98  * @details
99  * A null destination performs a size-only pass. A non-null destination never
100  * grows or replaces storage, which allows exact transport loans to be written
101  * in place. Every successful append advances @c position() by the encoded
102  * byte count; a failed append leaves the cursor unchanged. The writer never
103  * advances beyond @c kMaxPayloadSize.
104  */
105 class VLINK_EXPORT Writer final {
106  public:
107  /**
108  * @brief Creates a writer over @p data with @p capacity bytes.
109  *
110  * @details
111  * Passing @c nullptr selects size-only mode. Otherwise @p data must remain
112  * valid for @p capacity bytes throughout the writer lifetime. Values above
113  * @c kMaxPayloadSize are clamped to that wire-format limit. The writer does
114  * not own or initialize the destination storage.
115  *
116  * @param data Destination buffer, or @c nullptr for size-only mode.
117  * @param capacity Number of writable bytes, or the maximum size to measure.
118  * @param alignment AUTOSAR payload alignment: 1, 2, 4, 8, 16, or 32 bytes.
119  * @param endian Byte order for payload scalar values.
120  */
121  Writer(uint8_t* data, size_t capacity, size_t alignment = 1U, Endian endian = Endian::kBig) noexcept;
122 
123  /**
124  * @brief Returns the number of bytes consumed by this writer.
125  *
126  * @return Current zero-based write position in bytes.
127  */
128  [[nodiscard]] size_t position() const noexcept;
129 
130  /**
131  * @brief Reports whether this writer only measures encoded size.
132  *
133  * @return @c true when no destination buffer is attached.
134  */
135  [[nodiscard]] bool is_size_only() const noexcept;
136 
137  /**
138  * @brief Creates a size-only cursor at the current position.
139  *
140  * @return A writer preserving capacity, position, alignment, and byte order
141  * without a destination buffer.
142  */
143  [[nodiscard]] Writer size_only() const noexcept;
144 
145  /**
146  * @brief Appends @p size bytes without alignment padding.
147  *
148  * @details
149  * Size-only mode advances the cursor without reading @p data. In write mode,
150  * @p data must identify at least @p size readable bytes when @p size is not
151  * zero and must not overlap the destination range written by this operation.
152  *
153  * @param data Source bytes.
154  * @param size Number of bytes to append.
155  * @return @c true on success; @c false when the destination is too small.
156  */
157  [[nodiscard]] bool append(const uint8_t* data, size_t size) noexcept;
158 
159  /**
160  * @brief Appends the low @p width bytes of @p value in the configured byte order.
161  *
162  * @param value Unsigned value containing the bits to encode.
163  * @param width Encoded width in bytes; must be in the range @c [1,8].
164  * @return @c true on success; @c false for an invalid width or insufficient storage.
165  */
166  [[nodiscard]] bool append_unsigned(uint64_t value, size_t width) noexcept;
167 
168  /**
169  * @brief Appends the low @p width bytes of @p value in an explicit byte order.
170  *
171  * @details
172  * Wire-format metadata such as TLV tags and union type selectors keeps
173  * network byte order independently of the configured payload byte order.
174  *
175  * @param value Unsigned value containing the bits to encode.
176  * @param width Encoded width in bytes; must be in the range @c [1,8].
177  * @param endian Byte order for this value only.
178  * @return @c true on success; @c false for an invalid width or insufficient storage.
179  */
180  [[nodiscard]] bool append_unsigned(uint64_t value, size_t width, Endian endian) noexcept;
181 
182  /**
183  * @brief Reserves a length field and records its payload start.
184  *
185  * @param length_position Output offset of the reserved length field.
186  * @param data_position Output offset of the first length-delimited byte.
187  * @param width Encoded width in bytes; must be 1, 2, or 4.
188  * @return @c true on success; @c false when the field cannot be reserved.
189  */
190  [[nodiscard]] bool begin_length_delimited(size_t& length_position, size_t& data_position,
191  size_t width = sizeof(uint32_t)) noexcept;
192 
193  /**
194  * @brief Finalizes a reserved length field from the current position.
195  *
196  * @details
197  * Stores @c position()-@p data_position as an unsigned byte count at
198  * @p length_position. The current position is not changed.
199  *
200  * @param length_position Offset returned by @c begin_length_delimited().
201  * @param data_position Payload start returned by @c begin_length_delimited().
202  * @param width Encoded width in bytes; must be 1, 2, or 4.
203  * @return @c true on success; @c false on an invalid range or length overflow.
204  */
205  [[nodiscard]] bool end_length_delimited(size_t length_position, size_t data_position,
206  size_t width = sizeof(uint32_t)) noexcept;
207 
208  /**
209  * @brief Pads the current position to the configured AUTOSAR alignment.
210  *
211  * @return @c true on success; @c false when the destination is too small.
212  */
213  [[nodiscard]] bool align() noexcept;
214 
215  private:
216  uint8_t* data_{nullptr};
217  size_t capacity_{0};
218  size_t position_{0};
219  size_t alignment_{1U};
220  Endian endian_{Endian::kBig};
221 };
222 
223 /**
224  * @class Reader
225  * @brief Bounds-checked SOME/IP payload reader.
226  *
227  * @details
228  * Every operation accepts an enclosing end position, so nested arrays cannot
229  * consume bytes belonging to their parent structure. Successful operations
230  * advance the cursor. The cursor state after a failed compound field is not
231  * specified; a top-level failure may leave already decoded destination fields
232  * updated.
233  */
234 class VLINK_EXPORT Reader final {
235  public:
236  /**
237  * @brief Creates a reader over an immutable @p size-byte payload.
238  *
239  * @details
240  * The reader does not own the source storage. When @p size is non-zero,
241  * @p data must remain valid throughout the reader lifetime.
242  *
243  * @param data Source payload.
244  * @param size Total source size in bytes.
245  * @param alignment AUTOSAR payload alignment: 1, 2, 4, 8, 16, or 32 bytes.
246  * @param endian Byte order for payload scalar values.
247  */
248  Reader(const uint8_t* data, size_t size, size_t alignment = 1U, Endian endian = Endian::kBig) noexcept;
249 
250  /**
251  * @brief Returns the current read position.
252  *
253  * @return Current zero-based read position in bytes.
254  */
255  [[nodiscard]] size_t position() const noexcept;
256 
257  /**
258  * @brief Returns the total payload size.
259  *
260  * @return Source payload size supplied to the constructor.
261  */
262  [[nodiscard]] size_t size() const noexcept;
263 
264  /**
265  * @brief Returns the current byte pointer, or @c nullptr at the end.
266  *
267  * @return Pointer to the unread byte at @c position(), or @c nullptr when no bytes remain.
268  */
269  [[nodiscard]] const uint8_t* current_data() const noexcept;
270 
271  /**
272  * @brief Reads @p size bytes without exceeding @p end.
273  *
274  * @details
275  * The destination range must not overlap the source range read by this
276  * operation.
277  *
278  * @param data Destination buffer; must hold @p size bytes when non-zero.
279  * @param size Number of bytes to copy.
280  * @param end Exclusive enclosing boundary, not greater than @c size().
281  * @return @c true on success; @c false when the requested range is invalid.
282  */
283  [[nodiscard]] bool read(uint8_t* data, size_t size, size_t end) noexcept;
284 
285  /**
286  * @brief Advances by @p size bytes without exceeding @p end.
287  *
288  * @param size Number of bytes to skip.
289  * @param end Exclusive enclosing boundary, not greater than @c size().
290  * @return @c true on success; @c false when the requested range is invalid.
291  */
292  [[nodiscard]] bool skip(size_t size, size_t end) noexcept;
293 
294  /**
295  * @brief Reads a @p width-byte unsigned integer in the configured byte order.
296  *
297  * @param value Output value; modified only after the range is validated.
298  * @param width Encoded width in bytes; must be in the range @c [1,8].
299  * @param end Exclusive enclosing boundary, not greater than @c size().
300  * @return @c true on success; @c false for an invalid width or range.
301  */
302  [[nodiscard]] bool read_unsigned(uint64_t& value, size_t width, size_t end) noexcept;
303 
304  /**
305  * @brief Reads a @p width-byte unsigned integer in an explicit byte order.
306  *
307  * @details
308  * Wire-format metadata such as TLV tags and union type selectors keeps
309  * network byte order independently of the configured payload byte order.
310  *
311  * @param value Output value; modified only after the range is validated.
312  * @param width Encoded width in bytes; must be in the range @c [1,8].
313  * @param endian Byte order for this value only.
314  * @param end Exclusive enclosing boundary, not greater than @c size().
315  * @return @c true on success; @c false for an invalid width or range.
316  */
317  [[nodiscard]] bool read_unsigned(uint64_t& value, size_t width, Endian endian, size_t end) noexcept;
318 
319  /**
320  * @brief Reads a length field and returns its validated end position.
321  *
322  * @details
323  * The prefix is a big-endian byte count. On success, @p value_end is the
324  * exclusive end of the declared body and the reader points to its first byte.
325  *
326  * @param end Exclusive enclosing boundary.
327  * @param value_end Output exclusive boundary of the length-delimited body.
328  * @param width Encoded width in bytes; must be 1, 2, or 4.
329  * @return @c true on success; @c false when the prefix or declared body exceeds @p end.
330  */
331  [[nodiscard]] bool begin_length_delimited(size_t end, size_t& value_end, size_t width = sizeof(uint32_t)) noexcept;
332 
333  /**
334  * @brief Skips bytes up to the configured AUTOSAR alignment.
335  *
336  * @param end Exclusive enclosing boundary.
337  * @return @c true on success; @c false when the padding exceeds @p end.
338  */
339  [[nodiscard]] bool align(size_t end) noexcept;
340 
341  private:
342  const uint8_t* data_{nullptr};
343  size_t size_{0};
344  size_t position_{0};
345  size_t alignment_{1U};
346  Endian endian_{Endian::kBig};
347 };
348 
349 /**
350  * @brief Encodes an enum or macro-declared nested SOME/IP structure.
351  *
352  * @details
353  * Enums must use an unsigned fixed-width underlying type. Nested structures
354  * are expanded in the exact field order supplied to
355  * @c VLINK_SOMEIP_FIELDS.
356  *
357  * @tparam T Enum or macro-declared SOME/IP structure type.
358  * @param writer Destination cursor.
359  * @param value Field value to encode.
360  * @return @c true on success; @c false when a nested field cannot be encoded.
361  */
362 template <typename T>
363 inline bool write_value(Writer& writer, const T& value) noexcept;
364 
365 /**
366  * @brief Encodes a dynamic array with a configurable byte-length prefix.
367  *
368  * @details
369  * The prefix counts encoded bytes, not elements. The @c vector<bool>
370  * specialization is traversed by value to avoid proxy-reference dispatch.
371  * An element that encodes to zero bytes is rejected because its count cannot
372  * be represented by the byte-length prefix.
373  *
374  * @tparam T Element type supported by @c write_value().
375  * @tparam AllocatorT Vector allocator type.
376  * @tparam InnerLenT Optional length widths for the inner array dimensions.
377  * @tparam MaxT Maximum encoded element count.
378  * @param writer Destination cursor.
379  * @param value Array elements to encode in order.
380  * @param len Length field width in bytes; must be 1, 2, or 4.
381  * @return @c true on success; @c false on overflow or element encoding failure.
382  */
383 template <size_t MaxT = std::numeric_limits<size_t>::max(), typename T, typename AllocatorT, size_t... InnerLenT>
384 inline bool write_value(Writer& writer, const std::vector<T, AllocatorT>& value, size_t len = sizeof(uint32_t),
385  std::index_sequence<InnerLenT...> = {}) noexcept;
386 
387 /**
388  * @brief Encodes a fixed-size array with an optional byte-length prefix.
389  *
390  * @tparam T Element type supported by @c write_value().
391  * @tparam SizeT Compile-time element count.
392  * @tparam InnerLenT Optional length widths for the inner array dimensions.
393  * @param writer Destination cursor.
394  * @param value Array elements to encode in order.
395  * @param len Length field width in bytes, or zero to omit it.
396  * @return @c true on success; @c false on overflow or element encoding failure.
397  */
398 template <typename T, size_t SizeT, size_t... InnerLenT>
399 inline bool write_value(Writer& writer, const std::array<T, SizeT>& value, size_t len = sizeof(uint32_t),
400  std::index_sequence<InnerLenT...> = {}) noexcept;
401 
402 /**
403  * @brief Encodes an associative map with a configurable byte-length prefix.
404  *
405  * @details
406  * The prefix counts encoded bytes. Every entry is encoded as its key
407  * followed immediately by its mapped value, without padding inside or between
408  * entries; nested containers inside an entry use the default deployment.
409  * Iteration order of an @c std::unordered_map selects the encoded entry order.
410  *
411  * @tparam KeyT Key type supported by @c write_value().
412  * @tparam ValueT Mapped type supported by @c write_value().
413  * @param writer Destination cursor.
414  * @param value Map entries to encode.
415  * @param len Length field width in bytes; must be 1, 2, or 4.
416  * @return @c true on success; @c false on overflow or entry encoding failure.
417  * @{
418  */
419 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
420 inline bool write_value(Writer& writer, const std::map<KeyT, ValueT, CompareT, AllocatorT>& value,
421  size_t len = sizeof(uint32_t)) noexcept;
422 
423 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
424 inline bool write_value(Writer& writer, const std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>& value,
425  size_t len = sizeof(uint32_t)) noexcept;
426 /**
427  * @}
428  */
429 
430 /**
431  * @brief Encodes a union with a byte length and a type selector.
432  *
433  * @details
434  * The wire format is the data byte length, the type selector, and the encoded
435  * alternative. The length includes alternative padding and excludes the
436  * selector. Selector values identify
437  * alternatives in declaration order from one. When the first alternative is
438  * @c std::monostate, it represents the empty union with selector zero.
439  *
440  * @tparam AlternativeT Alternatives supported by @c write_value().
441  * @param writer Destination cursor.
442  * @param value Union value to encode.
443  * @param len Length field width in bytes; must be 1, 2, or 4.
444  * @param type_width Type selector width in bytes; must be 1, 2, or 4.
445  * @return @c true on success; @c false on overflow or alternative encoding failure.
446  */
447 template <typename... AlternativeT>
448 inline bool write_value(Writer& writer, const std::variant<AlternativeT...>& value, size_t len = sizeof(uint32_t),
449  size_t type_width = sizeof(uint32_t)) noexcept;
450 
451 /**
452  * @brief Decodes an enum or macro-declared nested SOME/IP structure.
453  *
454  * @details
455  * Enums must use an unsigned fixed-width underlying type. Nested structure
456  * fields are decoded in the order supplied to @c VLINK_SOMEIP_FIELDS.
457  *
458  * @tparam T Enum or macro-declared SOME/IP structure type.
459  * @param reader Source cursor.
460  * @param value Destination field.
461  * @param end Exclusive boundary of the enclosing field or payload.
462  * @return @c true on success; @c false when a nested field cannot be decoded.
463  */
464 template <typename T>
465 inline bool read_value(Reader& reader, T& value, size_t end) noexcept;
466 
467 /**
468  * @brief Decodes a byte-length-delimited dynamic array.
469  *
470  * @details
471  * Existing elements are decoded in place so their internal capacity can be reused; new
472  * elements are appended only as needed. On success, the vector is resized to the decoded
473  * element count. A failure may leave updated elements and untouched old tail elements.
474  *
475  * @tparam T Default-constructible element type supported by @c read_value().
476  * @tparam AllocatorT Vector allocator type.
477  * @tparam InnerLenT Optional length widths for the inner array dimensions.
478  * @tparam MaxT Maximum decoded element count; remaining bytes are skipped.
479  * @param reader Source cursor.
480  * @param value Destination vector whose existing elements are reused when possible.
481  * @param end Exclusive boundary of the enclosing field or payload.
482  * @param len Length field width in bytes; must be 1, 2, or 4.
483  * @return @c true on success; @c false for an invalid length or element encoding.
484  */
485 template <size_t MaxT = std::numeric_limits<size_t>::max(), typename T, typename AllocatorT, size_t... InnerLenT>
486 inline bool read_value(Reader& reader, std::vector<T, AllocatorT>& value, size_t end, size_t len = sizeof(uint32_t),
487  std::index_sequence<InnerLenT...> = {}) noexcept;
488 
489 /**
490  * @brief Decodes a byte-length-delimited fixed-size array.
491  *
492  * @details
493  * Exactly @c SizeT elements are decoded. Remaining bytes in a longer remote
494  * representation are skipped as required for compatible fixed-array growth;
495  * truncated content is rejected.
496  *
497  * @tparam T Element type supported by @c read_value().
498  * @tparam SizeT Compile-time element count.
499  * @tparam InnerLenT Optional length widths for the inner array dimensions.
500  * @param reader Source cursor.
501  * @param value Destination array.
502  * @param end Exclusive boundary of the enclosing field or payload.
503  * @param len Length field width in bytes, or zero when omitted.
504  * @return @c true on success; @c false when the length cannot contain all elements.
505  */
506 template <typename T, size_t SizeT, size_t... InnerLenT>
507 inline bool read_value(Reader& reader, std::array<T, SizeT>& value, size_t end, size_t len = sizeof(uint32_t),
508  std::index_sequence<InnerLenT...> = {}) noexcept;
509 
510 /**
511  * @brief Decodes a byte-length-delimited associative map.
512  *
513  * @details
514  * The map is cleared and rebuilt from the encoded entries. A duplicate key
515  * is rejected as malformed input.
516  *
517  * @tparam KeyT Default-constructible key type supported by @c read_value().
518  * @tparam ValueT Default-constructible mapped type supported by @c read_value().
519  * @param reader Source cursor.
520  * @param value Destination map.
521  * @param end Exclusive boundary of the enclosing field or payload.
522  * @param len Length field width in bytes; must be 1, 2, or 4.
523  * @return @c true on success; @c false for an invalid length or entry encoding.
524  * @{
525  */
526 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
527 inline bool read_value(Reader& reader, std::map<KeyT, ValueT, CompareT, AllocatorT>& value, size_t end,
528  size_t len = sizeof(uint32_t)) noexcept;
529 
530 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
531 inline bool read_value(Reader& reader, std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>& value, size_t end,
532  size_t len = sizeof(uint32_t)) noexcept;
533 /**
534  * @}
535  */
536 
537 /**
538  * @brief Decodes a union with a byte length and a type selector.
539  *
540  * @details
541  * Selector zero selects a first @c std::monostate alternative when present.
542  * Every other selector must identify a declared alternative, which is decoded
543  * in place of the previous value. Declared
544  * bytes past the decoded alternative are skipped for compatible peers that
545  * pad the union body.
546  *
547  * @tparam AlternativeT Default-constructible alternatives supported by @c read_value().
548  * @param reader Source cursor.
549  * @param value Destination union.
550  * @param end Exclusive boundary of the enclosing field or payload.
551  * @param len Length field width in bytes; must be 1, 2, or 4.
552  * @param type_width Type selector width in bytes; must be 1, 2, or 4.
553  * @return @c true on success; @c false for an unknown selector or malformed body.
554  */
555 template <typename... AlternativeT>
556 inline bool read_value(Reader& reader, std::variant<AlternativeT...>& value, size_t end, size_t len = sizeof(uint32_t),
557  size_t type_width = sizeof(uint32_t)) noexcept;
558 
559 /**
560  * @brief Returns the exact SOME/IP payload size for @p src.
561  *
562  * @details
563  * Executes the normal encoder in size-only mode, so validation and 32-bit
564  * length limits match @c serialize(). No destination buffer is allocated.
565  *
566  * @tparam T Macro-declared SOME/IP structure type.
567  * @param src Source structure to measure.
568  * @return Exact encoded byte count; @c 0 when validation or size calculation fails.
569  */
570 template <typename T>
571 [[nodiscard]] inline size_t get_serialized_size(const T& src) noexcept;
572 
573 /**
574  * @brief Serializes @p src into @p des using the SOME/IP payload format.
575  *
576  * @details
577  * A loaned destination must already have the exact encoded size and is never
578  * replaced. Sufficient owning capacity with a matching offset is reused;
579  * otherwise exact-size storage is allocated after a size-only pass.
580  * Destination storage must not overlap any storage reachable from @p src.
581  *
582  * @tparam T Macro-declared SOME/IP structure type.
583  * @param src Source structure.
584  * @param des Destination @c Bytes buffer.
585  * @return @c true on success; @c false on validation, sizing, or storage failure.
586  */
587 template <typename T>
588 inline bool serialize(const T& src, Bytes& des) noexcept;
589 
590 /**
591  * @brief Serializes @p src with reserved bytes before the payload.
592  *
593  * @details
594  * This overload is used by the generic serializer when a transport header
595  * offset is requested. The payload is written directly after the reserved
596  * prefix without an intermediate payload allocation or deep copy. The
597  * destination storage must not overlap any storage reachable from @p src.
598  *
599  * @tparam T Macro-declared SOME/IP structure type.
600  * @param src Source structure.
601  * @param des Destination @c Bytes buffer.
602  * @param offset Number of bytes reserved before the payload.
603  * @return @c true on success; @c false on validation, sizing, or storage failure.
604  */
605 template <typename T>
606 inline bool serialize(const T& src, Bytes& des, uint8_t offset) noexcept;
607 
608 /**
609  * @brief Deserializes a complete SOME/IP payload from @p src into @p des.
610  *
611  * @details
612  * Fields are decoded directly into @p des so existing string and vector
613  * capacity can be reused. Remaining top-level bytes are ignored for
614  * compatible extension at the end of a standard structure. A parse failure
615  * may leave fields decoded before the failure updated. Source storage must
616  * not overlap any storage reachable from @p des.
617  *
618  * @tparam T Macro-declared SOME/IP structure type.
619  * @param src Complete source payload.
620  * @param des Destination structure.
621  * @return @c true on success; @c false for malformed input.
622  */
623 template <typename T>
624 inline bool deserialize(const Bytes& src, T& des) noexcept;
625 
626 /**
627  * @brief Reports whether @p T encodes with a runtime-variable byte length.
628  *
629  * @tparam T Field type as listed in @c VLINK_SOMEIP_FIELDS.
630  * @return @c true when the encoded size depends on the field value.
631  */
632 template <typename T>
633 [[nodiscard]] constexpr bool is_variable_size() noexcept;
634 
635 ////////////////////////////////////////////////////////////////
636 /// Details
637 ////////////////////////////////////////////////////////////////
638 
639 namespace detail {
640 
641 VLINK_EXPORT bool write_value(Writer& writer, bool value) noexcept;
642 VLINK_EXPORT bool write_value(Writer& writer, uint8_t value) noexcept;
643 VLINK_EXPORT bool write_value(Writer& writer, uint16_t value) noexcept;
644 VLINK_EXPORT bool write_value(Writer& writer, uint32_t value) noexcept;
645 VLINK_EXPORT bool write_value(Writer& writer, uint64_t value) noexcept;
646 VLINK_EXPORT bool write_value(Writer& writer, int8_t value) noexcept;
647 VLINK_EXPORT bool write_value(Writer& writer, int16_t value) noexcept;
648 VLINK_EXPORT bool write_value(Writer& writer, int32_t value) noexcept;
649 VLINK_EXPORT bool write_value(Writer& writer, int64_t value) noexcept;
650 VLINK_EXPORT bool write_value(Writer& writer, float value) noexcept;
651 VLINK_EXPORT bool write_value(Writer& writer, double value) noexcept;
652 VLINK_EXPORT bool write_value(Writer& writer, const std::string& value, size_t len = sizeof(uint32_t),
653  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
654 VLINK_EXPORT bool write_value(Writer& writer, const Bytes& value, size_t len = sizeof(uint32_t),
655  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
656 VLINK_EXPORT bool write_value(Writer& writer, const std::u16string& value, size_t len = sizeof(uint32_t),
657  Endian encoding = Endian::kBig,
658  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
659 VLINK_EXPORT bool write_fixed_value(Writer& writer, const std::string& value, size_t size, size_t len,
660  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
661 VLINK_EXPORT bool write_fixed_value(Writer& writer, const std::u16string& value, size_t size, size_t len,
662  Endian encoding, size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
663 VLINK_EXPORT bool read_value(Reader& reader, bool& value, size_t end) noexcept;
664 VLINK_EXPORT bool read_value(Reader& reader, uint8_t& value, size_t end) noexcept;
665 VLINK_EXPORT bool read_value(Reader& reader, uint16_t& value, size_t end) noexcept;
666 VLINK_EXPORT bool read_value(Reader& reader, uint32_t& value, size_t end) noexcept;
667 VLINK_EXPORT bool read_value(Reader& reader, uint64_t& value, size_t end) noexcept;
668 VLINK_EXPORT bool read_value(Reader& reader, int8_t& value, size_t end) noexcept;
669 VLINK_EXPORT bool read_value(Reader& reader, int16_t& value, size_t end) noexcept;
670 VLINK_EXPORT bool read_value(Reader& reader, int32_t& value, size_t end) noexcept;
671 VLINK_EXPORT bool read_value(Reader& reader, int64_t& value, size_t end) noexcept;
672 VLINK_EXPORT bool read_value(Reader& reader, float& value, size_t end) noexcept;
673 VLINK_EXPORT bool read_value(Reader& reader, double& value, size_t end) noexcept;
674 VLINK_EXPORT bool read_value(Reader& reader, std::string& value, size_t end, size_t len = sizeof(uint32_t),
675  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
676 VLINK_EXPORT bool read_value(Reader& reader, Bytes& value, size_t end, size_t len = sizeof(uint32_t),
677  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
678 VLINK_EXPORT bool read_value(Reader& reader, std::u16string& value, size_t end, size_t len = sizeof(uint32_t),
679  Endian encoding = Endian::kBig,
680  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
681 VLINK_EXPORT bool read_fixed_value(Reader& reader, std::string& value, size_t end, size_t size, size_t len,
682  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
683 VLINK_EXPORT bool read_fixed_value(Reader& reader, std::u16string& value, size_t end, size_t size, size_t len,
684  Endian encoding, size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
685 VLINK_EXPORT bool read_value_body(Reader& reader, std::string& value, size_t end,
686  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
687 VLINK_EXPORT bool read_value_body(Reader& reader, std::u16string& value, size_t end, Endian encoding = Endian::kBig,
688  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
689 VLINK_EXPORT bool read_value_body(Reader& reader, Bytes& value, size_t end,
690  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
691 VLINK_EXPORT bool read_tag(Reader& reader, uint8_t& wire_type, uint16_t& data_id, size_t end) noexcept;
692 VLINK_EXPORT bool read_union_frame(Reader& reader, size_t len, size_t type_width, size_t end, uint64_t& selector,
693  size_t& data_end) noexcept;
694 VLINK_EXPORT bool write_value_body(Writer& writer, const std::string& value,
695  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
696 VLINK_EXPORT bool write_value_body(Writer& writer, const std::u16string& value, Endian encoding = Endian::kBig,
697  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
698 VLINK_EXPORT bool write_value_body(Writer& writer, const Bytes& value,
699  size_t maximum = std::numeric_limits<size_t>::max()) noexcept;
700 VLINK_EXPORT bool write_tag(Writer& writer, uint8_t wire_type, uint16_t data_id) noexcept;
701 VLINK_EXPORT bool write_union_frame(Writer& writer, uint64_t selector, size_t len, size_t type_width,
702  size_t& length_position, size_t& content_position) noexcept;
703 VLINK_EXPORT bool begin_tlv_body(Reader& reader, uint8_t wire_type, size_t configured_len, size_t end,
704  size_t& body_end) noexcept;
705 VLINK_EXPORT bool begin_tlv_complex(Writer& writer, uint16_t data_id, size_t len, bool dynamic, size_t& length_position,
706  size_t& data_position) noexcept;
707 VLINK_EXPORT bool skip_tlv_value(Reader& reader, uint8_t wire_type, size_t configured_len, size_t end) noexcept;
709 VLINK_EXPORT bool prepare_destination(Bytes& des, size_t size, uint8_t offset) noexcept;
710 
711 } // namespace detail
712 
713 template <typename T>
714 inline bool read_value_body(Reader& reader, T& value, size_t end) noexcept;
715 
716 template <typename T>
717 inline bool write_value_body(Writer& writer, const T& value) noexcept;
718 
719 template <typename T>
720 [[nodiscard]] constexpr size_t get_alignment() noexcept {
721  if constexpr (VLINK_HAS_MEMBER(T, vlink_someip_alignment())) {
722  constexpr size_t kAlignment = T::vlink_someip_alignment();
723 
724  static_assert(kAlignment == 1U || kAlignment == 2U || kAlignment == 4U || kAlignment == 8U || kAlignment == 16U ||
725  kAlignment == 32U,
726  "SOME/IP alignment must be 1, 2, 4, 8, 16, or 32 bytes.");
727  return kAlignment;
728  }
729 
730  return 1U;
731 }
732 
733 template <typename T>
734 [[nodiscard]] constexpr Endian get_endian() noexcept {
735  if constexpr (VLINK_HAS_MEMBER(T, vlink_someip_endian())) {
736  return T::vlink_someip_endian();
737  }
738 
739  return Endian::kBig;
740 }
741 
742 template <typename T>
743 [[nodiscard]] constexpr size_t get_struct_length() noexcept {
744  if constexpr (VLINK_HAS_MEMBER(T, vlink_someip_struct_length())) {
745  constexpr size_t kLength = T::vlink_someip_struct_length();
746 
747  static_assert(kLength == 0U || kLength == 1U || kLength == 2U || kLength == 4U,
748  "SOME/IP structure length field width must be 0, 1, 2, or 4 bytes.");
749  return kLength;
750  }
751 
752  return 0U;
753 }
754 
755 template <typename T>
756 [[nodiscard]] constexpr bool is_map(const T*) noexcept {
757  return false;
758 }
759 
760 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
761 [[nodiscard]] constexpr bool is_map(const std::map<KeyT, ValueT, CompareT, AllocatorT>*) noexcept {
762  return true;
763 }
764 
765 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
766 [[nodiscard]] constexpr bool is_map(const std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>*) noexcept {
767  return true;
768 }
769 
770 template <typename T>
771 [[nodiscard]] constexpr bool is_vector(const T*) noexcept {
772  return false;
773 }
774 
775 template <typename T, typename AllocatorT>
776 [[nodiscard]] constexpr bool is_vector(const std::vector<T, AllocatorT>*) noexcept {
777  return true;
778 }
779 
780 template <typename T>
781 [[nodiscard]] constexpr bool is_variant(const T*) noexcept {
782  return false;
783 }
784 
785 template <typename... AlternativeT>
786 [[nodiscard]] constexpr bool is_variant(const std::variant<AlternativeT...>*) noexcept {
787  return true;
788 }
789 
790 template <typename T>
791 [[nodiscard]] constexpr bool is_optional(const T*) noexcept {
792  return false;
793 }
794 
795 template <typename T>
796 [[nodiscard]] constexpr bool is_optional(const std::optional<T>*) noexcept {
797  return true;
798 }
799 
800 template <typename T>
801 [[nodiscard]] constexpr bool supports_maximum(const T*) noexcept {
802  using ValueType = std::remove_cv_t<T>;
803 
804  return std::is_same_v<ValueType, std::string> || std::is_same_v<ValueType, std::u16string> ||
805  std::is_same_v<ValueType, Bytes> || is_vector(static_cast<const ValueType*>(nullptr));
806 }
807 
808 template <typename T>
809 [[nodiscard]] constexpr bool supports_maximum(const std::optional<T>*) noexcept {
810  return supports_maximum(static_cast<const T*>(nullptr));
811 }
812 
813 static constexpr uint8_t kComplexWireType = 0xFFU;
814 
815 template <typename T>
816 [[nodiscard]] constexpr uint8_t get_fixed_wire_type() noexcept {
817  using ValueType = std::remove_cv_t<T>;
818 
819  if constexpr (std::is_enum_v<ValueType>) {
820  return get_fixed_wire_type<std::underlying_type_t<ValueType>>();
821  } else if constexpr (std::is_arithmetic_v<ValueType>) {
822  if constexpr (sizeof(ValueType) == sizeof(uint8_t)) {
823  return 0U;
824  } else if constexpr (sizeof(ValueType) == sizeof(uint16_t)) {
825  return 1U;
826  } else if constexpr (sizeof(ValueType) == sizeof(uint32_t)) {
827  return 2U;
828  } else {
829  return 3U;
830  }
831  } else {
832  return kComplexWireType;
833  }
834 }
835 
836 template <typename... AlternativeT>
837 [[nodiscard]] constexpr bool validate_union_alternatives() noexcept {
838  constexpr size_t kNullCount = (static_cast<size_t>(std::is_same_v<AlternativeT, std::monostate>) + ... + 0U);
839 
840  static_assert(kNullCount <= 1U, "SOME/IP unions accept at most one std::monostate alternative.");
841  static_assert(
842  kNullCount == 0U || std::is_same_v<std::tuple_element_t<0U, std::tuple<AlternativeT...>>, std::monostate>,
843  "SOME/IP union std::monostate must be the first alternative for selector zero.");
844  static_assert(kNullCount == 0U || sizeof...(AlternativeT) > 1U,
845  "SOME/IP unions require at least one non-null alternative.");
846 
847  return true;
848 }
849 
850 template <typename FirstT, typename... AlternativeT>
851 [[nodiscard]] constexpr bool union_alternatives_have_equal_size(const std::variant<FirstT, AlternativeT...>*) noexcept {
852  return (std::is_arithmetic_v<FirstT> || std::is_enum_v<FirstT>) &&
853  ((std::is_arithmetic_v<AlternativeT> || std::is_enum_v<AlternativeT>) && ...) &&
854  ((sizeof(FirstT) == sizeof(AlternativeT)) && ...);
855 }
856 
857 template <typename... AlternativeT>
858 [[nodiscard]] constexpr bool has_null_union_alternative() noexcept {
859  return std::is_same_v<std::tuple_element_t<0U, std::tuple<AlternativeT...>>, std::monostate>;
860 }
861 
862 template <size_t LenT, typename T>
863 [[nodiscard]] constexpr bool supports_length_field(const T*) noexcept {
864  return LenT > 0U && (std::is_same_v<T, std::string> || std::is_same_v<T, std::u16string> ||
865  std::is_same_v<T, Bytes> || is_map(static_cast<const T*>(nullptr)));
866 }
867 
868 template <size_t LenT, typename T, typename AllocatorT>
869 [[nodiscard]] constexpr bool supports_length_field(const std::vector<T, AllocatorT>*) noexcept {
870  return LenT > 0U;
871 }
872 
873 template <size_t LenT, typename T, size_t SizeT>
874 [[nodiscard]] constexpr bool supports_length_field(const std::array<T, SizeT>*) noexcept {
875  return true;
876 }
877 
878 template <size_t LenT, typename T, size_t MaxT = std::numeric_limits<size_t>::max()>
879 struct LengthField final {
880  static_assert(MaxT == std::numeric_limits<size_t>::max() || supports_maximum(static_cast<const T*>(nullptr)),
881  "SOME/IP maximum applies only to string, u16string, Bytes, and vector fields.");
882 
883  T& value;
884 };
885 
886 template <typename T, size_t LenT, size_t... InnerLenT>
887 struct ArrayLengthField final {
888  using ValueType = std::remove_cv_t<T>;
889 
890  static_assert((LenT == 0U || LenT == 1U || LenT == 2U || LenT == 4U) &&
891  ((InnerLenT == 0U || InnerLenT == 1U || InnerLenT == 2U || InnerLenT == 4U) && ...),
892  "SOME/IP array length field width must be 0, 1, 2, or 4 bytes.");
893  static_assert(!std::is_same_v<ValueType, std::string> && !std::is_same_v<ValueType, std::u16string> &&
894  !std::is_same_v<ValueType, Bytes> && !is_map(static_cast<const ValueType*>(nullptr)) &&
895  supports_length_field<LenT>(static_cast<const ValueType*>(nullptr)),
896  "VLINK_SOMEIP_ARRAY_LENGTH supports vector widths 1/2/4 and array widths 0/1/2/4.");
897 
898  T& value;
899 };
900 
901 template <size_t LenT, Endian EncodingT, typename T, size_t MaxT = std::numeric_limits<size_t>::max()>
902 struct Utf16Field final {
903  static_assert(LenT == 1U || LenT == 2U || LenT == 4U, "SOME/IP UTF-16 length field width must be 1, 2, or 4 bytes.");
904  static_assert(std::is_same_v<std::remove_cv_t<T>, std::u16string>,
905  "VLINK_SOMEIP_UTF16 requires a std::u16string field.");
906 
907  T& value;
908 };
909 
910 template <size_t SizeT, size_t LenT, Endian EncodingT, typename T, size_t MaxT = std::numeric_limits<size_t>::max()>
911 struct FixedStringField final {
912  using ValueType = std::remove_cv_t<T>;
913 
914  static_assert(LenT == 0U || LenT == 1U || LenT == 2U || LenT == 4U,
915  "SOME/IP fixed string length field width must be 0, 1, 2, or 4 bytes.");
916  static_assert(std::is_same_v<ValueType, std::string> || std::is_same_v<ValueType, std::u16string>,
917  "VLINK_SOMEIP_FIXED_STRING requires a std::string or std::u16string field.");
918  static_assert(SizeT >= 4U && (std::is_same_v<ValueType, std::string> || SizeT % 2U == 0U),
919  "SOME/IP fixed strings must hold a BOM and terminator; UTF-16 sizes must be even.");
920  static_assert(LenT == 0U || SizeT <= ((uint64_t{1U} << (LenT * 8U)) - 1U),
921  "SOME/IP fixed string size does not fit its length field.");
922 
923  T& value;
924 };
925 
926 template <size_t LenT, size_t TypeT, typename T>
927 struct UnionField final {
928  static_assert(LenT == 0U || LenT == 1U || LenT == 2U || LenT == 4U,
929  "SOME/IP union length field width must be 0, 1, 2, or 4 bytes.");
930  static_assert(TypeT == 1U || TypeT == 2U || TypeT == 4U,
931  "SOME/IP union type selector width must be 1, 2, or 4 bytes.");
932  static_assert(is_variant(static_cast<const std::remove_cv_t<T>*>(nullptr)),
933  "VLINK_SOMEIP_UNION requires a std::variant field.");
934  static_assert(LenT != 0U || union_alternatives_have_equal_size(static_cast<const std::remove_cv_t<T>*>(nullptr)),
935  "SOME/IP unions without a length field require equal-size arithmetic or enum alternatives.");
936 
937  T& value;
938 };
939 
940 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t MaxT = std::numeric_limits<size_t>::max()>
941 struct TlvField final {
942  static constexpr uint16_t kDataId = DataIdT;
943  static constexpr size_t kLengthWidth = LenT;
944 
945  static_assert(DataIdT <= 0x0FFFU, "SOME/IP TLV data IDs must fit the 12-bit tag field.");
946  static_assert(LenT == 1U || LenT == 2U || LenT == 4U, "SOME/IP TLV length field width must be 1, 2, or 4 bytes.");
947  static_assert(MaxT == std::numeric_limits<size_t>::max() || supports_maximum(static_cast<const T*>(nullptr)),
948  "SOME/IP maximum applies only to string, u16string, Bytes, and vector fields.");
949 
950  T& value;
951 };
952 
953 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t SizeT, Endian EncodingT, typename T,
954  size_t MaxT = std::numeric_limits<size_t>::max()>
955 struct TlvFixedStringField final {
956  using ValueType = std::remove_cv_t<T>;
957  static constexpr bool kUtf16 =
958  std::is_same_v<ValueType, std::u16string> || std::is_same_v<ValueType, std::optional<std::u16string>>;
959 
960  static constexpr uint16_t kDataId = DataIdT;
961  static constexpr size_t kLengthWidth = LenT;
962 
963  static_assert(DataIdT <= 0x0FFFU, "SOME/IP TLV data IDs must fit the 12-bit tag field.");
964  static_assert(LenT == 1U || LenT == 2U || LenT == 4U, "SOME/IP TLV length field width must be 1, 2, or 4 bytes.");
965  static_assert(std::is_same_v<ValueType, std::string> || std::is_same_v<ValueType, std::u16string> ||
966  std::is_same_v<ValueType, std::optional<std::string>> ||
967  std::is_same_v<ValueType, std::optional<std::u16string>>,
968  "VLINK_SOMEIP_TLV_FIXED_STRING requires a string or optional string field.");
969  static_assert(SizeT >= 4U && (!kUtf16 || SizeT % 2U == 0U),
970  "SOME/IP fixed strings must hold a BOM and terminator; UTF-16 sizes must be even.");
971  static_assert(DynamicT || SizeT <= ((uint64_t{1U} << (LenT * 8U)) - 1U),
972  "SOME/IP static TLV fixed string size does not fit its length field.");
973 
974  T& value;
975 };
976 
977 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t... InnerLenT>
978 struct TlvArrayField final {
979  static constexpr uint16_t kDataId = DataIdT;
980  static constexpr size_t kLengthWidth = LenT;
981 
982  static_assert(DataIdT <= 0x0FFFU, "SOME/IP TLV data IDs must fit the 12-bit tag field.");
983  static_assert(LenT == 1U || LenT == 2U || LenT == 4U, "SOME/IP TLV length field width must be 1, 2, or 4 bytes.");
984  static_assert(((InnerLenT == LenT) && ...), "SOME/IP TLV array dimensions must use the structure length width.");
985 
986  T& value;
987 };
988 
989 template <typename... FieldT>
990 [[nodiscard]] inline auto make_fields(FieldT&&... field) noexcept {
991  return std::tuple<FieldT...>(std::forward<FieldT>(field)...);
992 }
993 
994 template <size_t LenT, size_t MaxT = std::numeric_limits<size_t>::max(), typename T>
995 [[nodiscard]] inline auto length_field(T& value) noexcept {
996  using ValueType = std::remove_cv_t<T>;
997 
998  static_assert(LenT == 0U || LenT == 1U || LenT == 2U || LenT == 4U,
999  "SOME/IP length field width must be 0, 1, 2, or 4 bytes.");
1000  static_assert(supports_length_field<LenT>(static_cast<const ValueType*>(nullptr)),
1001  "VLINK_SOMEIP_LENGTH supports string, u16string, Bytes, vector, and map widths 1/2/4 or array "
1002  "widths 0/1/2/4.");
1003 
1004  return LengthField<LenT, T, MaxT>{value};
1005 }
1006 
1007 template <size_t LenT, size_t... InnerLenT, typename T>
1008 [[nodiscard]] inline auto array_length_field(T& value) noexcept {
1009  return ArrayLengthField<T, LenT, InnerLenT...>{value};
1010 }
1011 
1012 template <size_t LenT, Endian EncodingT, size_t MaxT = std::numeric_limits<size_t>::max(), typename T>
1013 [[nodiscard]] inline auto utf16_field(T& value) noexcept {
1015 }
1016 
1017 template <size_t SizeT, size_t LenT, Endian EncodingT = Endian::kBig, size_t MaxT = std::numeric_limits<size_t>::max(),
1018  typename T>
1019 [[nodiscard]] inline auto fixed_string_field(T& value) noexcept {
1021 }
1022 
1023 template <size_t LenT, size_t TypeT, typename T>
1024 [[nodiscard]] inline auto union_field(T& value) noexcept {
1025  return UnionField<LenT, TypeT, T>{value};
1026 }
1027 
1028 template <uint16_t DataIdT, size_t LenT = sizeof(uint32_t), bool DynamicT = true,
1029  size_t MaxT = std::numeric_limits<size_t>::max(), typename T>
1030 [[nodiscard]] inline auto tlv_field(T& value) noexcept {
1032 }
1033 
1034 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t SizeT, Endian EncodingT,
1035  size_t MaxT = std::numeric_limits<size_t>::max(), typename T>
1036 [[nodiscard]] inline auto tlv_fixed_string_field(T& value) noexcept {
1038 }
1039 
1040 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t... InnerLenT, typename T>
1041 [[nodiscard]] inline auto tlv_array_field(T& value) noexcept {
1042  return TlvArrayField<DataIdT, LenT, DynamicT, T, InnerLenT...>{value};
1043 }
1044 
1045 template <typename T>
1046 [[nodiscard]] constexpr bool is_tlv_field(const T*) noexcept {
1047  return false;
1048 }
1049 
1050 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t MaxT>
1051 [[nodiscard]] constexpr bool is_tlv_field(const TlvField<DataIdT, LenT, DynamicT, T, MaxT>*) noexcept {
1052  return true;
1053 }
1054 
1055 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t SizeT, Endian EncodingT, typename T, size_t MaxT>
1056 [[nodiscard]] constexpr bool is_tlv_field(
1058  return true;
1059 }
1060 
1061 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t... InnerLenT>
1062 [[nodiscard]] constexpr bool is_tlv_field(const TlvArrayField<DataIdT, LenT, DynamicT, T, InnerLenT...>*) noexcept {
1063  return true;
1064 }
1065 
1066 template <typename TupleT, size_t... IndexT>
1067 [[nodiscard]] constexpr size_t count_tlv_fields(std::index_sequence<IndexT...>) noexcept {
1068  return (static_cast<size_t>(is_tlv_field(
1069  static_cast<const std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>*>(nullptr))) +
1070  ... + 0U);
1071 }
1072 
1073 template <typename TupleT, size_t... IndexT>
1074 [[nodiscard]] constexpr bool tlv_data_ids_are_unique(std::index_sequence<IndexT...>) noexcept {
1075  constexpr size_t kFieldCount = sizeof...(IndexT);
1076  const uint16_t ids[kFieldCount] = {std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>::kDataId...};
1077 
1078  for (size_t left = 0U; left < kFieldCount; ++left) {
1079  for (size_t right = left + 1U; right < kFieldCount; ++right) {
1080  if (ids[left] == ids[right]) {
1081  return false;
1082  }
1083  }
1084  }
1085 
1086  return true;
1087 }
1088 
1089 template <size_t LenT, typename TupleT, size_t... IndexT>
1090 [[nodiscard]] constexpr bool tlv_length_widths_are_equal(std::index_sequence<IndexT...>) noexcept {
1091  return ((std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>::kLengthWidth == LenT) && ...);
1092 }
1093 
1094 template <typename TupleT, size_t... IndexT>
1095 [[nodiscard]] constexpr bool fields_are_variable(std::index_sequence<IndexT...>) noexcept {
1096  return (is_variable_size<std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>>() || ...);
1097 }
1098 
1099 template <typename T, typename AllocatorT>
1100 [[nodiscard]] constexpr bool is_variable_size(const std::vector<T, AllocatorT>*) noexcept {
1101  return true;
1102 }
1103 
1104 template <typename T, size_t SizeT>
1105 [[nodiscard]] constexpr bool is_variable_size(const std::array<T, SizeT>*) noexcept {
1106  return is_variable_size<T>();
1107 }
1108 
1109 template <size_t LenT, typename T, size_t MaxT>
1110 [[nodiscard]] constexpr bool is_variable_size(const LengthField<LenT, T, MaxT>*) noexcept {
1111  return is_variable_size<T>();
1112 }
1113 
1114 template <typename T, size_t LenT, size_t... InnerLenT>
1115 [[nodiscard]] constexpr bool is_variable_size(const ArrayLengthField<T, LenT, InnerLenT...>*) noexcept {
1116  return is_variable_size<T>();
1117 }
1118 
1119 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
1120 [[nodiscard]] constexpr bool is_variable_size(const std::map<KeyT, ValueT, CompareT, AllocatorT>*) noexcept {
1121  return true;
1122 }
1123 
1124 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
1125 [[nodiscard]] constexpr bool is_variable_size(
1126  const std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>*) noexcept {
1127  return true;
1128 }
1129 
1130 template <typename... AlternativeT>
1131 [[nodiscard]] constexpr bool is_variable_size(const std::variant<AlternativeT...>*) noexcept {
1132  return true;
1133 }
1134 
1135 template <size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1136 [[nodiscard]] constexpr bool is_variable_size(const Utf16Field<LenT, EncodingT, T, MaxT>*) noexcept {
1137  return true;
1138 }
1139 
1140 template <size_t SizeT, size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1141 [[nodiscard]] constexpr bool is_variable_size(const FixedStringField<SizeT, LenT, EncodingT, T, MaxT>*) noexcept {
1142  return false;
1143 }
1144 
1145 template <size_t LenT, size_t TypeT, typename T>
1146 [[nodiscard]] constexpr bool is_variable_size(const UnionField<LenT, TypeT, T>*) noexcept {
1147  return LenT != 0U;
1148 }
1149 
1150 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t MaxT>
1151 [[nodiscard]] constexpr bool is_variable_size(const TlvField<DataIdT, LenT, DynamicT, T, MaxT>*) noexcept {
1152  return true;
1153 }
1154 
1155 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t SizeT, Endian EncodingT, typename T, size_t MaxT>
1156 [[nodiscard]] constexpr bool is_variable_size(
1158  return true;
1159 }
1160 
1161 template <typename T>
1162 [[nodiscard]] constexpr bool is_variable_size(const T*) noexcept {
1163  if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, std::u16string> || std::is_same_v<T, Bytes>) {
1164  return true;
1165  } else if constexpr (VLINK_HAS_MEMBER(T, is_vlink_someip_type())) {
1166  using FieldsType = decltype(std::declval<T&>().get_vlink_someip_fields());
1167 
1168  return fields_are_variable<FieldsType>(std::make_index_sequence<std::tuple_size_v<FieldsType>>{});
1169  }
1170 
1171  return false;
1172 }
1173 
1174 template <typename T>
1175 [[nodiscard]] constexpr bool is_variable_size() noexcept {
1176  using ValueType = std::remove_cv_t<std::remove_reference_t<T>>;
1177 
1178  return is_variable_size(static_cast<const ValueType*>(nullptr));
1179 }
1180 
1181 template <typename T>
1182 inline bool write_value(Writer& writer, const T& value) noexcept {
1183  using ValueType = std::remove_cv_t<T>;
1184 
1185  if constexpr (std::is_enum_v<ValueType>) {
1186  using UnderlyingType = std::underlying_type_t<ValueType>;
1187 
1188  static_assert(std::is_unsigned_v<UnderlyingType> && !std::is_same_v<UnderlyingType, bool>,
1189  "SOME/IP enums must use uint8_t, uint16_t, uint32_t, or uint64_t storage.");
1190  return detail::write_value(writer, static_cast<UnderlyingType>(value));
1191  } else if constexpr (std::is_arithmetic_v<ValueType> || std::is_same_v<ValueType, std::string> ||
1192  std::is_same_v<ValueType, Bytes>) {
1193  return detail::write_value(writer, value);
1194  } else if constexpr (std::is_same_v<ValueType, std::u16string>) {
1195  return detail::write_value(writer, value, sizeof(uint32_t), Endian::kBig);
1196  } else if constexpr (VLINK_HAS_MEMBER(ValueType, is_vlink_someip_type())) {
1197  static constexpr size_t kStructLength = get_struct_length<ValueType>();
1198 
1199  if constexpr (VLINK_HAS_MEMBER(ValueType, check_available())) {
1200  static_assert(noexcept(value.check_available()), "SOME/IP check_available() must be noexcept.");
1201  if VUNLIKELY (!value.check_available()) {
1203 
1204  return false;
1205  }
1206  }
1207 
1208  size_t length_position = 0U;
1209  size_t data_position = 0U;
1210 
1211  if constexpr (kStructLength > 0U) {
1212  if VUNLIKELY (!writer.begin_length_delimited(length_position, data_position, kStructLength)) {
1213  return false;
1214  }
1215  }
1216 
1217  if VUNLIKELY (!write_value_body(writer, value)) {
1218  return false;
1219  }
1220 
1221  return kStructLength == 0U || writer.end_length_delimited(length_position, data_position, kStructLength);
1222  } else {
1223  static_assert(Traits::ExpectFalse<T>(), "Unsupported SOME/IP field type.");
1224 
1225  return false;
1226  }
1227 }
1228 
1229 template <size_t MaxT, typename T, typename AllocatorT, size_t... InnerLenT>
1230 inline bool write_value(Writer& writer, const std::vector<T, AllocatorT>& value, size_t len,
1231  std::index_sequence<InnerLenT...>) noexcept {
1232  if VUNLIKELY (value.size() > MaxT) {
1233  return false;
1234  }
1235 
1236  size_t length_position = 0U;
1237  size_t data_position = 0U;
1238 
1239  return writer.begin_length_delimited(length_position, data_position, len) &&
1240  write_value_body(writer, value, std::index_sequence<InnerLenT...>{}) &&
1241  writer.end_length_delimited(length_position, data_position, len);
1242 }
1243 
1244 template <typename T, size_t SizeT, size_t... InnerLenT>
1245 inline bool write_value(Writer& writer, const std::array<T, SizeT>& value, size_t len,
1246  std::index_sequence<InnerLenT...>) noexcept {
1247  size_t length_position = 0U;
1248  size_t data_position = 0U;
1249 
1250  if VUNLIKELY (len > 0U && !writer.begin_length_delimited(length_position, data_position, len)) {
1251  return false;
1252  }
1253 
1254  if VUNLIKELY (!write_value_body(writer, value, std::index_sequence<InnerLenT...>{})) {
1255  return false;
1256  }
1257 
1258  return len == 0U || writer.end_length_delimited(length_position, data_position, len);
1259 }
1260 
1261 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
1262 inline bool write_value(Writer& writer, const std::map<KeyT, ValueT, CompareT, AllocatorT>& value,
1263  size_t len) noexcept {
1264  size_t length_position = 0U;
1265  size_t data_position = 0U;
1266 
1267  return writer.begin_length_delimited(length_position, data_position, len) && write_map_entries(writer, value) &&
1268  writer.end_length_delimited(length_position, data_position, len);
1269 }
1270 
1271 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
1272 inline bool write_value(Writer& writer, const std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>& value,
1273  size_t len) noexcept {
1274  size_t length_position = 0U;
1275  size_t data_position = 0U;
1276 
1277  return writer.begin_length_delimited(length_position, data_position, len) && write_map_entries(writer, value) &&
1278  writer.end_length_delimited(length_position, data_position, len);
1279 }
1280 
1281 template <typename... AlternativeT>
1282 inline bool write_value(Writer& writer, const std::variant<AlternativeT...>& value, size_t len,
1283  size_t type_width) noexcept {
1284  static_assert(validate_union_alternatives<AlternativeT...>(), "SOME/IP union alternatives are invalid.");
1285 
1286  if VUNLIKELY (value.valueless_by_exception()) {
1287  return false;
1288  }
1289 
1290  static constexpr bool kHasNull = has_null_union_alternative<AlternativeT...>();
1291  const uint64_t selector = value.index() + (kHasNull ? 0U : 1U);
1292 
1293  size_t length_position = 0U;
1294  size_t content_position = 0U;
1295 
1296  if (len == 0U) {
1297  return writer.append_unsigned(selector, type_width, Endian::kBig) &&
1298  write_union_alternative(writer, value, std::make_index_sequence<sizeof...(AlternativeT)>{});
1299  }
1300 
1301  if VUNLIKELY (!detail::write_union_frame(writer, selector, len, type_width, length_position, content_position) ||
1302  !write_union_alternative(writer, value, std::make_index_sequence<sizeof...(AlternativeT)>{})) {
1303  return false;
1304  }
1305 
1306  if constexpr (kHasNull) {
1307  if (value.index() == 0U) {
1308  return writer.end_length_delimited(length_position, content_position, len);
1309  }
1310  }
1311 
1312  return writer.align() && writer.end_length_delimited(length_position, content_position, len);
1313 }
1314 
1315 template <typename T>
1316 inline bool read_value(Reader& reader, T& value, size_t end) noexcept {
1317  using ValueType = std::remove_cv_t<T>;
1318 
1319  if constexpr (std::is_enum_v<ValueType>) {
1320  using UnderlyingType = std::underlying_type_t<ValueType>;
1321 
1322  static_assert(std::is_unsigned_v<UnderlyingType> && !std::is_same_v<UnderlyingType, bool>,
1323  "SOME/IP enums must use uint8_t, uint16_t, uint32_t, or uint64_t storage.");
1324  UnderlyingType raw = 0;
1325 
1326  if VUNLIKELY (!detail::read_value(reader, raw, end)) {
1327  return false;
1328  }
1329 
1330  value = static_cast<T>(raw);
1331 
1332  return true;
1333  } else if constexpr (std::is_arithmetic_v<ValueType> || std::is_same_v<ValueType, std::string> ||
1334  std::is_same_v<ValueType, Bytes>) {
1335  return detail::read_value(reader, value, end);
1336  } else if constexpr (std::is_same_v<ValueType, std::u16string>) {
1337  return detail::read_value(reader, value, end, sizeof(uint32_t), Endian::kBig);
1338  } else if constexpr (VLINK_HAS_MEMBER(ValueType, is_vlink_someip_type())) {
1339  static constexpr size_t kStructLength = get_struct_length<ValueType>();
1340 
1341  size_t struct_end = end;
1342 
1343  if constexpr (kStructLength > 0U) {
1344  if VUNLIKELY (!reader.begin_length_delimited(end, struct_end, kStructLength)) {
1345  return false;
1346  }
1347  }
1348 
1349  if VUNLIKELY (!read_value_body(reader, value, struct_end)) {
1350  return false;
1351  }
1352 
1353  return kStructLength == 0U || reader.skip(struct_end - reader.position(), struct_end);
1354  } else {
1355  static_assert(Traits::ExpectFalse<T>(), "Unsupported SOME/IP field type.");
1356 
1357  return false;
1358  }
1359 }
1360 
1361 template <size_t MaxT, typename T, typename AllocatorT, size_t... InnerLenT>
1362 inline bool read_value(Reader& reader, std::vector<T, AllocatorT>& value, size_t end, size_t len,
1363  std::index_sequence<InnerLenT...>) noexcept {
1364  size_t array_end = 0U;
1365 
1366  return reader.begin_length_delimited(end, array_end, len) &&
1367  read_value_body<MaxT>(reader, value, array_end, std::index_sequence<InnerLenT...>{});
1368 }
1369 
1370 template <typename T, size_t SizeT, size_t... InnerLenT>
1371 inline bool read_value(Reader& reader, std::array<T, SizeT>& value, size_t end, size_t len,
1372  std::index_sequence<InnerLenT...>) noexcept {
1373  size_t array_end = end;
1374 
1375  if VUNLIKELY (len > 0U && !reader.begin_length_delimited(end, array_end, len)) {
1376  return false;
1377  }
1378 
1379  if VUNLIKELY (!read_value_body(reader, value, array_end, std::index_sequence<InnerLenT...>{})) {
1380  return false;
1381  }
1382 
1383  return len == 0U || reader.skip(array_end - reader.position(), array_end);
1384 }
1385 
1386 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
1387 inline bool read_value(Reader& reader, std::map<KeyT, ValueT, CompareT, AllocatorT>& value, size_t end,
1388  size_t len) noexcept {
1389  size_t map_end = 0U;
1390 
1391  return reader.begin_length_delimited(end, map_end, len) && read_map_entries(reader, value, map_end);
1392 }
1393 
1394 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
1395 inline bool read_value(Reader& reader, std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>& value, size_t end,
1396  size_t len) noexcept {
1397  size_t map_end = 0U;
1398 
1399  return reader.begin_length_delimited(end, map_end, len) && read_map_entries(reader, value, map_end);
1400 }
1401 
1402 template <typename... AlternativeT>
1403 inline bool read_value(Reader& reader, std::variant<AlternativeT...>& value, size_t end, size_t len,
1404  size_t type_width) noexcept {
1405  static_assert(validate_union_alternatives<AlternativeT...>(), "SOME/IP union alternatives are invalid.");
1406 
1407  uint64_t selector = 0U;
1408  size_t data_end = 0U;
1409 
1410  if (len == 0U) {
1411  return reader.read_unsigned(selector, type_width, Endian::kBig, end) &&
1412  read_union_alternative(reader, value, selector, end, std::make_index_sequence<sizeof...(AlternativeT)>{});
1413  }
1414 
1415  if VUNLIKELY (!detail::read_union_frame(reader, len, type_width, end, selector, data_end) ||
1416  (selector == 0U && reader.position() != data_end) ||
1417  !read_union_alternative(reader, value, selector, data_end,
1418  std::make_index_sequence<sizeof...(AlternativeT)>{})) {
1419  return false;
1420  }
1421 
1422  return reader.skip(data_end - reader.position(), data_end);
1423 }
1424 
1425 template <typename T>
1426 inline size_t get_serialized_size(const T& src) noexcept {
1427  Writer writer(nullptr, std::numeric_limits<size_t>::max(), get_alignment<T>(), get_endian<T>());
1428 
1429  return write_value(writer, src) ? writer.position() : 0U;
1430 }
1431 
1432 template <typename T>
1433 inline bool serialize(const T& src, Bytes& des) noexcept {
1434  return serialize(src, des, 0U);
1435 }
1436 
1437 template <typename T>
1438 inline bool serialize(const T& src, Bytes& des, uint8_t offset) noexcept {
1439  if (des.is_loaned()) {
1440  if VUNLIKELY (des.offset() != offset) {
1441  return false;
1442  }
1443 
1444  Writer writer(des.data(), des.size(), get_alignment<T>(), get_endian<T>());
1445 
1446  return write_value(writer, src) && writer.position() == des.size();
1447  }
1448 
1449  Writer size_writer(nullptr, std::numeric_limits<size_t>::max(), get_alignment<T>(), get_endian<T>());
1450 
1451  if VUNLIKELY (!write_value(size_writer, src) || !detail::prepare_destination(des, size_writer.position(), offset)) {
1452  return false;
1453  }
1454 
1455  Writer writer(des.data(), des.size(), get_alignment<T>(), get_endian<T>());
1456 
1457  return write_value(writer, src) && writer.position() == des.size();
1458 }
1459 
1460 template <typename T>
1461 inline bool deserialize(const Bytes& src, T& des) noexcept {
1462  if VUNLIKELY (src.size() > kMaxPayloadSize) {
1463  return false;
1464  }
1465 
1466  Reader reader(src.data(), src.size(), get_alignment<T>(), get_endian<T>());
1467 
1468  return read_value(reader, des, reader.size());
1469 }
1470 
1471 template <size_t LenT, typename T, size_t MaxT>
1472 inline bool read_value(Reader& reader, LengthField<LenT, T, MaxT>& field, size_t end) noexcept {
1473  using ValueType = std::remove_cv_t<T>;
1474 
1475  if constexpr (std::is_same_v<ValueType, std::string> || std::is_same_v<ValueType, Bytes>) {
1476  return detail::read_value(reader, field.value, end, LenT, MaxT);
1477  } else if constexpr (std::is_same_v<ValueType, std::u16string>) {
1478  return detail::read_value(reader, field.value, end, LenT, Endian::kBig, MaxT);
1479  } else if constexpr (is_vector(static_cast<const ValueType*>(nullptr))) {
1480  return read_value<MaxT>(reader, field.value, end, LenT, std::index_sequence<>{});
1481  } else if constexpr (is_map(static_cast<const ValueType*>(nullptr))) {
1482  return read_value(reader, field.value, end, LenT);
1483  } else {
1484  return read_value(reader, field.value, end, LenT, std::index_sequence<>{});
1485  }
1486 }
1487 
1488 template <typename T, size_t LenT, size_t... InnerLenT>
1489 inline bool read_value(Reader& reader, ArrayLengthField<T, LenT, InnerLenT...>& field, size_t end) noexcept {
1490  return read_value(reader, field.value, end, LenT, std::index_sequence<InnerLenT...>{});
1491 }
1492 
1493 template <size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1494 inline bool read_value(Reader& reader, Utf16Field<LenT, EncodingT, T, MaxT>& field, size_t end) noexcept {
1495  return detail::read_value(reader, field.value, end, LenT, EncodingT, MaxT);
1496 }
1497 
1498 template <size_t SizeT, size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1499 inline bool read_value(Reader& reader, FixedStringField<SizeT, LenT, EncodingT, T, MaxT>& field, size_t end) noexcept {
1500  if constexpr (std::is_same_v<std::remove_cv_t<T>, std::string>) {
1501  return detail::read_fixed_value(reader, field.value, end, SizeT, LenT, MaxT);
1502  } else {
1503  return detail::read_fixed_value(reader, field.value, end, SizeT, LenT, EncodingT, MaxT);
1504  }
1505 }
1506 
1507 template <size_t SizeT, size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1509  size_t end) noexcept {
1510  if VUNLIKELY (reader.position() > end || end - reader.position() > SizeT) {
1511  return false;
1512  }
1513 
1514  const size_t size = end - reader.position();
1515 
1516  if constexpr (std::is_same_v<std::remove_cv_t<T>, std::string>) {
1517  return detail::read_fixed_value(reader, field.value, end, size, 0U, MaxT);
1518  } else {
1519  return detail::read_fixed_value(reader, field.value, end, size, 0U, EncodingT, MaxT);
1520  }
1521 }
1522 
1523 template <size_t LenT, size_t TypeT, typename T>
1524 inline bool read_value(Reader& reader, UnionField<LenT, TypeT, T>& field, size_t end) noexcept {
1525  return read_value(reader, field.value, end, LenT, TypeT);
1526 }
1527 
1528 template <typename TupleT, size_t... IndexT>
1529 inline bool read_fields(Reader& reader, TupleT& fields, size_t end, std::index_sequence<IndexT...>) noexcept {
1530  static constexpr size_t kFieldCount = std::tuple_size_v<TupleT>;
1531 
1532  return ([&reader, &fields, end]() {
1533  if VUNLIKELY (!read_value(reader, std::get<IndexT>(fields), end)) {
1534  return false;
1535  }
1536 
1537  using FieldType = std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>;
1538 
1539  return IndexT + 1U == kFieldCount || !is_variable_size<FieldType>() || reader.align(end);
1540  }() && ...);
1541 }
1542 
1543 template <size_t MaxT = std::numeric_limits<size_t>::max(), typename T, typename AllocatorT, size_t... InnerLenT>
1544 inline bool read_value_body(Reader& reader, std::vector<T, AllocatorT>& value, size_t end,
1545  std::index_sequence<InnerLenT...> = {}) noexcept {
1546  if constexpr (std::is_arithmetic_v<T> || std::is_enum_v<T>) {
1547  static constexpr size_t kElementSize = sizeof(T);
1548 
1549  const size_t byte_length = end - reader.position();
1550  const size_t element_count = byte_length / kElementSize;
1551 
1552  if VUNLIKELY (byte_length % kElementSize != 0U && element_count < MaxT) {
1553  return false;
1554  }
1555 
1556  value.reserve(element_count < MaxT ? element_count : MaxT);
1557  }
1558 
1559  size_t index = 0U;
1560 
1561  while (reader.position() < end && index < MaxT) {
1562  const size_t element_position = reader.position();
1563 
1564  if constexpr (sizeof...(InnerLenT) > 0U) {
1565  if (index == value.size()) {
1566  value.emplace_back();
1567  }
1568 
1569  ArrayLengthField<T, InnerLenT...> field{value[index]};
1570 
1571  if VUNLIKELY (!read_value(reader, field, end) || reader.position() == element_position) {
1572  return false;
1573  }
1574  } else if constexpr (std::is_same_v<T, bool>) {
1575  bool element = false;
1576 
1577  if VUNLIKELY (!read_value(reader, element, end) || reader.position() == element_position) {
1578  return false;
1579  }
1580 
1581  if (index < value.size()) {
1582  value[index] = element;
1583  } else {
1584  value.emplace_back(element);
1585  }
1586  } else {
1587  if (index == value.size()) {
1588  value.emplace_back();
1589  }
1590 
1591  if VUNLIKELY (!read_value(reader, value[index], end) || reader.position() == element_position) {
1592  return false;
1593  }
1594  }
1595 
1596  ++index;
1597 
1598  if constexpr (is_variable_size<T>()) {
1599  if VUNLIKELY (reader.position() < end && !reader.align(end)) {
1600  return false;
1601  }
1602  }
1603  }
1604 
1605  value.resize(index);
1606 
1607  return reader.skip(end - reader.position(), end);
1608 }
1609 
1610 template <typename T, size_t SizeT, size_t... InnerLenT>
1611 inline bool read_value_body(Reader& reader, std::array<T, SizeT>& value, size_t end,
1612  std::index_sequence<InnerLenT...> = {}) noexcept {
1613  for (size_t index = 0U; index < SizeT; ++index) {
1614  if constexpr (sizeof...(InnerLenT) > 0U) {
1615  ArrayLengthField<T, InnerLenT...> field{value[index]};
1616 
1617  if VUNLIKELY (!read_value(reader, field, end)) {
1618  return false;
1619  }
1620  } else {
1621  if VUNLIKELY (!read_value(reader, value[index], end)) {
1622  return false;
1623  }
1624  }
1625 
1626  if constexpr (is_variable_size<T>()) {
1627  if VUNLIKELY (index + 1U < SizeT && !reader.align(end)) {
1628  return false;
1629  }
1630  }
1631  }
1632 
1633  return true;
1634 }
1635 
1636 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
1637 inline bool read_value_body(Reader& reader, std::map<KeyT, ValueT, CompareT, AllocatorT>& value, size_t end) noexcept {
1638  return read_map_entries(reader, value, end);
1639 }
1640 
1641 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
1642 inline bool read_value_body(Reader& reader, std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>& value,
1643  size_t end) noexcept {
1644  return read_map_entries(reader, value, end);
1645 }
1646 
1647 template <typename T, size_t LenT, size_t... InnerLenT>
1648 inline bool read_value_body(Reader& reader, ArrayLengthField<T, LenT, InnerLenT...>& field, size_t end) noexcept {
1649  return read_value_body(reader, field.value, end, std::index_sequence<InnerLenT...>{});
1650 }
1651 
1652 template <typename... AlternativeT>
1653 inline bool read_value_body(Reader& reader, std::variant<AlternativeT...>& value, size_t end) noexcept {
1654  static_assert(validate_union_alternatives<AlternativeT...>(), "SOME/IP union alternatives are invalid.");
1655 
1656  uint64_t selector = 0U;
1657 
1658  if VUNLIKELY (!reader.read_unsigned(selector, sizeof(uint32_t), Endian::kBig, end)) {
1659  return false;
1660  }
1661 
1662  return (selector != 0U || reader.position() == end) &&
1663  read_union_alternative(reader, value, selector, end, std::make_index_sequence<sizeof...(AlternativeT)>{});
1664 }
1665 
1666 template <typename MapT>
1667 inline bool read_map_entries(Reader& reader, MapT& value, size_t end) noexcept {
1668  value.clear();
1669 
1670  while (reader.position() < end) {
1671  const size_t entry_position = reader.position();
1672 
1673  typename MapT::key_type key{};
1674 
1675  if VUNLIKELY (!read_value(reader, key, end)) {
1676  return false;
1677  }
1678 
1679  typename MapT::mapped_type mapped{};
1680 
1681  if VUNLIKELY (!read_value(reader, mapped, end) || reader.position() == entry_position) {
1682  return false;
1683  }
1684 
1685  if VUNLIKELY (!value.emplace(std::move(key), std::move(mapped)).second) {
1686  return false;
1687  }
1688  }
1689 
1690  return true;
1691 }
1692 
1693 template <size_t IndexT, typename... AlternativeT>
1694 inline bool read_union_element(Reader& reader, std::variant<AlternativeT...>& value, size_t data_end) noexcept {
1695  if constexpr (IndexT == 0U && has_null_union_alternative<AlternativeT...>()) {
1696  value.template emplace<IndexT>();
1697  return true;
1698  } else {
1699  return read_value(reader, value.template emplace<IndexT>(), data_end);
1700  }
1701 }
1702 
1703 template <typename... AlternativeT, size_t... IndexT>
1704 inline bool read_union_alternative(Reader& reader, std::variant<AlternativeT...>& value, uint64_t selector,
1705  size_t data_end, std::index_sequence<IndexT...>) noexcept {
1706  static constexpr bool kHasNull = has_null_union_alternative<AlternativeT...>();
1707 
1708  return ((selector == IndexT + (kHasNull ? 0U : 1U) && read_union_element<IndexT>(reader, value, data_end)) || ...);
1709 }
1710 
1711 template <size_t LenT, size_t MaxT = std::numeric_limits<size_t>::max(), typename T>
1712 inline bool read_tlv_value(Reader& reader, T& value, uint8_t wire_type, size_t end) noexcept {
1713  static constexpr uint8_t kWireType = get_fixed_wire_type<T>();
1714 
1715  if constexpr (kWireType != kComplexWireType) {
1716  if VUNLIKELY (wire_type != kWireType) {
1717  return false;
1718  }
1719 
1720  return read_value(reader, value, end);
1721  } else {
1722  size_t body_end = 0U;
1723 
1724  if VUNLIKELY (!detail::begin_tlv_body(reader, wire_type, LenT, end, body_end)) {
1725  return false;
1726  }
1727 
1728  bool body_ok = false;
1729 
1730  if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, Bytes>) {
1731  body_ok = detail::read_value_body(reader, value, body_end, MaxT);
1732  } else if constexpr (std::is_same_v<T, std::u16string>) {
1733  body_ok = detail::read_value_body(reader, value, body_end, Endian::kBig, MaxT);
1734  } else if constexpr (is_vector(static_cast<const T*>(nullptr))) {
1735  body_ok = read_value_body<MaxT>(reader, value, body_end);
1736  } else {
1737  body_ok = read_value_body(reader, value, body_end);
1738  }
1739 
1740  return body_ok && reader.skip(body_end - reader.position(), body_end);
1741  }
1742 }
1743 
1744 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t MaxT>
1745 inline bool read_tlv_field(Reader& reader, TlvField<DataIdT, LenT, DynamicT, T, MaxT>& field, uint8_t wire_type,
1746  size_t end) noexcept {
1747  using ValueType = std::remove_cv_t<std::remove_reference_t<T>>;
1748 
1749  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
1750  if (!field.value.has_value()) {
1751  field.value.emplace();
1752  }
1753 
1754  return read_tlv_value<LenT, MaxT>(reader, *field.value, wire_type, end);
1755  } else {
1756  return read_tlv_value<LenT, MaxT>(reader, field.value, wire_type, end);
1757  }
1758 }
1759 
1760 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t SizeT, Endian EncodingT, typename T, size_t MaxT>
1761 inline bool read_tlv_field(Reader& reader,
1763  uint8_t wire_type, size_t end) noexcept {
1764  using ValueType = std::remove_cv_t<T>;
1765  size_t body_end = 0U;
1766 
1767  if VUNLIKELY (!detail::begin_tlv_body(reader, wire_type, LenT, end, body_end) ||
1768  body_end - reader.position() > SizeT) {
1769  return false;
1770  }
1771 
1772  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
1773  if (!field.value.has_value()) {
1774  field.value.emplace();
1775  }
1776 
1777  auto fixed = fixed_string_field<SizeT, 0U, EncodingT, MaxT>(*field.value);
1778  return read_value_body(reader, fixed, body_end);
1779  } else {
1780  auto fixed = fixed_string_field<SizeT, 0U, EncodingT, MaxT>(field.value);
1781  return read_value_body(reader, fixed, body_end);
1782  }
1783 }
1784 
1785 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t... InnerLenT>
1787  uint8_t wire_type, size_t end) noexcept {
1788  using ValueType = std::remove_cv_t<T>;
1789 
1790  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
1791  if (!field.value.has_value()) {
1792  field.value.emplace();
1793  }
1794 
1795  auto array = array_length_field<LenT, InnerLenT...>(*field.value);
1796  return read_tlv_value<LenT>(reader, array, wire_type, end);
1797  } else {
1798  auto array = array_length_field<LenT, InnerLenT...>(field.value);
1799  return read_tlv_value<LenT>(reader, array, wire_type, end);
1800  }
1801 }
1802 
1803 template <typename T>
1804 inline bool finish_missing_tlv_value(T& value) noexcept {
1805  using ValueType = std::remove_cv_t<std::remove_reference_t<T>>;
1806 
1807  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
1808  value.reset();
1809 
1810  return true;
1811  } else {
1812  return false;
1813  }
1814 }
1815 
1816 template <size_t LenT, typename TupleT, size_t... IndexT>
1817 inline bool read_tlv_fields(Reader& reader, TupleT& fields, size_t end, std::index_sequence<IndexT...>) noexcept {
1818  static constexpr size_t kFieldCount = sizeof...(IndexT);
1819 
1820  std::array<bool, kFieldCount> seen{};
1821 
1822  while (reader.position() < end) {
1823  uint8_t wire_type = 0U;
1824  uint16_t data_id = 0U;
1825 
1826  if VUNLIKELY (!detail::read_tag(reader, wire_type, data_id, end)) {
1827  return false;
1828  }
1829 
1830  bool field_ok = true;
1831 
1832  const bool matched = ([&]() {
1833  using FieldType = std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>;
1834 
1835  if (FieldType::kDataId != data_id) {
1836  return false;
1837  }
1838  if VUNLIKELY (seen[IndexT]) {
1839  field_ok = false;
1840 
1841  return true;
1842  }
1843 
1844  seen[IndexT] = true;
1845  field_ok = read_tlv_field(reader, std::get<IndexT>(fields), wire_type, end);
1846 
1847  return true;
1848  }() || ...);
1849 
1850  if (matched) {
1851  if VUNLIKELY (!field_ok) {
1852  return false;
1853  }
1854  } else if VUNLIKELY (!detail::skip_tlv_value(reader, wire_type, LenT, end)) {
1855  return false;
1856  }
1857  }
1858 
1859  bool required_ok = true;
1860 
1861  ((seen[IndexT] || (required_ok = finish_missing_tlv_value(std::get<IndexT>(fields).value) && required_ok)), ...);
1862 
1863  return required_ok;
1864 }
1865 
1866 template <typename T>
1867 inline bool read_value_body(Reader& reader, T& value, size_t end) noexcept {
1868  if constexpr (VLINK_HAS_MEMBER(T, is_vlink_someip_type())) {
1869  using FieldsType = decltype(value.get_vlink_someip_fields());
1870 
1871  static_assert(std::tuple_size_v<FieldsType> > 0U, "SOME/IP structures must declare at least one field.");
1872 
1873  static constexpr size_t kFieldCount = std::tuple_size_v<FieldsType>;
1874  static constexpr size_t kTlvCount = count_tlv_fields<FieldsType>(std::make_index_sequence<kFieldCount>{});
1875 
1876  static_assert(kTlvCount == 0U || kTlvCount == kFieldCount,
1877  "SOME/IP structures must tag either every field or no field with VLINK_SOMEIP_TLV.");
1878  static_assert(kTlvCount == 0U || get_struct_length<T>() > 0U,
1879  "SOME/IP TLV structures must declare a non-zero VLINK_SOMEIP_STRUCT_LENGTH.");
1880  static_assert(kTlvCount == 0U || get_alignment<T>() == 1U, "SOME/IP TLV structures require 1-byte alignment.");
1881 
1882  auto fields = value.get_vlink_someip_fields();
1883 
1884  if constexpr (kTlvCount > 0U) {
1885  static_assert(tlv_data_ids_are_unique<FieldsType>(std::make_index_sequence<kFieldCount>{}),
1886  "SOME/IP TLV data IDs must be unique within a structure.");
1887  static_assert(
1888  tlv_length_widths_are_equal<get_struct_length<T>(), FieldsType>(std::make_index_sequence<kFieldCount>{}),
1889  "SOME/IP TLV fields must use the structure length width.");
1890 
1891  return read_tlv_fields<get_struct_length<T>()>(reader, fields, end, std::make_index_sequence<kFieldCount>{});
1892  } else {
1893  return read_fields(reader, fields, end, std::make_index_sequence<kFieldCount>{});
1894  }
1895  } else {
1896  static_assert(Traits::ExpectFalse<T>(), "Unsupported SOME/IP TLV member type.");
1897 
1898  return false;
1899  }
1900 }
1901 
1902 template <size_t LenT, typename T, size_t MaxT>
1903 inline bool write_value(Writer& writer, const LengthField<LenT, T, MaxT>& field) noexcept {
1904  using ValueType = std::remove_cv_t<T>;
1905 
1906  if constexpr (std::is_same_v<ValueType, std::string> || std::is_same_v<ValueType, Bytes>) {
1907  return detail::write_value(writer, field.value, LenT, MaxT);
1908  } else if constexpr (std::is_same_v<ValueType, std::u16string>) {
1909  return detail::write_value(writer, field.value, LenT, Endian::kBig, MaxT);
1910  } else if constexpr (is_vector(static_cast<const ValueType*>(nullptr))) {
1911  return write_value<MaxT>(writer, field.value, LenT, std::index_sequence<>{});
1912  } else if constexpr (is_map(static_cast<const ValueType*>(nullptr))) {
1913  return write_value(writer, field.value, LenT);
1914  } else {
1915  return write_value(writer, field.value, LenT, std::index_sequence<>{});
1916  }
1917 }
1918 
1919 template <typename T, size_t LenT, size_t... InnerLenT>
1920 inline bool write_value(Writer& writer, const ArrayLengthField<T, LenT, InnerLenT...>& field) noexcept {
1921  return write_value(writer, field.value, LenT, std::index_sequence<InnerLenT...>{});
1922 }
1923 
1924 template <size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1925 inline bool write_value(Writer& writer, const Utf16Field<LenT, EncodingT, T, MaxT>& field) noexcept {
1926  return detail::write_value(writer, field.value, LenT, EncodingT, MaxT);
1927 }
1928 
1929 template <size_t SizeT, size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1930 inline bool write_value(Writer& writer, const FixedStringField<SizeT, LenT, EncodingT, T, MaxT>& field) noexcept {
1931  if constexpr (std::is_same_v<std::remove_cv_t<T>, std::string>) {
1932  return detail::write_fixed_value(writer, field.value, SizeT, LenT, MaxT);
1933  } else {
1934  return detail::write_fixed_value(writer, field.value, SizeT, LenT, EncodingT, MaxT);
1935  }
1936 }
1937 
1938 template <size_t SizeT, size_t LenT, Endian EncodingT, typename T, size_t MaxT>
1940  if constexpr (std::is_same_v<std::remove_cv_t<T>, std::string>) {
1941  return detail::write_fixed_value(writer, field.value, SizeT, 0U, MaxT);
1942  } else {
1943  return detail::write_fixed_value(writer, field.value, SizeT, 0U, EncodingT, MaxT);
1944  }
1945 }
1946 
1947 template <size_t LenT, size_t TypeT, typename T>
1948 inline bool write_value(Writer& writer, const UnionField<LenT, TypeT, T>& field) noexcept {
1949  return write_value(writer, field.value, LenT, TypeT);
1950 }
1951 
1952 template <typename TupleT, size_t... IndexT>
1953 inline bool write_fields(Writer& writer, const TupleT& fields, std::index_sequence<IndexT...>) noexcept {
1954  static constexpr size_t kFieldCount = std::tuple_size_v<TupleT>;
1955 
1956  return ([&writer, &fields]() noexcept {
1957  if VUNLIKELY (!write_value(writer, std::get<IndexT>(fields))) {
1958  return false;
1959  }
1960 
1961  using FieldType = std::remove_reference_t<std::tuple_element_t<IndexT, TupleT>>;
1962 
1963  return IndexT + 1U == kFieldCount || !is_variable_size<FieldType>() || writer.align();
1964  }() && ...);
1965 }
1966 
1967 template <typename T, typename AllocatorT, size_t... InnerLenT>
1968 inline bool write_value_body(Writer& writer, const std::vector<T, AllocatorT>& value,
1969  std::index_sequence<InnerLenT...> = {}) noexcept {
1970  for (size_t index = 0U; index < value.size(); ++index) {
1971  const size_t element_position = writer.position();
1972 
1973  if constexpr (sizeof...(InnerLenT) > 0U) {
1974  const ArrayLengthField<const T, InnerLenT...> field{value[index]};
1975 
1976  if VUNLIKELY (!write_value(writer, field)) {
1977  return false;
1978  }
1979  } else if constexpr (std::is_same_v<T, bool>) {
1980  if VUNLIKELY (!write_value(writer, static_cast<bool>(value[index]))) {
1981  return false;
1982  }
1983  } else if VUNLIKELY (!write_value(writer, value[index])) {
1984  return false;
1985  }
1986 
1987  if VUNLIKELY (writer.position() == element_position) {
1988  return false;
1989  }
1990 
1991  if constexpr (is_variable_size<T>()) {
1992  if VUNLIKELY (index + 1U < value.size() && !writer.align()) {
1993  return false;
1994  }
1995  }
1996  }
1997 
1998  return true;
1999 }
2000 
2001 template <typename T, size_t SizeT, size_t... InnerLenT>
2002 inline bool write_value_body(Writer& writer, const std::array<T, SizeT>& value,
2003  std::index_sequence<InnerLenT...> = {}) noexcept {
2004  for (size_t index = 0U; index < SizeT; ++index) {
2005  if constexpr (sizeof...(InnerLenT) > 0U) {
2006  const ArrayLengthField<const T, InnerLenT...> field{value[index]};
2007 
2008  if VUNLIKELY (!write_value(writer, field)) {
2009  return false;
2010  }
2011  } else {
2012  if VUNLIKELY (!write_value(writer, value[index])) {
2013  return false;
2014  }
2015  }
2016 
2017  if constexpr (is_variable_size<T>()) {
2018  if VUNLIKELY (index + 1U < SizeT && !writer.align()) {
2019  return false;
2020  }
2021  }
2022  }
2023 
2024  return true;
2025 }
2026 
2027 template <typename KeyT, typename ValueT, typename CompareT, typename AllocatorT>
2028 inline bool write_value_body(Writer& writer, const std::map<KeyT, ValueT, CompareT, AllocatorT>& value) noexcept {
2029  return write_map_entries(writer, value);
2030 }
2031 
2032 template <typename KeyT, typename ValueT, typename HashT, typename EqualT, typename AllocatorT>
2033 inline bool write_value_body(Writer& writer,
2034  const std::unordered_map<KeyT, ValueT, HashT, EqualT, AllocatorT>& value) noexcept {
2035  return write_map_entries(writer, value);
2036 }
2037 
2038 template <typename T, size_t LenT, size_t... InnerLenT>
2039 inline bool write_value_body(Writer& writer, const ArrayLengthField<T, LenT, InnerLenT...>& field) noexcept {
2040  return write_value_body(writer, field.value, std::index_sequence<InnerLenT...>{});
2041 }
2042 
2043 template <typename... AlternativeT>
2044 inline bool write_value_body(Writer& writer, const std::variant<AlternativeT...>& value) noexcept {
2045  static_assert(validate_union_alternatives<AlternativeT...>(), "SOME/IP union alternatives are invalid.");
2046 
2047  if VUNLIKELY (value.valueless_by_exception()) {
2048  return false;
2049  }
2050 
2051  static constexpr bool kHasNull = has_null_union_alternative<AlternativeT...>();
2052  const uint64_t selector = value.index() + (kHasNull ? 0U : 1U);
2053 
2054  return writer.append_unsigned(selector, sizeof(uint32_t), Endian::kBig) &&
2055  write_union_alternative(writer, value, std::make_index_sequence<sizeof...(AlternativeT)>{});
2056 }
2057 
2058 template <typename T>
2059 inline bool write_value_body(Writer& writer, const T& value) noexcept {
2060  if constexpr (VLINK_HAS_MEMBER(T, is_vlink_someip_type())) {
2061  using FieldsType = decltype(value.get_vlink_someip_fields());
2062 
2063  static_assert(std::tuple_size_v<FieldsType> > 0U, "SOME/IP structures must declare at least one field.");
2064 
2065  static constexpr size_t kFieldCount = std::tuple_size_v<FieldsType>;
2066  static constexpr size_t kTlvCount = count_tlv_fields<FieldsType>(std::make_index_sequence<kFieldCount>{});
2067 
2068  static_assert(kTlvCount == 0U || kTlvCount == kFieldCount,
2069  "SOME/IP structures must tag either every field or no field with VLINK_SOMEIP_TLV.");
2070  static_assert(kTlvCount == 0U || get_struct_length<T>() > 0U,
2071  "SOME/IP TLV structures must declare a non-zero VLINK_SOMEIP_STRUCT_LENGTH.");
2072  static_assert(kTlvCount == 0U || get_alignment<T>() == 1U, "SOME/IP TLV structures require 1-byte alignment.");
2073 
2074  const auto fields = value.get_vlink_someip_fields();
2075 
2076  if constexpr (kTlvCount > 0U) {
2077  static_assert(tlv_data_ids_are_unique<FieldsType>(std::make_index_sequence<kFieldCount>{}),
2078  "SOME/IP TLV data IDs must be unique within a structure.");
2079  static_assert(
2080  tlv_length_widths_are_equal<get_struct_length<T>(), FieldsType>(std::make_index_sequence<kFieldCount>{}),
2081  "SOME/IP TLV fields must use the structure length width.");
2082 
2083  return write_tlv_fields(writer, fields, std::make_index_sequence<kFieldCount>{});
2084  } else {
2085  return write_fields(writer, fields, std::make_index_sequence<kFieldCount>{});
2086  }
2087  } else {
2088  static_assert(Traits::ExpectFalse<T>(), "Unsupported SOME/IP TLV member type.");
2089 
2090  return false;
2091  }
2092 }
2093 
2094 template <typename MapT>
2095 inline bool write_map_entries(Writer& writer, const MapT& value) noexcept {
2096  for (const auto& entry : value) {
2097  const size_t entry_position = writer.position();
2098 
2099  if VUNLIKELY (!write_value(writer, entry.first)) {
2100  return false;
2101  }
2102 
2103  if VUNLIKELY (!write_value(writer, entry.second)) {
2104  return false;
2105  }
2106 
2107  if VUNLIKELY (writer.position() == entry_position) {
2108  return false;
2109  }
2110  }
2111 
2112  return true;
2113 }
2114 
2115 template <size_t IndexT, typename... AlternativeT>
2116 inline bool write_union_element(Writer& writer, const std::variant<AlternativeT...>& value) noexcept {
2117  if constexpr (IndexT == 0U && has_null_union_alternative<AlternativeT...>()) {
2118  return true;
2119  } else {
2120  return write_value(writer, std::get<IndexT>(value));
2121  }
2122 }
2123 
2124 template <typename... AlternativeT, size_t... IndexT>
2125 inline bool write_union_alternative(Writer& writer, const std::variant<AlternativeT...>& value,
2126  std::index_sequence<IndexT...>) noexcept {
2127  return ((value.index() != IndexT || write_union_element<IndexT>(writer, value)) && ...);
2128 }
2129 
2130 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t MaxT = std::numeric_limits<size_t>::max(), typename T>
2131 inline bool write_tlv_value(Writer& writer, const T& value) noexcept {
2132  static constexpr uint8_t kWireType = get_fixed_wire_type<T>();
2133 
2134  if constexpr (kWireType != kComplexWireType) {
2135  return detail::write_tag(writer, kWireType, DataIdT) && write_value(writer, value);
2136  } else {
2137  const auto write_body = [&value](Writer& target) noexcept {
2138  if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, Bytes>) {
2139  return detail::write_value_body(target, value, MaxT);
2140  } else if constexpr (std::is_same_v<T, std::u16string>) {
2141  return detail::write_value_body(target, value, Endian::kBig, MaxT);
2142  } else if constexpr (is_vector(static_cast<const T*>(nullptr))) {
2143  if VUNLIKELY (value.size() > MaxT) {
2144  return false;
2145  }
2146 
2147  return write_value_body(target, value);
2148  } else {
2149  return write_value_body(target, value);
2150  }
2151  };
2152 
2153  size_t length_width = LenT;
2154  size_t body_size = 0U;
2155 
2156  if constexpr (DynamicT) {
2157  Writer sizing = writer.size_only();
2158  const size_t start = sizing.position();
2159 
2160  if VUNLIKELY (!write_body(sizing)) {
2161  return false;
2162  }
2163 
2164  body_size = sizing.position() - start;
2165 
2166  if VLIKELY (body_size <= std::numeric_limits<uint8_t>::max()) {
2167  length_width = 1U;
2168  } else if (body_size <= std::numeric_limits<uint16_t>::max()) {
2169  length_width = 2U;
2170  } else {
2171  length_width = 4U;
2172  }
2173  }
2174 
2175  size_t length_position = 0U;
2176  size_t data_position = 0U;
2177 
2178  if VUNLIKELY (!detail::begin_tlv_complex(writer, DataIdT, length_width, DynamicT, length_position, data_position)) {
2179  return false;
2180  }
2181 
2182  if constexpr (DynamicT) {
2183  if (writer.is_size_only()) {
2184  return writer.append(nullptr, body_size) &&
2185  writer.end_length_delimited(length_position, data_position, length_width);
2186  }
2187  }
2188 
2189  return write_body(writer) && writer.end_length_delimited(length_position, data_position, length_width);
2190  }
2191 }
2192 
2193 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t MaxT>
2194 inline bool write_tlv_field(Writer& writer, const TlvField<DataIdT, LenT, DynamicT, T, MaxT>& field) noexcept {
2195  using ValueType = std::remove_cv_t<std::remove_reference_t<T>>;
2196 
2197  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
2198  if (!field.value.has_value()) {
2199  return true;
2200  }
2201 
2202  return write_tlv_value<DataIdT, LenT, DynamicT, MaxT>(writer, *field.value);
2203  } else {
2204  return write_tlv_value<DataIdT, LenT, DynamicT, MaxT>(writer, field.value);
2205  }
2206 }
2207 
2208 template <uint16_t DataIdT, size_t LenT, bool DynamicT, size_t SizeT, Endian EncodingT, typename T, size_t MaxT>
2209 inline bool write_tlv_field(
2211  using ValueType = std::remove_cv_t<T>;
2212 
2213  const auto write_fixed = [&writer](const auto& value) noexcept {
2214  size_t length_width = LenT;
2215  if constexpr (DynamicT) {
2216  if constexpr (SizeT <= std::numeric_limits<uint8_t>::max()) {
2217  length_width = 1U;
2218  } else if constexpr (SizeT <= std::numeric_limits<uint16_t>::max()) {
2219  length_width = 2U;
2220  } else {
2221  length_width = 4U;
2222  }
2223  }
2224 
2225  size_t length_position = 0U;
2226  size_t data_position = 0U;
2227  const auto fixed = fixed_string_field<SizeT, 0U, EncodingT, MaxT>(value);
2228 
2229  return detail::begin_tlv_complex(writer, DataIdT, length_width, DynamicT, length_position, data_position) &&
2230  write_value_body(writer, fixed) && writer.end_length_delimited(length_position, data_position, length_width);
2231  };
2232 
2233  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
2234  if (!field.value.has_value()) {
2235  return true;
2236  }
2237 
2238  return write_fixed(*field.value);
2239  } else {
2240  return write_fixed(field.value);
2241  }
2242 }
2243 
2244 template <uint16_t DataIdT, size_t LenT, bool DynamicT, typename T, size_t... InnerLenT>
2245 inline bool write_tlv_field(Writer& writer,
2247  using ValueType = std::remove_cv_t<T>;
2248 
2249  if constexpr (is_optional(static_cast<const ValueType*>(nullptr))) {
2250  if (!field.value.has_value()) {
2251  return true;
2252  }
2253 
2254  const auto array = array_length_field<LenT, InnerLenT...>(*field.value);
2255  return write_tlv_value<DataIdT, LenT, DynamicT>(writer, array);
2256  } else {
2257  const auto array = array_length_field<LenT, InnerLenT...>(field.value);
2258  return write_tlv_value<DataIdT, LenT, DynamicT>(writer, array);
2259  }
2260 }
2261 
2262 template <typename TupleT, size_t... IndexT>
2263 inline bool write_tlv_fields(Writer& writer, const TupleT& fields, std::index_sequence<IndexT...>) noexcept {
2264  return (write_tlv_field(writer, std::get<IndexT>(fields)) && ...);
2265 }
2266 
2267 } // namespace SomeipSerializer
2268 
2269 } // namespace vlink
2270 
2271 ////////////////////////////////////////////////////////////////
2272 /// Macro Definitions
2273 ////////////////////////////////////////////////////////////////
2274 
2275 /**
2276  * @def VLINK_SOMEIP_ALIGNMENT
2277  * @brief Selects the AUTOSAR alignment (1, 2, 4, 8, 16, or 32 bytes) for a
2278  * top-level payload structure; the default is one byte.
2279  */
2280 #define VLINK_SOMEIP_ALIGNMENT(alignment) \
2281  [[nodiscard]] static constexpr size_t vlink_someip_alignment() noexcept { return alignment; }
2282 
2283 /**
2284  * @def VLINK_SOMEIP_ENDIAN
2285  * @brief Selects the payload scalar byte order for a top-level structure;
2286  * the default is @c Endian::kBig.
2287  */
2288 #define VLINK_SOMEIP_ENDIAN(endian) \
2289  [[nodiscard]] static constexpr vlink::SomeipSerializer::Endian vlink_someip_endian() noexcept { return endian; }
2290 
2291 /**
2292  * @def VLINK_SOMEIP_ENDIAN_BIG
2293  * @brief Selects big-endian SOME/IP payload scalar values.
2294  */
2295 #define VLINK_SOMEIP_ENDIAN_BIG VLINK_SOMEIP_ENDIAN(vlink::SomeipSerializer::Endian::kBig)
2296 
2297 /**
2298  * @def VLINK_SOMEIP_ENDIAN_LITTLE
2299  * @brief Selects little-endian SOME/IP payload scalar values.
2300  */
2301 #define VLINK_SOMEIP_ENDIAN_LITTLE VLINK_SOMEIP_ENDIAN(vlink::SomeipSerializer::Endian::kLittle)
2302 
2303 /**
2304  * @def VLINK_SOMEIP_STRUCT_LENGTH
2305  * @brief Selects the structure length field width: 0 (default, omitted), 1,
2306  * 2, or 4 bytes; TLV structures must select a non-zero width.
2307  */
2308 #define VLINK_SOMEIP_STRUCT_LENGTH(width) \
2309  [[nodiscard]] static constexpr size_t vlink_someip_struct_length() noexcept { return width; }
2310 
2311 /**
2312  * @def VLINK_SOMEIP_LENGTH
2313  * @brief Wraps one UTF-8/UTF-16 string, @c Bytes, vector, or map field with
2314  * a 1, 2, or 4-byte length width; a fixed array may also use zero to
2315  * omit it. Unwrapped length-delimited fields use four bytes.
2316  */
2317 #define VLINK_SOMEIP_LENGTH(field, width) vlink::SomeipSerializer::length_field<width>(field)
2318 
2319 /**
2320  * @def VLINK_SOMEIP_LENGTH_MAX
2321  * @brief Adds a maximum character, element, or byte count to a length-delimited field.
2322  */
2323 #define VLINK_SOMEIP_LENGTH_MAX(field, width, maximum) vlink::SomeipSerializer::length_field<width, maximum>(field)
2324 
2325 /**
2326  * @def VLINK_SOMEIP_ARRAY_LENGTH
2327  * @brief Wraps one nested array field with per-dimension length widths from
2328  * outermost to innermost; unlisted dimensions keep four bytes and a
2329  * nested structure keeps its own field configuration.
2330  */
2331 #define VLINK_SOMEIP_ARRAY_LENGTH(field, ...) vlink::SomeipSerializer::array_length_field<__VA_ARGS__>(field)
2332 
2333 /**
2334  * @def VLINK_SOMEIP_UTF16
2335  * @brief Wraps one @c std::u16string field with a 1, 2, or 4-byte length
2336  * width and an explicit code unit byte order; unwrapped fields use
2337  * four bytes and UTF-16BE.
2338  */
2339 #define VLINK_SOMEIP_UTF16(field, width, endian) vlink::SomeipSerializer::utf16_field<width, endian>(field)
2340 
2341 /**
2342  * @def VLINK_SOMEIP_UTF16_MAX
2343  * @brief Adds a maximum Unicode character count to an explicitly encoded UTF-16 field.
2344  */
2345 #define VLINK_SOMEIP_UTF16_MAX(field, width, endian, maximum) \
2346  vlink::SomeipSerializer::utf16_field<width, endian, maximum>(field)
2347 
2348 /**
2349  * @def VLINK_SOMEIP_UTF16_BE
2350  * @brief Selects a UTF-16BE string field with a configurable length width.
2351  */
2352 #define VLINK_SOMEIP_UTF16_BE(field, width) VLINK_SOMEIP_UTF16(field, width, vlink::SomeipSerializer::Endian::kBig)
2353 
2354 /**
2355  * @def VLINK_SOMEIP_UTF16_LE
2356  * @brief Selects a UTF-16LE string field with a configurable length width.
2357  */
2358 #define VLINK_SOMEIP_UTF16_LE(field, width) VLINK_SOMEIP_UTF16(field, width, vlink::SomeipSerializer::Endian::kLittle)
2359 
2360 /**
2361  * @def VLINK_SOMEIP_FIXED_STRING
2362  * @brief Selects a fixed-size UTF-8 string; @p size includes BOM, content,
2363  * terminator, and zero padding, while @p width may be 0, 1, 2, or 4.
2364  */
2365 #define VLINK_SOMEIP_FIXED_STRING(field, size, width) vlink::SomeipSerializer::fixed_string_field<size, width>(field)
2366 
2367 /**
2368  * @def VLINK_SOMEIP_FIXED_STRING_MAX
2369  * @brief Adds a maximum Unicode character count to a fixed-size UTF-8 string.
2370  */
2371 #define VLINK_SOMEIP_FIXED_STRING_MAX(field, size, width, maximum) \
2372  vlink::SomeipSerializer::fixed_string_field<size, width, vlink::SomeipSerializer::Endian::kBig, maximum>(field)
2373 
2374 /**
2375  * @def VLINK_SOMEIP_FIXED_UTF16_BE
2376  * @brief Selects a fixed-size UTF-16BE string using the specified total byte size and length width.
2377  */
2378 #define VLINK_SOMEIP_FIXED_UTF16_BE(field, size, width) \
2379  vlink::SomeipSerializer::fixed_string_field<size, width, vlink::SomeipSerializer::Endian::kBig>(field)
2380 
2381 /**
2382  * @def VLINK_SOMEIP_FIXED_UTF16_BE_MAX
2383  * @brief Adds a maximum Unicode character count to a fixed-size UTF-16BE string.
2384  */
2385 #define VLINK_SOMEIP_FIXED_UTF16_BE_MAX(field, size, width, maximum) \
2386  vlink::SomeipSerializer::fixed_string_field<size, width, vlink::SomeipSerializer::Endian::kBig, maximum>(field)
2387 
2388 /**
2389  * @def VLINK_SOMEIP_FIXED_UTF16_LE
2390  * @brief Selects a fixed-size UTF-16LE string using the specified total byte size and length width.
2391  */
2392 #define VLINK_SOMEIP_FIXED_UTF16_LE(field, size, width) \
2393  vlink::SomeipSerializer::fixed_string_field<size, width, vlink::SomeipSerializer::Endian::kLittle>(field)
2394 
2395 /**
2396  * @def VLINK_SOMEIP_FIXED_UTF16_LE_MAX
2397  * @brief Adds a maximum Unicode character count to a fixed-size UTF-16LE string.
2398  */
2399 #define VLINK_SOMEIP_FIXED_UTF16_LE_MAX(field, size, width, maximum) \
2400  vlink::SomeipSerializer::fixed_string_field<size, width, vlink::SomeipSerializer::Endian::kLittle, maximum>(field)
2401 
2402 /**
2403  * @def VLINK_SOMEIP_UNION
2404  * @brief Wraps one @c std::variant field with 1, 2, or 4-byte length and
2405  * type selector widths; the length excludes the selector, selectors
2406  * count alternatives in declaration order from one. A first
2407  * @c std::monostate explicitly enables selector zero. Unwrapped fields
2408  * use four bytes.
2409  */
2410 #define VLINK_SOMEIP_UNION(field, length_width, type_width) \
2411  vlink::SomeipSerializer::union_field<length_width, type_width>(field)
2412 
2413 /**
2414  * @def VLINK_SOMEIP_TLV
2415  * @brief Declares one TLV member with its unique 12-bit data ID; every field
2416  * of a TLV structure must be tagged and the structure must declare
2417  * @c VLINK_SOMEIP_STRUCT_LENGTH. Complex members select a 1, 2, or
2418  * 4-byte length from their actual size, absent @c std::optional members are
2419  * omitted and reset on input, unknown data IDs are skipped, and a
2420  * repeated known data ID rejects the input. Nested length-delimited
2421  * values require their corresponding field macros.
2422  */
2423 #define VLINK_SOMEIP_TLV(data_id, field) vlink::SomeipSerializer::tlv_field<data_id>(field)
2424 
2425 /**
2426  * @def VLINK_SOMEIP_TLV_LENGTH
2427  * @brief Declares one dynamically sized TLV member and configures the 1, 2,
2428  * or 4-byte structure width used when receiving an unknown wire type 4;
2429  * fixed-width members still declare this shared width but emit wire types 0–3.
2430  */
2431 #define VLINK_SOMEIP_TLV_LENGTH(data_id, field, width) vlink::SomeipSerializer::tlv_field<data_id, width>(field)
2432 
2433 /**
2434  * @def VLINK_SOMEIP_TLV_LENGTH_MAX
2435  * @brief Adds a maximum character, element, or byte count to a dynamically sized TLV member.
2436  */
2437 #define VLINK_SOMEIP_TLV_LENGTH_MAX(data_id, field, width, maximum) \
2438  vlink::SomeipSerializer::tlv_field<data_id, width, true, maximum>(field)
2439 
2440 /**
2441  * @def VLINK_SOMEIP_TLV_FIXED_STRING
2442  * @brief Declares a dynamic TLV fixed string with a total byte size, structure width, and UTF-16 byte order.
2443  */
2444 #define VLINK_SOMEIP_TLV_FIXED_STRING(data_id, field, size, width, endian) \
2445  vlink::SomeipSerializer::tlv_fixed_string_field<data_id, width, true, size, endian>(field)
2446 
2447 /**
2448  * @def VLINK_SOMEIP_TLV_FIXED_STRING_MAX
2449  * @brief Adds a maximum Unicode character count to a dynamic TLV fixed string.
2450  */
2451 #define VLINK_SOMEIP_TLV_FIXED_STRING_MAX(data_id, field, size, width, endian, maximum) \
2452  vlink::SomeipSerializer::tlv_fixed_string_field<data_id, width, true, size, endian, maximum>(field)
2453 
2454 /**
2455  * @def VLINK_SOMEIP_TLV_ARRAY_LENGTH
2456  * @brief Declares a multidimensional TLV array member whose inner dimensions
2457  * inherit the structure-wide length width.
2458  */
2459 #define VLINK_SOMEIP_TLV_ARRAY_LENGTH(data_id, field, width, ...) \
2460  vlink::SomeipSerializer::tlv_array_field<data_id, width, true, __VA_ARGS__>(field)
2461 
2462 /**
2463  * @def VLINK_SOMEIP_TLV_STATIC_LENGTH
2464  * @brief Declares one complex TLV member that emits wire type 4 with the
2465  * configured 1, 2, or 4-byte static structure width; fixed-width members
2466  * still declare this shared width but emit wire types 0–3.
2467  */
2468 #define VLINK_SOMEIP_TLV_STATIC_LENGTH(data_id, field, width) \
2469  vlink::SomeipSerializer::tlv_field<data_id, width, false>(field)
2470 
2471 /**
2472  * @def VLINK_SOMEIP_TLV_STATIC_LENGTH_MAX
2473  * @brief Adds a maximum character, element, or byte count to a static-length TLV member.
2474  */
2475 #define VLINK_SOMEIP_TLV_STATIC_LENGTH_MAX(data_id, field, width, maximum) \
2476  vlink::SomeipSerializer::tlv_field<data_id, width, false, maximum>(field)
2477 
2478 /**
2479  * @def VLINK_SOMEIP_TLV_STATIC_FIXED_STRING
2480  * @brief Declares a static TLV fixed string with a total byte size, structure width, and UTF-16 byte order.
2481  */
2482 #define VLINK_SOMEIP_TLV_STATIC_FIXED_STRING(data_id, field, size, width, endian) \
2483  vlink::SomeipSerializer::tlv_fixed_string_field<data_id, width, false, size, endian>(field)
2484 
2485 /**
2486  * @def VLINK_SOMEIP_TLV_STATIC_FIXED_STRING_MAX
2487  * @brief Adds a maximum Unicode character count to a static TLV fixed string.
2488  */
2489 #define VLINK_SOMEIP_TLV_STATIC_FIXED_STRING_MAX(data_id, field, size, width, endian, maximum) \
2490  vlink::SomeipSerializer::tlv_fixed_string_field<data_id, width, false, size, endian, maximum>(field)
2491 
2492 /**
2493  * @def VLINK_SOMEIP_TLV_STATIC_ARRAY_LENGTH
2494  * @brief Declares a multidimensional static-length TLV array member whose
2495  * inner dimensions inherit the structure-wide length width.
2496  */
2497 #define VLINK_SOMEIP_TLV_STATIC_ARRAY_LENGTH(data_id, field, width, ...) \
2498  vlink::SomeipSerializer::tlv_array_field<data_id, width, false, __VA_ARGS__>(field)
2499 
2500 /**
2501  * @def VLINK_SOMEIP_FIELDS
2502  * @brief Declares a structure as a SOME/IP payload and lists its fields in
2503  * wire-format order.
2504  *
2505  * @details
2506  * Generates the SOME/IP marker, ordered field access, an exact-size query, a
2507  * @c serialize() member with an explicit offset parameter, a @c deserialize()
2508  * member that reads the @c Bytes payload region, and the @c vlink::Bytes stream
2509  * operators. Fields may be fixed-width
2510  * numeric values, unsigned fixed-width enums, @c std::string,
2511  * @c std::u16string, @c Bytes, @c std::vector, @c std::array, @c std::map,
2512  * @c std::unordered_map, @c std::variant, nested structures using the same
2513  * macro, or TLV members declared with @c VLINK_SOMEIP_TLV. At least one
2514  * field must be listed, and buffers passed to the generated operators must
2515  * not overlap storage reachable from the structure.
2516  */
2517 #define VLINK_SOMEIP_FIELDS(...) \
2518  [[nodiscard]] static constexpr bool is_vlink_someip_type() noexcept { return true; } \
2519  \
2520  [[nodiscard]] auto get_vlink_someip_fields() noexcept { return vlink::SomeipSerializer::make_fields(__VA_ARGS__); } \
2521  \
2522  [[nodiscard]] auto get_vlink_someip_fields() const noexcept { \
2523  return vlink::SomeipSerializer::make_fields(__VA_ARGS__); \
2524  } \
2525  \
2526  [[nodiscard]] size_t get_serialized_size() const noexcept { \
2527  return vlink::SomeipSerializer::get_serialized_size(*this); \
2528  } \
2529  \
2530  bool serialize(vlink::Bytes& out, uint8_t offset = 0U) const noexcept { \
2531  return vlink::SomeipSerializer::serialize(*this, out, offset); \
2532  } \
2533  \
2534  bool deserialize(const vlink::Bytes& in) noexcept { return vlink::SomeipSerializer::deserialize(in, *this); } \
2535  \
2536  bool operator>>(vlink::Bytes& out) const noexcept { return serialize(out); } \
2537  \
2538  bool operator<<(const vlink::Bytes& in) noexcept { return deserialize(in); }
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLINK_EXPORT
Definition: macros.h:81
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284
#define VLINK_HAS_MEMBER(T, member)
Macro Definitions.
Definition: traits.h:325