1 package net.jpountz.util;
3 import java.nio.ByteBuffer;
4 import java.nio.ByteOrder;
5 import java.nio.ReadOnlyBufferException;
7 public enum ByteBufferUtils {
10 public static void checkRange(ByteBuffer buf, int off, int len) {
11 SafeUtils.checkLength(len);
14 checkRange(buf, off + len - 1);
18 public static void checkRange(ByteBuffer buf, int off) {
19 if (off < 0 || off >= buf.capacity()) {
20 throw new ArrayIndexOutOfBoundsException(off);
24 public static ByteBuffer inLittleEndianOrder(ByteBuffer buf) {
25 if (buf.order().equals(ByteOrder.LITTLE_ENDIAN)) {
28 return buf.duplicate().order(ByteOrder.LITTLE_ENDIAN);
32 public static ByteBuffer inNativeByteOrder(ByteBuffer buf) {
33 if (buf.order().equals(Utils.NATIVE_BYTE_ORDER)) {
36 return buf.duplicate().order(Utils.NATIVE_BYTE_ORDER);
40 public static byte readByte(ByteBuffer buf, int i) {
44 public static void writeInt(ByteBuffer buf, int i, int v) {
45 assert buf.order() == Utils.NATIVE_BYTE_ORDER;
49 public static int readInt(ByteBuffer buf, int i) {
50 assert buf.order() == Utils.NATIVE_BYTE_ORDER;
54 public static int readIntLE(ByteBuffer buf, int i) {
55 assert buf.order() == ByteOrder.LITTLE_ENDIAN;
59 public static void writeLong(ByteBuffer buf, int i, long v) {
60 assert buf.order() == Utils.NATIVE_BYTE_ORDER;
64 public static long readLong(ByteBuffer buf, int i) {
65 assert buf.order() == Utils.NATIVE_BYTE_ORDER;
66 return buf.getLong(i);
69 public static long readLongLE(ByteBuffer buf, int i) {
70 assert buf.order() == ByteOrder.LITTLE_ENDIAN;
71 return buf.getLong(i);
74 public static void writeByte(ByteBuffer dest, int off, int i) {
75 dest.put(off, (byte) i);
78 public static void writeShortLE(ByteBuffer dest, int off, int i) {
79 dest.put(off, (byte) i);
80 dest.put(off + 1, (byte) (i >>> 8));
83 public static void checkNotReadOnly(ByteBuffer buffer) {
84 if (buffer.isReadOnly()) {
85 throw new ReadOnlyBufferException();
89 public static int readShortLE(ByteBuffer buf, int i) {
90 return (buf.get(i) & 0xFF) | ((buf.get(i+1) & 0xFF) << 8);