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 // Authors: wink@google.com (Wink Saville),
32 //          kenton@google.com (Kenton Varda)
33 //  Based on original Protocol Buffers design by
34 //  Sanjay Ghemawat, Jeff Dean, and others.
35 //
36 // Defines MessageLite, the abstract interface implemented by all (lite
37 // and non-lite) protocol message objects.
38 
39 #ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__
40 #define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
41 
42 #include <google/protobuf/stubs/common.h>
43 
44 
45 namespace google {
46 namespace protobuf {
47   class Arena;
48 namespace io {
49   class CodedInputStream;
50   class CodedOutputStream;
51   class ZeroCopyInputStream;
52   class ZeroCopyOutputStream;
53 }
54 namespace internal {
55   class WireFormatLite;
56 }
57 
58 // Interface to light weight protocol messages.
59 //
60 // This interface is implemented by all protocol message objects.  Non-lite
61 // messages additionally implement the Message interface, which is a
62 // subclass of MessageLite.  Use MessageLite instead when you only need
63 // the subset of features which it supports -- namely, nothing that uses
64 // descriptors or reflection.  You can instruct the protocol compiler
65 // to generate classes which implement only MessageLite, not the full
66 // Message interface, by adding the following line to the .proto file:
67 //
68 //   option optimize_for = LITE_RUNTIME;
69 //
70 // This is particularly useful on resource-constrained systems where
71 // the full protocol buffers runtime library is too big.
72 //
73 // Note that on non-constrained systems (e.g. servers) when you need
74 // to link in lots of protocol definitions, a better way to reduce
75 // total code footprint is to use optimize_for = CODE_SIZE.  This
76 // will make the generated code smaller while still supporting all the
77 // same features (at the expense of speed).  optimize_for = LITE_RUNTIME
78 // is best when you only have a small number of message types linked
79 // into your binary, in which case the size of the protocol buffers
80 // runtime itself is the biggest problem.
81 class LIBPROTOBUF_EXPORT MessageLite {
82  public:
MessageLite()83   inline MessageLite() {}
~MessageLite()84   virtual ~MessageLite() {}
85 
86   // Basic Operations ------------------------------------------------
87 
88   // Get the name of this message type, e.g. "foo.bar.BazProto".
89   virtual string GetTypeName() const = 0;
90 
91   // Construct a new instance of the same type.  Ownership is passed to the
92   // caller.
93   virtual MessageLite* New() const = 0;
94 
95   // Construct a new instance on the arena. Ownership is passed to the caller
96   // if arena is a NULL. Default implementation for backwards compatibility.
97   virtual MessageLite* New(::google::protobuf::Arena* arena) const;
98 
99   // Get the arena, if any, associated with this message. Virtual method
100   // required for generic operations but most arena-related operations should
101   // use the GetArenaNoVirtual() generated-code method. Default implementation
102   // to reduce code size by avoiding the need for per-type implementations when
103   // types do not implement arena support.
GetArena()104   virtual ::google::protobuf::Arena* GetArena() const { return NULL; }
105 
106   // Get a pointer that may be equal to this message's arena, or may not be. If
107   // the value returned by this method is equal to some arena pointer, then this
108   // message is on that arena; however, if this message is on some arena, this
109   // method may or may not return that arena's pointer. As a tradeoff, this
110   // method may be more efficient than GetArena(). The intent is to allow
111   // underlying representations that use e.g. tagged pointers to sometimes store
112   // the arena pointer directly, and sometimes in a more indirect way, and allow
113   // a fastpath comparison against the arena pointer when it's easy to obtain.
GetMaybeArenaPointer()114   virtual void* GetMaybeArenaPointer() const { return GetArena(); }
115 
116   // Clear all fields of the message and set them to their default values.
117   // Clear() avoids freeing memory, assuming that any memory allocated
118   // to hold parts of the message will be needed again to hold the next
119   // message.  If you actually want to free the memory used by a Message,
120   // you must delete it.
121   virtual void Clear() = 0;
122 
123   // Quickly check if all required fields have values set.
124   virtual bool IsInitialized() const = 0;
125 
126   // This is not implemented for Lite messages -- it just returns "(cannot
127   // determine missing fields for lite message)".  However, it is implemented
128   // for full messages.  See message.h.
129   virtual string InitializationErrorString() const;
130 
131   // If |other| is the exact same class as this, calls MergeFrom().  Otherwise,
132   // results are undefined (probably crash).
133   virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0;
134 
135   // Parsing ---------------------------------------------------------
136   // Methods for parsing in protocol buffer format.  Most of these are
137   // just simple wrappers around MergeFromCodedStream().  Clear() will be called
138   // before merging the input.
139 
140   // Fill the message with a protocol buffer parsed from the given input stream.
141   // Returns false on a read error or if the input is in the wrong format.  A
142   // successful return does not indicate the entire input is consumed, ensure
143   // you call ConsumedEntireMessage() to check that if applicable.
144   bool ParseFromCodedStream(io::CodedInputStream* input);
145   // Like ParseFromCodedStream(), but accepts messages that are missing
146   // required fields.
147   bool ParsePartialFromCodedStream(io::CodedInputStream* input);
148   // Read a protocol buffer from the given zero-copy input stream.  If
149   // successful, the entire input will be consumed.
150   bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input);
151   // Like ParseFromZeroCopyStream(), but accepts messages that are missing
152   // required fields.
153   bool ParsePartialFromZeroCopyStream(io::ZeroCopyInputStream* input);
154   // Read a protocol buffer from the given zero-copy input stream, expecting
155   // the message to be exactly "size" bytes long.  If successful, exactly
156   // this many bytes will have been consumed from the input.
157   bool ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
158   // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
159   // missing required fields.
160   bool ParsePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
161                                              int size);
162   // Parses a protocol buffer contained in a string. Returns true on success.
163   // This function takes a string in the (non-human-readable) binary wire
164   // format, matching the encoding output by MessageLite::SerializeToString().
165   // If you'd like to convert a human-readable string into a protocol buffer
166   // object, see google::protobuf::TextFormat::ParseFromString().
167   bool ParseFromString(const string& data);
168   // Like ParseFromString(), but accepts messages that are missing
169   // required fields.
170   bool ParsePartialFromString(const string& data);
171   // Parse a protocol buffer contained in an array of bytes.
172   bool ParseFromArray(const void* data, int size);
173   // Like ParseFromArray(), but accepts messages that are missing
174   // required fields.
175   bool ParsePartialFromArray(const void* data, int size);
176 
177 
178   // Reads a protocol buffer from the stream and merges it into this
179   // Message.  Singular fields read from the input overwrite what is
180   // already in the Message and repeated fields are appended to those
181   // already present.
182   //
183   // It is the responsibility of the caller to call input->LastTagWas()
184   // (for groups) or input->ConsumedEntireMessage() (for non-groups) after
185   // this returns to verify that the message's end was delimited correctly.
186   //
187   // ParsefromCodedStream() is implemented as Clear() followed by
188   // MergeFromCodedStream().
189   bool MergeFromCodedStream(io::CodedInputStream* input);
190 
191   // Like MergeFromCodedStream(), but succeeds even if required fields are
192   // missing in the input.
193   //
194   // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
195   // followed by IsInitialized().
196   virtual bool MergePartialFromCodedStream(io::CodedInputStream* input) = 0;
197 
198 
199   // Serialization ---------------------------------------------------
200   // Methods for serializing in protocol buffer format.  Most of these
201   // are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
202 
203   // Write a protocol buffer of this message to the given output.  Returns
204   // false on a write error.  If the message is missing required fields,
205   // this may GOOGLE_CHECK-fail.
206   bool SerializeToCodedStream(io::CodedOutputStream* output) const;
207   // Like SerializeToCodedStream(), but allows missing required fields.
208   bool SerializePartialToCodedStream(io::CodedOutputStream* output) const;
209   // Write the message to the given zero-copy output stream.  All required
210   // fields must be set.
211   bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
212   // Like SerializeToZeroCopyStream(), but allows missing required fields.
213   bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
214   // Serialize the message and store it in the given string.  All required
215   // fields must be set.
216   bool SerializeToString(string* output) const;
217   // Like SerializeToString(), but allows missing required fields.
218   bool SerializePartialToString(string* output) const;
219   // Serialize the message and store it in the given byte array.  All required
220   // fields must be set.
221   bool SerializeToArray(void* data, int size) const;
222   // Like SerializeToArray(), but allows missing required fields.
223   bool SerializePartialToArray(void* data, int size) const;
224 
225   // Make a string encoding the message. Is equivalent to calling
226   // SerializeToString() on a string and using that.  Returns the empty
227   // string if SerializeToString() would have returned an error.
228   // Note: If you intend to generate many such strings, you may
229   // reduce heap fragmentation by instead re-using the same string
230   // object with calls to SerializeToString().
231   string SerializeAsString() const;
232   // Like SerializeAsString(), but allows missing required fields.
233   string SerializePartialAsString() const;
234 
235   // Like SerializeToString(), but appends to the data to the string's existing
236   // contents.  All required fields must be set.
237   bool AppendToString(string* output) const;
238   // Like AppendToString(), but allows missing required fields.
239   bool AppendPartialToString(string* output) const;
240 
241   // Computes the serialized size of the message.  This recursively calls
242   // ByteSize() on all embedded messages.  If a subclass does not override
243   // this, it MUST override SetCachedSize().
244   //
245   // ByteSize() is generally linear in the number of fields defined for the
246   // proto.
247   virtual int ByteSize() const = 0;
248 
249   // Serializes the message without recomputing the size.  The message must
250   // not have changed since the last call to ByteSize(); if it has, the results
251   // are undefined.
252   virtual void SerializeWithCachedSizes(
253       io::CodedOutputStream* output) const = 0;
254 
255   // A version of SerializeWithCachedSizesToArray, below, that does
256   // not guarantee deterministic serialization.
SerializeWithCachedSizesToArray(uint8 * target)257   virtual uint8* SerializeWithCachedSizesToArray(uint8* target) const {
258     return InternalSerializeWithCachedSizesToArray(false, target);
259   }
260 
261   // Returns the result of the last call to ByteSize().  An embedded message's
262   // size is needed both to serialize it (because embedded messages are
263   // length-delimited) and to compute the outer message's size.  Caching
264   // the size avoids computing it multiple times.
265   //
266   // ByteSize() does not automatically use the cached size when available
267   // because this would require invalidating it every time the message was
268   // modified, which would be too hard and expensive.  (E.g. if a deeply-nested
269   // sub-message is changed, all of its parents' cached sizes would need to be
270   // invalidated, which is too much work for an otherwise inlined setter
271   // method.)
272   virtual int GetCachedSize() const = 0;
273 
274   // Functions below here are not part of the public interface.  It isn't
275   // enforced, but they should be treated as private, and will be private
276   // at some future time.  Unfortunately the implementation of the "friend"
277   // keyword in GCC is broken at the moment, but we expect it will be fixed.
278 
279   // Like SerializeWithCachedSizes, but writes directly to *target, returning
280   // a pointer to the byte immediately after the last byte written.  "target"
281   // must point at a byte array of at least ByteSize() bytes.  If deterministic
282   // is true then we use deterministic serialization, e.g., map keys are sorted.
283   // FOR INTERNAL USE ONLY!
284   virtual uint8* InternalSerializeWithCachedSizesToArray(bool deterministic,
285                                                          uint8* target) const;
286 
287  private:
288   friend class internal::WireFormatLite;
289 
290   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
291 };
292 
293 }  // namespace protobuf
294 
295 }  // namespace google
296 #endif  // GOOGLE_PROTOBUF_MESSAGE_LITE_H__
297