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