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