message.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc.
  3. # http://code.google.com/p/protobuf/
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # TODO(robinson): We should just make these methods all "pure-virtual" and move
  17. # all implementation out, into reflection.py for now.
  18. """Contains an abstract base class for protocol messages."""
  19. __author__ = 'robinson@google.com (Will Robinson)'
  20. from google.protobuf import text_format
  21. class Error(Exception): pass
  22. class DecodeError(Error): pass
  23. class EncodeError(Error): pass
  24. class Message(object):
  25. """Abstract base class for protocol messages.
  26. Protocol message classes are almost always generated by the protocol
  27. compiler. These generated types subclass Message and implement the methods
  28. shown below.
  29. TODO(robinson): Link to an HTML document here.
  30. TODO(robinson): Document that instances of this class will also
  31. have an Extensions attribute with __getitem__ and __setitem__.
  32. Again, not sure how to best convey this.
  33. TODO(robinson): Document that the class must also have a static
  34. RegisterExtension(extension_field) method.
  35. Not sure how to best express at this point.
  36. """
  37. # TODO(robinson): Document these fields and methods.
  38. __slots__ = []
  39. DESCRIPTOR = None
  40. def __eq__(self, other_msg):
  41. raise NotImplementedError
  42. def __ne__(self, other_msg):
  43. # Can't just say self != other_msg, since that would infinitely recurse. :)
  44. return not self == other_msg
  45. def __str__(self):
  46. return text_format.MessageToString(self)
  47. def MergeFrom(self, other_msg):
  48. """Merges the contents of the specified message into current message.
  49. This method merges the contents of the specified message into the current
  50. message. Singular fields that are set in the specified message overwrite
  51. the corresponding fields in the current message. Repeated fields are
  52. appended. Singular sub-messages and groups are recursively merged.
  53. Args:
  54. other_msg: Message to merge into the current message.
  55. """
  56. raise NotImplementedError
  57. def CopyFrom(self, other_msg):
  58. """Copies the content of the specified message into the current message.
  59. The method clears the current message and then merges the specified
  60. message using MergeFrom.
  61. Args:
  62. other_msg: Message to copy into the current one.
  63. """
  64. if self == other_msg:
  65. return
  66. self.Clear()
  67. self.MergeFrom(other_msg)
  68. def Clear(self):
  69. """Clears all data that was set in the message."""
  70. raise NotImplementedError
  71. def IsInitialized(self):
  72. """Checks if the message is initialized.
  73. Returns:
  74. The method returns True if the message is initialized (i.e. all of its
  75. required fields are set).
  76. """
  77. raise NotImplementedError
  78. # TODO(robinson): MergeFromString() should probably return None and be
  79. # implemented in terms of a helper that returns the # of bytes read. Our
  80. # deserialization routines would use the helper when recursively
  81. # deserializing, but the end user would almost always just want the no-return
  82. # MergeFromString().
  83. def MergeFromString(self, serialized):
  84. """Merges serialized protocol buffer data into this message.
  85. When we find a field in |serialized| that is already present
  86. in this message:
  87. - If it's a "repeated" field, we append to the end of our list.
  88. - Else, if it's a scalar, we overwrite our field.
  89. - Else, (it's a nonrepeated composite), we recursively merge
  90. into the existing composite.
  91. TODO(robinson): Document handling of unknown fields.
  92. Args:
  93. serialized: Any object that allows us to call buffer(serialized)
  94. to access a string of bytes using the buffer interface.
  95. TODO(robinson): When we switch to a helper, this will return None.
  96. Returns:
  97. The number of bytes read from |serialized|.
  98. For non-group messages, this will always be len(serialized),
  99. but for messages which are actually groups, this will
  100. generally be less than len(serialized), since we must
  101. stop when we reach an END_GROUP tag. Note that if
  102. we *do* stop because of an END_GROUP tag, the number
  103. of bytes returned does not include the bytes
  104. for the END_GROUP tag information.
  105. """
  106. raise NotImplementedError
  107. def ParseFromString(self, serialized):
  108. """Like MergeFromString(), except we clear the object first."""
  109. self.Clear()
  110. self.MergeFromString(serialized)
  111. def SerializeToString(self):
  112. """Serializes the protocol message to a binary string.
  113. Returns:
  114. A binary string representation of the message if all of the required
  115. fields in the message are set (i.e. the message is initialized).
  116. Raises:
  117. message.EncodeError if the message isn't initialized.
  118. """
  119. raise NotImplementedError
  120. def SerializePartialToString(self):
  121. """Serializes the protocol message to a binary string.
  122. This method is similar to SerializeToString but doesn't check if the
  123. message is initialized.
  124. Returns:
  125. A string representation of the partial message.
  126. """
  127. raise NotImplementedError
  128. # TODO(robinson): Decide whether we like these better
  129. # than auto-generated has_foo() and clear_foo() methods
  130. # on the instances themselves. This way is less consistent
  131. # with C++, but it makes reflection-type access easier and
  132. # reduces the number of magically autogenerated things.
  133. #
  134. # TODO(robinson): Be sure to document (and test) exactly
  135. # which field names are accepted here. Are we case-sensitive?
  136. # What do we do with fields that share names with Python keywords
  137. # like 'lambda' and 'yield'?
  138. #
  139. # nnorwitz says:
  140. # """
  141. # Typically (in python), an underscore is appended to names that are
  142. # keywords. So they would become lambda_ or yield_.
  143. # """
  144. def ListFields(self, field_name):
  145. """Returns a list of (FieldDescriptor, value) tuples for all
  146. fields in the message which are not empty. A singular field is non-empty
  147. if HasField() would return true, and a repeated field is non-empty if
  148. it contains at least one element. The fields are ordered by field
  149. number"""
  150. raise NotImplementedError
  151. def HasField(self, field_name):
  152. raise NotImplementedError
  153. def ClearField(self, field_name):
  154. raise NotImplementedError
  155. def HasExtension(self, extension_handle):
  156. raise NotImplementedError
  157. def ClearExtension(self, extension_handle):
  158. raise NotImplementedError
  159. def ByteSize(self):
  160. """Returns the serialized size of this message.
  161. Recursively calls ByteSize() on all contained messages.
  162. """
  163. raise NotImplementedError
  164. def _SetListener(self, message_listener):
  165. """Internal method used by the protocol message implementation.
  166. Clients should not call this directly.
  167. Sets a listener that this message will call on certain state transitions.
  168. The purpose of this method is to register back-edges from children to
  169. parents at runtime, for the purpose of setting "has" bits and
  170. byte-size-dirty bits in the parent and ancestor objects whenever a child or
  171. descendant object is modified.
  172. If the client wants to disconnect this Message from the object tree, she
  173. explicitly sets callback to None.
  174. If message_listener is None, unregisters any existing listener. Otherwise,
  175. message_listener must implement the MessageListener interface in
  176. internal/message_listener.py, and we discard any listener registered
  177. via a previous _SetListener() call.
  178. """
  179. raise NotImplementedError