Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

280 lines
9.9 KiB

  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. # TODO(robinson): We should just make these methods all "pure-virtual" and move
  31. # all implementation out, into reflection.py for now.
  32. """Contains an abstract base class for protocol messages."""
  33. __author__ = '[email protected] (Will Robinson)'
  34. class Error(Exception): pass
  35. class DecodeError(Error): pass
  36. class EncodeError(Error): pass
  37. class Message(object):
  38. """Abstract base class for protocol messages.
  39. Protocol message classes are almost always generated by the protocol
  40. compiler. These generated types subclass Message and implement the methods
  41. shown below.
  42. TODO(robinson): Link to an HTML document here.
  43. TODO(robinson): Document that instances of this class will also
  44. have an Extensions attribute with __getitem__ and __setitem__.
  45. Again, not sure how to best convey this.
  46. TODO(robinson): Document that the class must also have a static
  47. RegisterExtension(extension_field) method.
  48. Not sure how to best express at this point.
  49. """
  50. # TODO(robinson): Document these fields and methods.
  51. __slots__ = []
  52. DESCRIPTOR = None
  53. def __deepcopy__(self, memo=None):
  54. clone = type(self)()
  55. clone.MergeFrom(self)
  56. return clone
  57. def __eq__(self, other_msg):
  58. """Recursively compares two messages by value and structure."""
  59. raise NotImplementedError
  60. def __ne__(self, other_msg):
  61. # Can't just say self != other_msg, since that would infinitely recurse. :)
  62. return not self == other_msg
  63. def __hash__(self):
  64. raise TypeError('unhashable object')
  65. def __str__(self):
  66. """Outputs a human-readable representation of the message."""
  67. raise NotImplementedError
  68. def __unicode__(self):
  69. """Outputs a human-readable representation of the message."""
  70. raise NotImplementedError
  71. def MergeFrom(self, other_msg):
  72. """Merges the contents of the specified message into current message.
  73. This method merges the contents of the specified message into the current
  74. message. Singular fields that are set in the specified message overwrite
  75. the corresponding fields in the current message. Repeated fields are
  76. appended. Singular sub-messages and groups are recursively merged.
  77. Args:
  78. other_msg: Message to merge into the current message.
  79. """
  80. raise NotImplementedError
  81. def CopyFrom(self, other_msg):
  82. """Copies the content of the specified message into the current message.
  83. The method clears the current message and then merges the specified
  84. message using MergeFrom.
  85. Args:
  86. other_msg: Message to copy into the current one.
  87. """
  88. if self is other_msg:
  89. return
  90. self.Clear()
  91. self.MergeFrom(other_msg)
  92. def Clear(self):
  93. """Clears all data that was set in the message."""
  94. raise NotImplementedError
  95. def SetInParent(self):
  96. """Mark this as present in the parent.
  97. This normally happens automatically when you assign a field of a
  98. sub-message, but sometimes you want to make the sub-message
  99. present while keeping it empty. If you find yourself using this,
  100. you may want to reconsider your design."""
  101. raise NotImplementedError
  102. def IsInitialized(self):
  103. """Checks if the message is initialized.
  104. Returns:
  105. The method returns True if the message is initialized (i.e. all of its
  106. required fields are set).
  107. """
  108. raise NotImplementedError
  109. # TODO(robinson): MergeFromString() should probably return None and be
  110. # implemented in terms of a helper that returns the # of bytes read. Our
  111. # deserialization routines would use the helper when recursively
  112. # deserializing, but the end user would almost always just want the no-return
  113. # MergeFromString().
  114. def MergeFromString(self, serialized):
  115. """Merges serialized protocol buffer data into this message.
  116. When we find a field in |serialized| that is already present
  117. in this message:
  118. - If it's a "repeated" field, we append to the end of our list.
  119. - Else, if it's a scalar, we overwrite our field.
  120. - Else, (it's a nonrepeated composite), we recursively merge
  121. into the existing composite.
  122. TODO(robinson): Document handling of unknown fields.
  123. Args:
  124. serialized: Any object that allows us to call buffer(serialized)
  125. to access a string of bytes using the buffer interface.
  126. TODO(robinson): When we switch to a helper, this will return None.
  127. Returns:
  128. The number of bytes read from |serialized|.
  129. For non-group messages, this will always be len(serialized),
  130. but for messages which are actually groups, this will
  131. generally be less than len(serialized), since we must
  132. stop when we reach an END_GROUP tag. Note that if
  133. we *do* stop because of an END_GROUP tag, the number
  134. of bytes returned does not include the bytes
  135. for the END_GROUP tag information.
  136. """
  137. raise NotImplementedError
  138. def ParseFromString(self, serialized):
  139. """Like MergeFromString(), except we clear the object first."""
  140. self.Clear()
  141. self.MergeFromString(serialized)
  142. def SerializeToString(self):
  143. """Serializes the protocol message to a binary string.
  144. Returns:
  145. A binary string representation of the message if all of the required
  146. fields in the message are set (i.e. the message is initialized).
  147. Raises:
  148. message.EncodeError if the message isn't initialized.
  149. """
  150. raise NotImplementedError
  151. def SerializePartialToString(self):
  152. """Serializes the protocol message to a binary string.
  153. This method is similar to SerializeToString but doesn't check if the
  154. message is initialized.
  155. Returns:
  156. A string representation of the partial message.
  157. """
  158. raise NotImplementedError
  159. # TODO(robinson): Decide whether we like these better
  160. # than auto-generated has_foo() and clear_foo() methods
  161. # on the instances themselves. This way is less consistent
  162. # with C++, but it makes reflection-type access easier and
  163. # reduces the number of magically autogenerated things.
  164. #
  165. # TODO(robinson): Be sure to document (and test) exactly
  166. # which field names are accepted here. Are we case-sensitive?
  167. # What do we do with fields that share names with Python keywords
  168. # like 'lambda' and 'yield'?
  169. #
  170. # nnorwitz says:
  171. # """
  172. # Typically (in python), an underscore is appended to names that are
  173. # keywords. So they would become lambda_ or yield_.
  174. # """
  175. def ListFields(self):
  176. """Returns a list of (FieldDescriptor, value) tuples for all
  177. fields in the message which are not empty. A singular field is non-empty
  178. if HasField() would return true, and a repeated field is non-empty if
  179. it contains at least one element. The fields are ordered by field
  180. number"""
  181. raise NotImplementedError
  182. def HasField(self, field_name):
  183. """Checks if a certain field is set for the message. Note if the
  184. field_name is not defined in the message descriptor, ValueError will be
  185. raised."""
  186. raise NotImplementedError
  187. def ClearField(self, field_name):
  188. raise NotImplementedError
  189. def HasExtension(self, extension_handle):
  190. raise NotImplementedError
  191. def ClearExtension(self, extension_handle):
  192. raise NotImplementedError
  193. def ByteSize(self):
  194. """Returns the serialized size of this message.
  195. Recursively calls ByteSize() on all contained messages.
  196. """
  197. raise NotImplementedError
  198. def _SetListener(self, message_listener):
  199. """Internal method used by the protocol message implementation.
  200. Clients should not call this directly.
  201. Sets a listener that this message will call on certain state transitions.
  202. The purpose of this method is to register back-edges from children to
  203. parents at runtime, for the purpose of setting "has" bits and
  204. byte-size-dirty bits in the parent and ancestor objects whenever a child or
  205. descendant object is modified.
  206. If the client wants to disconnect this Message from the object tree, she
  207. explicitly sets callback to None.
  208. If message_listener is None, unregisters any existing listener. Otherwise,
  209. message_listener must implement the MessageListener interface in
  210. internal/message_listener.py, and we discard any listener registered
  211. via a previous _SetListener() call.
  212. """
  213. raise NotImplementedError
  214. def __getstate__(self):
  215. """Support the pickle protocol."""
  216. return dict(serialized=self.SerializePartialToString())
  217. def __setstate__(self, state):
  218. """Support the pickle protocol."""
  219. self.__init__()
  220. self.ParseFromString(state['serialized'])