]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.lz4/src/net/jpountz/util/ByteBufferUtils.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.lz4 / src / net / jpountz / util / ByteBufferUtils.java
1 package net.jpountz.util;
2
3 import java.nio.ByteBuffer;
4 import java.nio.ByteOrder;
5 import java.nio.ReadOnlyBufferException;
6
7 public enum ByteBufferUtils {
8   ;
9
10   public static void checkRange(ByteBuffer buf, int off, int len) {
11     SafeUtils.checkLength(len);
12     if (len > 0) {
13       checkRange(buf, off);
14       checkRange(buf, off + len - 1);
15     }
16   }
17
18   public static void checkRange(ByteBuffer buf, int off) {
19     if (off < 0 || off >= buf.capacity()) {
20       throw new ArrayIndexOutOfBoundsException(off);
21     }
22   }
23
24   public static ByteBuffer inLittleEndianOrder(ByteBuffer buf) {
25     if (buf.order().equals(ByteOrder.LITTLE_ENDIAN)) {
26       return buf;
27     } else {
28       return buf.duplicate().order(ByteOrder.LITTLE_ENDIAN);
29     }
30   }
31
32   public static ByteBuffer inNativeByteOrder(ByteBuffer buf) {
33     if (buf.order().equals(Utils.NATIVE_BYTE_ORDER)) {
34       return buf;
35     } else {
36       return buf.duplicate().order(Utils.NATIVE_BYTE_ORDER);
37     }
38   }
39
40   public static byte readByte(ByteBuffer buf, int i) {
41     return buf.get(i);
42   }
43
44   public static void writeInt(ByteBuffer buf, int i, int v) {
45     assert buf.order() == Utils.NATIVE_BYTE_ORDER;
46     buf.putInt(i, v);
47   }
48
49   public static int readInt(ByteBuffer buf, int i) {
50     assert buf.order() == Utils.NATIVE_BYTE_ORDER;
51     return buf.getInt(i);
52   }
53
54   public static int readIntLE(ByteBuffer buf, int i) {
55     assert buf.order() == ByteOrder.LITTLE_ENDIAN;
56     return buf.getInt(i);
57   }
58
59   public static void writeLong(ByteBuffer buf, int i, long v) {
60     assert buf.order() == Utils.NATIVE_BYTE_ORDER;
61     buf.putLong(i, v);
62   }
63
64   public static long readLong(ByteBuffer buf, int i) {
65     assert buf.order() == Utils.NATIVE_BYTE_ORDER;
66     return buf.getLong(i);
67   }
68
69   public static long readLongLE(ByteBuffer buf, int i) {
70     assert buf.order() == ByteOrder.LITTLE_ENDIAN;
71     return buf.getLong(i);
72   }
73
74   public static void writeByte(ByteBuffer dest, int off, int i) {
75     dest.put(off, (byte) i);
76   }
77
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));
81   }
82
83   public static void checkNotReadOnly(ByteBuffer buffer) {
84     if (buffer.isReadOnly()) {
85       throw new ReadOnlyBufferException();
86     }
87   }
88
89   public static int readShortLE(ByteBuffer buf, int i) {
90     return (buf.get(i) & 0xFF) | ((buf.get(i+1) & 0xFF) << 8);
91   }
92 }