31 """Constants and static functions to support protocol buffer wire format."""
33 __author__ =
'robinson@google.com (Will Robinson)'
41 TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1
49 WIRETYPE_LENGTH_DELIMITED = 2
50 WIRETYPE_START_GROUP = 3
51 WIRETYPE_END_GROUP = 4
57 INT32_MAX = int((1 << 31) - 1)
58 INT32_MIN = int(-(1 << 31))
59 UINT32_MAX = (1 << 32) - 1
61 INT64_MAX = (1 << 63) - 1
62 INT64_MIN = -(1 << 63)
63 UINT64_MAX = (1 << 64) - 1
66 FORMAT_UINT32_LITTLE_ENDIAN =
'<I'
67 FORMAT_UINT64_LITTLE_ENDIAN =
'<Q'
68 FORMAT_FLOAT_LITTLE_ENDIAN =
'<f'
69 FORMAT_DOUBLE_LITTLE_ENDIAN =
'<d'
74 if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4:
75 raise AssertionError(
'Format "I" is not a 32-bit number.')
76 if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8:
77 raise AssertionError(
'Format "Q" is not a 64-bit number.')
81 """Returns an unsigned 32-bit integer that encodes the field number and
82 wire type information in standard protocol message wire format.
85 field_number: Expected to be an integer in the range [1, 1 << 29)
86 wire_type: One of the WIRETYPE_* constants.
88 if not 0 <= wire_type <= _WIRETYPE_MAX:
89 raise message.EncodeError(
'Unknown wire type: %d' % wire_type)
90 return (field_number << TAG_TYPE_BITS) | wire_type
94 """The inverse of PackTag(). Given an unsigned 32-bit number,
95 returns a (field_number, wire_type) tuple.
97 return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK)
101 """ZigZag Transform: Encodes signed integers so that they can be
102 effectively used with varint encoding. See wire_format.h for
107 return (value << 1) ^ (~0)
111 """Inverse of ZigZagEncode()."""
114 return (value >> 1) ^ (~0)
195 + message.ByteSize())
201 + message.ByteSize())
214 message_size = msg.ByteSize()
220 total_size += message_size
225 """Returns the bytes required to serialize a tag with this field number."""
233 """Returns the number of bytes required to serialize a single varint
234 using boundary value comparisons. (unrolled loop optimization -WPierce)
235 uint64 must be unsigned.
237 if uint64 <= 0x7f:
return 1
238 if uint64 <= 0x3fff:
return 2
239 if uint64 <= 0x1fffff:
return 3
240 if uint64 <= 0xfffffff:
return 4
241 if uint64 <= 0x7ffffffff:
return 5
242 if uint64 <= 0x3ffffffffff:
return 6
243 if uint64 <= 0x1ffffffffffff:
return 7
244 if uint64 <= 0xffffffffffffff:
return 8
245 if uint64 <= 0x7fffffffffffffff:
return 9
246 if uint64 > UINT64_MAX:
247 raise message.EncodeError(
'Value out of range: %d' % uint64)
251 NON_PACKABLE_TYPES = (
252 descriptor.FieldDescriptor.TYPE_STRING,
253 descriptor.FieldDescriptor.TYPE_GROUP,
254 descriptor.FieldDescriptor.TYPE_MESSAGE,
255 descriptor.FieldDescriptor.TYPE_BYTES
260 """Return true iff packable = true is valid for fields of this type.
263 field_type: a FieldDescriptor::Type value.
266 True iff fields of this type are packable.
268 return field_type
not in NON_PACKABLE_TYPES