| 1 |
/* |
| 2 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
* you may not use this file except in compliance with the License. |
| 4 |
* You may obtain a copy of the License at |
| 5 |
* |
| 6 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
* |
| 8 |
* Unless required by applicable law or agreed to in writing, software |
| 9 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
* See the License for the specific language governing permissions and |
| 12 |
* limitations under the License. |
| 13 |
*/ |
| 14 |
package io.airlift.slice; |
| 15 |
|
| 16 |
import static io.airlift.slice.JvmUtils.unsafe; |
| 17 |
import static io.airlift.slice.Preconditions.checkPositionIndexes; |
| 18 |
import static io.airlift.slice.SizeOf.SIZE_OF_DOUBLE; |
| 19 |
import static io.airlift.slice.SizeOf.SIZE_OF_FLOAT; |
| 20 |
import static io.airlift.slice.SizeOf.SIZE_OF_INT; |
| 21 |
import static io.airlift.slice.SizeOf.SIZE_OF_LONG; |
| 22 |
import static io.airlift.slice.SizeOf.SIZE_OF_SHORT; |
| 23 |
import static sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET; |
| 24 |
|
| 25 |
public final class ByteArrays |
| 26 |
{ |
| 27 |
private ByteArrays() {} |
| 28 |
|
| 29 |
public static short getShort(byte[] bytes, int index) |
| 30 |
{ |
| 31 |
checkIndexLength(bytes.length, index, SIZE_OF_SHORT); |
| 32 |
return unsafe.getShort(bytes, ((long) ARRAY_BYTE_BASE_OFFSET) + index); |
| 33 |
} |
| 34 |
|
| 35 |
public static int getInt(byte[] bytes, int index) |
| 36 |
{ |
| 37 |
checkIndexLength(bytes.length, index, SIZE_OF_INT); |
| 38 |
return unsafe.getInt(bytes, ((long) ARRAY_BYTE_BASE_OFFSET) + index); |
| 39 |
} |
| 40 |
|
| 41 |
public static long getLong(byte[] bytes, int index) |
| 42 |
{ |
| 43 |
checkIndexLength(bytes.length, index, SIZE_OF_LONG); |
| 44 |
return unsafe.getLong(bytes, ((long) ARRAY_BYTE_BASE_OFFSET) + index); |
| 45 |
} |
| 46 |
|
| 47 |
public static float getFloat(byte[] bytes, int index) |
| 48 |
{ |
| 49 |
checkIndexLength(bytes.length, index, SIZE_OF_FLOAT); |
| 50 |
return unsafe.getFloat(bytes, ((long) ARRAY_BYTE_BASE_OFFSET) + index); |
| 51 |
} |
| 52 |
|
| 53 |
public static double getDouble(byte[] bytes, int index) |
| 54 |
{ |
| 55 |
checkIndexLength(bytes.length, index, SIZE_OF_DOUBLE); |
| 56 |
return unsafe.getDouble(bytes, ((long) ARRAY_BYTE_BASE_OFFSET) + index); |
| 57 |
} |
| 58 |
|
| 59 |
private static void checkIndexLength(int arrayLength, int index, int typeLength) |
| 60 |
{ |
| 61 |
checkPositionIndexes(index, index + typeLength, arrayLength); |
| 62 |
} |
| 63 |
} |