Skip to content

Commit

Permalink
Add stack.malloc
Browse files Browse the repository at this point in the history
  • Loading branch information
ah-OOG-ah committed Nov 27, 2024
1 parent adc5093 commit 70ffe74
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public class CompatMemoryUtil {

static final sun.misc.Unsafe UNSAFE;

static final ByteOrder NATIVE_ORDER = ByteOrder.nativeOrder();

private static final Class<? extends ByteBuffer> BUFFER_BYTE;
private static final Class<? extends IntBuffer> BUFFER_INT;
private static final Class<? extends FloatBuffer> BUFFER_FLOAT;
Expand Down Expand Up @@ -341,6 +343,22 @@ private static long getCapacityOffset() {
return getFieldOffsetInt(bb, MAGIC_CAPACITY);
}

static ByteBuffer wrapBufferByte(long address, int capacity) {
ByteBuffer buffer;
try {
buffer = (ByteBuffer)UNSAFE.allocateInstance(BUFFER_BYTE);
} catch (InstantiationException e) {
throw new UnsupportedOperationException(e);
}

UNSAFE.putLong(buffer, ADDRESS, address);
UNSAFE.putInt(buffer, MARK, -1);
UNSAFE.putInt(buffer, LIMIT, capacity);
UNSAFE.putInt(buffer, CAPACITY, capacity);

return buffer.order(NATIVE_ORDER);
}

static IntBuffer wrapBufferInt(long address, int capacity) {
IntBuffer buffer;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import static com.gtnewhorizon.gtnhlib.client.lwjgl3.CompatMemoryUtil.memPutLong;
import static com.gtnewhorizon.gtnhlib.client.lwjgl3.CompatMemoryUtil.memPutShort;
import static com.gtnewhorizon.gtnhlib.client.lwjgl3.CompatMemoryUtil.memSet;
import static com.gtnewhorizon.gtnhlib.client.lwjgl3.CompatMemoryUtil.wrapBufferByte;
import static com.gtnewhorizon.gtnhlib.client.lwjgl3.CompatMemoryUtil.wrapBufferFloat;
import static com.gtnewhorizon.gtnhlib.client.lwjgl3.CompatMemoryUtil.wrapBufferInt;

Expand Down Expand Up @@ -329,6 +330,23 @@ public long ncalloc(int alignment, int num, int size) {

// -------------------------------------------------

/**
* Allocates an aligned {@link ByteBuffer} on the stack.
*
* @param alignment the required buffer alignment
* @param size the number of elements in the buffer
*
* @return the allocated buffer
*/
public ByteBuffer malloc(int alignment, int size) {
if (/*DEBUG*/ false) {
checkAlignment(alignment);
}
return wrapBufferByte(nmalloc(alignment, size), size);
}

// -------------------------------------------------

/** Unsafe version of {@link #shorts(short)}. */
public long nshort(short value) {
long a = nmalloc(2, 2);
Expand Down

0 comments on commit 70ffe74

Please sign in to comment.