View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package com.google.protobuf;  // This is a lie.
19  
20  /**
21   * Helper class to extract byte arrays from {@link ByteString} without copy.
22   * <p>
23   * Without this protobufs would force us to copy every single byte array out
24   * of the objects de-serialized from the wire (which already do one copy, on
25   * top of the copies the JVM does to go from kernel buffer to C buffer and
26   * from C buffer to JVM buffer).
27   *
28   * @since 0.96.1
29   */
30  public final class HBaseZeroCopyByteString extends LiteralByteString {
31    // Gotten from AsyncHBase code base with permission.
32    /** Private constructor so this class cannot be instantiated. */
33    private HBaseZeroCopyByteString() {
34      super(null);
35      throw new UnsupportedOperationException("Should never be here.");
36    }
37  
38    /**
39     * Wraps a byte array in a {@link ByteString} without copying it.
40     */
41    public static ByteString wrap(final byte[] array) {
42      return new LiteralByteString(array);
43    }
44  
45    /**
46     * Wraps a subset of a byte array in a {@link ByteString} without copying it.
47     */
48    public static ByteString wrap(final byte[] array, int offset, int length) {
49      return new BoundedByteString(array, offset, length);
50    }
51  
52    // TODO:
53    // ZeroCopyLiteralByteString.wrap(this.buf, 0, this.count);
54  
55    /**
56     * Extracts the byte array from the given {@link ByteString} without copy.
57     * @param buf A buffer from which to extract the array.  This buffer must be
58     * actually an instance of a {@code LiteralByteString}.
59     */
60    public static byte[] zeroCopyGetBytes(final ByteString buf) {
61      if (buf instanceof LiteralByteString) {
62        return ((LiteralByteString) buf).bytes;
63      }
64      throw new UnsupportedOperationException("Need a LiteralByteString, got a "
65                                              + buf.getClass().getName());
66    }
67  
68  }