2 * Copyright 2015-present Open Networking Foundation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package io.atomix.storage.buffer;
18 import java.nio.ByteBuffer;
21 * {@link ByteBuffer} based heap bytes.
23 public class HeapBytes extends ByteBufferBytes {
24 public static final byte[] EMPTY = new byte[0];
27 * Allocates a new heap byte array.
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}
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);
38 return new HeapBytes(ByteBuffer.allocate((int) size));
42 * Wraps the given bytes in a {@link HeapBytes} object.
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}.
48 * @param bytes The bytes to wrap.
50 public static HeapBytes wrap(byte[] bytes) {
51 return new HeapBytes(ByteBuffer.wrap(bytes));
54 protected HeapBytes(ByteBuffer buffer) {
59 protected ByteBuffer newByteBuffer(int size) {
60 return ByteBuffer.allocate((int) size);
64 public boolean hasArray() {