1 package net.jpountz.util;
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.
17 import java.nio.ByteOrder;
19 public enum SafeUtils {
22 public static void checkRange(byte[] buf, int off) {
23 if (off < 0 || off >= buf.length) {
24 throw new ArrayIndexOutOfBoundsException(off);
28 public static void checkRange(byte[] buf, int off, int len) {
32 checkRange(buf, off + len - 1);
36 public static void checkLength(int len) {
38 throw new IllegalArgumentException("lengths must be >= 0");
42 public static byte readByte(byte[] buf, int i) {
46 public static int readIntBE(byte[] buf, int i) {
47 return ((buf[i] & 0xFF) << 24) | ((buf[i+1] & 0xFF) << 16) | ((buf[i+2] & 0xFF) << 8) | (buf[i+3] & 0xFF);
50 public static int readIntLE(byte[] buf, int i) {
51 return (buf[i] & 0xFF) | ((buf[i+1] & 0xFF) << 8) | ((buf[i+2] & 0xFF) << 16) | ((buf[i+3] & 0xFF) << 24);
54 public static int readInt(byte[] buf, int i) {
55 if (Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) {
56 return readIntBE(buf, i);
58 return readIntLE(buf, i);
62 public static long readLongLE(byte[] buf, int i) {
63 return (buf[i] & 0xFFL) | ((buf[i+1] & 0xFFL) << 8) | ((buf[i+2] & 0xFFL) << 16) | ((buf[i+3] & 0xFFL) << 24)
64 | ((buf[i+4] & 0xFFL) << 32) | ((buf[i+5] & 0xFFL) << 40) | ((buf[i+6] & 0xFFL) << 48) | ((buf[i+7] & 0xFFL) << 56);
67 public static void writeShortLE(byte[] buf, int off, int v) {
68 buf[off++] = (byte) v;
69 buf[off++] = (byte) (v >>> 8);
72 public static void writeInt(int[] buf, int off, int v) {
76 public static int readInt(int[] buf, int off) {
80 public static void writeByte(byte[] dest, int off, int i) {
84 public static void writeShort(short[] buf, int off, int v) {
88 public static int readShortLE(byte[] buf, int i) {
89 return (buf[i] & 0xFF) | ((buf[i+1] & 0xFF) << 8);
92 public static int readShort(short[] buf, int off) {
93 return buf[off] & 0xFFFF;