• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #ifndef ANDROID_PDX_RPC_SERIALIZATION_H_
2 #define ANDROID_PDX_RPC_SERIALIZATION_H_
3 
4 #include <cstdint>
5 #include <cstring>
6 #include <iterator>
7 #include <map>
8 #include <numeric>
9 #include <sstream>
10 #include <string>
11 #include <tuple>
12 #include <type_traits>
13 #include <unordered_map>
14 #include <utility>
15 #include <vector>
16 
17 #include <pdx/channel_handle.h>
18 #include <pdx/file_handle.h>
19 #include <pdx/message_reader.h>
20 #include <pdx/message_writer.h>
21 #include <pdx/trace.h>
22 #include <pdx/utility.h>
23 
24 #include "array_wrapper.h"
25 #include "default_initialization_allocator.h"
26 #include "encoding.h"
27 #include "pointer_wrapper.h"
28 #include "string_wrapper.h"
29 #include "variant.h"
30 
31 namespace android {
32 namespace pdx {
33 namespace rpc {
34 
35 // Automatic serialization/deserialization library based on MessagePack
36 // (http://msgpack.org). This library provides top level Serialize() and
37 // Deserialize() functions to encode/decode a variety of data types.
38 //
39 // The following data types are supported:
40 //   * Standard signed integer types: int8_t, int16_t, int32_t, and int64_t.
41 //   * Regular signed integer types equivalent to the standard types:
42 //     signed char, short, int, long, and long long.
43 //   * Standard unsigned integer types: uint8_t, uint16_t, uint32_t, and
44 //     uint64_t.
45 //   * Regular unsigned integer types equivalent to the standard types:
46 //     unsigned char, unsigned short, unsigned int, unsigned long,
47 //     and unsigned long long.
48 //   * char without signed/unsigned qualifiers.
49 //   * bool.
50 //   * std::vector with value type of any supported type, including nesting.
51 //   * std::string.
52 //   * std::tuple with elements of any supported type, including nesting.
53 //   * std::pair with elements of any supported type, including nesting.
54 //   * std::map with keys and values of any supported type, including nesting.
55 //   * std::unordered_map with keys and values of any supported type, including
56 //     nesting.
57 //   * std::array with values of any supported type, including nesting.
58 //   * ArrayWrapper of any supported basic type.
59 //   * BufferWrapper of any POD type.
60 //   * StringWrapper of any supported char type.
61 //   * User types with correctly defined SerializableMembers member type.
62 //
63 // Planned support for:
64 //   * std::basic_string with all supported char types.
65 
66 // Counting template for managing template recursion.
67 template <std::size_t N>
68 struct Index {};
69 
70 // Forward declaration of traits type to access types with a SerializedMembers
71 // member type.
72 template <typename T>
73 class SerializableTraits;
74 
75 template <typename T, typename... MemberPointers>
76 struct SerializableMembersType;
77 
78 // Utility to deduce the template type from a derived type.
79 template <template <typename...> class TT, typename... Ts>
80 std::true_type DeduceTemplateType(const TT<Ts...>*);
81 template <template <typename...> class TT>
82 std::false_type DeduceTemplateType(...);
83 
84 // Utility determining whether template type TT<...> is a base of type T.
85 template <template <typename...> class TT, typename T>
86 using IsTemplateBaseOf = decltype(DeduceTemplateType<TT>(std::declval<T*>()));
87 
88 // Utility type for SFINAE in HasHasSerializableMembers.
89 template <typename... Ts>
90 using TrySerializableMembersType = void;
91 
92 // Determines whether type T has a member type named SerializableMembers of
93 // template type SerializableMembersType.
94 template <typename, typename = void>
95 struct HasSerializableMembers : std::false_type {};
96 template <typename T>
97 struct HasSerializableMembers<
98     T, TrySerializableMembersType<typename T::SerializableMembers>>
99     : std::integral_constant<
100           bool, IsTemplateBaseOf<SerializableMembersType,
101                                  typename T::SerializableMembers>::value> {};
102 
103 // Utility to simplify overload enable expressions for types with correctly
104 // defined SerializableMembers.
105 template <typename T>
106 using EnableIfHasSerializableMembers =
107     typename std::enable_if<HasSerializableMembers<T>::value>::type;
108 
109 // Utility to simplify overload enable expressions for enum types.
110 template <typename T, typename ReturnType = void>
111 using EnableIfEnum =
112     typename std::enable_if<std::is_enum<T>::value, ReturnType>::type;
113 
114 ///////////////////////////////////////////////////////////////////////////////
115 // Error Reporting //
116 ///////////////////////////////////////////////////////////////////////////////
117 
118 // Error codes returned by the deserialization code.
119 enum class ErrorCode {
120   NO_ERROR = 0,
121   UNEXPECTED_ENCODING,
122   UNEXPECTED_TYPE_SIZE,
123   INSUFFICIENT_BUFFER,
124   INSUFFICIENT_DESTINATION_SIZE,
125   GET_FILE_DESCRIPTOR_FAILED,
126   GET_CHANNEL_HANDLE_FAILED,
127   INVALID_VARIANT_ELEMENT,
128 };
129 
130 // Type for errors returned by the deserialization code.
131 class ErrorType {
132  public:
133   ErrorType() : error_code_(ErrorCode::NO_ERROR) {}
134 
135   // ErrorType constructor for generic error codes. Explicitly not explicit,
136   // implicit conversion from ErrorCode to ErrorType is desirable behavior.
137   // NOLINTNEXTLINE(runtime/explicit)
138   ErrorType(ErrorCode error_code) : error_code_(error_code) {}
139 
140   // ErrorType constructor for encoding type errors.
141   ErrorType(ErrorCode error_code, EncodingClass encoding_class,
142             EncodingType encoding_type)
143       : error_code_(error_code) {
144     unexpected_encoding_.encoding_class = encoding_class;
145     unexpected_encoding_.encoding_type = encoding_type;
146   }
147 
148   // Evaluates to true if the ErrorType represents an error.
149   explicit operator bool() const { return error_code_ != ErrorCode::NO_ERROR; }
150 
151   operator ErrorCode() const { return error_code_; }
152   ErrorCode error_code() const { return error_code_; }
153 
154   // Accessors for extra info about unexpected encoding errors.
155   EncodingClass encoding_class() const {
156     return unexpected_encoding_.encoding_class;
157   }
158   EncodingType encoding_type() const {
159     return unexpected_encoding_.encoding_type;
160   }
161 
162   operator std::string() const {
163     std::ostringstream stream;
164 
165     switch (error_code_) {
166       case ErrorCode::NO_ERROR:
167         return "NO_ERROR";
168       case ErrorCode::UNEXPECTED_ENCODING:
169         stream << "UNEXPECTED_ENCODING: " << static_cast<int>(encoding_class())
170                << ", " << static_cast<int>(encoding_type());
171         return stream.str();
172       case ErrorCode::UNEXPECTED_TYPE_SIZE:
173         return "UNEXPECTED_TYPE_SIZE";
174       case ErrorCode::INSUFFICIENT_BUFFER:
175         return "INSUFFICIENT_BUFFER";
176       case ErrorCode::INSUFFICIENT_DESTINATION_SIZE:
177         return "INSUFFICIENT_DESTINATION_SIZE";
178       default:
179         return "[Unknown Error]";
180     }
181   }
182 
183  private:
184   ErrorCode error_code_;
185 
186   // Union of extra information for different error code types.
187   union {
188     // UNEXPECTED_ENCODING.
189     struct {
190       EncodingClass encoding_class;
191       EncodingType encoding_type;
192     } unexpected_encoding_;
193   };
194 };
195 
196 ///////////////////////////////////////////////////////////////////////////////
197 // Object Size //
198 ///////////////////////////////////////////////////////////////////////////////
199 
200 inline constexpr std::size_t GetSerializedSize(const bool& b) {
201   return GetEncodingSize(EncodeType(b));
202 }
203 
204 // Overloads of GetSerializedSize() for standard integer types.
205 inline constexpr std::size_t GetSerializedSize(const char& c) {
206   return GetEncodingSize(EncodeType(c));
207 }
208 inline constexpr std::size_t GetSerializedSize(const std::uint8_t& i) {
209   return GetEncodingSize(EncodeType(i));
210 }
211 inline constexpr std::size_t GetSerializedSize(const std::int8_t& i) {
212   return GetEncodingSize(EncodeType(i));
213 }
214 inline constexpr std::size_t GetSerializedSize(const std::uint16_t& i) {
215   return GetEncodingSize(EncodeType(i));
216 }
217 inline constexpr std::size_t GetSerializedSize(const std::int16_t& i) {
218   return GetEncodingSize(EncodeType(i));
219 }
220 inline constexpr std::size_t GetSerializedSize(const std::uint32_t& i) {
221   return GetEncodingSize(EncodeType(i));
222 }
223 inline constexpr std::size_t GetSerializedSize(const std::int32_t& i) {
224   return GetEncodingSize(EncodeType(i));
225 }
226 inline constexpr std::size_t GetSerializedSize(const std::uint64_t& i) {
227   return GetEncodingSize(EncodeType(i));
228 }
229 inline constexpr std::size_t GetSerializedSize(const std::int64_t& i) {
230   return GetEncodingSize(EncodeType(i));
231 }
232 
233 inline constexpr std::size_t GetSerializedSize(const float& f) {
234   return GetEncodingSize(EncodeType(f));
235 }
236 inline constexpr std::size_t GetSerializedSize(const double& d) {
237   return GetEncodingSize(EncodeType(d));
238 }
239 
240 // Overload for enum types.
241 template <typename T>
242 inline EnableIfEnum<T, std::size_t> GetSerializedSize(T v) {
243   return GetSerializedSize(static_cast<std::underlying_type_t<T>>(v));
244 }
245 
246 // Forward declaration for nested definitions.
247 inline std::size_t GetSerializedSize(const EmptyVariant&);
248 template <typename... Types>
249 inline std::size_t GetSerializedSize(const Variant<Types...>&);
250 template <typename T, typename Enabled = EnableIfHasSerializableMembers<T>>
251 inline constexpr std::size_t GetSerializedSize(const T&);
252 template <typename T>
253 inline constexpr std::size_t GetSerializedSize(const PointerWrapper<T>&);
254 inline constexpr std::size_t GetSerializedSize(const std::string&);
255 template <typename T>
256 inline constexpr std::size_t GetSerializedSize(const StringWrapper<T>&);
257 template <typename T>
258 inline constexpr std::size_t GetSerializedSize(const BufferWrapper<T>&);
259 template <FileHandleMode Mode>
260 inline constexpr std::size_t GetSerializedSize(const FileHandle<Mode>&);
261 template <ChannelHandleMode Mode>
262 inline constexpr std::size_t GetSerializedSize(const ChannelHandle<Mode>&);
263 template <typename T, typename Allocator>
264 inline std::size_t GetSerializedSize(const std::vector<T, Allocator>& v);
265 template <typename Key, typename T, typename Compare, typename Allocator>
266 inline std::size_t GetSerializedSize(
267     const std::map<Key, T, Compare, Allocator>& m);
268 template <typename Key, typename T, typename Hash, typename KeyEqual,
269           typename Allocator>
270 inline std::size_t GetSerializedSize(
271     const std::unordered_map<Key, T, Hash, KeyEqual, Allocator>&);
272 template <typename T>
273 inline std::size_t GetSerializedSize(const ArrayWrapper<T>&);
274 template <typename T, std::size_t Size>
275 inline std::size_t GetSerializedSize(const std::array<T, Size>& v);
276 template <typename T, typename U>
277 inline std::size_t GetSerializedSize(const std::pair<T, U>& p);
278 template <typename... T>
279 inline std::size_t GetSerializedSize(const std::tuple<T...>& tuple);
280 
281 // Overload for empty variant type.
282 inline std::size_t GetSerializedSize(const EmptyVariant& empty) {
283   return GetEncodingSize(EncodeType(empty));
284 }
285 
286 // Overload for Variant types.
287 template <typename... Types>
288 inline std::size_t GetSerializedSize(const Variant<Types...>& variant) {
289   return GetEncodingSize(EncodeType(variant)) +
290          GetSerializedSize(variant.index()) +
291          variant.Visit(
292              [](const auto& value) { return GetSerializedSize(value); });
293 }
294 
295 // Overload for structs/classes with SerializableMembers defined.
296 template <typename T, typename Enabled>
297 inline constexpr std::size_t GetSerializedSize(const T& value) {
298   return SerializableTraits<T>::GetSerializedSize(value);
299 }
300 
301 // Overload for PointerWrapper.
302 template <typename T>
303 inline constexpr std::size_t GetSerializedSize(const PointerWrapper<T>& p) {
304   return GetSerializedSize(p.Dereference());
305 }
306 
307 // Overload for std::string.
308 inline constexpr std::size_t GetSerializedSize(const std::string& s) {
309   return GetEncodingSize(EncodeType(s)) +
310          s.length() * sizeof(std::string::value_type);
311 }
312 
313 // Overload for StringWrapper.
314 template <typename T>
315 inline constexpr std::size_t GetSerializedSize(const StringWrapper<T>& s) {
316   return GetEncodingSize(EncodeType(s)) +
317          s.length() * sizeof(typename StringWrapper<T>::value_type);
318 }
319 
320 // Overload for BufferWrapper types.
321 template <typename T>
322 inline constexpr std::size_t GetSerializedSize(const BufferWrapper<T>& b) {
323   return GetEncodingSize(EncodeType(b)) +
324          b.size() * sizeof(typename BufferWrapper<T>::value_type);
325 }
326 
327 // Overload for FileHandle. FileHandle is encoded as a FIXEXT2, with a type code
328 // of "FileHandle" and a signed 16-bit offset into the pushed fd array. Empty
329 // FileHandles are encoded with an array index of -1.
330 template <FileHandleMode Mode>
331 inline constexpr std::size_t GetSerializedSize(const FileHandle<Mode>& fd) {
332   return GetEncodingSize(EncodeType(fd)) + sizeof(std::int16_t);
333 }
334 
335 // Overload for ChannelHandle. ChannelHandle is encoded as a FIXEXT4, with a
336 // type code of "ChannelHandle" and a signed 32-bit offset into the pushed
337 // channel array. Empty ChannelHandles are encoded with an array index of -1.
338 template <ChannelHandleMode Mode>
339 inline constexpr std::size_t GetSerializedSize(
340     const ChannelHandle<Mode>& channel_handle) {
341   return GetEncodingSize(EncodeType(channel_handle)) + sizeof(std::int32_t);
342 }
343 
344 // Overload for standard vector types.
345 template <typename T, typename Allocator>
346 inline std::size_t GetSerializedSize(const std::vector<T, Allocator>& v) {
347   return std::accumulate(v.begin(), v.end(), GetEncodingSize(EncodeType(v)),
348                          [](const std::size_t& sum, const T& object) {
349                            return sum + GetSerializedSize(object);
350                          });
351 }
352 
353 // Overload for standard map types.
354 template <typename Key, typename T, typename Compare, typename Allocator>
355 inline std::size_t GetSerializedSize(
356     const std::map<Key, T, Compare, Allocator>& v) {
357   return std::accumulate(
358       v.begin(), v.end(), GetEncodingSize(EncodeType(v)),
359       [](const std::size_t& sum, const std::pair<Key, T>& object) {
360         return sum + GetSerializedSize(object.first) +
361                GetSerializedSize(object.second);
362       });
363 }
364 
365 // Overload for standard unordered_map types.
366 template <typename Key, typename T, typename Hash, typename KeyEqual,
367           typename Allocator>
368 inline std::size_t GetSerializedSize(
369     const std::unordered_map<Key, T, Hash, KeyEqual, Allocator>& v) {
370   return std::accumulate(
371       v.begin(), v.end(), GetEncodingSize(EncodeType(v)),
372       [](const std::size_t& sum, const std::pair<Key, T>& object) {
373         return sum + GetSerializedSize(object.first) +
374                GetSerializedSize(object.second);
375       });
376 }
377 
378 // Overload for ArrayWrapper types.
379 template <typename T>
380 inline std::size_t GetSerializedSize(const ArrayWrapper<T>& v) {
381   return std::accumulate(v.begin(), v.end(), GetEncodingSize(EncodeType(v)),
382                          [](const std::size_t& sum, const T& object) {
383                            return sum + GetSerializedSize(object);
384                          });
385 }
386 
387 // Overload for std::array types.
388 template <typename T, std::size_t Size>
389 inline std::size_t GetSerializedSize(const std::array<T, Size>& v) {
390   return std::accumulate(v.begin(), v.end(), GetEncodingSize(EncodeType(v)),
391                          [](const std::size_t& sum, const T& object) {
392                            return sum + GetSerializedSize(object);
393                          });
394 }
395 
396 // Overload for std::pair.
397 template <typename T, typename U>
398 inline std::size_t GetSerializedSize(const std::pair<T, U>& p) {
399   return GetEncodingSize(EncodeType(p)) + GetSerializedSize(p.first) +
400          GetSerializedSize(p.second);
401 }
402 
403 // Stops template recursion when the last tuple element is reached.
404 template <typename... T>
405 inline std::size_t GetTupleSize(const std::tuple<T...>&, Index<0>) {
406   return 0;
407 }
408 
409 // Gets the size of each element in a tuple recursively.
410 template <typename... T, std::size_t index>
411 inline std::size_t GetTupleSize(const std::tuple<T...>& tuple, Index<index>) {
412   return GetTupleSize(tuple, Index<index - 1>()) +
413          GetSerializedSize(std::get<index - 1>(tuple));
414 }
415 
416 // Overload for tuple types. Gets the size of the tuple, recursing
417 // through the elements.
418 template <typename... T>
419 inline std::size_t GetSerializedSize(const std::tuple<T...>& tuple) {
420   return GetEncodingSize(EncodeType(tuple)) +
421          GetTupleSize(tuple, Index<sizeof...(T)>());
422 }
423 
424 // Stops template recursion when the last member of a Serializable
425 // type is reached.
426 template <typename Members, typename T>
427 inline std::size_t GetMemberSize(const T&, Index<0>) {
428   return 0;
429 }
430 
431 // Gets the size of each member of a Serializable type recursively.
432 template <typename Members, typename T, std::size_t index>
433 inline std::size_t GetMemberSize(const T& object, Index<index>) {
434   return GetMemberSize<Members>(object, Index<index - 1>()) +
435          GetSerializedSize(Members::template At<index - 1>::Resolve(object));
436 }
437 
438 // Gets the size of a type using the given SerializableMembersType
439 // type.
440 template <typename Members, typename T>
441 inline std::size_t GetMembersSize(const T& object) {
442   return GetMemberSize<Members>(object, Index<Members::MemberCount>());
443 }
444 
445 ///////////////////////////////////////////////////////////////////////////////
446 // Object Serialization //
447 ///////////////////////////////////////////////////////////////////////////////
448 
449 //
450 // SerializeRaw() converts a primitive array or type into a raw byte string.
451 // These functions are named differently from SerializeObject() expressly to
452 // avoid catch-all specialization of that template, which can be difficult to
453 // detect otherwise.
454 //
455 
456 inline void WriteRawData(void*& dest, const void* src, size_t size) {
457   memcpy(dest, src, size);
458   dest = static_cast<uint8_t*>(dest) + size;
459 }
460 
461 // Serializes a primitive array into a raw byte string.
462 template <typename T,
463           typename = typename std::enable_if<std::is_pod<T>::value>::type>
464 inline void SerializeRaw(const T& value, void*& buffer) {
465   WriteRawData(buffer, &value, sizeof(value));
466 }
467 
468 inline void SerializeEncoding(EncodingType encoding, void*& buffer) {
469   SerializeRaw(encoding, buffer);
470 }
471 
472 inline void SerializeType(const bool& value, void*& buffer) {
473   const EncodingType encoding = EncodeType(value);
474   SerializeEncoding(encoding, buffer);
475 }
476 
477 // Serializes the type code, extended type code, and size for
478 // extension types.
479 inline void SerializeExtEncoding(EncodingType encoding,
480                                  EncodingExtType ext_type, std::size_t size,
481                                  void*& buffer) {
482   SerializeEncoding(encoding, buffer);
483   if (encoding == ENCODING_TYPE_EXT8) {
484     std::uint8_t length = size;
485     SerializeRaw(length, buffer);
486   } else if (encoding == ENCODING_TYPE_EXT16) {
487     std::uint16_t length = size;
488     SerializeRaw(length, buffer);
489   } else if (encoding == ENCODING_TYPE_EXT32) {
490     std::uint32_t length = size;
491     SerializeRaw(length, buffer);
492   } else /* if (IsFixextEncoding(encoding) */ {
493     // Encoding byte contains the fixext length, nothing else to do.
494   }
495   SerializeRaw(ext_type, buffer);
496 }
497 
498 // Serializes the type code for file descriptor types.
499 template <FileHandleMode Mode>
500 inline void SerializeType(const FileHandle<Mode>& value, void*& buffer) {
501   SerializeExtEncoding(EncodeType(value), ENCODING_EXT_TYPE_FILE_DESCRIPTOR, 2,
502                        buffer);
503 }
504 
505 // Serializes the type code for channel handle types.
506 template <ChannelHandleMode Mode>
507 inline void SerializeType(const ChannelHandle<Mode>& handle, void*& buffer) {
508   SerializeExtEncoding(EncodeType(handle), ENCODING_EXT_TYPE_CHANNEL_HANDLE, 4,
509                        buffer);
510 }
511 
512 // Serializes type code for variant types.
513 template <typename... Types>
514 inline void SerializeType(const Variant<Types...>& value, void*& buffer) {
515   const EncodingType encoding = EncodeType(value);
516   SerializeEncoding(encoding, buffer);
517 }
518 
519 // Serializes the type code for string types.
520 template <typename StringType>
521 inline void SerializeStringType(const StringType& value, void*& buffer) {
522   const EncodingType encoding = EncodeType(value);
523   SerializeEncoding(encoding, buffer);
524   if (encoding == ENCODING_TYPE_STR8) {
525     std::uint8_t length = value.length();
526     SerializeRaw(length, buffer);
527   } else if (encoding == ENCODING_TYPE_STR16) {
528     std::uint16_t length = value.length();
529     SerializeRaw(length, buffer);
530   } else if (encoding == ENCODING_TYPE_STR32) {
531     std::uint32_t length = value.length();
532     SerializeRaw(length, buffer);
533   } else /* if (IsFixstrEncoding(encoding) */ {
534     // Encoding byte contains the fixstr length, nothing else to do.
535   }
536 }
537 
538 // Serializes the type code for std::string and StringWrapper. These types are
539 // interchangeable and must serialize to the same format.
540 inline void SerializeType(const std::string& value, void*& buffer) {
541   SerializeStringType(value, buffer);
542 }
543 template <typename T>
544 inline void SerializeType(const StringWrapper<T>& value, void*& buffer) {
545   SerializeStringType(value, buffer);
546 }
547 
548 // Serializes the type code for bin types.
549 inline void SerializeBinEncoding(EncodingType encoding, std::size_t size,
550                                  void*& buffer) {
551   SerializeEncoding(encoding, buffer);
552   if (encoding == ENCODING_TYPE_BIN8) {
553     std::uint8_t length = size;
554     SerializeRaw(length, buffer);
555   } else if (encoding == ENCODING_TYPE_BIN16) {
556     std::uint16_t length = size;
557     SerializeRaw(length, buffer);
558   } else if (encoding == ENCODING_TYPE_BIN32) {
559     std::uint32_t length = size;
560     SerializeRaw(length, buffer);
561   } else {
562     // Invalid encoding for BIN type.
563   }
564 }
565 
566 // Serializes the type code for BufferWrapper types.
567 template <typename T>
568 inline void SerializeType(const BufferWrapper<T>& value, void*& buffer) {
569   const EncodingType encoding = EncodeType(value);
570   SerializeBinEncoding(
571       encoding, value.size() * sizeof(typename BufferWrapper<T>::value_type),
572       buffer);
573 }
574 
575 // Serializes the array encoding type and length.
576 inline void SerializeArrayEncoding(EncodingType encoding, std::size_t size,
577                                    void*& buffer) {
578   SerializeEncoding(encoding, buffer);
579   if (encoding == ENCODING_TYPE_ARRAY16) {
580     std::uint16_t length = size;
581     SerializeRaw(length, buffer);
582   } else if (encoding == ENCODING_TYPE_ARRAY32) {
583     std::uint32_t length = size;
584     SerializeRaw(length, buffer);
585   } else /* if (IsFixarrayEncoding(encoding) */ {
586     // Encoding byte contains the fixarray length, nothing else to do.
587   }
588 }
589 
590 // Serializes the map encoding type and length.
591 inline void SerializeMapEncoding(EncodingType encoding, std::size_t size,
592                                  void*& buffer) {
593   SerializeEncoding(encoding, buffer);
594   if (encoding == ENCODING_TYPE_MAP16) {
595     std::uint16_t length = size;
596     SerializeRaw(length, buffer);
597   } else if (encoding == ENCODING_TYPE_MAP32) {
598     std::uint32_t length = size;
599     SerializeRaw(length, buffer);
600   } else /* if (IsFixmapEncoding(encoding) */ {
601     // Encoding byte contains the fixmap length, nothing else to do.
602   }
603 }
604 
605 // Serializes the type code for array types.
606 template <typename ArrayType>
607 inline void SerializeArrayType(const ArrayType& value, std::size_t size,
608                                void*& buffer) {
609   const EncodingType encoding = EncodeType(value);
610   SerializeArrayEncoding(encoding, size, buffer);
611 }
612 
613 // Serializes the type code for map types.
614 template <typename MapType>
615 inline void SerializeMapType(const MapType& value, std::size_t size,
616                              void*& buffer) {
617   const EncodingType encoding = EncodeType(value);
618   SerializeMapEncoding(encoding, size, buffer);
619 }
620 
621 // Serializes the type code for std::vector and ArrayWrapper. These types are
622 // interchangeable and must serialize to the same format.
623 template <typename T, typename Allocator>
624 inline void SerializeType(const std::vector<T, Allocator>& value,
625                           void*& buffer) {
626   SerializeArrayType(value, value.size(), buffer);
627 }
628 template <typename T>
629 inline void SerializeType(const ArrayWrapper<T>& value, void*& buffer) {
630   SerializeArrayType(value, value.size(), buffer);
631 }
632 
633 // Serializes the type code for std::array. This type serializes to the same
634 // format as std::vector and ArrayWrapper and is interchangeable in certain
635 // situations.
636 template <typename T, std::size_t Size>
637 inline void SerializeType(const std::array<T, Size>& value, void*& buffer) {
638   SerializeArrayType(value, Size, buffer);
639 }
640 
641 // Serializes the type code for std::map types.
642 template <typename Key, typename T, typename Compare, typename Allocator>
643 inline void SerializeType(const std::map<Key, T, Compare, Allocator>& value,
644                           void*& buffer) {
645   SerializeMapType(value, value.size(), buffer);
646 }
647 
648 // Serializes the type code for std::unordered_map types.
649 template <typename Key, typename T, typename Hash, typename KeyEqual,
650           typename Allocator>
651 inline void SerializeType(
652     const std::unordered_map<Key, T, Hash, KeyEqual, Allocator>& value,
653     void*& buffer) {
654   SerializeMapType(value, value.size(), buffer);
655 }
656 
657 // Serializes the type code for std::pair types.
658 template <typename T, typename U>
659 inline void SerializeType(const std::pair<T, U>& value, void*& buffer) {
660   SerializeArrayType(value, 2, buffer);
661 }
662 
663 // Serializes the type code for std::tuple types.
664 template <typename... T>
665 inline void SerializeType(const std::tuple<T...>& value, void*& buffer) {
666   SerializeArrayType(value, sizeof...(T), buffer);
667 }
668 
669 // Specialization of SerializeObject for boolean type.
670 inline void SerializeObject(const bool& value, MessageWriter* /*writer*/,
671                             void*& buffer) {
672   SerializeType(value, buffer);
673   // Encoding contains the boolean value, nothing else to do.
674 }
675 
676 // Overloads of SerializeObject for float and double types.
677 inline void SerializeObject(const float& value, MessageWriter* /*writer*/,
678                             void*& buffer) {
679   const EncodingType encoding = EncodeType(value);
680   SerializeEncoding(encoding, buffer);
681   SerializeRaw(value, buffer);
682 }
683 
684 inline void SerializeObject(const double& value, MessageWriter* /*writer*/,
685                             void*& buffer) {
686   const EncodingType encoding = EncodeType(value);
687   SerializeEncoding(encoding, buffer);
688   SerializeRaw(value, buffer);
689 }
690 
691 // Overloads of SerializeObject() for standard integer types.
692 inline void SerializeObject(const char& value, MessageWriter* /*writer*/,
693                             void*& buffer) {
694   const EncodingType encoding = EncodeType(value);
695   SerializeEncoding(encoding, buffer);
696   if (encoding == ENCODING_TYPE_UINT8) {
697     SerializeRaw(value, buffer);
698   } else /* if (IsUnsignedFixintEncoding(encoding) */ {
699     // Encoding byte contains the value, nothing else to do.
700   }
701 }
702 
703 inline void SerializeObject(const int8_t& value, MessageWriter* /*writer*/,
704                             void*& buffer) {
705   const EncodingType encoding = EncodeType(value);
706   SerializeEncoding(encoding, buffer);
707   if (encoding == ENCODING_TYPE_INT8) {
708     SerializeRaw(value, buffer);
709   } else /* if (IsFixintEncoding(encoding) */ {
710     // Encoding byte contains the value, nothing else to do.
711   }
712 }
713 
714 inline void SerializeObject(const uint8_t& value, MessageWriter* /*writer*/,
715                             void*& buffer) {
716   const EncodingType encoding = EncodeType(value);
717   SerializeEncoding(encoding, buffer);
718   if (encoding == ENCODING_TYPE_UINT8) {
719     SerializeRaw(value, buffer);
720   } else /* if (IsUnsignedFixintEncoding(encoding) */ {
721     // Encoding byte contains the value, nothing else to do.
722   }
723 }
724 
725 inline void SerializeObject(const int16_t& value, MessageWriter* /*writer*/,
726                             void*& buffer) {
727   const EncodingType encoding = EncodeType(value);
728   SerializeEncoding(encoding, buffer);
729   if (encoding == ENCODING_TYPE_INT8) {
730     const int8_t byte = value;
731     SerializeRaw(byte, buffer);
732   } else if (encoding == ENCODING_TYPE_INT16) {
733     SerializeRaw(value, buffer);
734   } else /* if (IsFixintEncoding(encoding) */ {
735     // Encoding byte contains the value, nothing else to do.
736   }
737 }
738 
739 inline void SerializeObject(const uint16_t& value, MessageWriter* /*writer*/,
740                             void*& buffer) {
741   const EncodingType encoding = EncodeType(value);
742   SerializeEncoding(encoding, buffer);
743   if (encoding == ENCODING_TYPE_UINT8) {
744     const uint8_t byte = value;
745     SerializeRaw(byte, buffer);
746   } else if (encoding == ENCODING_TYPE_UINT16) {
747     SerializeRaw(value, buffer);
748   } else /* if (IsUnsignedFixintEncoding(encoding) */ {
749     // Encoding byte contains the value, nothing else to do.
750   }
751 }
752 
753 inline void SerializeObject(const int32_t& value, MessageWriter* /*writer*/,
754                             void*& buffer) {
755   const EncodingType encoding = EncodeType(value);
756   SerializeEncoding(encoding, buffer);
757   if (encoding == ENCODING_TYPE_INT8) {
758     const int8_t byte = value;
759     SerializeRaw(byte, buffer);
760   } else if (encoding == ENCODING_TYPE_INT16) {
761     const int16_t half = value;
762     SerializeRaw(half, buffer);
763   } else if (encoding == ENCODING_TYPE_INT32) {
764     SerializeRaw(value, buffer);
765   } else /* if (IsFixintEncoding(encoding) */ {
766     // Encoding byte contains the value, nothing else to do.
767   }
768 }
769 
770 inline void SerializeObject(const uint32_t& value, MessageWriter* /*writer*/,
771                             void*& buffer) {
772   const EncodingType encoding = EncodeType(value);
773   SerializeEncoding(encoding, buffer);
774   if (encoding == ENCODING_TYPE_UINT8) {
775     const uint8_t byte = value;
776     SerializeRaw(byte, buffer);
777   } else if (encoding == ENCODING_TYPE_UINT16) {
778     const uint16_t half = value;
779     SerializeRaw(half, buffer);
780   } else if (encoding == ENCODING_TYPE_UINT32) {
781     SerializeRaw(value, buffer);
782   } else /* if (IsUnsignedFixintEncoding(encoding) */ {
783     // Encoding byte contains the value, nothing else to do.
784   }
785 }
786 
787 inline void SerializeObject(const int64_t& value, MessageWriter* /*writer*/,
788                             void*& buffer) {
789   const EncodingType encoding = EncodeType(value);
790   SerializeEncoding(encoding, buffer);
791   if (encoding == ENCODING_TYPE_INT8) {
792     const int8_t byte = value;
793     SerializeRaw(byte, buffer);
794   } else if (encoding == ENCODING_TYPE_INT16) {
795     const int16_t half = value;
796     SerializeRaw(half, buffer);
797   } else if (encoding == ENCODING_TYPE_INT32) {
798     const int32_t word = value;
799     SerializeRaw(word, buffer);
800   } else if (encoding == ENCODING_TYPE_INT64) {
801     SerializeRaw(value, buffer);
802   } else /* if (IsFixintEncoding(encoding) */ {
803     // Encoding byte contains the value, nothing else to do.
804   }
805 }
806 
807 inline void SerializeObject(const uint64_t& value, MessageWriter* /*writer*/,
808                             void*& buffer) {
809   const EncodingType encoding = EncodeType(value);
810   SerializeEncoding(encoding, buffer);
811   if (encoding == ENCODING_TYPE_UINT8) {
812     const uint8_t byte = value;
813     SerializeRaw(byte, buffer);
814   } else if (encoding == ENCODING_TYPE_UINT16) {
815     const uint16_t half = value;
816     SerializeRaw(half, buffer);
817   } else if (encoding == ENCODING_TYPE_UINT32) {
818     const uint32_t word = value;
819     SerializeRaw(word, buffer);
820   } else if (encoding == ENCODING_TYPE_UINT64) {
821     SerializeRaw(value, buffer);
822   } else /* if (IsUnsignedFixintEncoding(encoding) */ {
823     // Encoding byte contains the value, nothing else to do.
824   }
825 }
826 
827 // Serialize enum types.
828 template <typename T>
829 inline EnableIfEnum<T> SerializeObject(const T& value, MessageWriter* writer,
830                                        void*& buffer) {
831   SerializeObject(static_cast<std::underlying_type_t<T>>(value), writer,
832                   buffer);
833 }
834 
835 // Forward declaration for nested definitions.
836 inline void SerializeObject(const EmptyVariant&, MessageWriter*, void*&);
837 template <typename... Types>
838 inline void SerializeObject(const Variant<Types...>&, MessageWriter*, void*&);
839 template <typename T, typename Enabled = EnableIfHasSerializableMembers<T>>
840 inline void SerializeObject(const T&, MessageWriter*, void*&);
841 template <typename T>
842 inline void SerializeObject(const PointerWrapper<T>&, MessageWriter*, void*&);
843 template <FileHandleMode Mode>
844 inline void SerializeObject(const FileHandle<Mode>&, MessageWriter*, void*&);
845 template <ChannelHandleMode Mode>
846 inline void SerializeObject(const ChannelHandle<Mode>&, MessageWriter*, void*&);
847 template <typename T, typename Allocator>
848 inline void SerializeObject(const BufferWrapper<std::vector<T, Allocator>>&, MessageWriter*, void*&);
849 template <typename T>
850 inline void SerializeObject(const BufferWrapper<T*>&, MessageWriter*, void*&);
851 inline void SerializeObject(const std::string&, MessageWriter*, void*&);
852 template <typename T>
853 inline void SerializeObject(const StringWrapper<T>&, MessageWriter*, void*&);
854 template <typename T, typename Allocator>
855 inline void SerializeObject(const std::vector<T, Allocator>&, MessageWriter*, void*&);
856 template <typename T>
857 inline void SerializeObject(const ArrayWrapper<T>&, MessageWriter*, void*&);
858 template <typename T, std::size_t Size>
859 inline void SerializeObject(const std::array<T, Size>&, MessageWriter*, void*&);
860 template <typename Key, typename T, typename Compare, typename Allocator>
861 inline void SerializeObject(const std::map<Key, T, Compare, Allocator>&, MessageWriter*, void*&);
862 template <typename Key, typename T, typename Hash, typename KeyEqual,
863           typename Allocator>
864 inline void SerializeObject(
865     const std::unordered_map<Key, T, Hash, KeyEqual, Allocator>&, MessageWriter*, void*&);
866 template <typename T, typename U>
867 inline void SerializeObject(const std::pair<T, U>&, MessageWriter*, void*&);
868 template <typename... T>
869 inline void SerializeObject(const std::tuple<T...>&, MessageWriter*, void*&);
870 
871 // Overload for empty variant type.
872 inline void SerializeObject(const EmptyVariant& empty,
873                             MessageWriter* /*writer*/, void*& buffer) {
874   const EncodingType encoding = EncodeType(empty);
875   SerializeEncoding(encoding, buffer);
876 }
877 
878 // Overload for Variant types.
879 template <typename... Types>
880 inline void SerializeObject(const Variant<Types...>& variant,
881                             MessageWriter* writer, void*& buffer) {
882   SerializeType(variant, buffer);
883   SerializeObject(variant.index(), writer, buffer);
884   return variant.Visit([writer, &buffer](const auto& value) {
885     return SerializeObject(value, writer, buffer);
886   });
887 }
888 
889 // Overload for serializable structure/class types.
890 template <typename T, typename Enabled>
891 inline void SerializeObject(const T& value, MessageWriter* writer,
892                             void*& buffer) {
893   SerializableTraits<T>::SerializeObject(value, writer, buffer);
894 }
895 
896 // Serializes the payload of a PointerWrapper.
897 template <typename T>
898 inline void SerializeObject(const PointerWrapper<T>& pointer,
899                             MessageWriter* writer, void*& buffer) {
900   SerializeObject(pointer.Dereference(), writer, buffer);
901 }
902 
903 // Serializes the payload of file descriptor types.
904 template <FileHandleMode Mode>
905 inline void SerializeObject(const FileHandle<Mode>& fd, MessageWriter* writer,
906                             void*& buffer) {
907   SerializeType(fd, buffer);
908   const Status<FileReference> status =
909       writer->GetOutputResourceMapper()->PushFileHandle(fd);
910   FileReference value = status ? status.get() : -status.error();
911   SerializeRaw(value, buffer);
912 }
913 
914 // Serializes the payload of channel handle types.
915 template <ChannelHandleMode Mode>
916 inline void SerializeObject(const ChannelHandle<Mode>& handle,
917                             MessageWriter* writer, void*& buffer) {
918   SerializeType(handle, buffer);
919   const Status<ChannelReference> status =
920       writer->GetOutputResourceMapper()->PushChannelHandle(handle);
921   ChannelReference value = status ? status.get() : -status.error();
922   SerializeRaw(value, buffer);
923 }
924 
925 // Serializes the payload of BufferWrapper types.
926 template <typename T, typename Allocator>
927 inline void SerializeObject(const BufferWrapper<std::vector<T, Allocator>>& b,
928                             MessageWriter* /*writer*/, void*& buffer) {
929   const auto value_type_size =
930       sizeof(typename BufferWrapper<std::vector<T, Allocator>>::value_type);
931   SerializeType(b, buffer);
932   WriteRawData(buffer, b.data(), b.size() * value_type_size);
933 }
934 template <typename T>
935 inline void SerializeObject(const BufferWrapper<T*>& b,
936                             MessageWriter* /*writer*/, void*& buffer) {
937   const auto value_type_size = sizeof(typename BufferWrapper<T*>::value_type);
938   SerializeType(b, buffer);
939   WriteRawData(buffer, b.data(), b.size() * value_type_size);
940 }
941 
942 // Serializes the payload of string types.
943 template <typename StringType>
944 inline void SerializeString(const StringType& s, void*& buffer) {
945   const auto value_type_size = sizeof(typename StringType::value_type);
946   SerializeType(s, buffer);
947   WriteRawData(buffer, s.data(), s.length() * value_type_size);
948 }
949 
950 // Overload of SerializeObject() for std::string and StringWrapper. These types
951 // are interchangeable and must serialize to the same format.
952 inline void SerializeObject(const std::string& s, MessageWriter* /*writer*/,
953                             void*& buffer) {
954   SerializeString(s, buffer);
955 }
956 template <typename T>
957 inline void SerializeObject(const StringWrapper<T>& s,
958                             MessageWriter* /*writer*/, void*& buffer) {
959   SerializeString(s, buffer);
960 }
961 
962 // Serializes the payload of array types.
963 template <typename ArrayType>
964 inline void SerializeArray(const ArrayType& v, MessageWriter* writer,
965                            void*& buffer) {
966   SerializeType(v, buffer);
967   for (const auto& element : v)
968     SerializeObject(element, writer, buffer);
969 }
970 
971 // Serializes the payload for map types.
972 template <typename MapType>
973 inline void SerializeMap(const MapType& v, MessageWriter* writer,
974                          void*& buffer) {
975   SerializeType(v, buffer);
976   for (const auto& element : v) {
977     SerializeObject(element.first, writer, buffer);
978     SerializeObject(element.second, writer, buffer);
979   }
980 }
981 
982 // Overload of SerializeObject() for std::vector and ArrayWrapper types. These
983 // types are interchangeable and must serialize to the same format.
984 template <typename T, typename Allocator>
985 inline void SerializeObject(const std::vector<T, Allocator>& v,
986                             MessageWriter* writer, void*& buffer) {
987   SerializeArray(v, writer, buffer);
988 }
989 template <typename T>
990 inline void SerializeObject(const ArrayWrapper<T>& v, MessageWriter* writer,
991                             void*& buffer) {
992   SerializeArray(v, writer, buffer);
993 }
994 
995 // Overload of SerializeObject() for std::array types. These types serialize to
996 // the same format at std::vector and ArrayWrapper and are interchangeable in
997 // certain situations.
998 template <typename T, std::size_t Size>
999 inline void SerializeObject(const std::array<T, Size>& v, MessageWriter* writer,
1000                             void*& buffer) {
1001   SerializeArray(v, writer, buffer);
1002 }
1003 
1004 // Overload of SerializeObject() for std::map types.
1005 template <typename Key, typename T, typename Compare, typename Allocator>
1006 inline void SerializeObject(const std::map<Key, T, Compare, Allocator>& v,
1007                             MessageWriter* writer, void*& buffer) {
1008   SerializeMap(v, writer, buffer);
1009 }
1010 
1011 // Overload of SerializeObject() for std::unordered_map types.
1012 template <typename Key, typename T, typename Hash, typename KeyEqual,
1013           typename Allocator>
1014 inline void SerializeObject(
1015     const std::unordered_map<Key, T, Hash, KeyEqual, Allocator>& v,
1016     MessageWriter* writer, void*& buffer) {
1017   SerializeMap(v, writer, buffer);
1018 }
1019 
1020 // Overload of SerializeObject() for std:pair types.
1021 template <typename T, typename U>
1022 inline void SerializeObject(const std::pair<T, U>& pair, MessageWriter* writer,
1023                             void*& buffer) {
1024   SerializeType(pair, buffer);
1025   SerializeObject(pair.first, writer, buffer);
1026   SerializeObject(pair.second, writer, buffer);
1027 }
1028 
1029 // Stops template recursion when the last tuple element is reached.
1030 template <typename... T>
1031 inline void SerializeTuple(const std::tuple<T...>&, MessageWriter*, void*&,
1032                            Index<0>) {}
1033 
1034 // Serializes each element of a tuple recursively.
1035 template <typename... T, std::size_t index>
1036 inline void SerializeTuple(const std::tuple<T...>& tuple, MessageWriter* writer,
1037                            void*& buffer, Index<index>) {
1038   SerializeTuple(tuple, writer, buffer, Index<index - 1>());
1039   SerializeObject(std::get<index - 1>(tuple), writer, buffer);
1040 }
1041 
1042 // Overload of SerializeObject() for tuple types.
1043 template <typename... T>
1044 inline void SerializeObject(const std::tuple<T...>& tuple,
1045                             MessageWriter* writer, void*& buffer) {
1046   SerializeType(tuple, buffer);
1047   SerializeTuple(tuple, writer, buffer, Index<sizeof...(T)>());
1048 }
1049 
1050 // Stops template recursion when the last member pointer is reached.
1051 template <typename Members, typename T>
1052 inline void SerializeMember(const T&, MessageWriter*, void*&, Index<0>) {}
1053 
1054 // Serializes each member pointer recursively.
1055 template <typename Members, typename T, std::size_t index>
1056 inline void SerializeMember(const T& object, MessageWriter* writer,
1057                             void*& buffer, Index<index>) {
1058   SerializeMember<Members>(object, writer, buffer, Index<index - 1>());
1059   SerializeObject(Members::template At<index - 1>::Resolve(object), writer,
1060                   buffer);
1061 }
1062 
1063 // Serializes the members of a type using the given SerializableMembersType
1064 // type.
1065 template <typename Members, typename T>
1066 inline void SerializeMembers(const T& object, MessageWriter* writer,
1067                              void*& buffer) {
1068   SerializeMember<Members>(object, writer, buffer,
1069                            Index<Members::MemberCount>());
1070 }
1071 
1072 // Top level serialization function that replaces the buffer's contents.
1073 template <typename T>
1074 inline void Serialize(const T& object, MessageWriter* writer) {
1075   PDX_TRACE_NAME("Serialize");
1076   const std::size_t size = GetSerializedSize(object);
1077 
1078   // Reserve the space needed for the object(s).
1079   void* buffer = writer->GetNextWriteBufferSection(size);
1080   SerializeObject(object, writer, buffer);
1081 }
1082 
1083 ///////////////////////////////////////////////////////////////////////////////
1084 // Object Deserialization //
1085 ///////////////////////////////////////////////////////////////////////////////
1086 
1087 inline ErrorType ReadRawDataFromNextSection(void* dest, MessageReader* reader,
1088                                             const void*& start,
1089                                             const void*& end, size_t size) {
1090   while (AdvancePointer(start, size) > end) {
1091     auto remaining_size = PointerDistance(end, start);
1092     if (remaining_size > 0) {
1093       memcpy(dest, start, remaining_size);
1094       dest = AdvancePointer(dest, remaining_size);
1095       size -= remaining_size;
1096     }
1097     reader->ConsumeReadBufferSectionData(AdvancePointer(start, remaining_size));
1098     std::tie(start, end) = reader->GetNextReadBufferSection();
1099     if (start == end)
1100       return ErrorCode::INSUFFICIENT_BUFFER;
1101   }
1102   memcpy(dest, start, size);
1103   start = AdvancePointer(start, size);
1104   return ErrorCode::NO_ERROR;
1105 }
1106 
1107 inline ErrorType ReadRawData(void* dest, MessageReader* /*reader*/,
1108                              const void*& start, const void*& end,
1109                              size_t size) {
1110   if (PDX_UNLIKELY(AdvancePointer(start, size) > end)) {
1111     // TODO(avakulenko): Enabling reading from next sections of input buffer
1112     // (using ReadRawDataFromNextSection) screws up clang compiler optimizations
1113     // (probably inefficient inlining) making the whole deserialization
1114     // code path about twice as slow. Investigate and enable more generic
1115     // deserialization code, but right now we don't really need/support this
1116     // scenario, so I keep this commented out for the time being...
1117 
1118     // return ReadRawDataFromNextSection(dest, reader, start, end, size);
1119     return ErrorCode::INSUFFICIENT_BUFFER;
1120   }
1121   memcpy(dest, start, size);
1122   start = AdvancePointer(start, size);
1123   return ErrorCode::NO_ERROR;
1124 }
1125 
1126 // Deserializes a primitive object from raw bytes.
1127 template <typename T,
1128           typename = typename std::enable_if<std::is_pod<T>::value>::type>
1129 inline ErrorType DeserializeRaw(T* value, MessageReader* reader,
1130                                 const void*& start, const void*& end) {
1131   return ReadRawData(value, reader, start, end, sizeof(T));
1132 }
1133 
1134 // Utility to deserialize POD types when the serialized type is different
1135 // (smaller) than the target real type. This happens when values are serialized
1136 // into more compact encodings.
1137 template <typename SerializedType, typename RealType>
1138 ErrorType DeserializeValue(RealType* real_value, MessageReader* reader,
1139                            const void*& start, const void*& end) {
1140   SerializedType serialized_value;
1141   if (const auto error =
1142           DeserializeRaw(&serialized_value, reader, start, end)) {
1143     return error;
1144   } else {
1145     *real_value = serialized_value;
1146     return ErrorCode::NO_ERROR;
1147   }
1148 }
1149 
1150 inline ErrorType DeserializeEncoding(EncodingType* encoding,
1151                                      MessageReader* reader, const void*& start,
1152                                      const void*& end) {
1153   return DeserializeRaw(encoding, reader, start, end);
1154 }
1155 
1156 // Overload to deserialize bool type.
1157 inline ErrorType DeserializeObject(bool* value, MessageReader* reader,
1158                                    const void*& start, const void*& end) {
1159   EncodingType encoding;
1160   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1161     return error;
1162   } else if (IsBoolEncoding(encoding)) {
1163     *value = (encoding == ENCODING_TYPE_TRUE);
1164     return ErrorCode::NO_ERROR;
1165   } else {
1166     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_BOOL,
1167                      encoding);
1168   }
1169 }
1170 
1171 // Specializations to deserialize float and double types.
1172 inline ErrorType DeserializeObject(float* value, MessageReader* reader,
1173                                    const void*& start, const void*& end) {
1174   EncodingType encoding;
1175   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1176     return error;
1177   } else if (IsFloat32Encoding(encoding)) {
1178     return DeserializeValue<float>(value, reader, start, end);
1179   } else {
1180     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_FLOAT,
1181                      encoding);
1182   }
1183 }
1184 
1185 inline ErrorType DeserializeObject(double* value, MessageReader* reader,
1186                                    const void*& start, const void*& end) {
1187   EncodingType encoding;
1188   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1189     return error;
1190   } else if (IsFloat32Encoding(encoding)) {
1191     return DeserializeValue<float>(value, reader, start, end);
1192   } else if (IsFloat64Encoding(encoding)) {
1193     return DeserializeValue<double>(value, reader, start, end);
1194   } else {
1195     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_FLOAT,
1196                      encoding);
1197   }
1198 }
1199 
1200 // Specializations to deserialize standard integer types.
1201 inline ErrorType DeserializeObject(char* value, MessageReader* reader,
1202                                    const void*& start, const void*& end) {
1203   EncodingType encoding;
1204   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1205     return error;
1206   } else if (IsUnsignedFixintEncoding(encoding)) {
1207     *value = static_cast<char>(encoding);
1208     return ErrorCode::NO_ERROR;
1209   } else if (IsUInt8Encoding(encoding)) {
1210     return DeserializeValue<char>(value, reader, start, end);
1211   } else {
1212     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_UINT,
1213                      encoding);
1214   }
1215 }
1216 
1217 inline ErrorType DeserializeObject(std::int8_t* value, MessageReader* reader,
1218                                    const void*& start, const void*& end) {
1219   EncodingType encoding;
1220   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1221     return error;
1222   } else if (IsFixintEncoding(encoding)) {
1223     *value = static_cast<std::int8_t>(encoding);
1224     return ErrorCode::NO_ERROR;
1225   } else if (IsInt8Encoding(encoding)) {
1226     return DeserializeValue<std::int8_t>(value, reader, start, end);
1227   } else {
1228     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_INT,
1229                      encoding);
1230   }
1231 }
1232 
1233 inline ErrorType DeserializeObject(std::uint8_t* value, MessageReader* reader,
1234                                    const void*& start, const void*& end) {
1235   EncodingType encoding;
1236   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1237     return error;
1238   } else if (IsUnsignedFixintEncoding(encoding)) {
1239     *value = encoding;
1240     return ErrorCode::NO_ERROR;
1241   } else if (IsUInt8Encoding(encoding)) {
1242     return DeserializeValue<std::uint8_t>(value, reader, start, end);
1243   } else {
1244     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_UINT,
1245                      encoding);
1246   }
1247 }
1248 
1249 inline ErrorType DeserializeObject(std::int16_t* value, MessageReader* reader,
1250                                    const void*& start, const void*& end) {
1251   EncodingType encoding;
1252   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1253     return error;
1254   } else if (IsFixintEncoding(encoding)) {
1255     *value = static_cast<std::int8_t>(encoding);
1256     return ErrorCode::NO_ERROR;
1257   } else if (IsInt8Encoding(encoding)) {
1258     return DeserializeValue<std::int8_t>(value, reader, start, end);
1259   } else if (IsInt16Encoding(encoding)) {
1260     return DeserializeValue<std::int16_t>(value, reader, start, end);
1261   } else {
1262     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_INT,
1263                      encoding);
1264   }
1265 }
1266 
1267 inline ErrorType DeserializeObject(std::uint16_t* value, MessageReader* reader,
1268                                    const void*& start, const void*& end) {
1269   EncodingType encoding;
1270   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1271     return error;
1272   } else if (IsUnsignedFixintEncoding(encoding)) {
1273     *value = encoding;
1274     return ErrorCode::NO_ERROR;
1275   } else if (IsUInt8Encoding(encoding)) {
1276     return DeserializeValue<std::uint8_t>(value, reader, start, end);
1277   } else if (IsUInt16Encoding(encoding)) {
1278     return DeserializeValue<std::uint16_t>(value, reader, start, end);
1279   } else {
1280     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_UINT,
1281                      encoding);
1282   }
1283 }
1284 
1285 inline ErrorType DeserializeObject(std::int32_t* value, MessageReader* reader,
1286                                    const void*& start, const void*& end) {
1287   EncodingType encoding;
1288   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1289     return error;
1290   } else if (IsFixintEncoding(encoding)) {
1291     *value = static_cast<std::int8_t>(encoding);
1292     return ErrorCode::NO_ERROR;
1293   } else if (IsInt8Encoding(encoding)) {
1294     return DeserializeValue<std::int8_t>(value, reader, start, end);
1295   } else if (IsInt16Encoding(encoding)) {
1296     return DeserializeValue<std::int16_t>(value, reader, start, end);
1297   } else if (IsInt32Encoding(encoding)) {
1298     return DeserializeValue<std::int32_t>(value, reader, start, end);
1299   } else {
1300     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_INT,
1301                      encoding);
1302   }
1303 }
1304 
1305 inline ErrorType DeserializeObject(std::uint32_t* value, MessageReader* reader,
1306                                    const void*& start, const void*& end) {
1307   EncodingType encoding;
1308   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1309     return error;
1310   } else if (IsUnsignedFixintEncoding(encoding)) {
1311     *value = encoding;
1312     return ErrorCode::NO_ERROR;
1313   } else if (IsUInt8Encoding(encoding)) {
1314     return DeserializeValue<std::uint8_t>(value, reader, start, end);
1315   } else if (IsUInt16Encoding(encoding)) {
1316     return DeserializeValue<std::uint16_t>(value, reader, start, end);
1317   } else if (IsUInt32Encoding(encoding)) {
1318     return DeserializeValue<std::uint32_t>(value, reader, start, end);
1319   } else {
1320     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_UINT,
1321                      encoding);
1322   }
1323 }
1324 
1325 inline ErrorType DeserializeObject(std::int64_t* value, MessageReader* reader,
1326                                    const void*& start, const void*& end) {
1327   EncodingType encoding;
1328   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1329     return error;
1330   } else if (IsFixintEncoding(encoding)) {
1331     *value = static_cast<std::int8_t>(encoding);
1332     return ErrorCode::NO_ERROR;
1333   } else if (IsInt8Encoding(encoding)) {
1334     return DeserializeValue<std::int8_t>(value, reader, start, end);
1335   } else if (IsInt16Encoding(encoding)) {
1336     return DeserializeValue<std::int16_t>(value, reader, start, end);
1337   } else if (IsInt32Encoding(encoding)) {
1338     return DeserializeValue<std::int32_t>(value, reader, start, end);
1339   } else if (IsInt64Encoding(encoding)) {
1340     return DeserializeValue<std::int64_t>(value, reader, start, end);
1341   } else {
1342     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_INT,
1343                      encoding);
1344   }
1345 }
1346 
1347 inline ErrorType DeserializeObject(std::uint64_t* value, MessageReader* reader,
1348                                    const void*& start, const void*& end) {
1349   EncodingType encoding;
1350   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1351     return error;
1352   } else if (IsUnsignedFixintEncoding(encoding)) {
1353     *value = encoding;
1354     return ErrorCode::NO_ERROR;
1355   } else if (IsUInt8Encoding(encoding)) {
1356     return DeserializeValue<std::uint8_t>(value, reader, start, end);
1357   } else if (IsUInt16Encoding(encoding)) {
1358     return DeserializeValue<std::uint16_t>(value, reader, start, end);
1359   } else if (IsUInt32Encoding(encoding)) {
1360     return DeserializeValue<std::uint32_t>(value, reader, start, end);
1361   } else if (IsUInt64Encoding(encoding)) {
1362     return DeserializeValue<std::uint64_t>(value, reader, start, end);
1363   } else {
1364     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_UINT,
1365                      encoding);
1366   }
1367 }
1368 
1369 template <typename T>
1370 inline EnableIfEnum<T, ErrorType> DeserializeObject(T* value,
1371                                                     MessageReader* reader,
1372                                                     const void*& start,
1373                                                     const void*& end) {
1374   std::underlying_type_t<T> enum_value;
1375   ErrorType error = DeserializeObject(&enum_value, reader, start, end);
1376   if (!error)
1377     *value = static_cast<T>(enum_value);
1378   return error;
1379 }
1380 
1381 // Forward declarations for nested definitions.
1382 template <typename T, typename Enabled = EnableIfHasSerializableMembers<T>>
1383 inline ErrorType DeserializeObject(T*, MessageReader*, const void*&,
1384                                    const void*&);
1385 template <typename T>
1386 inline ErrorType DeserializeObject(PointerWrapper<T>*, MessageReader*,
1387                                    const void*&, const void*&);
1388 inline ErrorType DeserializeObject(LocalHandle*, MessageReader*, const void*&,
1389                                    const void*&);
1390 inline ErrorType DeserializeObject(LocalChannelHandle*, MessageReader*,
1391                                    const void*&, const void*&);
1392 template <typename T, typename Allocator>
1393 inline ErrorType DeserializeObject(BufferWrapper<std::vector<T, Allocator>>*,
1394                                    MessageReader*, const void*&, const void*&);
1395 template <typename T>
1396 inline ErrorType DeserializeObject(BufferWrapper<T*>*, MessageReader*,
1397                                    const void*&, const void*&);
1398 inline ErrorType DeserializeObject(std::string*, MessageReader*, const void*&,
1399                                    const void*&);
1400 template <typename T>
1401 inline ErrorType DeserializeObject(StringWrapper<T>*, MessageReader*,
1402                                    const void*&, const void*&);
1403 template <typename T, typename U>
1404 inline ErrorType DeserializeObject(std::pair<T, U>*, MessageReader*,
1405                                    const void*&, const void*&);
1406 template <typename... T>
1407 inline ErrorType DeserializeObject(std::tuple<T...>*, MessageReader*,
1408                                    const void*&, const void*&);
1409 template <typename T, typename Allocator>
1410 inline ErrorType DeserializeObject(std::vector<T, Allocator>*, MessageReader*,
1411                                    const void*&, const void*&);
1412 template <typename Key, typename T, typename Compare, typename Allocator>
1413 inline ErrorType DeserializeObject(std::map<Key, T, Compare, Allocator>*,
1414                                    MessageReader*, const void*&, const void*&);
1415 template <typename Key, typename T, typename Hash, typename KeyEqual,
1416           typename Allocator>
1417 inline ErrorType DeserializeObject(
1418     std::unordered_map<Key, T, Hash, KeyEqual, Allocator>*, MessageReader*,
1419     const void*&, const void*&);
1420 template <typename T>
1421 inline ErrorType DeserializeObject(ArrayWrapper<T>*, MessageReader*,
1422                                    const void*&, const void*&);
1423 template <typename T, std::size_t Size>
1424 inline ErrorType DeserializeObject(std::array<T, Size>*, MessageReader*,
1425                                    const void*&, const void*&);
1426 template <typename T, typename U>
1427 inline ErrorType DeserializeObject(std::pair<T, U>*, MessageReader*,
1428                                    const void*&, const void*&);
1429 template <typename... T>
1430 inline ErrorType DeserializeObject(std::tuple<T...>*, MessageReader*,
1431                                    const void*&, const void*&);
1432 inline ErrorType DeserializeObject(EmptyVariant*,
1433                                    MessageReader*, const void*&,
1434                                    const void*&);
1435 template <typename... Types>
1436 inline ErrorType DeserializeObject(Variant<Types...>*,
1437                                    MessageReader*, const void*&,
1438                                    const void*&);
1439 
1440 // Deserializes a Serializable type.
1441 template <typename T, typename Enable>
1442 inline ErrorType DeserializeObject(T* value, MessageReader* reader,
1443                                    const void*& start, const void*& end) {
1444   return SerializableTraits<T>::DeserializeObject(value, reader, start, end);
1445 }
1446 
1447 // Deserializes a PointerWrapper.
1448 template <typename T>
1449 inline ErrorType DeserializeObject(PointerWrapper<T>* pointer,
1450                                    MessageReader* reader, const void*& start,
1451                                    const void*& end) {
1452   return DeserializeObject(&pointer->Dereference(), reader, start, end);
1453 }
1454 
1455 // Deserializes the type code and size for extension types.
1456 inline ErrorType DeserializeExtType(EncodingType* encoding,
1457                                     EncodingExtType* type, std::size_t* size,
1458                                     MessageReader* reader, const void*& start,
1459                                     const void*& end) {
1460   if (const auto error = DeserializeEncoding(encoding, reader, start, end)) {
1461     return error;
1462   } else if (IsFixextEncoding(*encoding)) {
1463     *size = GetFixextSize(*encoding);
1464   } else if (*encoding == ENCODING_TYPE_EXT8) {
1465     if (const auto error =
1466             DeserializeValue<std::uint8_t>(size, reader, start, end))
1467       return error;
1468   } else if (*encoding == ENCODING_TYPE_EXT16) {
1469     if (const auto error =
1470             DeserializeValue<std::uint16_t>(size, reader, start, end))
1471       return error;
1472   } else if (*encoding == ENCODING_TYPE_EXT32) {
1473     if (const auto error =
1474             DeserializeValue<std::uint32_t>(size, reader, start, end))
1475       return error;
1476   } else {
1477     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_EXTENSION,
1478                      *encoding);
1479   }
1480 
1481   // The extension type code follows the encoding and size.
1482   return DeserializeRaw(type, reader, start, end);
1483 }
1484 
1485 // Deserializes a file handle and performs handle space translation, if
1486 // required.
1487 inline ErrorType DeserializeObject(LocalHandle* value, MessageReader* reader,
1488                                    const void*& start, const void*& end) {
1489   EncodingType encoding;
1490   EncodingExtType type;
1491   std::size_t size;
1492 
1493   if (const auto error =
1494           DeserializeExtType(&encoding, &type, &size, reader, start, end)) {
1495     return error;
1496   } else if (size != 2) {
1497     return ErrorType(ErrorCode::UNEXPECTED_TYPE_SIZE, ENCODING_CLASS_EXTENSION,
1498                      encoding);
1499   } else if (type == ENCODING_EXT_TYPE_FILE_DESCRIPTOR) {
1500     // Read the encoded file descriptor value.
1501     FileReference ref;
1502     if (const auto error = DeserializeRaw(&ref, reader, start, end)) {
1503       return error;
1504     }
1505 
1506     return reader->GetInputResourceMapper()->GetFileHandle(ref, value)
1507                ? ErrorCode::NO_ERROR
1508                : ErrorCode::GET_FILE_DESCRIPTOR_FAILED;
1509   } else {
1510     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_EXTENSION,
1511                      encoding);
1512   }
1513 }
1514 
1515 inline ErrorType DeserializeObject(LocalChannelHandle* value,
1516                                    MessageReader* reader, const void*& start,
1517                                    const void*& end) {
1518   EncodingType encoding;
1519   EncodingExtType type;
1520   std::size_t size;
1521 
1522   if (const auto error =
1523           DeserializeExtType(&encoding, &type, &size, reader, start, end)) {
1524     return error;
1525   } else if (size != 4) {
1526     return ErrorType(ErrorCode::UNEXPECTED_TYPE_SIZE, ENCODING_CLASS_EXTENSION,
1527                      encoding);
1528   } else if (type == ENCODING_EXT_TYPE_CHANNEL_HANDLE) {
1529     // Read the encoded channel handle value.
1530     ChannelReference ref;
1531     if (const auto error = DeserializeRaw(&ref, reader, start, end)) {
1532       return error;
1533     }
1534     return reader->GetInputResourceMapper()->GetChannelHandle(ref, value)
1535                ? ErrorCode::NO_ERROR
1536                : ErrorCode::GET_CHANNEL_HANDLE_FAILED;
1537   } else {
1538     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_EXTENSION,
1539                      encoding);
1540   }
1541 }
1542 
1543 // Deserializes the type code and size for bin types.
1544 inline ErrorType DeserializeBinType(EncodingType* encoding, std::size_t* size,
1545                                     MessageReader* reader, const void*& start,
1546                                     const void*& end) {
1547   if (const auto error = DeserializeEncoding(encoding, reader, start, end)) {
1548     return error;
1549   } else if (*encoding == ENCODING_TYPE_BIN8) {
1550     return DeserializeValue<std::uint8_t>(size, reader, start, end);
1551   } else if (*encoding == ENCODING_TYPE_BIN16) {
1552     return DeserializeValue<std::uint16_t>(size, reader, start, end);
1553   } else if (*encoding == ENCODING_TYPE_BIN32) {
1554     return DeserializeValue<std::uint32_t>(size, reader, start, end);
1555   } else {
1556     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_BINARY,
1557                      *encoding);
1558   }
1559 }
1560 
1561 // Overload of DeserializeObject() for BufferWrapper types.
1562 template <typename T, typename Allocator>
1563 inline ErrorType DeserializeObject(
1564     BufferWrapper<std::vector<T, Allocator>>* value, MessageReader* reader,
1565     const void*& start, const void*& end) {
1566   const auto value_type_size =
1567       sizeof(typename BufferWrapper<std::vector<T, Allocator>>::value_type);
1568   EncodingType encoding;
1569   std::size_t size;
1570 
1571   if (const auto error =
1572           DeserializeBinType(&encoding, &size, reader, start, end))
1573     return error;
1574 
1575   // Try to resize the BufferWrapper to the size of the payload.
1576   value->resize(size / value_type_size);
1577 
1578   if (size > value->size() * value_type_size || size % value_type_size != 0) {
1579     return ErrorCode::INSUFFICIENT_DESTINATION_SIZE;
1580   } else if (size == 0U) {
1581     return ErrorCode::NO_ERROR;
1582   } else {
1583     return ReadRawData(value->data(), reader, start, end, size);
1584   }
1585 }
1586 template <typename T>
1587 inline ErrorType DeserializeObject(BufferWrapper<T*>* value,
1588                                    MessageReader* reader, const void*& start,
1589                                    const void*& end) {
1590   const auto value_type_size = sizeof(typename BufferWrapper<T*>::value_type);
1591   EncodingType encoding;
1592   std::size_t size;
1593 
1594   if (const auto error =
1595           DeserializeBinType(&encoding, &size, reader, start, end))
1596     return error;
1597 
1598   // Try to resize the BufferWrapper to the size of the payload.
1599   value->resize(size / value_type_size);
1600 
1601   if (size > value->size() * value_type_size || size % value_type_size != 0) {
1602     return ErrorCode::INSUFFICIENT_DESTINATION_SIZE;
1603   } else if (size == 0U) {
1604     return ErrorCode::NO_ERROR;
1605   } else {
1606     return ReadRawData(value->data(), reader, start, end, size);
1607   }
1608 }
1609 
1610 // Deserializes the type code and size for string types.
1611 inline ErrorType DeserializeStringType(EncodingType* encoding,
1612                                        std::size_t* size, MessageReader* reader,
1613                                        const void*& start, const void*& end) {
1614   if (const auto error = DeserializeEncoding(encoding, reader, start, end)) {
1615     return error;
1616   } else if (IsFixstrEncoding(*encoding)) {
1617     *size = GetFixstrSize(*encoding);
1618     return ErrorCode::NO_ERROR;
1619   } else if (*encoding == ENCODING_TYPE_STR8) {
1620     return DeserializeValue<std::uint8_t>(size, reader, start, end);
1621   } else if (*encoding == ENCODING_TYPE_STR16) {
1622     return DeserializeValue<std::uint16_t>(size, reader, start, end);
1623   } else if (*encoding == ENCODING_TYPE_STR32) {
1624     return DeserializeValue<std::uint32_t>(size, reader, start, end);
1625   } else {
1626     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_STRING,
1627                      *encoding);
1628   }
1629 }
1630 
1631 // Overload of DeserializeObject() for std::string types.
1632 inline ErrorType DeserializeObject(std::string* value, MessageReader* reader,
1633                                    const void*& start, const void*& end) {
1634   EncodingType encoding;
1635   std::size_t size;
1636 
1637   if (const auto error =
1638           DeserializeStringType(&encoding, &size, reader, start, end)) {
1639     return error;
1640   } else if (size == 0U) {
1641     value->clear();
1642     return ErrorCode::NO_ERROR;
1643   } else {
1644     value->resize(size);
1645     return ReadRawData(&(*value)[0], reader, start, end, size);
1646   }
1647 }
1648 
1649 // Overload of DeserializeObject() for StringWrapper types.
1650 template <typename T>
1651 inline ErrorType DeserializeObject(StringWrapper<T>* value,
1652                                    MessageReader* reader, const void*& start,
1653                                    const void*& end) {
1654   const auto value_type_size = sizeof(typename StringWrapper<T>::value_type);
1655   EncodingType encoding;
1656   std::size_t size;
1657 
1658   if (const auto error =
1659           DeserializeStringType(&encoding, &size, reader, start, end))
1660     return error;
1661 
1662   // Try to resize the StringWrapper to the size of the payload
1663   // string.
1664   value->resize(size / value_type_size);
1665 
1666   if (size > value->length() * value_type_size || size % value_type_size != 0) {
1667     return ErrorCode::INSUFFICIENT_DESTINATION_SIZE;
1668   } else if (size == 0U) {
1669     return ErrorCode::NO_ERROR;
1670   } else {
1671     return ReadRawData(value->data(), reader, start, end, size);
1672   }
1673 }
1674 
1675 // Deserializes the type code and size of array types.
1676 inline ErrorType DeserializeArrayType(EncodingType* encoding, std::size_t* size,
1677                                       MessageReader* reader, const void*& start,
1678                                       const void*& end) {
1679   if (const auto error = DeserializeEncoding(encoding, reader, start, end)) {
1680     return error;
1681   } else if (IsFixarrayEncoding(*encoding)) {
1682     *size = GetFixarraySize(*encoding);
1683     return ErrorCode::NO_ERROR;
1684   } else if (*encoding == ENCODING_TYPE_ARRAY16) {
1685     return DeserializeValue<std::uint16_t>(size, reader, start, end);
1686   } else if (*encoding == ENCODING_TYPE_ARRAY32) {
1687     return DeserializeValue<std::uint32_t>(size, reader, start, end);
1688   } else {
1689     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_ARRAY,
1690                      *encoding);
1691   }
1692 }
1693 
1694 // Deserializes the type code and size of map types.
1695 inline ErrorType DeserializeMapType(EncodingType* encoding, std::size_t* size,
1696                                     MessageReader* reader, const void*& start,
1697                                     const void*& end) {
1698   if (const auto error = DeserializeEncoding(encoding, reader, start, end)) {
1699     return error;
1700   } else if (IsFixmapEncoding(*encoding)) {
1701     *size = GetFixmapSize(*encoding);
1702     return ErrorCode::NO_ERROR;
1703   } else if (*encoding == ENCODING_TYPE_MAP16) {
1704     return DeserializeValue<std::uint16_t>(size, reader, start, end);
1705   } else if (*encoding == ENCODING_TYPE_MAP32) {
1706     return DeserializeValue<std::uint32_t>(size, reader, start, end);
1707   } else {
1708     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_MAP,
1709                      *encoding);
1710   }
1711 }
1712 
1713 // Overload for std::vector types.
1714 template <typename T, typename Allocator>
1715 inline ErrorType DeserializeObject(std::vector<T, Allocator>* value,
1716                                    MessageReader* reader, const void*& start,
1717                                    const void*& end) {
1718   EncodingType encoding;
1719   std::size_t size;
1720 
1721   if (const auto error =
1722           DeserializeArrayType(&encoding, &size, reader, start, end))
1723     return error;
1724 
1725   std::vector<T, Allocator> result(size);
1726   for (std::size_t i = 0; i < size; i++) {
1727     if (const auto error = DeserializeObject(&result[i], reader, start, end))
1728       return error;
1729   }
1730 
1731   *value = std::move(result);
1732   return ErrorCode::NO_ERROR;
1733 
1734 // TODO(eieio): Consider the benefits and trade offs of this alternative.
1735 #if 0
1736   value->resize(size);
1737   for (std::size_t i = 0; i < size; i++) {
1738     if (const auto error = DeserializeObject(&(*value)[i], reader, start, end))
1739       return error;
1740   }
1741   return ErrorCode::NO_ERROR;
1742 #endif
1743 }
1744 
1745 // Deserializes an EmptyVariant value.
1746 inline ErrorType DeserializeObject(EmptyVariant* /*empty*/,
1747                                    MessageReader* reader, const void*& start,
1748                                    const void*& end) {
1749   EncodingType encoding;
1750 
1751   if (const auto error = DeserializeEncoding(&encoding, reader, start, end)) {
1752     return error;
1753   } else if (encoding != ENCODING_TYPE_NIL) {
1754     return ErrorType(ErrorCode::UNEXPECTED_ENCODING, ENCODING_CLASS_MAP,
1755                      encoding);
1756   } else {
1757     return ErrorCode::NO_ERROR;
1758   }
1759 }
1760 
1761 // Deserializes a Variant type.
1762 template <typename... Types>
1763 inline ErrorType DeserializeObject(Variant<Types...>* variant,
1764                                    MessageReader* reader, const void*& start,
1765                                    const void*& end) {
1766   EncodingType encoding;
1767   std::size_t size;
1768 
1769   if (const auto error =
1770           DeserializeMapType(&encoding, &size, reader, start, end)) {
1771     return error;
1772   }
1773 
1774   if (size != 1)
1775     return ErrorType(ErrorCode::UNEXPECTED_TYPE_SIZE, ENCODING_CLASS_MAP,
1776                      encoding);
1777 
1778   std::int32_t type;
1779   if (const auto error = DeserializeObject(&type, reader, start, end)) {
1780     return error;
1781   } else if (type < Variant<Types...>::kEmptyIndex ||
1782              type >= static_cast<std::int32_t>(sizeof...(Types))) {
1783     return ErrorCode::INVALID_VARIANT_ELEMENT;
1784   } else {
1785     variant->Become(type);
1786     return variant->Visit([reader, &start, &end](auto&& value) {
1787       return DeserializeObject(&value, reader, start, end);
1788     });
1789   }
1790 }
1791 
1792 // Deserializes map types.
1793 template <typename MapType>
1794 inline ErrorType DeserializeMap(MapType* value, MessageReader* reader,
1795                                 const void*& start, const void*& end) {
1796   EncodingType encoding;
1797   std::size_t size;
1798 
1799   if (const auto error =
1800           DeserializeMapType(&encoding, &size, reader, start, end))
1801     return error;
1802 
1803   MapType result;
1804   for (std::size_t i = 0; i < size; i++) {
1805     std::pair<typename MapType::key_type, typename MapType::mapped_type>
1806         element;
1807     if (const auto error =
1808             DeserializeObject(&element.first, reader, start, end))
1809       return error;
1810     if (const auto error =
1811             DeserializeObject(&element.second, reader, start, end))
1812       return error;
1813     result.emplace(std::move(element));
1814   }
1815 
1816   *value = std::move(result);
1817   return ErrorCode::NO_ERROR;
1818 }
1819 
1820 // Overload for std::map types.
1821 template <typename Key, typename T, typename Compare, typename Allocator>
1822 inline ErrorType DeserializeObject(std::map<Key, T, Compare, Allocator>* value,
1823                                    MessageReader* reader, const void*& start,
1824                                    const void*& end) {
1825   return DeserializeMap(value, reader, start, end);
1826 }
1827 
1828 // Overload for std::unordered_map types.
1829 template <typename Key, typename T, typename Hash, typename KeyEqual,
1830           typename Allocator>
1831 inline ErrorType DeserializeObject(
1832     std::unordered_map<Key, T, Hash, KeyEqual, Allocator>* value,
1833     MessageReader* reader, const void*& start, const void*& end) {
1834   return DeserializeMap(value, reader, start, end);
1835 }
1836 
1837 // Overload for ArrayWrapper types.
1838 template <typename T>
1839 inline ErrorType DeserializeObject(ArrayWrapper<T>* value,
1840                                    MessageReader* reader, const void*& start,
1841                                    const void*& end) {
1842   EncodingType encoding;
1843   std::size_t size;
1844 
1845   if (const auto error =
1846           DeserializeArrayType(&encoding, &size, reader, start, end)) {
1847     return error;
1848   }
1849 
1850   // Try to resize the wrapper.
1851   value->resize(size);
1852 
1853   // Make sure there is enough space in the ArrayWrapper for the
1854   // payload.
1855   if (size > value->capacity())
1856     return ErrorCode::INSUFFICIENT_DESTINATION_SIZE;
1857 
1858   for (std::size_t i = 0; i < size; i++) {
1859     if (const auto error = DeserializeObject(&(*value)[i], reader, start, end))
1860       return error;
1861   }
1862 
1863   return ErrorCode::NO_ERROR;
1864 }
1865 
1866 // Overload for std::array types.
1867 template <typename T, std::size_t Size>
1868 inline ErrorType DeserializeObject(std::array<T, Size>* value,
1869                                    MessageReader* reader, const void*& start,
1870                                    const void*& end) {
1871   EncodingType encoding;
1872   std::size_t size;
1873 
1874   if (const auto error =
1875           DeserializeArrayType(&encoding, &size, reader, start, end)) {
1876     return error;
1877   }
1878 
1879   if (size != Size)
1880     return ErrorCode::INSUFFICIENT_DESTINATION_SIZE;
1881 
1882   for (std::size_t i = 0; i < size; i++) {
1883     if (const auto error = DeserializeObject(&(*value)[i], reader, start, end))
1884       return error;
1885   }
1886 
1887   return ErrorCode::NO_ERROR;
1888 }
1889 
1890 // Deserializes std::pair types.
1891 template <typename T, typename U>
1892 inline ErrorType DeserializeObject(std::pair<T, U>* value,
1893                                    MessageReader* reader, const void*& start,
1894                                    const void*& end) {
1895   EncodingType encoding;
1896   std::size_t size;
1897 
1898   if (const auto error =
1899           DeserializeArrayType(&encoding, &size, reader, start, end)) {
1900     return error;
1901   } else if (size != 2) {
1902     return ErrorCode::UNEXPECTED_TYPE_SIZE;
1903   } else if (const auto error =
1904                  DeserializeObject(&value->first, reader, start, end)) {
1905     return error;
1906   } else if (const auto error =
1907                  DeserializeObject(&value->second, reader, start, end)) {
1908     return error;
1909   } else {
1910     return ErrorCode::NO_ERROR;
1911   }
1912 }
1913 
1914 // Stops template recursion when the last tuple element is reached.
1915 template <typename... T>
1916 inline ErrorType DeserializeTuple(std::tuple<T...>*, MessageReader*,
1917                                   const void*&, const void*, Index<0>) {
1918   return ErrorCode::NO_ERROR;
1919 }
1920 
1921 // Deserializes each element of a tuple recursively.
1922 template <typename... T, std::size_t index>
1923 inline ErrorType DeserializeTuple(std::tuple<T...>* tuple,
1924                                   MessageReader* reader, const void*& start,
1925                                   const void*& end, Index<index>) {
1926   if (const auto error =
1927           DeserializeTuple(tuple, reader, start, end, Index<index - 1>()))
1928     return error;
1929   else
1930     return DeserializeObject(&std::get<index - 1>(*tuple), reader, start, end);
1931 }
1932 
1933 // Overload for standard tuple types.
1934 template <typename... T>
1935 inline ErrorType DeserializeObject(std::tuple<T...>* value,
1936                                    MessageReader* reader, const void*& start,
1937                                    const void*& end) {
1938   EncodingType encoding;
1939   std::size_t size;
1940 
1941   if (const auto error =
1942           DeserializeArrayType(&encoding, &size, reader, start, end)) {
1943     return error;
1944   } else if (size != sizeof...(T)) {
1945     return ErrorCode::UNEXPECTED_TYPE_SIZE;
1946   } else {
1947     return DeserializeTuple(value, reader, start, end, Index<sizeof...(T)>());
1948   }
1949 }
1950 
1951 // Stops template recursion when the last member of a Serializable type is
1952 // reached.
1953 template <typename Members, typename T>
1954 inline ErrorType DeserializeMember(T*, MessageReader*, const void*&,
1955                                    const void*, Index<0>) {
1956   return ErrorCode::NO_ERROR;
1957 }
1958 
1959 // Deserializes each member of a Serializable type recursively.
1960 template <typename Members, typename T, std::size_t index>
1961 inline ErrorType DeserializeMember(T* value, MessageReader* reader,
1962                                    const void*& start, const void*& end,
1963                                    Index<index>) {
1964   if (const auto error = DeserializeMember<Members>(value, reader, start, end,
1965                                                     Index<index - 1>()))
1966     return error;
1967   else
1968     return DeserializeObject(&Members::template At<index - 1>::Resolve(*value),
1969                              reader, start, end);
1970 }
1971 
1972 // Deserializes the members of a Serializable type using the given
1973 // SerializableMembersType type.
1974 template <typename Members, typename T>
1975 inline ErrorType DeserializeMembers(T* value, MessageReader* reader,
1976                                     const void*& start, const void*& end) {
1977   return DeserializeMember<Members>(value, reader, start, end,
1978                                     Index<Members::MemberCount>());
1979 }
1980 
1981 // Top level deserialization function.
1982 template <typename T>
1983 inline ErrorType Deserialize(T* value, MessageReader* reader) {
1984   PDX_TRACE_NAME("Deserialize");
1985   MessageReader::BufferSection section = reader->GetNextReadBufferSection();
1986   if (section.first == section.second)
1987     return ErrorCode::INSUFFICIENT_BUFFER;
1988   ErrorType error =
1989       DeserializeObject(value, reader, section.first, section.second);
1990   reader->ConsumeReadBufferSectionData(section.first);
1991   return error;
1992 }
1993 
1994 }  // namespace rpc
1995 }  // namespace pdx
1996 }  // namespace android
1997 
1998 #endif  // ANDROID_PDX_RPC_SERIALIZATION_H_
1999