blob: eeb0d5763fae33fee239d9ae71c654d6a1f1d837 [file] [log] [blame]
Brian Silverman9c614bc2016-02-15 20:20:02 -05001# 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
Austin Schuh40c16522018-10-28 20:27:54 -0700187 def SerializeToString(self, **kwargs):
Brian Silverman9c614bc2016-02-15 20:20:02 -0500188 """Serializes the protocol message to a binary string.
189
Austin Schuh40c16522018-10-28 20:27:54 -0700190 Arguments:
191 **kwargs: Keyword arguments to the serialize method, accepts
192 the following keyword args:
193 deterministic: If true, requests deterministic serialization of the
194 protobuf, with predictable ordering of map keys.
195
Brian Silverman9c614bc2016-02-15 20:20:02 -0500196 Returns:
197 A binary string representation of the message if all of the required
198 fields in the message are set (i.e. the message is initialized).
199
200 Raises:
201 message.EncodeError if the message isn't initialized.
202 """
203 raise NotImplementedError
204
Austin Schuh40c16522018-10-28 20:27:54 -0700205 def SerializePartialToString(self, **kwargs):
Brian Silverman9c614bc2016-02-15 20:20:02 -0500206 """Serializes the protocol message to a binary string.
207
208 This method is similar to SerializeToString but doesn't check if the
209 message is initialized.
210
Austin Schuh40c16522018-10-28 20:27:54 -0700211 Arguments:
212 **kwargs: Keyword arguments to the serialize method, accepts
213 the following keyword args:
214 deterministic: If true, requests deterministic serialization of the
215 protobuf, with predictable ordering of map keys.
216
Brian Silverman9c614bc2016-02-15 20:20:02 -0500217 Returns:
218 A string representation of the partial message.
219 """
220 raise NotImplementedError
221
222 # TODO(robinson): Decide whether we like these better
223 # than auto-generated has_foo() and clear_foo() methods
224 # on the instances themselves. This way is less consistent
225 # with C++, but it makes reflection-type access easier and
226 # reduces the number of magically autogenerated things.
227 #
228 # TODO(robinson): Be sure to document (and test) exactly
229 # which field names are accepted here. Are we case-sensitive?
230 # What do we do with fields that share names with Python keywords
231 # like 'lambda' and 'yield'?
232 #
233 # nnorwitz says:
234 # """
235 # Typically (in python), an underscore is appended to names that are
236 # keywords. So they would become lambda_ or yield_.
237 # """
238 def ListFields(self):
239 """Returns a list of (FieldDescriptor, value) tuples for all
Austin Schuh40c16522018-10-28 20:27:54 -0700240 fields in the message which are not empty. A message field is
241 non-empty if HasField() would return true. A singular primitive field
242 is non-empty if HasField() would return true in proto2 or it is non zero
243 in proto3. A repeated field is non-empty if it contains at least one
244 element. The fields are ordered by field number"""
Brian Silverman9c614bc2016-02-15 20:20:02 -0500245 raise NotImplementedError
246
247 def HasField(self, field_name):
248 """Checks if a certain field is set for the message, or if any field inside
249 a oneof group is set. Note that if the field_name is not defined in the
250 message descriptor, ValueError will be raised."""
251 raise NotImplementedError
252
253 def ClearField(self, field_name):
254 """Clears the contents of a given field, or the field set inside a oneof
255 group. If the name neither refers to a defined field or oneof group,
256 ValueError is raised."""
257 raise NotImplementedError
258
259 def WhichOneof(self, oneof_group):
260 """Returns the name of the field that is set inside a oneof group, or
261 None if no field is set. If no group with the given name exists, ValueError
262 will be raised."""
263 raise NotImplementedError
264
265 def HasExtension(self, extension_handle):
266 raise NotImplementedError
267
268 def ClearExtension(self, extension_handle):
269 raise NotImplementedError
270
Austin Schuh40c16522018-10-28 20:27:54 -0700271 def DiscardUnknownFields(self):
272 raise NotImplementedError
273
Brian Silverman9c614bc2016-02-15 20:20:02 -0500274 def ByteSize(self):
275 """Returns the serialized size of this message.
276 Recursively calls ByteSize() on all contained messages.
277 """
278 raise NotImplementedError
279
280 def _SetListener(self, message_listener):
281 """Internal method used by the protocol message implementation.
282 Clients should not call this directly.
283
284 Sets a listener that this message will call on certain state transitions.
285
286 The purpose of this method is to register back-edges from children to
287 parents at runtime, for the purpose of setting "has" bits and
288 byte-size-dirty bits in the parent and ancestor objects whenever a child or
289 descendant object is modified.
290
291 If the client wants to disconnect this Message from the object tree, she
292 explicitly sets callback to None.
293
294 If message_listener is None, unregisters any existing listener. Otherwise,
295 message_listener must implement the MessageListener interface in
296 internal/message_listener.py, and we discard any listener registered
297 via a previous _SetListener() call.
298 """
299 raise NotImplementedError
300
301 def __getstate__(self):
302 """Support the pickle protocol."""
303 return dict(serialized=self.SerializePartialToString())
304
305 def __setstate__(self, state):
306 """Support the pickle protocol."""
307 self.__init__()
308 self.ParseFromString(state['serialized'])