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 * @param array array to be wrapped
41 * @return wrapped array
42 */
43 public static ByteString wrap(final byte[] array) {
44 return new LiteralByteString(array);
45 }
46
47 /**
48 * Wraps a subset of a byte array in a {@link ByteString} without copying it.
49 * @param array array to be wrapped
50 * @param offset from
51 * @param length length
52 * @return wrapped array
53 */
54 public static ByteString wrap(final byte[] array, int offset, int length) {
55 return new BoundedByteString(array, offset, length);
56 }
57
58 // TODO:
59 // ZeroCopyLiteralByteString.wrap(this.buf, 0, this.count);
60
61 /**
62 * Extracts the byte array from the given {@link ByteString} without copy.
63 * @param buf A buffer from which to extract the array. This buffer must be
64 * actually an instance of a {@code LiteralByteString}.
65 * @return byte[] representation
66 */
67 public static byte[] zeroCopyGetBytes(final ByteString buf) {
68 if (buf instanceof LiteralByteString) {
69 return ((LiteralByteString) buf).bytes;
70 }
71 // In case it's BoundedByteString
72 return buf.toByteArray();
73 }
74 }