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):
40  """Base error type for this module."""
41  pass
42
43
44class DecodeError(Error):
45  """Exception raised when deserializing messages."""
46  pass
47
48
49class EncodeError(Error):
50  """Exception raised when serializing messages."""
51  pass
52
53
54class Message(object):
55
56  """Abstract base class for protocol messages.
57
58  Protocol message classes are almost always generated by the protocol
59  compiler.  These generated types subclass Message and implement the methods
60  shown below.
61  """
62
63  # TODO(robinson): Link to an HTML document here.
64
65  # TODO(robinson): Document that instances of this class will also
66  # have an Extensions attribute with __getitem__ and __setitem__.
67  # Again, not sure how to best convey this.
68
69  # TODO(robinson): Document that the class must also have a static
70  #   RegisterExtension(extension_field) method.
71  #   Not sure how to best express at this point.
72
73  # TODO(robinson): Document these fields and methods.
74
75  __slots__ = []
76
77  #: The :class:`google.protobuf.descriptor.Descriptor` for this message type.
78  DESCRIPTOR = None
79
80  def __deepcopy__(self, memo=None):
81    clone = type(self)()
82    clone.MergeFrom(self)
83    return clone
84
85  def __eq__(self, other_msg):
86    """Recursively compares two messages by value and structure."""
87    raise NotImplementedError
88
89  def __ne__(self, other_msg):
90    # Can't just say self != other_msg, since that would infinitely recurse. :)
91    return not self == other_msg
92
93  def __hash__(self):
94    raise TypeError('unhashable object')
95
96  def __str__(self):
97    """Outputs a human-readable representation of the message."""
98    raise NotImplementedError
99
100  def __unicode__(self):
101    """Outputs a human-readable representation of the message."""
102    raise NotImplementedError
103
104  def MergeFrom(self, other_msg):
105    """Merges the contents of the specified message into current message.
106
107    This method merges the contents of the specified message into the current
108    message. Singular fields that are set in the specified message overwrite
109    the corresponding fields in the current message. Repeated fields are
110    appended. Singular sub-messages and groups are recursively merged.
111
112    Args:
113      other_msg (Message): A message to merge into the current message.
114    """
115    raise NotImplementedError
116
117  def CopyFrom(self, other_msg):
118    """Copies the content of the specified message into the current message.
119
120    The method clears the current message and then merges the specified
121    message using MergeFrom.
122
123    Args:
124      other_msg (Message): A message to copy into the current one.
125    """
126    if self is other_msg:
127      return
128    self.Clear()
129    self.MergeFrom(other_msg)
130
131  def Clear(self):
132    """Clears all data that was set in the message."""
133    raise NotImplementedError
134
135  def SetInParent(self):
136    """Mark this as present in the parent.
137
138    This normally happens automatically when you assign a field of a
139    sub-message, but sometimes you want to make the sub-message
140    present while keeping it empty.  If you find yourself using this,
141    you may want to reconsider your design.
142    """
143    raise NotImplementedError
144
145  def IsInitialized(self):
146    """Checks if the message is initialized.
147
148    Returns:
149      bool: The method returns True if the message is initialized (i.e. all of
150      its required fields are set).
151    """
152    raise NotImplementedError
153
154  # TODO(robinson): MergeFromString() should probably return None and be
155  # implemented in terms of a helper that returns the # of bytes read.  Our
156  # deserialization routines would use the helper when recursively
157  # deserializing, but the end user would almost always just want the no-return
158  # MergeFromString().
159
160  def MergeFromString(self, serialized):
161    """Merges serialized protocol buffer data into this message.
162
163    When we find a field in `serialized` that is already present
164    in this message:
165
166    -   If it's a "repeated" field, we append to the end of our list.
167    -   Else, if it's a scalar, we overwrite our field.
168    -   Else, (it's a nonrepeated composite), we recursively merge
169        into the existing composite.
170
171    Args:
172      serialized (bytes): Any object that allows us to call
173        ``memoryview(serialized)`` to access a string of bytes using the
174        buffer interface.
175
176    Returns:
177      int: The number of bytes read from `serialized`.
178      For non-group messages, this will always be `len(serialized)`,
179      but for messages which are actually groups, this will
180      generally be less than `len(serialized)`, since we must
181      stop when we reach an ``END_GROUP`` tag.  Note that if
182      we *do* stop because of an ``END_GROUP`` tag, the number
183      of bytes returned does not include the bytes
184      for the ``END_GROUP`` tag information.
185
186    Raises:
187      DecodeError: if the input cannot be parsed.
188    """
189    # TODO(robinson): Document handling of unknown fields.
190    # TODO(robinson): When we switch to a helper, this will return None.
191    raise NotImplementedError
192
193  def ParseFromString(self, serialized):
194    """Parse serialized protocol buffer data into this message.
195
196    Like :func:`MergeFromString()`, except we clear the object first.
197    """
198    self.Clear()
199    return self.MergeFromString(serialized)
200
201  def SerializeToString(self, **kwargs):
202    """Serializes the protocol message to a binary string.
203
204    Keyword Args:
205      deterministic (bool): If true, requests deterministic serialization
206        of the protobuf, with predictable ordering of map keys.
207
208    Returns:
209      A binary string representation of the message if all of the required
210      fields in the message are set (i.e. the message is initialized).
211
212    Raises:
213      EncodeError: if the message isn't initialized (see :func:`IsInitialized`).
214    """
215    raise NotImplementedError
216
217  def SerializePartialToString(self, **kwargs):
218    """Serializes the protocol message to a binary string.
219
220    This method is similar to SerializeToString but doesn't check if the
221    message is initialized.
222
223    Keyword Args:
224      deterministic (bool): If true, requests deterministic serialization
225        of the protobuf, with predictable ordering of map keys.
226
227    Returns:
228      bytes: A serialized representation of the partial message.
229    """
230    raise NotImplementedError
231
232  # TODO(robinson): Decide whether we like these better
233  # than auto-generated has_foo() and clear_foo() methods
234  # on the instances themselves.  This way is less consistent
235  # with C++, but it makes reflection-type access easier and
236  # reduces the number of magically autogenerated things.
237  #
238  # TODO(robinson): Be sure to document (and test) exactly
239  # which field names are accepted here.  Are we case-sensitive?
240  # What do we do with fields that share names with Python keywords
241  # like 'lambda' and 'yield'?
242  #
243  # nnorwitz says:
244  # """
245  # Typically (in python), an underscore is appended to names that are
246  # keywords. So they would become lambda_ or yield_.
247  # """
248  def ListFields(self):
249    """Returns a list of (FieldDescriptor, value) tuples for present fields.
250
251    A message field is non-empty if HasField() would return true. A singular
252    primitive field is non-empty if HasField() would return true in proto2 or it
253    is non zero in proto3. A repeated field is non-empty if it contains at least
254    one element. The fields are ordered by field number.
255
256    Returns:
257      list[tuple(FieldDescriptor, value)]: field descriptors and values
258      for all fields in the message which are not empty. The values vary by
259      field type.
260    """
261    raise NotImplementedError
262
263  def HasField(self, field_name):
264    """Checks if a certain field is set for the message.
265
266    For a oneof group, checks if any field inside is set. Note that if the
267    field_name is not defined in the message descriptor, :exc:`ValueError` will
268    be raised.
269
270    Args:
271      field_name (str): The name of the field to check for presence.
272
273    Returns:
274      bool: Whether a value has been set for the named field.
275
276    Raises:
277      ValueError: if the `field_name` is not a member of this message.
278    """
279    raise NotImplementedError
280
281  def ClearField(self, field_name):
282    """Clears the contents of a given field.
283
284    Inside a oneof group, clears the field set. If the name neither refers to a
285    defined field or oneof group, :exc:`ValueError` is raised.
286
287    Args:
288      field_name (str): The name of the field to check for presence.
289
290    Raises:
291      ValueError: if the `field_name` is not a member of this message.
292    """
293    raise NotImplementedError
294
295  def WhichOneof(self, oneof_group):
296    """Returns the name of the field that is set inside a oneof group.
297
298    If no field is set, returns None.
299
300    Args:
301      oneof_group (str): the name of the oneof group to check.
302
303    Returns:
304      str or None: The name of the group that is set, or None.
305
306    Raises:
307      ValueError: no group with the given name exists
308    """
309    raise NotImplementedError
310
311  def HasExtension(self, extension_handle):
312    """Checks if a certain extension is present for this message.
313
314    Extensions are retrieved using the :attr:`Extensions` mapping (if present).
315
316    Args:
317      extension_handle: The handle for the extension to check.
318
319    Returns:
320      bool: Whether the extension is present for this message.
321
322    Raises:
323      KeyError: if the extension is repeated. Similar to repeated fields,
324        there is no separate notion of presence: a "not present" repeated
325        extension is an empty list.
326    """
327    raise NotImplementedError
328
329  def ClearExtension(self, extension_handle):
330    """Clears the contents of a given extension.
331
332    Args:
333      extension_handle: The handle for the extension to clear.
334    """
335    raise NotImplementedError
336
337  def UnknownFields(self):
338    """Returns the UnknownFieldSet.
339
340    Returns:
341      UnknownFieldSet: The unknown fields stored in this message.
342    """
343    raise NotImplementedError
344
345  def DiscardUnknownFields(self):
346    """Clears all fields in the :class:`UnknownFieldSet`.
347
348    This operation is recursive for nested message.
349    """
350    raise NotImplementedError
351
352  def ByteSize(self):
353    """Returns the serialized size of this message.
354
355    Recursively calls ByteSize() on all contained messages.
356
357    Returns:
358      int: The number of bytes required to serialize this message.
359    """
360    raise NotImplementedError
361
362  def _SetListener(self, message_listener):
363    """Internal method used by the protocol message implementation.
364    Clients should not call this directly.
365
366    Sets a listener that this message will call on certain state transitions.
367
368    The purpose of this method is to register back-edges from children to
369    parents at runtime, for the purpose of setting "has" bits and
370    byte-size-dirty bits in the parent and ancestor objects whenever a child or
371    descendant object is modified.
372
373    If the client wants to disconnect this Message from the object tree, she
374    explicitly sets callback to None.
375
376    If message_listener is None, unregisters any existing listener.  Otherwise,
377    message_listener must implement the MessageListener interface in
378    internal/message_listener.py, and we discard any listener registered
379    via a previous _SetListener() call.
380    """
381    raise NotImplementedError
382
383  def __getstate__(self):
384    """Support the pickle protocol."""
385    return dict(serialized=self.SerializePartialToString())
386
387  def __setstate__(self, state):
388    """Support the pickle protocol."""
389    self.__init__()
390    serialized = state['serialized']
391    # On Python 3, using encoding='latin1' is required for unpickling
392    # protos pickled by Python 2.
393    if not isinstance(serialized, bytes):
394      serialized = serialized.encode('latin1')
395    self.ParseFromString(serialized)
396
397  def __reduce__(self):
398    message_descriptor = self.DESCRIPTOR
399    if message_descriptor.containing_type is None:
400      return type(self), (), self.__getstate__()
401    # the message type must be nested.
402    # Python does not pickle nested classes; use the symbol_database on the
403    # receiving end.
404    container = message_descriptor
405    return (_InternalConstructMessage, (container.full_name,),
406            self.__getstate__())
407
408
409def _InternalConstructMessage(full_name):
410  """Constructs a nested message."""
411  from google.protobuf import symbol_database  # pylint:disable=g-import-not-at-top
412
413  return symbol_database.Default().GetSymbol(full_name)()
414