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 io.atomix.utils.memory.Memory;
20 import static com.google.common.base.Preconditions.checkArgument;
23 * Direct {@link java.nio.ByteBuffer} based buffer.
25 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
27 public class DirectBuffer extends ByteBufferBuffer {
30 * Allocates a direct buffer with an initial capacity of {@code 4096} and a maximum capacity of {@link Long#MAX_VALUE}.
32 * @return The direct buffer.
33 * @see DirectBuffer#allocate(int)
34 * @see DirectBuffer#allocate(int, int)
36 public static DirectBuffer allocate() {
37 return allocate(DEFAULT_INITIAL_CAPACITY, MAX_SIZE);
41 * Allocates a direct buffer with the given initial capacity.
43 * @param initialCapacity The initial capacity of the buffer to allocate (in bytes).
44 * @return The direct buffer.
45 * @throws IllegalArgumentException If {@code capacity} is greater than the maximum allowed count for
46 * a {@link java.nio.ByteBuffer} - {@code Integer.MAX_VALUE - 5}
47 * @see DirectBuffer#allocate()
48 * @see DirectBuffer#allocate(int, int)
50 public static DirectBuffer allocate(int initialCapacity) {
51 return allocate(initialCapacity, MAX_SIZE);
55 * Allocates a new direct buffer.
57 * @param initialCapacity The initial capacity of the buffer to allocate (in bytes).
58 * @param maxCapacity The maximum capacity of the buffer.
59 * @return The direct buffer.
60 * @throws IllegalArgumentException If {@code capacity} or {@code maxCapacity} is greater than the maximum
61 * allowed count for a {@link java.nio.ByteBuffer} - {@code Integer.MAX_VALUE - 5}
62 * @see DirectBuffer#allocate()
63 * @see DirectBuffer#allocate(int)
65 public static DirectBuffer allocate(int initialCapacity, int maxCapacity) {
66 checkArgument(initialCapacity <= maxCapacity, "initial capacity cannot be greater than maximum capacity");
67 return new DirectBuffer(DirectBytes.allocate((int) Math.min(Memory.Util.toPow2(initialCapacity), MAX_SIZE)), 0, initialCapacity, maxCapacity);
70 protected DirectBuffer(DirectBytes bytes, int offset, int initialCapacity, int maxCapacity) {
71 super(bytes, offset, initialCapacity, maxCapacity, null);
75 public DirectBuffer duplicate() {
76 return new DirectBuffer((DirectBytes) bytes, offset(), capacity(), maxCapacity());