Import atomix/{storage,utils}
[controller.git] / third-party / atomix / storage / src / main / java / io / atomix / storage / buffer / HeapBytes.java
1 /*
2  * Copyright 2015-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.storage.buffer;
17
18 import java.nio.ByteBuffer;
19
20 /**
21  * {@link ByteBuffer} based heap bytes.
22  */
23 public class HeapBytes extends ByteBufferBytes {
24   public static final byte[] EMPTY = new byte[0];
25
26   /**
27    * Allocates a new heap byte array.
28    *
29    * @param size The count of the buffer to allocate (in bytes).
30    * @return The heap buffer.
31    * @throws IllegalArgumentException If {@code count} is greater than the maximum allowed count for
32    *                                  an array on the Java heap - {@code Integer.MAX_VALUE - 5}
33    */
34   public static HeapBytes allocate(int size) {
35     if (size > MAX_SIZE) {
36       throw new IllegalArgumentException("size cannot for HeapBytes cannot be greater than " + MAX_SIZE);
37     }
38     return new HeapBytes(ByteBuffer.allocate((int) size));
39   }
40
41   /**
42    * Wraps the given bytes in a {@link HeapBytes} object.
43    * <p>
44    * The returned {@link Bytes} object will be backed by a {@link ByteBuffer} instance that
45    * wraps the given byte array. The {@link Bytes#size()} will be equivalent to the provided
46    * by array {@code length}.
47    *
48    * @param bytes The bytes to wrap.
49    */
50   public static HeapBytes wrap(byte[] bytes) {
51     return new HeapBytes(ByteBuffer.wrap(bytes));
52   }
53
54   protected HeapBytes(ByteBuffer buffer) {
55     super(buffer);
56   }
57
58   @Override
59   protected ByteBuffer newByteBuffer(int size) {
60     return ByteBuffer.allocate((int) size);
61   }
62
63   @Override
64   public boolean hasArray() {
65     return true;
66   }
67 }