-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
RawBuffer.java
53 lines (44 loc) · 1.13 KB
/
RawBuffer.java
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
package me.nallar.unsafe;
import sun.misc.Cleaner;
import sun.misc.Unsafe;
/**
* Be very careful using this class!
*/
public class RawBuffer {
public static final Unsafe $ = UnsafeAccess.$;
public final long address;
int sizeBytes;
int size;
public RawBuffer(int sizeBytes, int size) {
this.address = $.allocateMemory(sizeBytes);
this.sizeBytes = sizeBytes;
this.size = size;
Cleaner.create(this, new UnsafeDeallocator(address));
}
public int size() {
return size;
}
/**
* Raw resize - no checking is done, be careful!
*/
public void resize(int sizeBytes, int size) {
assert sizeBytes > 0 && size > 0;
int oldSizeBytes = this.sizeBytes;
$.reallocateMemory(address, sizeBytes);
if (sizeBytes > oldSizeBytes) {
$.setMemory(address + oldSizeBytes, address + sizeBytes, (byte) 0);
}
this.sizeBytes = sizeBytes;
this.size = size;
}
private static class UnsafeDeallocator implements Runnable {
private final long address;
UnsafeDeallocator(long address) {
this.address = address;
}
@Override
public void run() {
$.freeMemory(address);
}
}
}