Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/tools/ExternalEvaluation/Java/ExternalEvaluation.Service/src/com/google/protobuf/ByteString.java @ 15014

Last change on this file since 15014 was 15014, checked in by pfleck, 7 years ago

Added code and tools for the ExternalEvaluationProblem. (e.g. Java-side evaluation)

File size: 11.5 KB
Line 
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
31package com.google.protobuf;
32
33import java.io.InputStream;
34import java.io.ByteArrayInputStream;
35import java.io.ByteArrayOutputStream;
36import java.io.FilterOutputStream;
37import java.io.UnsupportedEncodingException;
38import java.nio.ByteBuffer;
39import java.util.List;
40
41/**
42 * Immutable array of bytes.
43 *
44 * @author crazybob@google.com Bob Lee
45 * @author kenton@google.com Kenton Varda
46 */
47public final class ByteString {
48  private final byte[] bytes;
49
50  private ByteString(final byte[] bytes) {
51    this.bytes = bytes;
52  }
53
54  /**
55   * Gets the byte at the given index.
56   *
57   * @throws ArrayIndexOutOfBoundsException {@code index} is < 0 or >= size
58   */
59  public byte byteAt(final int index) {
60    return bytes[index];
61  }
62
63  /**
64   * Gets the number of bytes.
65   */
66  public int size() {
67    return bytes.length;
68  }
69
70  /**
71   * Returns {@code true} if the size is {@code 0}, {@code false} otherwise.
72   */
73  public boolean isEmpty() {
74    return bytes.length == 0;
75  }
76
77  // =================================================================
78  // byte[] -> ByteString
79
80  /**
81   * Empty ByteString.
82   */
83  public static final ByteString EMPTY = new ByteString(new byte[0]);
84
85  /**
86   * Copies the given bytes into a {@code ByteString}.
87   */
88  public static ByteString copyFrom(final byte[] bytes, final int offset,
89                                    final int size) {
90    final byte[] copy = new byte[size];
91    System.arraycopy(bytes, offset, copy, 0, size);
92    return new ByteString(copy);
93  }
94
95  /**
96   * Copies the given bytes into a {@code ByteString}.
97   */
98  public static ByteString copyFrom(final byte[] bytes) {
99    return copyFrom(bytes, 0, bytes.length);
100  }
101
102  /**
103   * Copies {@code size} bytes from a {@code java.nio.ByteBuffer} into
104   * a {@code ByteString}.
105   */
106  public static ByteString copyFrom(final ByteBuffer bytes, final int size) {
107    final byte[] copy = new byte[size];
108    bytes.get(copy);
109    return new ByteString(copy);
110  }
111
112  /**
113   * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into
114   * a {@code ByteString}.
115   */
116  public static ByteString copyFrom(final ByteBuffer bytes) {
117    return copyFrom(bytes, bytes.remaining());
118  }
119
120  /**
121   * Encodes {@code text} into a sequence of bytes using the named charset
122   * and returns the result as a {@code ByteString}.
123   */
124  public static ByteString copyFrom(final String text, final String charsetName)
125      throws UnsupportedEncodingException {
126    return new ByteString(text.getBytes(charsetName));
127  }
128
129  /**
130   * Encodes {@code text} into a sequence of UTF-8 bytes and returns the
131   * result as a {@code ByteString}.
132   */
133  public static ByteString copyFromUtf8(final String text) {
134    try {
135      return new ByteString(text.getBytes("UTF-8"));
136    } catch (UnsupportedEncodingException e) {
137      throw new RuntimeException("UTF-8 not supported?", e);
138    }
139  }
140
141  /**
142   * Concatenates all byte strings in the list and returns the result.
143   *
144   * <p>The returned {@code ByteString} is not necessarily a unique object.
145   * If the list is empty, the returned object is the singleton empty
146   * {@code ByteString}.  If the list has only one element, that
147   * {@code ByteString} will be returned without copying.
148   */
149  public static ByteString copyFrom(List<ByteString> list) {
150    if (list.size() == 0) {
151      return EMPTY;
152    } else if (list.size() == 1) {
153      return list.get(0);
154    }
155
156    int size = 0;
157    for (ByteString str : list) {
158      size += str.size();
159    }
160    byte[] bytes = new byte[size];
161    int pos = 0;
162    for (ByteString str : list) {
163      System.arraycopy(str.bytes, 0, bytes, pos, str.size());
164      pos += str.size();
165    }
166    return new ByteString(bytes);
167  }
168
169  // =================================================================
170  // ByteString -> byte[]
171
172  /**
173   * Copies bytes into a buffer at the given offset.
174   *
175   * @param target buffer to copy into
176   * @param offset in the target buffer
177   */
178  public void copyTo(final byte[] target, final int offset) {
179    System.arraycopy(bytes, 0, target, offset, bytes.length);
180  }
181
182  /**
183   * Copies bytes into a buffer.
184   *
185   * @param target buffer to copy into
186   * @param sourceOffset offset within these bytes
187   * @param targetOffset offset within the target buffer
188   * @param size number of bytes to copy
189   */
190  public void copyTo(final byte[] target, final int sourceOffset,
191                     final int targetOffset,
192      final int size) {
193    System.arraycopy(bytes, sourceOffset, target, targetOffset, size);
194  }
195
196  /**
197   * Copies bytes into a ByteBuffer.
198   *
199   * @param target ByteBuffer to copy into.
200   * @throws ReadOnlyBufferException if the {@code target} is read-only
201   * @throws BufferOverflowException if the {@code target}'s remaining()
202   *         space is not large enough to hold the data.
203   */
204  public void copyTo(ByteBuffer target) {
205    target.put(bytes, 0, bytes.length);
206  }
207
208  /**
209   * Copies bytes to a {@code byte[]}.
210   */
211  public byte[] toByteArray() {
212    final int size = bytes.length;
213    final byte[] copy = new byte[size];
214    System.arraycopy(bytes, 0, copy, 0, size);
215    return copy;
216  }
217
218  /**
219   * Constructs a new read-only {@code java.nio.ByteBuffer} with the
220   * same backing byte array.
221   */
222  public ByteBuffer asReadOnlyByteBuffer() {
223    final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
224    return byteBuffer.asReadOnlyBuffer();
225  }
226
227  /**
228   * Constructs a new {@code String} by decoding the bytes using the
229   * specified charset.
230   */
231  public String toString(final String charsetName)
232      throws UnsupportedEncodingException {
233    return new String(bytes, charsetName);
234  }
235
236  /**
237   * Constructs a new {@code String} by decoding the bytes as UTF-8.
238   */
239  public String toStringUtf8() {
240    try {
241      return new String(bytes, "UTF-8");
242    } catch (UnsupportedEncodingException e) {
243      throw new RuntimeException("UTF-8 not supported?", e);
244    }
245  }
246
247  // =================================================================
248  // equals() and hashCode()
249
250  @Override
251  public boolean equals(final Object o) {
252    if (o == this) {
253      return true;
254    }
255
256    if (!(o instanceof ByteString)) {
257      return false;
258    }
259
260    final ByteString other = (ByteString) o;
261    final int size = bytes.length;
262    if (size != other.bytes.length) {
263      return false;
264    }
265
266    final byte[] thisBytes = bytes;
267    final byte[] otherBytes = other.bytes;
268    for (int i = 0; i < size; i++) {
269      if (thisBytes[i] != otherBytes[i]) {
270        return false;
271      }
272    }
273
274    return true;
275  }
276
277  private volatile int hash = 0;
278
279  @Override
280  public int hashCode() {
281    int h = hash;
282
283    if (h == 0) {
284      final byte[] thisBytes = bytes;
285      final int size = bytes.length;
286
287      h = size;
288      for (int i = 0; i < size; i++) {
289        h = h * 31 + thisBytes[i];
290      }
291      if (h == 0) {
292        h = 1;
293      }
294
295      hash = h;
296    }
297
298    return h;
299  }
300
301  // =================================================================
302  // Input stream
303
304  /**
305   * Creates an {@code InputStream} which can be used to read the bytes.
306   */
307  public InputStream newInput() {
308    return new ByteArrayInputStream(bytes);
309  }
310
311  /**
312   * Creates a {@link CodedInputStream} which can be used to read the bytes.
313   * Using this is more efficient than creating a {@link CodedInputStream}
314   * wrapping the result of {@link #newInput()}.
315   */
316  public CodedInputStream newCodedInput() {
317    // We trust CodedInputStream not to modify the bytes, or to give anyone
318    // else access to them.
319    return CodedInputStream.newInstance(bytes);
320  }
321
322  // =================================================================
323  // Output stream
324
325  /**
326   * Creates a new {@link Output} with the given initial capacity.
327   */
328  public static Output newOutput(final int initialCapacity) {
329    return new Output(new ByteArrayOutputStream(initialCapacity));
330  }
331
332  /**
333   * Creates a new {@link Output}.
334   */
335  public static Output newOutput() {
336    return newOutput(32);
337  }
338
339  /**
340   * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to
341   * create the {@code ByteString} instance.
342   */
343  public static final class Output extends FilterOutputStream {
344    private final ByteArrayOutputStream bout;
345
346    /**
347     * Constructs a new output with the given initial capacity.
348     */
349    private Output(final ByteArrayOutputStream bout) {
350      super(bout);
351      this.bout = bout;
352    }
353
354    /**
355     * Creates a {@code ByteString} instance from this {@code Output}.
356     */
357    public ByteString toByteString() {
358      final byte[] byteArray = bout.toByteArray();
359      return new ByteString(byteArray);
360    }
361  }
362
363  /**
364   * Constructs a new ByteString builder, which allows you to efficiently
365   * construct a {@code ByteString} by writing to a {@link CodedOutputStream}.
366   * Using this is much more efficient than calling {@code newOutput()} and
367   * wrapping that in a {@code CodedOutputStream}.
368   *
369   * <p>This is package-private because it's a somewhat confusing interface.
370   * Users can call {@link Message#toByteString()} instead of calling this
371   * directly.
372   *
373   * @param size The target byte size of the {@code ByteString}.  You must
374   *             write exactly this many bytes before building the result.
375   */
376  static CodedBuilder newCodedBuilder(final int size) {
377    return new CodedBuilder(size);
378  }
379
380  /** See {@link ByteString#newCodedBuilder(int)}. */
381  static final class CodedBuilder {
382    private final CodedOutputStream output;
383    private final byte[] buffer;
384
385    private CodedBuilder(final int size) {
386      buffer = new byte[size];
387      output = CodedOutputStream.newInstance(buffer);
388    }
389
390    public ByteString build() {
391      output.checkNoSpaceLeft();
392
393      // We can be confident that the CodedOutputStream will not modify the
394      // underlying bytes anymore because it already wrote all of them.  So,
395      // no need to make a copy.
396      return new ByteString(buffer);
397    }
398
399    public CodedOutputStream getCodedOutput() {
400      return output;
401    }
402  }
403}
Note: See TracBrowser for help on using the repository browser.