-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathBufferUtils.java
More file actions
96 lines (83 loc) · 2.46 KB
/
BufferUtils.java
File metadata and controls
96 lines (83 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Copyright 2013 Luca Longinotti <[email protected]>
* See LICENSE.md for licensing information.
*/
package org.usb4java;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
/**
* Provides some utility methods for working with {@link IntBuffer} and
* {@link ByteBuffer}.
*
* @author Luca Longinotti ([email protected])
*/
public final class BufferUtils
{
/** The native size of the type <code>int</code>. */
private static final int INT_SIZE = Integer.SIZE / Byte.SIZE;
/** The native size of the type <code>long</code>. */
private static final int LONG_SIZE = Long.SIZE / Byte.SIZE;
/**
* Private constructor to prevent instantiation.
*/
private BufferUtils()
{
// Empty
}
/**
* Allocates a new direct {@link ByteBuffer} with the specified size and
* returns it.
*
* @param bytes
* The size of the new byte buffer.
* @return The allocated direct byte buffer.
*/
public static ByteBuffer allocateByteBuffer(final int bytes)
{
return ByteBuffer.allocateDirect(bytes);
}
/**
* Allocates a new {@link IntBuffer} with space for exactly one integer
* value.
*
* @return The allocated int buffer.
*/
public static IntBuffer allocateIntBuffer()
{
return ByteBuffer.allocateDirect(INT_SIZE).asIntBuffer();
}
/**
* Allocates a new {@link LongBuffer} with space for exactly one long value.
*
* @return The allocated long buffer.
*/
public static LongBuffer allocateLongBuffer()
{
return ByteBuffer.allocateDirect(LONG_SIZE).asLongBuffer();
}
/**
* Slices a part of the specified {@link ByteBuffer} into a new byte buffer
* and returns it.
*
* @param buffer
* The byte buffer to slice data from.
* @param offset
* The offset of the part to slice.
* @param length
* The length of the part to slice.
* @return The new byte buffer with the sliced part.
*/
public static ByteBuffer slice(final ByteBuffer buffer, final int offset,
final int length)
{
final int oldPosition = buffer.position();
final int oldLimit = buffer.limit();
buffer.position(offset);
buffer.limit(offset + length);
final ByteBuffer slice = buffer.slice();
buffer.position(oldPosition);
buffer.limit(oldLimit);
return slice;
}
}