MessageNano.java revision 47107914acbad70ff4db1664d3664ccc994315af
1// Protocol Buffers - Google's data interchange format
2// Copyright 2013 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
31package com.google.protobuf.nano;
32
33import java.io.IOException;
34
35/**
36 * Abstract interface implemented by Protocol Message objects.
37 *
38 * @author wink@google.com Wink Saville
39 */
40public abstract class MessageNano {
41    /**
42     * Get the number of bytes required to encode this message.
43     * Returns the cached size or calls getSerializedSize which
44     * sets the cached size. This is used internally when serializing
45     * so the size is only computed once. If a member is modified
46     * then this could be stale call getSerializedSize if in doubt.
47     */
48    abstract public int getCachedSize();
49
50    /**
51     * Computes the number of bytes required to encode this message.
52     * The size is cached and the cached result can be retrieved
53     * using getCachedSize().
54     */
55    abstract public int getSerializedSize();
56
57    /**
58     * Serializes the message and writes it to {@code output}.  This does not
59     * flush or close the stream.
60     */
61    abstract public void writeTo(CodedOutputByteBufferNano output) throws java.io.IOException;
62
63    /**
64     * Parse {@code input} as a message of this type and merge it with the
65     * message being built.
66     */
67    abstract public MessageNano mergeFrom(final CodedInputByteBufferNano input) throws IOException;
68
69    /**
70     * Serialize to a byte array.
71     * @return byte array with the serialized data.
72     */
73    public static final byte[] toByteArray(MessageNano msg) {
74        final byte[] result = new byte[msg.getSerializedSize()];
75        toByteArray(msg, result, 0, result.length);
76        return result;
77    }
78
79    /**
80     * Serialize to a byte array starting at offset through length. The
81     * method getSerializedSize must have been called prior to calling
82     * this method so the proper length is know.  If an attempt to
83     * write more than length bytes OutOfSpaceException will be thrown
84     * and if length bytes are not written then IllegalStateException
85     * is thrown.
86     * @return byte array with the serialized data.
87     */
88    public static final void toByteArray(MessageNano msg, byte [] data, int offset, int length) {
89        try {
90            final CodedOutputByteBufferNano output =
91                CodedOutputByteBufferNano.newInstance(data, offset, length);
92            msg.writeTo(output);
93            output.checkNoSpaceLeft();
94        } catch (IOException e) {
95            throw new RuntimeException("Serializing to a byte array threw an IOException "
96                    + "(should never happen).");
97        }
98    }
99
100    /**
101     * Parse {@code data} as a message of this type and merge it with the
102     * message being built.
103     */
104    public static final MessageNano mergeFrom(MessageNano msg, final byte[] data)
105        throws InvalidProtocolBufferNanoException {
106        return mergeFrom(msg, data, 0, data.length);
107    }
108
109    /**
110     * Parse {@code data} as a message of this type and merge it with the
111     * message being built.
112     */
113    public static final MessageNano mergeFrom(MessageNano msg, final byte[] data, final int off,
114        final int len) throws InvalidProtocolBufferNanoException {
115        try {
116            final CodedInputByteBufferNano input =
117                CodedInputByteBufferNano.newInstance(data, off, len);
118            msg.mergeFrom(input);
119            input.checkLastTagWas(0);
120            return msg;
121        } catch (InvalidProtocolBufferNanoException e) {
122            throw e;
123        } catch (IOException e) {
124            throw new RuntimeException("Reading from a byte array threw an IOException (should "
125                    + "never happen).");
126        }
127    }
128
129    /**
130     * Intended for debugging purposes only. It does not use ASCII protobuf formatting.
131     */
132    @Override
133    public String toString() {
134        return MessageNanoPrinter.print(this);
135    }
136}
137