/thirdparty/breakpad/third_party/protobuf/protobuf/python/google/protobuf/internal/type_checkers.py

http://github.com/tomahawk-player/tomahawk · Python · 286 lines · 169 code · 40 blank · 77 comment · 8 complexity · cb92b4e0a9d5ae87f5c18afc4ac99540 MD5 · raw file

  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # http://code.google.com/p/protobuf/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Provides type checking routines.
  31. This module defines type checking utilities in the forms of dictionaries:
  32. VALUE_CHECKERS: A dictionary of field types and a value validation object.
  33. TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing
  34. function.
  35. TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization
  36. function.
  37. FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their
  38. coresponding wire types.
  39. TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization
  40. function.
  41. """
  42. __author__ = 'robinson@google.com (Will Robinson)'
  43. from google.protobuf.internal import decoder
  44. from google.protobuf.internal import encoder
  45. from google.protobuf.internal import wire_format
  46. from google.protobuf import descriptor
  47. _FieldDescriptor = descriptor.FieldDescriptor
  48. def GetTypeChecker(cpp_type, field_type):
  49. """Returns a type checker for a message field of the specified types.
  50. Args:
  51. cpp_type: C++ type of the field (see descriptor.py).
  52. field_type: Protocol message field type (see descriptor.py).
  53. Returns:
  54. An instance of TypeChecker which can be used to verify the types
  55. of values assigned to a field of the specified type.
  56. """
  57. if (cpp_type == _FieldDescriptor.CPPTYPE_STRING and
  58. field_type == _FieldDescriptor.TYPE_STRING):
  59. return UnicodeValueChecker()
  60. return _VALUE_CHECKERS[cpp_type]
  61. # None of the typecheckers below make any attempt to guard against people
  62. # subclassing builtin types and doing weird things. We're not trying to
  63. # protect against malicious clients here, just people accidentally shooting
  64. # themselves in the foot in obvious ways.
  65. class TypeChecker(object):
  66. """Type checker used to catch type errors as early as possible
  67. when the client is setting scalar fields in protocol messages.
  68. """
  69. def __init__(self, *acceptable_types):
  70. self._acceptable_types = acceptable_types
  71. def CheckValue(self, proposed_value):
  72. if not isinstance(proposed_value, self._acceptable_types):
  73. message = ('%.1024r has type %s, but expected one of: %s' %
  74. (proposed_value, type(proposed_value), self._acceptable_types))
  75. raise TypeError(message)
  76. # IntValueChecker and its subclasses perform integer type-checks
  77. # and bounds-checks.
  78. class IntValueChecker(object):
  79. """Checker used for integer fields. Performs type-check and range check."""
  80. def CheckValue(self, proposed_value):
  81. if not isinstance(proposed_value, (int, long)):
  82. message = ('%.1024r has type %s, but expected one of: %s' %
  83. (proposed_value, type(proposed_value), (int, long)))
  84. raise TypeError(message)
  85. if not self._MIN <= proposed_value <= self._MAX:
  86. raise ValueError('Value out of range: %d' % proposed_value)
  87. class UnicodeValueChecker(object):
  88. """Checker used for string fields."""
  89. def CheckValue(self, proposed_value):
  90. if not isinstance(proposed_value, (str, unicode)):
  91. message = ('%.1024r has type %s, but expected one of: %s' %
  92. (proposed_value, type(proposed_value), (str, unicode)))
  93. raise TypeError(message)
  94. # If the value is of type 'str' make sure that it is in 7-bit ASCII
  95. # encoding.
  96. if isinstance(proposed_value, str):
  97. try:
  98. unicode(proposed_value, 'ascii')
  99. except UnicodeDecodeError:
  100. raise ValueError('%.1024r has type str, but isn\'t in 7-bit ASCII '
  101. 'encoding. Non-ASCII strings must be converted to '
  102. 'unicode objects before being added.' %
  103. (proposed_value))
  104. class Int32ValueChecker(IntValueChecker):
  105. # We're sure to use ints instead of longs here since comparison may be more
  106. # efficient.
  107. _MIN = -2147483648
  108. _MAX = 2147483647
  109. class Uint32ValueChecker(IntValueChecker):
  110. _MIN = 0
  111. _MAX = (1 << 32) - 1
  112. class Int64ValueChecker(IntValueChecker):
  113. _MIN = -(1 << 63)
  114. _MAX = (1 << 63) - 1
  115. class Uint64ValueChecker(IntValueChecker):
  116. _MIN = 0
  117. _MAX = (1 << 64) - 1
  118. # Type-checkers for all scalar CPPTYPEs.
  119. _VALUE_CHECKERS = {
  120. _FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(),
  121. _FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(),
  122. _FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(),
  123. _FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(),
  124. _FieldDescriptor.CPPTYPE_DOUBLE: TypeChecker(
  125. float, int, long),
  126. _FieldDescriptor.CPPTYPE_FLOAT: TypeChecker(
  127. float, int, long),
  128. _FieldDescriptor.CPPTYPE_BOOL: TypeChecker(bool, int),
  129. _FieldDescriptor.CPPTYPE_ENUM: Int32ValueChecker(),
  130. _FieldDescriptor.CPPTYPE_STRING: TypeChecker(str),
  131. }
  132. # Map from field type to a function F, such that F(field_num, value)
  133. # gives the total byte size for a value of the given type. This
  134. # byte size includes tag information and any other additional space
  135. # associated with serializing "value".
  136. TYPE_TO_BYTE_SIZE_FN = {
  137. _FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize,
  138. _FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize,
  139. _FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize,
  140. _FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize,
  141. _FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize,
  142. _FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize,
  143. _FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize,
  144. _FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize,
  145. _FieldDescriptor.TYPE_STRING: wire_format.StringByteSize,
  146. _FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize,
  147. _FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize,
  148. _FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize,
  149. _FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize,
  150. _FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize,
  151. _FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize,
  152. _FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize,
  153. _FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize,
  154. _FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize
  155. }
  156. # Maps from field types to encoder constructors.
  157. TYPE_TO_ENCODER = {
  158. _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder,
  159. _FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder,
  160. _FieldDescriptor.TYPE_INT64: encoder.Int64Encoder,
  161. _FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder,
  162. _FieldDescriptor.TYPE_INT32: encoder.Int32Encoder,
  163. _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder,
  164. _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder,
  165. _FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder,
  166. _FieldDescriptor.TYPE_STRING: encoder.StringEncoder,
  167. _FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder,
  168. _FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder,
  169. _FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder,
  170. _FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder,
  171. _FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder,
  172. _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder,
  173. _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder,
  174. _FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder,
  175. _FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder,
  176. }
  177. # Maps from field types to sizer constructors.
  178. TYPE_TO_SIZER = {
  179. _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer,
  180. _FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer,
  181. _FieldDescriptor.TYPE_INT64: encoder.Int64Sizer,
  182. _FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer,
  183. _FieldDescriptor.TYPE_INT32: encoder.Int32Sizer,
  184. _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer,
  185. _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer,
  186. _FieldDescriptor.TYPE_BOOL: encoder.BoolSizer,
  187. _FieldDescriptor.TYPE_STRING: encoder.StringSizer,
  188. _FieldDescriptor.TYPE_GROUP: encoder.GroupSizer,
  189. _FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer,
  190. _FieldDescriptor.TYPE_BYTES: encoder.BytesSizer,
  191. _FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer,
  192. _FieldDescriptor.TYPE_ENUM: encoder.EnumSizer,
  193. _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer,
  194. _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer,
  195. _FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer,
  196. _FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer,
  197. }
  198. # Maps from field type to a decoder constructor.
  199. TYPE_TO_DECODER = {
  200. _FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder,
  201. _FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder,
  202. _FieldDescriptor.TYPE_INT64: decoder.Int64Decoder,
  203. _FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder,
  204. _FieldDescriptor.TYPE_INT32: decoder.Int32Decoder,
  205. _FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder,
  206. _FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder,
  207. _FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder,
  208. _FieldDescriptor.TYPE_STRING: decoder.StringDecoder,
  209. _FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder,
  210. _FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder,
  211. _FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder,
  212. _FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder,
  213. _FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder,
  214. _FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder,
  215. _FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder,
  216. _FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder,
  217. _FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder,
  218. }
  219. # Maps from field type to expected wiretype.
  220. FIELD_TYPE_TO_WIRE_TYPE = {
  221. _FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64,
  222. _FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32,
  223. _FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT,
  224. _FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT,
  225. _FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT,
  226. _FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64,
  227. _FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32,
  228. _FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT,
  229. _FieldDescriptor.TYPE_STRING:
  230. wire_format.WIRETYPE_LENGTH_DELIMITED,
  231. _FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP,
  232. _FieldDescriptor.TYPE_MESSAGE:
  233. wire_format.WIRETYPE_LENGTH_DELIMITED,
  234. _FieldDescriptor.TYPE_BYTES:
  235. wire_format.WIRETYPE_LENGTH_DELIMITED,
  236. _FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT,
  237. _FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT,
  238. _FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32,
  239. _FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64,
  240. _FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT,
  241. _FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT,
  242. }