MessageLite.java revision fbaaef999ba563838ebd00874ed8a1c01fbf286d
1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// http://code.google.com/p/protobuf/
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(kenton):  Use generics?  E.g. Builder<BuilderType extends Builder>, then
32//   mergeFrom*() could return BuilderType for better type-safety.
33
34package com.google.protobuf;
35
36import java.io.IOException;
37import java.io.InputStream;
38import java.io.OutputStream;
39
40/**
41 * Abstract interface implemented by Protocol Message objects.
42 *
43 * <p>This interface is implemented by all protocol message objects.  Non-lite
44 * messages additionally implement the Message interface, which is a subclass
45 * of MessageLite.  Use MessageLite instead when you only need the subset of
46 * features which it supports -- namely, nothing that uses descriptors or
47 * reflection.  You can instruct the protocol compiler to generate classes
48 * which implement only MessageLite, not the full Message interface, by adding
49 * the follow line to the .proto file:
50 * <pre>
51 *   option optimize_for = LITE_RUNTIME;
52 * </pre>
53 *
54 * <p>This is particularly useful on resource-constrained systems where the
55 * full protocol buffers runtime library is too big.
56 *
57 * <p>Note that on non-constrained systems (e.g. servers) when you need to link
58 * in lots of protocol definitions, a better way to reduce total code footprint
59 * is to use {@code optimize_for = CODE_SIZE}.  This will make the generated
60 * code smaller while still supporting all the same features (at the expense of
61 * speed).  {@code optimize_for = LITE_RUNTIME} is best when you only have a
62 * small number of message types linked into your binary, in which case the
63 * size of the protocol buffers runtime itself is the biggest problem.
64 *
65 * @author kenton@google.com Kenton Varda
66 */
67public interface MessageLite {
68  /**
69   * Get an instance of the type with all fields set to their default values.
70   * This may or may not be a singleton.  This differs from the
71   * {@code getDefaultInstance()} method of generated message classes in that
72   * this method is an abstract method of the {@code MessageLite} interface
73   * whereas {@code getDefaultInstance()} is a static method of a specific
74   * class.  They return the same thing.
75   */
76  MessageLite getDefaultInstanceForType();
77
78  /**
79   * Returns true if all required fields in the message and all embedded
80   * messages are set, false otherwise.
81   */
82  boolean isInitialized();
83
84  /**
85   * Serializes the message and writes it to {@code output}.  This does not
86   * flush or close the stream.
87   */
88  void writeTo(CodedOutputStream output) throws IOException;
89
90  /**
91   * Get the number of bytes required to encode this message.  The result
92   * is only computed on the first call and memoized after that.
93   */
94  int getSerializedSize();
95
96  // -----------------------------------------------------------------
97  // Convenience methods.
98
99  /**
100   * Serializes the message to a {@code ByteString} and returns it. This is
101   * just a trivial wrapper around
102   * {@link #writeTo(CodedOutputStream)}.
103   */
104  ByteString toByteString();
105
106  /**
107   * Serializes the message to a {@code byte} array and returns it.  This is
108   * just a trivial wrapper around
109   * {@link #writeTo(CodedOutputStream)}.
110   */
111  byte[] toByteArray();
112
113  /**
114   * Serializes the message and writes it to {@code output}.  This is just a
115   * trivial wrapper around {@link #writeTo(CodedOutputStream)}.  This does
116   * not flush or close the stream.
117   * <p>
118   * NOTE:  Protocol Buffers are not self-delimiting.  Therefore, if you write
119   * any more data to the stream after the message, you must somehow ensure
120   * that the parser on the receiving end does not interpret this as being
121   * part of the protocol message.  This can be done e.g. by writing the size
122   * of the message before the data, then making sure to limit the input to
123   * that size on the receiving end (e.g. by wrapping the InputStream in one
124   * which limits the input).  Alternatively, just use
125   * {@link #writeDelimitedTo(OutputStream)}.
126   */
127  void writeTo(OutputStream output) throws IOException;
128
129  /**
130   * Like {@link #writeTo(OutputStream)}, but writes the size of the message
131   * as a varint before writing the data.  This allows more data to be written
132   * to the stream after the message without the need to delimit the message
133   * data yourself.  Use {@link Builder#mergeDelimitedFrom(InputStream)} (or
134   * the static method {@code YourMessageType.parseDelimitedFrom(InputStream)})
135   * to parse messages written by this method.
136   */
137  void writeDelimitedTo(OutputStream output) throws IOException;
138
139  // =================================================================
140  // Builders
141
142  /**
143   * Constructs a new builder for a message of the same type as this message.
144   */
145  Builder newBuilderForType();
146
147  /**
148   * Constructs a builder initialized with the current message.  Use this to
149   * derive a new message from the current one.
150   */
151  Builder toBuilder();
152
153  /**
154   * Abstract interface implemented by Protocol Message builders.
155   */
156  interface Builder extends Cloneable {
157    /** Resets all fields to their default values. */
158    Builder clear();
159
160    /**
161     * Construct the final message.  Once this is called, the Builder is no
162     * longer valid, and calling any other method will result in undefined
163     * behavior and may throw a NullPointerException.  If you need to continue
164     * working with the builder after calling {@code build()}, {@code clone()}
165     * it first.
166     * @throws UninitializedMessageException The message is missing one or more
167     *         required fields (i.e. {@link #isInitialized()} returns false).
168     *         Use {@link #buildPartial()} to bypass this check.
169     */
170    MessageLite build();
171
172    /**
173     * Like {@link #build()}, but does not throw an exception if the message
174     * is missing required fields.  Instead, a partial message is returned.
175     * Once this is called, the Builder is no longer valid, and calling any
176     * will result in undefined behavior and may throw a NullPointerException.
177     *
178     * If you need to continue working with the builder after calling
179     * {@code buildPartial()}, {@code clone()} it first.
180     */
181    MessageLite buildPartial();
182
183    /**
184     * Clones the Builder.
185     * @see Object#clone()
186     */
187    Builder clone();
188
189    /**
190     * Returns true if all required fields in the message and all embedded
191     * messages are set, false otherwise.
192     */
193    boolean isInitialized();
194
195    /**
196     * Parses a message of this type from the input and merges it with this
197     * message, as if using {@link Builder#mergeFrom(MessageLite)}.
198     *
199     * <p>Warning:  This does not verify that all required fields are present in
200     * the input message.  If you call {@link #build()} without setting all
201     * required fields, it will throw an {@link UninitializedMessageException},
202     * which is a {@code RuntimeException} and thus might not be caught.  There
203     * are a few good ways to deal with this:
204     * <ul>
205     *   <li>Call {@link #isInitialized()} to verify that all required fields
206     *       are set before building.
207     *   <li>Parse the message separately using one of the static
208     *       {@code parseFrom} methods, then use {@link #mergeFrom(MessageLite)}
209     *       to merge it with this one.  {@code parseFrom} will throw an
210     *       {@link InvalidProtocolBufferException} (an {@code IOException})
211     *       if some required fields are missing.
212     *   <li>Use {@code buildPartial()} to build, which ignores missing
213     *       required fields.
214     * </ul>
215     *
216     * <p>Note:  The caller should call
217     * {@link CodedInputStream#checkLastTagWas(int)} after calling this to
218     * verify that the last tag seen was the appropriate end-group tag,
219     * or zero for EOF.
220     */
221    Builder mergeFrom(CodedInputStream input) throws IOException;
222
223    /**
224     * Like {@link Builder#mergeFrom(CodedInputStream)}, but also
225     * parses extensions.  The extensions that you want to be able to parse
226     * must be registered in {@code extensionRegistry}.  Extensions not in
227     * the registry will be treated as unknown fields.
228     */
229    Builder mergeFrom(CodedInputStream input,
230                      ExtensionRegistryLite extensionRegistry)
231                      throws IOException;
232
233    /**
234     * Get the message's type's default instance.
235     * See {@link MessageLite#getDefaultInstanceForType()}.
236     */
237    MessageLite getDefaultInstanceForType();
238
239    // ---------------------------------------------------------------
240    // Convenience methods.
241
242    /**
243     * Parse {@code data} as a message of this type and merge it with the
244     * message being built.  This is just a small wrapper around
245     * {@link #mergeFrom(CodedInputStream)}.
246     */
247    Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException;
248
249    /**
250     * Parse {@code data} as a message of this type and merge it with the
251     * message being built.  This is just a small wrapper around
252     * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}.
253     */
254    Builder mergeFrom(ByteString data,
255                      ExtensionRegistryLite extensionRegistry)
256                      throws InvalidProtocolBufferException;
257
258    /**
259     * Parse {@code data} as a message of this type and merge it with the
260     * message being built.  This is just a small wrapper around
261     * {@link #mergeFrom(CodedInputStream)}.
262     */
263    Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException;
264
265    /**
266     * Parse {@code data} as a message of this type and merge it with the
267     * message being built.  This is just a small wrapper around
268     * {@link #mergeFrom(CodedInputStream)}.
269     */
270    Builder mergeFrom(byte[] data, int off, int len)
271                      throws InvalidProtocolBufferException;
272
273    /**
274     * Parse {@code data} as a message of this type and merge it with the
275     * message being built.  This is just a small wrapper around
276     * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}.
277     */
278    Builder mergeFrom(byte[] data,
279                      ExtensionRegistryLite extensionRegistry)
280                      throws InvalidProtocolBufferException;
281
282    /**
283     * Parse {@code data} as a message of this type and merge it with the
284     * message being built.  This is just a small wrapper around
285     * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}.
286     */
287    Builder mergeFrom(byte[] data, int off, int len,
288                      ExtensionRegistryLite extensionRegistry)
289                      throws InvalidProtocolBufferException;
290
291    /**
292     * Parse a message of this type from {@code input} and merge it with the
293     * message being built.  This is just a small wrapper around
294     * {@link #mergeFrom(CodedInputStream)}.  Note that this method always
295     * reads the <i>entire</i> input (unless it throws an exception).  If you
296     * want it to stop earlier, you will need to wrap your input in some
297     * wrapper stream that limits reading.  Or, use
298     * {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message
299     * and {@link #mergeDelimitedFrom(InputStream)} to read it.
300     * <p>
301     * Despite usually reading the entire input, this does not close the stream.
302     */
303    Builder mergeFrom(InputStream input) throws IOException;
304
305    /**
306     * Parse a message of this type from {@code input} and merge it with the
307     * message being built.  This is just a small wrapper around
308     * {@link #mergeFrom(CodedInputStream,ExtensionRegistry)}.
309     */
310    Builder mergeFrom(InputStream input,
311                      ExtensionRegistryLite extensionRegistry)
312                      throws IOException;
313
314    /**
315     * Like {@link #mergeFrom(InputStream)}, but does not read until EOF.
316     * Instead, the size of the message (encoded as a varint) is read first,
317     * then the message data.  Use
318     * {@link MessageLite#writeDelimitedTo(OutputStream)} to write messages in
319     * this format.
320     */
321    Builder mergeDelimitedFrom(InputStream input)
322                               throws IOException;
323
324    /**
325     * Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions.
326     */
327    Builder mergeDelimitedFrom(InputStream input,
328                               ExtensionRegistryLite extensionRegistry)
329                               throws IOException;
330  }
331}
332