• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lint as: python3
2# Copyright 2020 Google Inc. All rights reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Implementation of FlexBuffers binary format.
16
17For more info check https://google.github.io/flatbuffers/flexbuffers.html and
18corresponding C++ implementation at
19https://github.com/google/flatbuffers/blob/master/include/flatbuffers/flexbuffers.h
20"""
21
22# pylint: disable=invalid-name
23# TODO(dkovalev): Add type hints everywhere, so tools like pytypes could work.
24
25import array
26import contextlib
27import enum
28import struct
29
30__all__ = ('Type', 'Builder', 'GetRoot', 'Dumps', 'Loads')
31
32
33class BitWidth(enum.IntEnum):
34  """Supported bit widths of value types.
35
36  These are used in the lower 2 bits of a type field to determine the size of
37  the elements (and or size field) of the item pointed to (e.g. vector).
38  """
39  W8 = 0  # 2^0 = 1 byte
40  W16 = 1  # 2^1 = 2 bytes
41  W32 = 2  # 2^2 = 4 bytes
42  W64 = 3  # 2^3 = 8 bytes
43
44  @staticmethod
45  def U(value):
46    """Returns the minimum `BitWidth` to encode unsigned integer value."""
47    assert value >= 0
48
49    if value < (1 << 8):
50      return BitWidth.W8
51    elif value < (1 << 16):
52      return BitWidth.W16
53    elif value < (1 << 32):
54      return BitWidth.W32
55    elif value < (1 << 64):
56      return BitWidth.W64
57    else:
58      raise ValueError('value is too big to encode: %s' % value)
59
60  @staticmethod
61  def I(value):
62    """Returns the minimum `BitWidth` to encode signed integer value."""
63    # -2^(n-1) <=     value < 2^(n-1)
64    # -2^n     <= 2 * value < 2^n
65    # 2 * value < 2^n, when value >= 0 or 2 * (-value) <= 2^n, when value < 0
66    # 2 * value < 2^n, when value >= 0 or 2 * (-value) - 1 < 2^n, when value < 0
67    #
68    # if value >= 0:
69    #   return BitWidth.U(2 * value)
70    # else:
71    #   return BitWidth.U(2 * (-value) - 1)  # ~x = -x - 1
72    value *= 2
73    return BitWidth.U(value if value >= 0 else ~value)
74
75  @staticmethod
76  def F(value):
77    """Returns the `BitWidth` to encode floating point value."""
78    if struct.unpack('<f', struct.pack('<f', value))[0] == value:
79      return BitWidth.W32
80    return BitWidth.W64
81
82  @staticmethod
83  def B(byte_width):
84    return {
85        1: BitWidth.W8,
86        2: BitWidth.W16,
87        4: BitWidth.W32,
88        8: BitWidth.W64
89    }[byte_width]
90
91
92I = {1: 'b', 2: 'h', 4: 'i', 8: 'q'}  # Integer formats
93U = {1: 'B', 2: 'H', 4: 'I', 8: 'Q'}  # Unsigned integer formats
94F = {4: 'f', 8: 'd'}  # Floating point formats
95
96
97def _Unpack(fmt, buf):
98  return struct.unpack('<%s' % fmt[len(buf)], buf)[0]
99
100
101def _UnpackVector(fmt, buf, length):
102  byte_width = len(buf) // length
103  return struct.unpack('<%d%s' % (length, fmt[byte_width]), buf)
104
105
106def _Pack(fmt, value, byte_width):
107  return struct.pack('<%s' % fmt[byte_width], value)
108
109
110def _PackVector(fmt, values, byte_width):
111  return struct.pack('<%d%s' % (len(values), fmt[byte_width]), *values)
112
113
114def _Mutate(fmt, buf, value, byte_width, value_bit_width):
115  if (1 << value_bit_width) <= byte_width:
116    buf[:byte_width] = _Pack(fmt, value, byte_width)
117    return True
118  return False
119
120
121# Computes how many bytes you'd have to pad to be able to write an
122# "scalar_size" scalar if the buffer had grown to "buf_size",
123# "scalar_size" is a power of two.
124def _PaddingBytes(buf_size, scalar_size):
125  # ((buf_size + (scalar_size - 1)) // scalar_size) * scalar_size - buf_size
126  return -buf_size & (scalar_size - 1)
127
128
129def _ShiftSlice(s, offset, length):
130  start = offset + (0 if s.start is None else s.start)
131  stop = offset + (length if s.stop is None else s.stop)
132  return slice(start, stop, s.step)
133
134
135# https://en.cppreference.com/w/cpp/algorithm/lower_bound
136def _LowerBound(values, value, pred):
137  """Implementation of C++ std::lower_bound() algorithm."""
138  first, last = 0, len(values)
139  count = last - first
140  while count > 0:
141    i = first
142    step = count // 2
143    i += step
144    if pred(values[i], value):
145      i += 1
146      first = i
147      count -= step + 1
148    else:
149      count = step
150  return first
151
152
153# https://en.cppreference.com/w/cpp/algorithm/binary_search
154def _BinarySearch(values, value, pred=lambda x, y: x < y):
155  """Implementation of C++ std::binary_search() algorithm."""
156  index = _LowerBound(values, value, pred)
157  if index != len(values) and not pred(value, values[index]):
158    return index
159  return -1
160
161
162class Type(enum.IntEnum):
163  """Supported types of encoded data.
164
165  These are used as the upper 6 bits of a type field to indicate the actual
166  type.
167  """
168  NULL = 0
169  INT = 1
170  UINT = 2
171  FLOAT = 3
172  # Types above stored inline, types below store an offset.
173  KEY = 4
174  STRING = 5
175  INDIRECT_INT = 6
176  INDIRECT_UINT = 7
177  INDIRECT_FLOAT = 8
178  MAP = 9
179  VECTOR = 10  # Untyped.
180
181  VECTOR_INT = 11  # Typed any size (stores no type table).
182  VECTOR_UINT = 12
183  VECTOR_FLOAT = 13
184  VECTOR_KEY = 14
185  # DEPRECATED, use VECTOR or VECTOR_KEY instead.
186  # Read test.cpp/FlexBuffersDeprecatedTest() for details on why.
187  VECTOR_STRING_DEPRECATED = 15
188
189  VECTOR_INT2 = 16  # Typed tuple (no type table, no size field).
190  VECTOR_UINT2 = 17
191  VECTOR_FLOAT2 = 18
192  VECTOR_INT3 = 19  # Typed triple (no type table, no size field).
193  VECTOR_UINT3 = 20
194  VECTOR_FLOAT3 = 21
195  VECTOR_INT4 = 22  # Typed quad (no type table, no size field).
196  VECTOR_UINT4 = 23
197  VECTOR_FLOAT4 = 24
198
199  BLOB = 25
200  BOOL = 26
201  VECTOR_BOOL = 36  # To do the same type of conversion of type to vector type
202
203  @staticmethod
204  def Pack(type_, bit_width):
205    return (int(type_) << 2) | bit_width
206
207  @staticmethod
208  def Unpack(packed_type):
209    return 1 << (packed_type & 0b11), Type(packed_type >> 2)
210
211  @staticmethod
212  def IsInline(type_):
213    return type_ <= Type.FLOAT or type_ == Type.BOOL
214
215  @staticmethod
216  def IsTypedVector(type_):
217    return Type.VECTOR_INT <= type_ <= Type.VECTOR_STRING_DEPRECATED or \
218           type_ == Type.VECTOR_BOOL
219
220  @staticmethod
221  def IsTypedVectorElementType(type_):
222    return Type.INT <= type_ <= Type.STRING or type_ == Type.BOOL
223
224  @staticmethod
225  def ToTypedVectorElementType(type_):
226    if not Type.IsTypedVector(type_):
227      raise ValueError('must be typed vector type')
228
229    return Type(type_ - Type.VECTOR_INT + Type.INT)
230
231  @staticmethod
232  def IsFixedTypedVector(type_):
233    return Type.VECTOR_INT2 <= type_ <= Type.VECTOR_FLOAT4
234
235  @staticmethod
236  def IsFixedTypedVectorElementType(type_):
237    return Type.INT <= type_ <= Type.FLOAT
238
239  @staticmethod
240  def ToFixedTypedVectorElementType(type_):
241    if not Type.IsFixedTypedVector(type_):
242      raise ValueError('must be fixed typed vector type')
243
244    # 3 types each, starting from length 2.
245    fixed_type = type_ - Type.VECTOR_INT2
246    return Type(fixed_type % 3 + Type.INT), fixed_type // 3 + 2
247
248  @staticmethod
249  def ToTypedVector(element_type, fixed_len=0):
250    """Converts element type to corresponding vector type.
251
252    Args:
253      element_type: vector element type
254      fixed_len: number of elements: 0 for typed vector; 2, 3, or 4 for fixed
255        typed vector.
256
257    Returns:
258      Typed vector type or fixed typed vector type.
259    """
260    if fixed_len == 0:
261      if not Type.IsTypedVectorElementType(element_type):
262        raise ValueError('must be typed vector element type')
263    else:
264      if not Type.IsFixedTypedVectorElementType(element_type):
265        raise ValueError('must be fixed typed vector element type')
266
267    offset = element_type - Type.INT
268    if fixed_len == 0:
269      return Type(offset + Type.VECTOR_INT)  # TypedVector
270    elif fixed_len == 2:
271      return Type(offset + Type.VECTOR_INT2)  # FixedTypedVector
272    elif fixed_len == 3:
273      return Type(offset + Type.VECTOR_INT3)  # FixedTypedVector
274    elif fixed_len == 4:
275      return Type(offset + Type.VECTOR_INT4)  # FixedTypedVector
276    else:
277      raise ValueError('unsupported fixed_len: %s' % fixed_len)
278
279
280class Buf:
281  """Class to access underlying buffer object starting from the given offset."""
282
283  def __init__(self, buf, offset):
284    self._buf = buf
285    self._offset = offset if offset >= 0 else len(buf) + offset
286    self._length = len(buf) - self._offset
287
288  def __getitem__(self, key):
289    if isinstance(key, slice):
290      return self._buf[_ShiftSlice(key, self._offset, self._length)]
291    elif isinstance(key, int):
292      return self._buf[self._offset + key]
293    else:
294      raise TypeError('invalid key type')
295
296  def __setitem__(self, key, value):
297    if isinstance(key, slice):
298      self._buf[_ShiftSlice(key, self._offset, self._length)] = value
299    elif isinstance(key, int):
300      self._buf[self._offset + key] = key
301    else:
302      raise TypeError('invalid key type')
303
304  def __repr__(self):
305    return 'buf[%d:]' % self._offset
306
307  def Find(self, sub):
308    """Returns the lowest index where the sub subsequence is found."""
309    return self._buf[self._offset:].find(sub)
310
311  def Slice(self, offset):
312    """Returns new `Buf` which starts from the given offset."""
313    return Buf(self._buf, self._offset + offset)
314
315  def Indirect(self, offset, byte_width):
316    """Return new `Buf` based on the encoded offset (indirect encoding)."""
317    return self.Slice(offset - _Unpack(U, self[offset:offset + byte_width]))
318
319
320class Object:
321  """Base class for all non-trivial data accessors."""
322  __slots__ = '_buf', '_byte_width'
323
324  def __init__(self, buf, byte_width):
325    self._buf = buf
326    self._byte_width = byte_width
327
328  @property
329  def ByteWidth(self):
330    return self._byte_width
331
332
333class Sized(Object):
334  """Base class for all data accessors which need to read encoded size."""
335  __slots__ = '_size',
336
337  def __init__(self, buf, byte_width, size=0):
338    super().__init__(buf, byte_width)
339    if size == 0:
340      self._size = _Unpack(U, self.SizeBytes)
341    else:
342      self._size = size
343
344  @property
345  def SizeBytes(self):
346    return self._buf[-self._byte_width:0]
347
348  def __len__(self):
349    return self._size
350
351
352class Blob(Sized):
353  """Data accessor for the encoded blob bytes."""
354  __slots__ = ()
355
356  @property
357  def Bytes(self):
358    return self._buf[0:len(self)]
359
360  def __repr__(self):
361    return 'Blob(%s, size=%d)' % (self._buf, len(self))
362
363
364class String(Sized):
365  """Data accessor for the encoded string bytes."""
366  __slots__ = ()
367
368  @property
369  def Bytes(self):
370    return self._buf[0:len(self)]
371
372  def Mutate(self, value):
373    """Mutates underlying string bytes in place.
374
375    Args:
376      value: New string to replace the existing one. New string must have less
377        or equal UTF-8-encoded bytes than the existing one to successfully
378        mutate underlying byte buffer.
379
380    Returns:
381      Whether the value was mutated or not.
382    """
383    encoded = value.encode('utf-8')
384    n = len(encoded)
385    if n <= len(self):
386      self._buf[-self._byte_width:0] = _Pack(U, n, self._byte_width)
387      self._buf[0:n] = encoded
388      self._buf[n:len(self)] = bytearray(len(self) - n)
389      return True
390    return False
391
392  def __str__(self):
393    return self.Bytes.decode('utf-8')
394
395  def __repr__(self):
396    return 'String(%s, size=%d)' % (self._buf, len(self))
397
398
399class Key(Object):
400  """Data accessor for the encoded key bytes."""
401  __slots__ = ()
402
403  def __init__(self, buf, byte_width):
404    assert byte_width == 1
405    super().__init__(buf, byte_width)
406
407  @property
408  def Bytes(self):
409    return self._buf[0:len(self)]
410
411  def __len__(self):
412    return self._buf.Find(0)
413
414  def __str__(self):
415    return self.Bytes.decode('ascii')
416
417  def __repr__(self):
418    return 'Key(%s, size=%d)' % (self._buf, len(self))
419
420
421class Vector(Sized):
422  """Data accessor for the encoded vector bytes."""
423  __slots__ = ()
424
425  def __getitem__(self, index):
426    if index < 0 or index >= len(self):
427      raise IndexError('vector index %s is out of [0, %d) range' % \
428          (index, len(self)))
429
430    packed_type = self._buf[len(self) * self._byte_width + index]
431    buf = self._buf.Slice(index * self._byte_width)
432    return Ref.PackedType(buf, self._byte_width, packed_type)
433
434  @property
435  def Value(self):
436    """Returns the underlying encoded data as a list object."""
437    return [e.Value for e in self]
438
439  def __repr__(self):
440    return 'Vector(%s, byte_width=%d, size=%d)' % \
441        (self._buf, self._byte_width, self._size)
442
443
444class TypedVector(Sized):
445  """Data accessor for the encoded typed vector or fixed typed vector bytes."""
446  __slots__ = '_element_type', '_size'
447
448  def __init__(self, buf, byte_width, element_type, size=0):
449    super().__init__(buf, byte_width, size)
450
451    if element_type == Type.STRING:
452      # These can't be accessed as strings, since we don't know the bit-width
453      # of the size field, see the declaration of
454      # FBT_VECTOR_STRING_DEPRECATED above for details.
455      # We change the type here to be keys, which are a subtype of strings,
456      # and will ignore the size field. This will truncate strings with
457      # embedded nulls.
458      element_type = Type.KEY
459
460    self._element_type = element_type
461
462  @property
463  def Bytes(self):
464    return self._buf[:self._byte_width * len(self)]
465
466  @property
467  def ElementType(self):
468    return self._element_type
469
470  def __getitem__(self, index):
471    if index < 0 or index >= len(self):
472      raise IndexError('vector index %s is out of [0, %d) range' % \
473          (index, len(self)))
474
475    buf = self._buf.Slice(index * self._byte_width)
476    return Ref(buf, self._byte_width, 1, self._element_type)
477
478  @property
479  def Value(self):
480    """Returns underlying data as list object."""
481    if not self:
482      return []
483
484    if self._element_type is Type.BOOL:
485      return [bool(e) for e in _UnpackVector(U, self.Bytes, len(self))]
486    elif self._element_type is Type.INT:
487      return list(_UnpackVector(I, self.Bytes, len(self)))
488    elif self._element_type is Type.UINT:
489      return list(_UnpackVector(U, self.Bytes, len(self)))
490    elif self._element_type is Type.FLOAT:
491      return list(_UnpackVector(F, self.Bytes, len(self)))
492    elif self._element_type is Type.KEY:
493      return [e.AsKey for e in self]
494    elif self._element_type is Type.STRING:
495      return [e.AsString for e in self]
496    else:
497      raise TypeError('unsupported element_type: %s' % self._element_type)
498
499  def __repr__(self):
500    return 'TypedVector(%s, byte_width=%d, element_type=%s, size=%d)' % \
501        (self._buf, self._byte_width, self._element_type, self._size)
502
503
504class Map(Vector):
505  """Data accessor for the encoded map bytes."""
506
507  @staticmethod
508  def CompareKeys(a, b):
509    if isinstance(a, Ref):
510      a = a.AsKeyBytes
511    if isinstance(b, Ref):
512      b = b.AsKeyBytes
513    return a < b
514
515  def __getitem__(self, key):
516    if isinstance(key, int):
517      return super().__getitem__(key)
518
519    index = _BinarySearch(self.Keys, key.encode('ascii'), self.CompareKeys)
520    if index != -1:
521      return super().__getitem__(index)
522
523    raise KeyError(key)
524
525  @property
526  def Keys(self):
527    byte_width = _Unpack(U, self._buf[-2 * self._byte_width:-self._byte_width])
528    buf = self._buf.Indirect(-3 * self._byte_width, self._byte_width)
529    return TypedVector(buf, byte_width, Type.KEY)
530
531  @property
532  def Values(self):
533    return Vector(self._buf, self._byte_width)
534
535  @property
536  def Value(self):
537    return {k.Value: v.Value for k, v in zip(self.Keys, self.Values)}
538
539  def __repr__(self):
540    return 'Map(%s, size=%d)' % (self._buf, len(self))
541
542
543class Ref:
544  """Data accessor for the encoded data bytes."""
545  __slots__ = '_buf', '_parent_width', '_byte_width', '_type'
546
547  @staticmethod
548  def PackedType(buf, parent_width, packed_type):
549    byte_width, type_ = Type.Unpack(packed_type)
550    return Ref(buf, parent_width, byte_width, type_)
551
552  def __init__(self, buf, parent_width, byte_width, type_):
553    self._buf = buf
554    self._parent_width = parent_width
555    self._byte_width = byte_width
556    self._type = type_
557
558  def __repr__(self):
559    return 'Ref(%s, parent_width=%d, byte_width=%d, type_=%s)' % \
560            (self._buf, self._parent_width, self._byte_width, self._type)
561
562  @property
563  def _Bytes(self):
564    return self._buf[:self._parent_width]
565
566  def _ConvertError(self, target_type):
567    raise TypeError('cannot convert %s to %s' % (self._type, target_type))
568
569  def _Indirect(self):
570    return self._buf.Indirect(0, self._parent_width)
571
572  @property
573  def IsNull(self):
574    return self._type is Type.NULL
575
576  @property
577  def IsBool(self):
578    return self._type is Type.BOOL
579
580  @property
581  def AsBool(self):
582    if self._type is Type.BOOL:
583      return bool(_Unpack(U, self._Bytes))
584    else:
585      return self.AsInt != 0
586
587  def MutateBool(self, value):
588    """Mutates underlying boolean value bytes in place.
589
590    Args:
591      value: New boolean value.
592
593    Returns:
594      Whether the value was mutated or not.
595    """
596    return self.IsBool and \
597           _Mutate(U, self._buf, value, self._parent_width, BitWidth.W8)
598
599  @property
600  def IsNumeric(self):
601    return self.IsInt or self.IsFloat
602
603  @property
604  def IsInt(self):
605    return self._type in (Type.INT, Type.INDIRECT_INT, Type.UINT,
606                          Type.INDIRECT_UINT)
607
608  @property
609  def AsInt(self):
610    """Returns current reference as integer value."""
611    if self.IsNull:
612      return 0
613    elif self.IsBool:
614      return int(self.AsBool)
615    elif self._type is Type.INT:
616      return _Unpack(I, self._Bytes)
617    elif self._type is Type.INDIRECT_INT:
618      return _Unpack(I, self._Indirect()[:self._byte_width])
619    if self._type is Type.UINT:
620      return _Unpack(U, self._Bytes)
621    elif self._type is Type.INDIRECT_UINT:
622      return _Unpack(U, self._Indirect()[:self._byte_width])
623    elif self.IsString:
624      return len(self.AsString)
625    elif self.IsKey:
626      return len(self.AsKey)
627    elif self.IsBlob:
628      return len(self.AsBlob)
629    elif self.IsVector:
630      return len(self.AsVector)
631    elif self.IsTypedVector:
632      return len(self.AsTypedVector)
633    elif self.IsFixedTypedVector:
634      return len(self.AsFixedTypedVector)
635    else:
636      raise self._ConvertError(Type.INT)
637
638  def MutateInt(self, value):
639    """Mutates underlying integer value bytes in place.
640
641    Args:
642      value: New integer value. It must fit to the byte size of the existing
643        encoded value.
644
645    Returns:
646      Whether the value was mutated or not.
647    """
648    if self._type is Type.INT:
649      return _Mutate(I, self._buf, value, self._parent_width, BitWidth.I(value))
650    elif self._type is Type.INDIRECT_INT:
651      return _Mutate(I, self._Indirect(), value, self._byte_width,
652                     BitWidth.I(value))
653    elif self._type is Type.UINT:
654      return _Mutate(U, self._buf, value, self._parent_width, BitWidth.U(value))
655    elif self._type is Type.INDIRECT_UINT:
656      return _Mutate(U, self._Indirect(), value, self._byte_width,
657                     BitWidth.U(value))
658    else:
659      return False
660
661  @property
662  def IsFloat(self):
663    return self._type in (Type.FLOAT, Type.INDIRECT_FLOAT)
664
665  @property
666  def AsFloat(self):
667    """Returns current reference as floating point value."""
668    if self.IsNull:
669      return 0.0
670    elif self.IsBool:
671      return float(self.AsBool)
672    elif self.IsInt:
673      return float(self.AsInt)
674    elif self._type is Type.FLOAT:
675      return _Unpack(F, self._Bytes)
676    elif self._type is Type.INDIRECT_FLOAT:
677      return _Unpack(F, self._Indirect()[:self._byte_width])
678    elif self.IsString:
679      return float(self.AsString)
680    elif self.IsVector:
681      return float(len(self.AsVector))
682    elif self.IsTypedVector():
683      return float(len(self.AsTypedVector))
684    elif self.IsFixedTypedVector():
685      return float(len(self.FixedTypedVector))
686    else:
687      raise self._ConvertError(Type.FLOAT)
688
689  def MutateFloat(self, value):
690    """Mutates underlying floating point value bytes in place.
691
692    Args:
693      value: New float value. It must fit to the byte size of the existing
694        encoded value.
695
696    Returns:
697      Whether the value was mutated or not.
698    """
699    if self._type is Type.FLOAT:
700      return _Mutate(F, self._buf, value, self._parent_width,
701                     BitWidth.B(self._parent_width))
702    elif self._type is Type.INDIRECT_FLOAT:
703      return _Mutate(F, self._Indirect(), value, self._byte_width,
704                     BitWidth.B(self._byte_width))
705    else:
706      return False
707
708  @property
709  def IsKey(self):
710    return self._type is Type.KEY
711
712  @property
713  def AsKeyBytes(self):
714    if self.IsKey:
715      return Key(self._Indirect(), self._byte_width).Bytes
716    else:
717      raise self._ConvertError(Type.KEY)
718
719  @property
720  def AsKey(self):
721    if self.IsKey:
722      return str(Key(self._Indirect(), self._byte_width))
723    else:
724      raise self._ConvertError(Type.KEY)
725
726  @property
727  def IsString(self):
728    return self._type is Type.STRING
729
730  @property
731  def AsStringBytes(self):
732    if self.IsString:
733      return String(self._Indirect(), self._byte_width).Bytes
734    elif self.IsKey:
735      return self.AsKeyBytes
736    else:
737      raise self._ConvertError(Type.STRING)
738
739  @property
740  def AsString(self):
741    if self.IsString:
742      return str(String(self._Indirect(), self._byte_width))
743    elif self.IsKey:
744      return self.AsKey
745    else:
746      raise self._ConvertError(Type.STRING)
747
748  def MutateString(self, value):
749    return String(self._Indirect(), self._byte_width).Mutate(value)
750
751  @property
752  def IsBlob(self):
753    return self._type is Type.BLOB
754
755  @property
756  def AsBlob(self):
757    if self.IsBlob:
758      return Blob(self._Indirect(), self._byte_width).Bytes
759    else:
760      raise self._ConvertError(Type.BLOB)
761
762  @property
763  def IsAnyVector(self):
764    return self.IsVector or self.IsTypedVector or self.IsFixedTypedVector()
765
766  @property
767  def IsVector(self):
768    return self._type in (Type.VECTOR, Type.MAP)
769
770  @property
771  def AsVector(self):
772    if self.IsVector:
773      return Vector(self._Indirect(), self._byte_width)
774    else:
775      raise self._ConvertError(Type.VECTOR)
776
777  @property
778  def IsTypedVector(self):
779    return Type.IsTypedVector(self._type)
780
781  @property
782  def AsTypedVector(self):
783    if self.IsTypedVector:
784      return TypedVector(self._Indirect(), self._byte_width,
785                         Type.ToTypedVectorElementType(self._type))
786    else:
787      raise self._ConvertError('TYPED_VECTOR')
788
789  @property
790  def IsFixedTypedVector(self):
791    return Type.IsFixedTypedVector(self._type)
792
793  @property
794  def AsFixedTypedVector(self):
795    if self.IsFixedTypedVector:
796      element_type, size = Type.ToFixedTypedVectorElementType(self._type)
797      return TypedVector(self._Indirect(), self._byte_width, element_type, size)
798    else:
799      raise self._ConvertError('FIXED_TYPED_VECTOR')
800
801  @property
802  def IsMap(self):
803    return self._type is Type.MAP
804
805  @property
806  def AsMap(self):
807    if self.IsMap:
808      return Map(self._Indirect(), self._byte_width)
809    else:
810      raise self._ConvertError(Type.MAP)
811
812  @property
813  def Value(self):
814    """Converts current reference to value of corresponding type.
815
816    This is equivalent to calling `AsInt` for integer values, `AsFloat` for
817    floating point values, etc.
818
819    Returns:
820      Value of corresponding type.
821    """
822    if self.IsNull:
823      return None
824    elif self.IsBool:
825      return self.AsBool
826    elif self.IsInt:
827      return self.AsInt
828    elif self.IsFloat:
829      return self.AsFloat
830    elif self.IsString:
831      return self.AsString
832    elif self.IsKey:
833      return self.AsKey
834    elif self.IsBlob:
835      return self.AsBlob
836    elif self.IsMap:
837      return self.AsMap.Value
838    elif self.IsVector:
839      return self.AsVector.Value
840    elif self.IsTypedVector:
841      return self.AsTypedVector.Value
842    elif self.IsFixedTypedVector:
843      return self.AsFixedTypedVector.Value
844    else:
845      raise TypeError('cannot convert %r to value' % self)
846
847
848def _IsIterable(obj):
849  try:
850    iter(obj)
851    return True
852  except TypeError:
853    return False
854
855
856class Value:
857  """Class to represent given value during the encoding process."""
858
859  @staticmethod
860  def Null():
861    return Value(0, Type.NULL, BitWidth.W8)
862
863  @staticmethod
864  def Bool(value):
865    return Value(value, Type.BOOL, BitWidth.W8)
866
867  @staticmethod
868  def Int(value, bit_width):
869    return Value(value, Type.INT, bit_width)
870
871  @staticmethod
872  def UInt(value, bit_width):
873    return Value(value, Type.UINT, bit_width)
874
875  @staticmethod
876  def Float(value, bit_width):
877    return Value(value, Type.FLOAT, bit_width)
878
879  @staticmethod
880  def Key(offset):
881    return Value(offset, Type.KEY, BitWidth.W8)
882
883  def __init__(self, value, type_, min_bit_width):
884    self._value = value
885    self._type = type_
886
887    # For scalars: of itself, for vector: of its elements, for string: length.
888    self._min_bit_width = min_bit_width
889
890  @property
891  def Value(self):
892    return self._value
893
894  @property
895  def Type(self):
896    return self._type
897
898  @property
899  def MinBitWidth(self):
900    return self._min_bit_width
901
902  def StoredPackedType(self, parent_bit_width=BitWidth.W8):
903    return Type.Pack(self._type, self.StoredWidth(parent_bit_width))
904
905  # We have an absolute offset, but want to store a relative offset
906  # elem_index elements beyond the current buffer end. Since whether
907  # the relative offset fits in a certain byte_width depends on
908  # the size of the elements before it (and their alignment), we have
909  # to test for each size in turn.
910  def ElemWidth(self, buf_size, elem_index=0):
911    if Type.IsInline(self._type):
912      return self._min_bit_width
913    for byte_width in 1, 2, 4, 8:
914      offset_loc = buf_size + _PaddingBytes(buf_size, byte_width) + \
915                   elem_index * byte_width
916      bit_width = BitWidth.U(offset_loc - self._value)
917      if byte_width == (1 << bit_width):
918        return bit_width
919    raise ValueError('relative offset is too big')
920
921  def StoredWidth(self, parent_bit_width=BitWidth.W8):
922    if Type.IsInline(self._type):
923      return max(self._min_bit_width, parent_bit_width)
924    return self._min_bit_width
925
926  def __repr__(self):
927    return 'Value(%s, %s, %s)' % (self._value, self._type, self._min_bit_width)
928
929  def __str__(self):
930    return str(self._value)
931
932
933def InMap(func):
934  def wrapper(self, *args, **kwargs):
935    if isinstance(args[0], str):
936      self.Key(args[0])
937      func(self, *args[1:], **kwargs)
938    else:
939      func(self, *args, **kwargs)
940  return wrapper
941
942
943def InMapForString(func):
944  def wrapper(self, *args):
945    if len(args) == 1:
946      func(self, args[0])
947    elif len(args) == 2:
948      self.Key(args[0])
949      func(self, args[1])
950    else:
951      raise ValueError('invalid number of arguments')
952  return wrapper
953
954
955class Pool:
956  """Collection of (data, offset) pairs sorted by data for quick access."""
957
958  def __init__(self):
959    self._pool = []  # sorted list of (data, offset) tuples
960
961  def FindOrInsert(self, data, offset):
962    do = data, offset
963    index = _BinarySearch(self._pool, do, lambda a, b: a[0] < b[0])
964    if index != -1:
965      _, offset = self._pool[index]
966      return offset
967    self._pool.insert(index, do)
968    return None
969
970  def Clear(self):
971    self._pool = []
972
973  @property
974  def Elements(self):
975    return [data for data, _ in self._pool]
976
977
978class Builder:
979  """Helper class to encode structural data into flexbuffers format."""
980
981  def __init__(self,
982               share_strings=False,
983               share_keys=True,
984               force_min_bit_width=BitWidth.W8):
985    self._share_strings = share_strings
986    self._share_keys = share_keys
987    self._force_min_bit_width = force_min_bit_width
988
989    self._string_pool = Pool()
990    self._key_pool = Pool()
991
992    self._finished = False
993    self._buf = bytearray()
994    self._stack = []
995
996  def __len__(self):
997    return len(self._buf)
998
999  @property
1000  def StringPool(self):
1001    return self._string_pool
1002
1003  @property
1004  def KeyPool(self):
1005    return self._key_pool
1006
1007  def Clear(self):
1008    self._string_pool.Clear()
1009    self._key_pool.Clear()
1010    self._finished = False
1011    self._buf = bytearray()
1012    self._stack = []
1013
1014  def Finish(self):
1015    """Finishes encoding process and returns underlying buffer."""
1016    if self._finished:
1017      raise RuntimeError('builder has been already finished')
1018
1019    # If you hit this exception, you likely have objects that were never
1020    # included in a parent. You need to have exactly one root to finish a
1021    # buffer. Check your Start/End calls are matched, and all objects are inside
1022    # some other object.
1023    if len(self._stack) != 1:
1024      raise RuntimeError('internal stack size must be one')
1025
1026    value = self._stack[0]
1027    byte_width = self._Align(value.ElemWidth(len(self._buf)))
1028    self._WriteAny(value, byte_width=byte_width)  # Root value
1029    self._Write(U, value.StoredPackedType(), byte_width=1)  # Root type
1030    self._Write(U, byte_width, byte_width=1)  # Root size
1031
1032    self.finished = True
1033    return self._buf
1034
1035  def _ReadKey(self, offset):
1036    key = self._buf[offset:]
1037    return key[:key.find(0)]
1038
1039  def _Align(self, alignment):
1040    byte_width = 1 << alignment
1041    self._buf.extend(b'\x00' * _PaddingBytes(len(self._buf), byte_width))
1042    return byte_width
1043
1044  def _Write(self, fmt, value, byte_width):
1045    self._buf.extend(_Pack(fmt, value, byte_width))
1046
1047  def _WriteVector(self, fmt, values, byte_width):
1048    self._buf.extend(_PackVector(fmt, values, byte_width))
1049
1050  def _WriteOffset(self, offset, byte_width):
1051    relative_offset = len(self._buf) - offset
1052    assert byte_width == 8 or relative_offset < (1 << (8 * byte_width))
1053    self._Write(U, relative_offset, byte_width)
1054
1055  def _WriteAny(self, value, byte_width):
1056    fmt = {
1057        Type.NULL: U, Type.BOOL: U, Type.INT: I, Type.UINT: U, Type.FLOAT: F
1058    }.get(value.Type)
1059    if fmt:
1060      self._Write(fmt, value.Value, byte_width)
1061    else:
1062      self._WriteOffset(value.Value, byte_width)
1063
1064  def _WriteBlob(self, data, append_zero, type_):
1065    bit_width = BitWidth.U(len(data))
1066    byte_width = self._Align(bit_width)
1067    self._Write(U, len(data), byte_width)
1068    loc = len(self._buf)
1069    self._buf.extend(data)
1070    if append_zero:
1071      self._buf.append(0)
1072    self._stack.append(Value(loc, type_, bit_width))
1073    return loc
1074
1075  def _WriteScalarVector(self, element_type, byte_width, elements, fixed):
1076    """Writes scalar vector elements to the underlying buffer."""
1077    bit_width = BitWidth.B(byte_width)
1078    # If you get this exception, you're trying to write a vector with a size
1079    # field that is bigger than the scalars you're trying to write (e.g. a
1080    # byte vector > 255 elements). For such types, write a "blob" instead.
1081    if BitWidth.U(len(elements)) > bit_width:
1082      raise ValueError('too many elements for the given byte_width')
1083
1084    self._Align(bit_width)
1085    if not fixed:
1086      self._Write(U, len(elements), byte_width)
1087
1088    loc = len(self._buf)
1089
1090    fmt = {Type.INT: I, Type.UINT: U, Type.FLOAT: F}.get(element_type)
1091    if not fmt:
1092      raise TypeError('unsupported element_type')
1093    self._WriteVector(fmt, elements, byte_width)
1094
1095    type_ = Type.ToTypedVector(element_type, len(elements) if fixed else 0)
1096    self._stack.append(Value(loc, type_, bit_width))
1097    return loc
1098
1099  def _CreateVector(self, elements, typed, fixed, keys=None):
1100    """Writes vector elements to the underlying buffer."""
1101    length = len(elements)
1102
1103    if fixed and not typed:
1104      raise ValueError('fixed vector must be typed')
1105
1106    # Figure out smallest bit width we can store this vector with.
1107    bit_width = max(self._force_min_bit_width, BitWidth.U(length))
1108    prefix_elems = 1  # Vector size
1109    if keys:
1110      bit_width = max(bit_width, keys.ElemWidth(len(self._buf)))
1111      prefix_elems += 2  # Offset to the keys vector and its byte width.
1112
1113    vector_type = Type.KEY
1114    # Check bit widths and types for all elements.
1115    for i, e in enumerate(elements):
1116      bit_width = max(bit_width, e.ElemWidth(len(self._buf), prefix_elems + i))
1117
1118      if typed:
1119        if i == 0:
1120          vector_type = e.Type
1121        else:
1122          if vector_type != e.Type:
1123            raise RuntimeError('typed vector elements must be of the same type')
1124
1125    if fixed and not Type.IsFixedTypedVectorElementType(vector_type):
1126      raise RuntimeError('must be fixed typed vector element type')
1127
1128    byte_width = self._Align(bit_width)
1129    # Write vector. First the keys width/offset if available, and size.
1130    if keys:
1131      self._WriteOffset(keys.Value, byte_width)
1132      self._Write(U, 1 << keys.MinBitWidth, byte_width)
1133
1134    if not fixed:
1135      self._Write(U, length, byte_width)
1136
1137    # Then the actual data.
1138    loc = len(self._buf)
1139    for e in elements:
1140      self._WriteAny(e, byte_width)
1141
1142    # Then the types.
1143    if not typed:
1144      for e in elements:
1145        self._buf.append(e.StoredPackedType(bit_width))
1146
1147    if keys:
1148      type_ = Type.MAP
1149    else:
1150      if typed:
1151        type_ = Type.ToTypedVector(vector_type, length if fixed else 0)
1152      else:
1153        type_ = Type.VECTOR
1154
1155    return Value(loc, type_, bit_width)
1156
1157  def _PushIndirect(self, value, type_, bit_width):
1158    byte_width = self._Align(bit_width)
1159    loc = len(self._buf)
1160    fmt = {
1161        Type.INDIRECT_INT: I,
1162        Type.INDIRECT_UINT: U,
1163        Type.INDIRECT_FLOAT: F
1164    }[type_]
1165    self._Write(fmt, value, byte_width)
1166    self._stack.append(Value(loc, type_, bit_width))
1167
1168  @InMapForString
1169  def String(self, value):
1170    """Encodes string value."""
1171    reset_to = len(self._buf)
1172    encoded = value.encode('utf-8')
1173    loc = self._WriteBlob(encoded, append_zero=True, type_=Type.STRING)
1174    if self._share_strings:
1175      prev_loc = self._string_pool.FindOrInsert(encoded, loc)
1176      if prev_loc is not None:
1177        del self._buf[reset_to:]
1178        self._stack[-1]._value = loc = prev_loc  # pylint: disable=protected-access
1179
1180    return loc
1181
1182  @InMap
1183  def Blob(self, value):
1184    """Encodes binary blob value.
1185
1186    Args:
1187      value: A byte/bytearray value to encode
1188
1189    Returns:
1190      Offset of the encoded value in underlying the byte buffer.
1191    """
1192    return self._WriteBlob(value, append_zero=False, type_=Type.BLOB)
1193
1194  def Key(self, value):
1195    """Encodes key value.
1196
1197    Args:
1198      value: A byte/bytearray/str value to encode. Byte object must not contain
1199        zero bytes. String object must be convertible to ASCII.
1200
1201    Returns:
1202      Offset of the encoded value in the underlying byte buffer.
1203    """
1204    if isinstance(value, (bytes, bytearray)):
1205      encoded = value
1206    else:
1207      encoded = value.encode('ascii')
1208
1209    if 0 in encoded:
1210      raise ValueError('key contains zero byte')
1211
1212    loc = len(self._buf)
1213    self._buf.extend(encoded)
1214    self._buf.append(0)
1215    if self._share_keys:
1216      prev_loc = self._key_pool.FindOrInsert(encoded, loc)
1217      if prev_loc is not None:
1218        del self._buf[loc:]
1219        loc = prev_loc
1220
1221    self._stack.append(Value.Key(loc))
1222    return loc
1223
1224  def Null(self, key=None):
1225    """Encodes None value."""
1226    if key:
1227      self.Key(key)
1228    self._stack.append(Value.Null())
1229
1230  @InMap
1231  def Bool(self, value):
1232    """Encodes boolean value.
1233
1234    Args:
1235      value: A boolean value.
1236    """
1237    self._stack.append(Value.Bool(value))
1238
1239  @InMap
1240  def Int(self, value, byte_width=0):
1241    """Encodes signed integer value.
1242
1243    Args:
1244      value: A signed integer value.
1245      byte_width: Number of bytes to use: 1, 2, 4, or 8.
1246    """
1247    bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width)
1248    self._stack.append(Value.Int(value, bit_width))
1249
1250  @InMap
1251  def IndirectInt(self, value, byte_width=0):
1252    """Encodes signed integer value indirectly.
1253
1254    Args:
1255      value: A signed integer value.
1256      byte_width: Number of bytes to use: 1, 2, 4, or 8.
1257    """
1258    bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width)
1259    self._PushIndirect(value, Type.INDIRECT_INT, bit_width)
1260
1261  @InMap
1262  def UInt(self, value, byte_width=0):
1263    """Encodes unsigned integer value.
1264
1265    Args:
1266      value: An unsigned integer value.
1267      byte_width: Number of bytes to use: 1, 2, 4, or 8.
1268    """
1269    bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width)
1270    self._stack.append(Value.UInt(value, bit_width))
1271
1272  @InMap
1273  def IndirectUInt(self, value, byte_width=0):
1274    """Encodes unsigned integer value indirectly.
1275
1276    Args:
1277      value: An unsigned integer value.
1278      byte_width: Number of bytes to use: 1, 2, 4, or 8.
1279    """
1280    bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width)
1281    self._PushIndirect(value, Type.INDIRECT_UINT, bit_width)
1282
1283  @InMap
1284  def Float(self, value, byte_width=0):
1285    """Encodes floating point value.
1286
1287    Args:
1288      value: A floating point value.
1289      byte_width: Number of bytes to use: 4 or 8.
1290    """
1291    bit_width = BitWidth.F(value) if byte_width == 0 else BitWidth.B(byte_width)
1292    self._stack.append(Value.Float(value, bit_width))
1293
1294  @InMap
1295  def IndirectFloat(self, value, byte_width=0):
1296    """Encodes floating point value indirectly.
1297
1298    Args:
1299      value: A floating point value.
1300      byte_width: Number of bytes to use: 4 or 8.
1301    """
1302    bit_width = BitWidth.F(value) if byte_width == 0 else BitWidth.B(byte_width)
1303    self._PushIndirect(value, Type.INDIRECT_FLOAT, bit_width)
1304
1305  def _StartVector(self):
1306    """Starts vector construction."""
1307    return len(self._stack)
1308
1309  def _EndVector(self, start, typed, fixed):
1310    """Finishes vector construction by encodung its elements."""
1311    vec = self._CreateVector(self._stack[start:], typed, fixed)
1312    del self._stack[start:]
1313    self._stack.append(vec)
1314    return vec.Value
1315
1316  @contextlib.contextmanager
1317  def Vector(self, key=None):
1318    if key:
1319      self.Key(key)
1320
1321    try:
1322      start = self._StartVector()
1323      yield self
1324    finally:
1325      self._EndVector(start, typed=False, fixed=False)
1326
1327  @InMap
1328  def VectorFromElements(self, elements):
1329    """Encodes sequence of any elements as a vector.
1330
1331    Args:
1332      elements: sequence of elements, they may have different types.
1333    """
1334    with self.Vector():
1335      for e in elements:
1336        self.Add(e)
1337
1338  @contextlib.contextmanager
1339  def TypedVector(self, key=None):
1340    if key:
1341      self.Key(key)
1342
1343    try:
1344      start = self._StartVector()
1345      yield self
1346    finally:
1347      self._EndVector(start, typed=True, fixed=False)
1348
1349  @InMap
1350  def TypedVectorFromElements(self, elements, element_type=None):
1351    """Encodes sequence of elements of the same type as typed vector.
1352
1353    Args:
1354      elements: Sequence of elements, they must be of the same type.
1355      element_type: Suggested element type. Setting it to None means determining
1356        correct value automatically based on the given elements.
1357    """
1358    if isinstance(elements, array.array):
1359      if elements.typecode == 'f':
1360        self._WriteScalarVector(Type.FLOAT, 4, elements, fixed=False)
1361      elif elements.typecode == 'd':
1362        self._WriteScalarVector(Type.FLOAT, 8, elements, fixed=False)
1363      elif elements.typecode in ('b', 'h', 'i', 'l', 'q'):
1364        self._WriteScalarVector(
1365            Type.INT, elements.itemsize, elements, fixed=False)
1366      elif elements.typecode in ('B', 'H', 'I', 'L', 'Q'):
1367        self._WriteScalarVector(
1368            Type.UINT, elements.itemsize, elements, fixed=False)
1369      else:
1370        raise ValueError('unsupported array typecode: %s' % elements.typecode)
1371    else:
1372      add = self.Add if element_type is None else self.Adder(element_type)
1373      with self.TypedVector():
1374        for e in elements:
1375          add(e)
1376
1377  @InMap
1378  def FixedTypedVectorFromElements(self,
1379                                   elements,
1380                                   element_type=None,
1381                                   byte_width=0):
1382    """Encodes sequence of elements of the same type as fixed typed vector.
1383
1384    Args:
1385      elements: Sequence of elements, they must be of the same type. Allowed
1386        types are `Type.INT`, `Type.UINT`, `Type.FLOAT`. Allowed number of
1387        elements are 2, 3, or 4.
1388      element_type: Suggested element type. Setting it to None means determining
1389        correct value automatically based on the given elements.
1390      byte_width: Number of bytes to use per element. For `Type.INT` and
1391        `Type.UINT`: 1, 2, 4, or 8. For `Type.FLOAT`: 4 or 8. Setting it to 0
1392        means determining correct value automatically based on the given
1393        elements.
1394    """
1395    if not 2 <= len(elements) <= 4:
1396      raise ValueError('only 2, 3, or 4 elements are supported')
1397
1398    types = {type(e) for e in elements}
1399    if len(types) != 1:
1400      raise TypeError('all elements must be of the same type')
1401
1402    type_, = types
1403
1404    if element_type is None:
1405      element_type = {int: Type.INT, float: Type.FLOAT}.get(type_)
1406      if not element_type:
1407        raise TypeError('unsupported element_type: %s' % type_)
1408
1409    if byte_width == 0:
1410      width = {
1411          Type.UINT: BitWidth.U,
1412          Type.INT: BitWidth.I,
1413          Type.FLOAT: BitWidth.F
1414      }[element_type]
1415      byte_width = 1 << max(width(e) for e in elements)
1416
1417    self._WriteScalarVector(element_type, byte_width, elements, fixed=True)
1418
1419  def _StartMap(self):
1420    """Starts map construction."""
1421    return len(self._stack)
1422
1423  def _EndMap(self, start):
1424    """Finishes map construction by encodung its elements."""
1425    # Interleaved keys and values on the stack.
1426    stack = self._stack[start:]
1427
1428    if len(stack) % 2 != 0:
1429      raise RuntimeError('must be even number of keys and values')
1430
1431    for key in stack[::2]:
1432      if key.Type is not Type.KEY:
1433        raise RuntimeError('all map keys must be of %s type' % Type.KEY)
1434
1435    pairs = zip(stack[::2], stack[1::2])  # [(key, value), ...]
1436    pairs = sorted(pairs, key=lambda pair: self._ReadKey(pair[0].Value))
1437
1438    del self._stack[start:]
1439    for pair in pairs:
1440      self._stack.extend(pair)
1441
1442    keys = self._CreateVector(self._stack[start::2], typed=True, fixed=False)
1443    values = self._CreateVector(
1444        self._stack[start + 1::2], typed=False, fixed=False, keys=keys)
1445
1446    del self._stack[start:]
1447    self._stack.append(values)
1448    return values.Value
1449
1450  @contextlib.contextmanager
1451  def Map(self, key=None):
1452    if key:
1453      self.Key(key)
1454
1455    try:
1456      start = self._StartMap()
1457      yield self
1458    finally:
1459      self._EndMap(start)
1460
1461  def MapFromElements(self, elements):
1462    start = self._StartMap()
1463    for k, v in elements.items():
1464      self.Key(k)
1465      self.Add(v)
1466    self._EndMap(start)
1467
1468  def Adder(self, type_):
1469    return {
1470        Type.BOOL: self.Bool,
1471        Type.INT: self.Int,
1472        Type.INDIRECT_INT: self.IndirectInt,
1473        Type.UINT: self.UInt,
1474        Type.INDIRECT_UINT: self.IndirectUInt,
1475        Type.FLOAT: self.Float,
1476        Type.INDIRECT_FLOAT: self.IndirectFloat,
1477        Type.KEY: self.Key,
1478        Type.BLOB: self.Blob,
1479        Type.STRING: self.String,
1480    }[type_]
1481
1482  @InMapForString
1483  def Add(self, value):
1484    """Encodes value of any supported type."""
1485    if value is None:
1486      self.Null()
1487    elif isinstance(value, bool):
1488      self.Bool(value)
1489    elif isinstance(value, int):
1490      self.Int(value)
1491    elif isinstance(value, float):
1492      self.Float(value)
1493    elif isinstance(value, str):
1494      self.String(value)
1495    elif isinstance(value, (bytes, bytearray)):
1496      self.Blob(value)
1497    elif isinstance(value, dict):
1498      with self.Map():
1499        for k, v in value.items():
1500          self.Key(k)
1501          self.Add(v)
1502    elif isinstance(value, array.array):
1503      self.TypedVectorFromElements(value)
1504    elif _IsIterable(value):
1505      self.VectorFromElements(value)
1506    else:
1507      raise TypeError('unsupported python type: %s' % type(value))
1508
1509  @property
1510  def LastValue(self):
1511    return self._stack[-1]
1512
1513  @InMap
1514  def ReuseValue(self, value):
1515    self._stack.append(value)
1516
1517
1518def GetRoot(buf):
1519  """Returns root `Ref` object for the given buffer."""
1520  if len(buf) < 3:
1521    raise ValueError('buffer is too small')
1522  byte_width = buf[-1]
1523  return Ref.PackedType(
1524      Buf(buf, -(2 + byte_width)), byte_width, packed_type=buf[-2])
1525
1526
1527def Dumps(obj):
1528  """Returns bytearray with the encoded python object."""
1529  fbb = Builder()
1530  fbb.Add(obj)
1531  return fbb.Finish()
1532
1533
1534def Loads(buf):
1535  """Returns python object decoded from the buffer."""
1536  return GetRoot(buf).Value
1537