mirror of
https://github.com/GTNewHorizons/GTNHLib.git
synced 2026-11-26 14:53:14 +00:00
Backport LWJGL3 memory utilities to enable more efficient ByteBuffer usage (#105)
This commit is contained in:
1 parent
656c98d84d
commit
39d1bed635
18 files changed
+6559
-17
No files matched your search
@@ -0,0 +1,510 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.DEBUG;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.POINTER_SHIFT;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.POINTER_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.NULL;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memASCII;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetAddress;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPointerBuffer;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutAddress;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutDouble;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutLong;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.nmemFree;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferByte;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
|
||||
/**
|
||||
* Utility class useful to API bindings. [INTERNAL USE ONLY]
|
||||
*
|
||||
* <p>
|
||||
* Method names in this class are prefixed with {@code api} to avoid ambiguities when used with static imports.
|
||||
* </p>
|
||||
*
|
||||
*/
|
||||
public final class APIUtil {
|
||||
|
||||
/**
|
||||
* The {@link PrintStream} used by LWJGL to print debug information and non-fatal errors. Defaults to
|
||||
* {@link System#err} which can be changed with
|
||||
*/
|
||||
public static final PrintStream DEBUG_STREAM = getDebugStream();
|
||||
|
||||
private static final Pattern API_VERSION_PATTERN;
|
||||
|
||||
static {
|
||||
String PREFIX = "[^\\d\\n\\r]*";
|
||||
String VERSION = "(\\d+)[.](\\d+)(?:[.](\\S+))?";
|
||||
String IMPLEMENTATION = "(?:\\s+(.+?))?\\s*";
|
||||
|
||||
API_VERSION_PATTERN = Pattern.compile("^" + PREFIX + VERSION + IMPLEMENTATION + "$", Pattern.DOTALL);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "UseOfSystemOutOrSystemErr" })
|
||||
private static PrintStream getDebugStream() {
|
||||
PrintStream debugStream = System.err;
|
||||
|
||||
Object state = System.err;
|
||||
if (state instanceof String) {
|
||||
try {
|
||||
Supplier<PrintStream> factory = (Supplier<PrintStream>) Class.forName((String) state).getConstructor()
|
||||
.newInstance();
|
||||
debugStream = factory.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else if (state instanceof Supplier<?>) {
|
||||
debugStream = ((Supplier<PrintStream>) state).get();
|
||||
} else if (state instanceof PrintStream) {
|
||||
debugStream = (PrintStream) state;
|
||||
}
|
||||
|
||||
return debugStream;
|
||||
}
|
||||
|
||||
private APIUtil() {}
|
||||
|
||||
/**
|
||||
* Prints the specified message to the {@link #DEBUG_STREAM} if {@link Checks#DEBUG} is true.
|
||||
*
|
||||
* @param msg the message to print
|
||||
*/
|
||||
public static void apiLog(CharSequence msg) {
|
||||
if (DEBUG) {
|
||||
DEBUG_STREAM.print("[LWJGL] " + msg + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as {@link #apiLog}, but replaces the LWJGL prefix with a tab character.
|
||||
*
|
||||
* @param msg the message to print, in continuation of a previous message
|
||||
*/
|
||||
public static void apiLogMore(CharSequence msg) {
|
||||
if (DEBUG) {
|
||||
DEBUG_STREAM.print("\t" + msg + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
public static void apiLogMissing(String api, ByteBuffer functionName) {
|
||||
if (DEBUG) {
|
||||
String function = memASCII(functionName, functionName.remaining() - 1);
|
||||
DEBUG_STREAM.print("[LWJGL] Failed to locate address for " + api + " function " + function + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable ByteBuffer apiGetMappedBuffer(@Nullable ByteBuffer buffer, long mappedAddress,
|
||||
int capacity) {
|
||||
if (buffer != null && memAddress(buffer) == mappedAddress && buffer.capacity() == capacity) {
|
||||
return buffer;
|
||||
}
|
||||
return mappedAddress == NULL ? null : wrapBufferByte(mappedAddress, capacity);
|
||||
}
|
||||
|
||||
public static long apiGetBytes(int elements, int elementShift) {
|
||||
return (elements & 0xFFFF_FFFFL) << elementShift;
|
||||
}
|
||||
|
||||
public static long apiCheckAllocation(int elements, long bytes, long maxBytes) {
|
||||
if (DEBUG) {
|
||||
if (elements < 0) {
|
||||
throw new IllegalArgumentException("Invalid number of elements");
|
||||
}
|
||||
if ((maxBytes + Long.MIN_VALUE) < (bytes + Long.MIN_VALUE)) { // unsigned comparison
|
||||
throw new IllegalArgumentException("The request allocation is too large");
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** A data class for API versioning information. */
|
||||
public static class APIVersion implements Comparable<APIVersion> {
|
||||
|
||||
/** Returns the API major version. */
|
||||
public final int major;
|
||||
/** Returns the API minor version. */
|
||||
public final int minor;
|
||||
|
||||
/** Returns the API revision. May be null. */
|
||||
public final @Nullable String revision;
|
||||
/** Returns the API implementation-specific versioning information. May be null. */
|
||||
public final @Nullable String implementation;
|
||||
|
||||
public APIVersion(int major, int minor) {
|
||||
this(major, minor, null, null);
|
||||
}
|
||||
|
||||
public APIVersion(int major, int minor, @Nullable String revision, @Nullable String implementation) {
|
||||
this.major = major;
|
||||
this.minor = minor;
|
||||
this.revision = revision;
|
||||
this.implementation = implementation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder(16);
|
||||
sb.append(major).append('.').append(minor);
|
||||
if (revision != null) {
|
||||
sb.append('.').append(revision);
|
||||
}
|
||||
if (implementation != null) {
|
||||
sb.append(" (").append(implementation).append(')');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof APIVersion)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
APIVersion that = (APIVersion) o;
|
||||
|
||||
return this.major == that.major && this.minor == that.major
|
||||
&& Objects.equals(this.revision, that.revision)
|
||||
&& Objects.equals(this.implementation, that.implementation);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = major;
|
||||
result = 31 * result + minor;
|
||||
result = 31 * result + (revision != null ? revision.hashCode() : 0);
|
||||
result = 31 * result + (implementation != null ? implementation.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(APIVersion other) {
|
||||
if (this.major != other.major) {
|
||||
return Integer.compare(this.major, other.major);
|
||||
}
|
||||
|
||||
if (this.minor != other.minor) {
|
||||
return Integer.compare(this.minor, other.minor);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@link APIVersion} value of the specified option.
|
||||
*
|
||||
* @param option the option to query
|
||||
*/
|
||||
public static @Nullable APIVersion apiParseVersion(Object option) {
|
||||
APIVersion version;
|
||||
|
||||
Object state = option;
|
||||
if (state instanceof String) {
|
||||
version = apiParseVersion((String) state);
|
||||
} else if (state instanceof APIVersion) {
|
||||
version = (APIVersion) state;
|
||||
} else {
|
||||
version = null;
|
||||
}
|
||||
|
||||
return version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a version string.
|
||||
*
|
||||
* <p>
|
||||
* The version string must have the format {@code PREFIX MAJOR.MINOR.REVISION IMPL}, where {@code PREFIX} is a
|
||||
* prefix without digits (string, optional), {@code MAJOR} is the major version (integer), {@code MINOR} is the
|
||||
* minor version (integer), {@code REVISION} is the revision version (string, optional) and {@code IMPL} is
|
||||
* implementation-specific information (string, optional).
|
||||
* </p>
|
||||
*
|
||||
* @param version the version string
|
||||
*
|
||||
* @return the parsed {@link APIVersion}
|
||||
*/
|
||||
public static APIVersion apiParseVersion(String version) {
|
||||
Matcher matcher = API_VERSION_PATTERN.matcher(version);
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalArgumentException(String.format("Malformed API version string [%s]", version));
|
||||
}
|
||||
|
||||
return new APIVersion(
|
||||
Integer.parseInt(matcher.group(1)),
|
||||
Integer.parseInt(matcher.group(2)),
|
||||
matcher.group(3),
|
||||
matcher.group(4));
|
||||
}
|
||||
|
||||
public static String apiUnknownToken(int token) {
|
||||
return apiUnknownToken("Unknown", token);
|
||||
}
|
||||
|
||||
public static String apiUnknownToken(String description, int token) {
|
||||
return String.format("%s [0x%X]", description, token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a map of public static final integer fields in the specified classes, to their String representations. An
|
||||
* optional filter can be specified to only include specific fields. The target map may be null, in which case a new
|
||||
* map is allocated and returned.
|
||||
*
|
||||
* <p>
|
||||
* This method is useful when debugging to quickly identify values returned from an API.
|
||||
* </p>
|
||||
*
|
||||
* @param filter the filter to use (optional)
|
||||
* @param target the target map (optional)
|
||||
* @param tokenClasses the classes to get tokens from
|
||||
*
|
||||
* @return the token map
|
||||
*/
|
||||
public static Map<Integer, String> apiClassTokens(@Nullable BiPredicate<Field, Integer> filter,
|
||||
@Nullable Map<Integer, String> target, Class<?>... tokenClasses) {
|
||||
if (target == null) {
|
||||
// noinspection AssignmentToMethodParameter
|
||||
target = new HashMap<>(64);
|
||||
}
|
||||
|
||||
int TOKEN_MODIFIERS = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL;
|
||||
|
||||
for (Class<?> tokenClass : tokenClasses) {
|
||||
for (Field field : tokenClass.getDeclaredFields()) {
|
||||
// Get only <public static final int> fields.
|
||||
if ((field.getModifiers() & TOKEN_MODIFIERS) == TOKEN_MODIFIERS && field.getType() == int.class) {
|
||||
try {
|
||||
Integer value = field.getInt(null);
|
||||
if (filter != null && !filter.test(field, value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String name = target.get(value);
|
||||
target.put(value, name == null ? field.getName() : name + "|" + field.getName());
|
||||
} catch (IllegalAccessException e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
// ----------------------------------------
|
||||
|
||||
/**
|
||||
* Stores the specified array of pointer addresses on the specified {@link MemoryStack}.
|
||||
*
|
||||
* @param stack the stack to use
|
||||
* @param addresses the pointer addresses to store
|
||||
*
|
||||
* @return the pointer array address on the stack
|
||||
*/
|
||||
public static long apiArray(MemoryStack stack, long... addresses) {
|
||||
PointerBuffer pointers = memPointerBuffer(
|
||||
stack.nmalloc(POINTER_SIZE, addresses.length << POINTER_SHIFT),
|
||||
addresses.length);
|
||||
|
||||
for (long address : addresses) {
|
||||
pointers.put(address);
|
||||
}
|
||||
|
||||
return memAddress(pointers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the addresses of the specified array of buffers on the specified {@link MemoryStack}.
|
||||
*
|
||||
* @param stack the stack to use
|
||||
* @param buffers the buffers to store
|
||||
*
|
||||
* @return the pointer array address on the stack
|
||||
*/
|
||||
public static long apiArray(MemoryStack stack, ByteBuffer... buffers) {
|
||||
PointerBuffer pointers = memPointerBuffer(
|
||||
stack.nmalloc(POINTER_SIZE, buffers.length << POINTER_SHIFT),
|
||||
buffers.length);
|
||||
|
||||
for (ByteBuffer buffer : buffers) {
|
||||
pointers.put(memAddress(buffer));
|
||||
}
|
||||
|
||||
return memAddress(pointers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the addresses of the specified array of buffers on the specified {@link MemoryStack}. A second array that
|
||||
* contains the buffer remaining bytes is stored immediately after the pointer array. Length values are
|
||||
* pointer-sized integers.
|
||||
*
|
||||
* @param stack the stack to use
|
||||
* @param buffers the buffers to store
|
||||
*
|
||||
* @return the pointer array address on the stack
|
||||
*/
|
||||
public static long apiArrayp(MemoryStack stack, ByteBuffer... buffers) {
|
||||
long pointers = apiArray(stack, buffers);
|
||||
|
||||
PointerBuffer lengths = stack.mallocPointer(buffers.length);
|
||||
for (ByteBuffer buffer : buffers) {
|
||||
lengths.put(buffer.remaining());
|
||||
}
|
||||
|
||||
return pointers;
|
||||
}
|
||||
|
||||
// ----------------------------------------
|
||||
|
||||
public interface Encoder {
|
||||
|
||||
ByteBuffer encode(CharSequence text, boolean nullTerminated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the specified strings with the specified {@link Encoder} and stores an array of pointers to the encoded
|
||||
* data on the specified {@link MemoryStack}. The encoded strings include null-termination.
|
||||
*
|
||||
* @param stack the stack to use
|
||||
* @param encoder the encoder to use
|
||||
* @param strings the strings to encode
|
||||
*
|
||||
* @return the pointer array address on the stack
|
||||
*/
|
||||
public static long apiArray(MemoryStack stack, Encoder encoder, CharSequence... strings) {
|
||||
PointerBuffer pointers = stack.mallocPointer(strings.length);
|
||||
|
||||
for (CharSequence s : strings) {
|
||||
pointers.put(memAddress(encoder.encode(s, true)));
|
||||
}
|
||||
|
||||
return memAddress(pointers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the specified strings with the specified {@link Encoder} and stores an array of pointers to the encoded
|
||||
* data on the specified {@link MemoryStack}. A second array that contains the string lengths is stored immediately
|
||||
* after the pointer array. Length values are 4-byte integers.
|
||||
*
|
||||
* <p>
|
||||
* The encoded buffers must be freed with {@link #apiArrayFree}.
|
||||
* </p>
|
||||
*
|
||||
* @param stack the stack to use
|
||||
* @param encoder the encoder to use
|
||||
* @param strings the strings to encode
|
||||
*
|
||||
* @return the pointer array address on the stack
|
||||
*/
|
||||
public static long apiArrayi(MemoryStack stack, Encoder encoder, CharSequence... strings) {
|
||||
// Alignment rules guarantee these two will be contiguous
|
||||
PointerBuffer pointers = stack.mallocPointer(strings.length);
|
||||
IntBuffer lengths = stack.mallocInt(strings.length);
|
||||
|
||||
for (CharSequence s : strings) {
|
||||
ByteBuffer buffer = encoder.encode(s, false);
|
||||
|
||||
pointers.put(memAddress(buffer));
|
||||
lengths.put(buffer.capacity());
|
||||
}
|
||||
|
||||
return memAddress(pointers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the specified strings with the specified {@link Encoder} and stores an array of pointers to the encoded
|
||||
* data on the specified {@link MemoryStack}. A second array that contains the string lengths is stored immediately
|
||||
* after the pointer array. Length values are pointer-sized integers.
|
||||
*
|
||||
* <p>
|
||||
* The encoded buffers must be freed with {@link #apiArrayFree}.
|
||||
* </p>
|
||||
*
|
||||
* @param stack the stack to use
|
||||
* @param encoder the encoder to use
|
||||
* @param strings the strings to encode
|
||||
*
|
||||
* @return the pointer array address on the stack
|
||||
*/
|
||||
public static long apiArrayp(MemoryStack stack, Encoder encoder, CharSequence... strings) {
|
||||
PointerBuffer pointers = stack.mallocPointer(strings.length);
|
||||
PointerBuffer lengths = stack.mallocPointer(strings.length);
|
||||
|
||||
for (CharSequence s : strings) {
|
||||
ByteBuffer buffer = encoder.encode(s, false);
|
||||
|
||||
pointers.put(memAddress(buffer));
|
||||
lengths.put(buffer.capacity());
|
||||
}
|
||||
|
||||
return memAddress(pointers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Frees the specified array of pointers.
|
||||
*
|
||||
* @param pointers the pointer array to free
|
||||
* @param length the pointer array length
|
||||
*/
|
||||
public static void apiArrayFree(long pointers, int length) {
|
||||
for (int i = length; --i >= 0;) {
|
||||
nmemFree(memGetAddress(pointers + Integer.toUnsignedLong(i) * Pointer.POINTER_SIZE));
|
||||
}
|
||||
}
|
||||
|
||||
public static void apiClosureRet(long ret, boolean __result) {
|
||||
memPutAddress(ret, __result ? 1L : 0L);
|
||||
}
|
||||
|
||||
public static void apiClosureRet(long ret, byte __result) {
|
||||
memPutAddress(ret, __result & 0xFFL);
|
||||
}
|
||||
|
||||
public static void apiClosureRet(long ret, short __result) {
|
||||
memPutAddress(ret, __result & 0xFFFFL);
|
||||
}
|
||||
|
||||
public static void apiClosureRet(long ret, int __result) {
|
||||
memPutAddress(ret, __result & 0xFFFF_FFFFL);
|
||||
}
|
||||
|
||||
public static void apiClosureRetL(long ret, long __result) {
|
||||
memPutLong(ret, __result);
|
||||
}
|
||||
|
||||
public static void apiClosureRetP(long ret, long __result) {
|
||||
memPutAddress(ret, __result);
|
||||
}
|
||||
|
||||
public static void apiClosureRet(long ret, float __result) {
|
||||
memPutFloat(ret, __result);
|
||||
}
|
||||
|
||||
public static void apiClosureRet(long ret, double __result) {
|
||||
memPutDouble(ret, __result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/**
|
||||
* Simple index checks.
|
||||
*
|
||||
* <p>
|
||||
* On Java 9 these checks are replaced with the corresponding {@link java.util.Objects} methods, which perform better.
|
||||
* </p>
|
||||
*/
|
||||
public final class CheckIntrinsics {
|
||||
|
||||
private CheckIntrinsics() {}
|
||||
|
||||
public static int classVersion() {
|
||||
return 8;
|
||||
}
|
||||
|
||||
public static int checkIndex(int index, int length) {
|
||||
if (index < 0 || length <= index) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public static int checkFromToIndex(int fromIndex, int toIndex, int length) {
|
||||
if (fromIndex < 0 || toIndex < fromIndex || length < toIndex) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
return fromIndex;
|
||||
}
|
||||
|
||||
public static int checkFromIndexSize(int fromIndex, int size, int length) {
|
||||
if ((length | fromIndex | size) < 0 || length - fromIndex < size) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
return fromIndex;
|
||||
}
|
||||
|
||||
public static ByteBuffer NewDirectByteBuffer(long address, int capacity) {
|
||||
try {
|
||||
// Should work on OpenJDK 8 and OpenJ9 8
|
||||
@SuppressWarnings("unchecked")
|
||||
final Class<? extends ByteBuffer> dbb = (Class<? extends ByteBuffer>) Class
|
||||
.forName("java.nio.DirectByteBuffer");
|
||||
final Constructor<? extends ByteBuffer> newDbb = dbb.getDeclaredConstructor(long.class, int.class);
|
||||
newDbb.setAccessible(true);
|
||||
return newDbb.newInstance(address, capacity);
|
||||
} catch (Throwable t) {
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
|
||||
public static MemoryUtilities.MemoryAllocator getLwjgl3ifyAllocator() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.CheckIntrinsics.checkIndex;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.NULL;
|
||||
|
||||
import java.nio.Buffer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.FloatBuffer;
|
||||
import java.nio.IntBuffer;
|
||||
import java.nio.LongBuffer;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
|
||||
/**
|
||||
* A class to check buffer boundaries in general. If there is insufficient space in the buffer when the call is made
|
||||
* then a buffer overflow would otherwise occur and cause unexpected behaviour, a crash, or worse, a security risk.
|
||||
*
|
||||
* <p>
|
||||
* Internal class, don't use.
|
||||
* </p>
|
||||
*
|
||||
*/
|
||||
final class Checks {
|
||||
|
||||
/**
|
||||
* Runtime checks flag.
|
||||
*
|
||||
* <p>
|
||||
* When enabled, LWJGL will perform basic checks during its operation, mainly to avoid crashes in native code.
|
||||
* Examples of such checks are: context-specific function address validation, buffer capacity checks,
|
||||
* null-termination checks, etc. These checks are generally low-overhead and should not have a measurable effect on
|
||||
* performance, so its recommended to have them enabled both during development and in production releases.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* If maximum performance is required, they can be disabled by setting to true.
|
||||
* </p>
|
||||
*/
|
||||
public static final boolean CHECKS = !Boolean.getBoolean("org.lwjgl.util.NoChecks");
|
||||
|
||||
/**
|
||||
* Debug mode flag.
|
||||
*
|
||||
* <p>
|
||||
* When enabled, LWJGL will perform additional checks during its operation. These checks are more expensive than the
|
||||
* ones enabled with {@link #CHECKS} and will have a noticeable effect on performance, so they are disabled by
|
||||
* default. Examples of such checks are: buffer object binding state check (GL), buffer capacity checks for texture
|
||||
* images (GL & CL), etc. LWJGL will also print additional information, mainly during start-up.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Can be enabled by setting to true.
|
||||
* </p>
|
||||
*/
|
||||
public static final boolean DEBUG = Boolean.getBoolean("org.lwjgl.util.Debug");
|
||||
|
||||
/**
|
||||
* Debug functions flag.
|
||||
*
|
||||
* <p>
|
||||
* When enabled, a warning message will be output to the debug stream when LWJGL fails to retrieve a function
|
||||
* pointer.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Can be enabled by setting to true.
|
||||
* </p>
|
||||
*/
|
||||
public static final boolean DEBUG_FUNCTIONS = Boolean.getBoolean("org.lwjgl.util.DebugFunctions");
|
||||
|
||||
private Checks() {}
|
||||
|
||||
public static int lengthSafe(short @Nullable [] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
public static int lengthSafe(int @Nullable [] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
public static int lengthSafe(long @Nullable [] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
public static int lengthSafe(float @Nullable [] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
public static int lengthSafe(double @Nullable [] array) {
|
||||
return array == null ? 0 : array.length;
|
||||
}
|
||||
|
||||
public static int remainingSafe(@Nullable Buffer buffer) {
|
||||
return buffer == null ? 0 : buffer.remaining();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if any of the specified functions pointers is {@code NULL}.
|
||||
*
|
||||
* @param functions the function pointers to check
|
||||
*
|
||||
* @return true if all function pointers are valid, false otherwise.
|
||||
*/
|
||||
public static boolean checkFunctions(long... functions) {
|
||||
for (long pointer : functions) {
|
||||
if (pointer == NULL) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the specified pointer is not {@code NULL} (0L).
|
||||
*
|
||||
* @param pointer the pointer to check
|
||||
*
|
||||
* @throws NullPointerException if {@code pointer} is {@code NULL}
|
||||
*/
|
||||
public static long check(long pointer) {
|
||||
if (pointer == NULL) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
|
||||
return pointer;
|
||||
}
|
||||
|
||||
private static void assertNT(boolean found) {
|
||||
if (!found) {
|
||||
throw new IllegalArgumentException("Missing termination");
|
||||
}
|
||||
}
|
||||
|
||||
/** Ensures that the specified array is null-terminated. */
|
||||
public static void checkNT(int[] buf) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == 0);
|
||||
}
|
||||
|
||||
/** Ensures that the specified array is terminated with the specified terminator. */
|
||||
public static void checkNT(int[] buf, int terminator) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == terminator);
|
||||
}
|
||||
|
||||
/** Ensures that the specified array is null-terminated. */
|
||||
public static void checkNT(long[] buf) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == NULL);
|
||||
}
|
||||
|
||||
/** Ensures that the specified array is null-terminated. */
|
||||
public static void checkNT(float[] buf) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == 0.0f);
|
||||
}
|
||||
|
||||
/** Ensures that the specified ByteBuffer is null-terminated (last byte equal to 0). */
|
||||
public static void checkNT1(ByteBuffer buf) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == 0);
|
||||
}
|
||||
|
||||
/** Ensures that the specified ByteBuffer is null-terminated (last 2 bytes equal to 0). */
|
||||
public static void checkNT2(ByteBuffer buf) {
|
||||
checkBuffer(buf.remaining(), 2);
|
||||
assertNT(buf.get(buf.limit() - 2) == 0);
|
||||
}
|
||||
|
||||
/** Ensures that the specified IntBuffer is null-terminated. */
|
||||
public static void checkNT(IntBuffer buf) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == 0);
|
||||
}
|
||||
|
||||
/** Ensures that the specified IntBuffer is terminated with the specified terminator. */
|
||||
public static void checkNT(IntBuffer buf, int terminator) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == terminator);
|
||||
}
|
||||
|
||||
/** Ensures that the specified LongBuffer is null-terminated. */
|
||||
public static void checkNT(LongBuffer buf) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == NULL);
|
||||
}
|
||||
|
||||
/** Ensures that the specified FloatBuffer is null-terminated. */
|
||||
public static void checkNT(FloatBuffer buf) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == 0.0f);
|
||||
}
|
||||
|
||||
/** Ensures that the specified PointerBuffer is null-terminated. */
|
||||
public static void checkNT(PointerBuffer buf) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == NULL);
|
||||
}
|
||||
|
||||
/** Ensures that the specified PointerBuffer is terminated with the specified terminator. */
|
||||
public static void checkNT(PointerBuffer buf, long terminator) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == terminator);
|
||||
}
|
||||
|
||||
public static void checkNTSafe(int @Nullable [] buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(int @Nullable [] buf, int terminator) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == terminator);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(long @Nullable [] buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == NULL);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(float @Nullable [] buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, 1);
|
||||
assertNT(buf[buf.length - 1] == 0.0f);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNT1Safe(@Nullable ByteBuffer buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNT2Safe(@Nullable ByteBuffer buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 2);
|
||||
assertNT(buf.get(buf.limit() - 2) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(@Nullable IntBuffer buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(@Nullable IntBuffer buf, int terminator) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == terminator);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(@Nullable LongBuffer buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == NULL);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(@Nullable FloatBuffer buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == 0.0f);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(@Nullable PointerBuffer buf) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == NULL);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNTSafe(@Nullable PointerBuffer buf, long terminator) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), 1);
|
||||
assertNT(buf.get(buf.limit() - 1) == terminator);
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkBuffer(int bufferSize, int minimumSize) {
|
||||
if (bufferSize < minimumSize) {
|
||||
throwIAE(bufferSize, minimumSize);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a array has enough capacity.
|
||||
*
|
||||
* @param buf the array to check
|
||||
* @param size the minimum array capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.length < size}
|
||||
*/
|
||||
public static void check(byte[] buf, int size) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a array has enough capacity.
|
||||
*
|
||||
* @param buf the array to check
|
||||
* @param size the minimum array capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.length < size}
|
||||
*/
|
||||
public static void check(short[] buf, int size) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a array has enough capacity.
|
||||
*
|
||||
* @param buf the array to check
|
||||
* @param size the minimum array capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.length < size}
|
||||
*/
|
||||
public static void check(int[] buf, int size) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a array has enough capacity.
|
||||
*
|
||||
* @param buf the array to check
|
||||
* @param size the minimum array capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.length < size}
|
||||
*/
|
||||
public static void check(long[] buf, int size) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a array has enough capacity.
|
||||
*
|
||||
* @param buf the array to check
|
||||
* @param size the minimum array capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.length < size}
|
||||
*/
|
||||
public static void check(float[] buf, int size) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a array has enough capacity.
|
||||
*
|
||||
* @param buf the array to check
|
||||
* @param size the minimum array capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.length < size}
|
||||
*/
|
||||
public static void check(double[] buf, int size) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a CharSequence has enough characters.
|
||||
*
|
||||
* @param text the text to check
|
||||
* @param size the minimum number of characters
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code text.length() < size}
|
||||
*/
|
||||
public static void check(CharSequence text, int size) {
|
||||
checkBuffer(text.length(), size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to ensure a buffer has enough capacity.
|
||||
*
|
||||
* @param buf the buffer to check
|
||||
* @param size the minimum buffer capacity
|
||||
*
|
||||
* @throws IllegalArgumentException if {@code buf.remaining() < size}
|
||||
*/
|
||||
public static void check(Buffer buf, int size) {
|
||||
checkBuffer(buf.remaining(), size);
|
||||
}
|
||||
|
||||
/** @see #check(Buffer, int) */
|
||||
public static void check(Buffer buf, long size) {
|
||||
checkBuffer(buf.remaining(), (int) size);
|
||||
}
|
||||
|
||||
public static void checkSafe(short @Nullable [] buf, int size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkSafe(int @Nullable [] buf, int size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkSafe(long @Nullable [] buf, int size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkSafe(float @Nullable [] buf, int size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkSafe(double @Nullable [] buf, int size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.length, size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkSafe(@Nullable Buffer buf, int size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkSafe(@Nullable Buffer buf, long size) {
|
||||
if (buf != null) {
|
||||
checkBuffer(buf.remaining(), (int) size);
|
||||
}
|
||||
}
|
||||
|
||||
public static void check(Object[] array, int size) {
|
||||
checkBuffer(array.length, size);
|
||||
}
|
||||
|
||||
private static void checkBufferGT(int bufferSize, int maximumSize) {
|
||||
if (maximumSize < bufferSize) {
|
||||
throwIAEGT(bufferSize, maximumSize);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkGT(Buffer buf, int size) {
|
||||
checkBufferGT(buf.remaining(), size);
|
||||
}
|
||||
|
||||
public static long check(int index, int length) {
|
||||
if (CHECKS) {
|
||||
checkIndex(index, length);
|
||||
}
|
||||
// Convert to long to support addressing up to 2^31-1 elements, regardless of sizeof(element).
|
||||
// The unsigned conversion helps the JIT produce code that is as fast as if int was returned.
|
||||
return Integer.toUnsignedLong(index);
|
||||
}
|
||||
|
||||
// Separate calls to help inline check.
|
||||
|
||||
private static void throwIAE(int bufferSize, int minimumSize) {
|
||||
throw new IllegalArgumentException(
|
||||
"Number of remaining elements is " + bufferSize + ", must be at least " + minimumSize);
|
||||
}
|
||||
|
||||
private static void throwIAEGT(int bufferSize, int maximumSize) {
|
||||
throw new IllegalArgumentException(
|
||||
"Number of remaining buffer elements is " + bufferSize + ", must be at most " + maximumSize);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.MemoryAllocator;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.getUnsafeInstance;
|
||||
|
||||
import net.minecraft.launchwrapper.Launch;
|
||||
|
||||
/** Provides {@link MemoryAllocator} implementations for {@link MemoryUtilities} to use. */
|
||||
final class MemoryManage {
|
||||
|
||||
private MemoryManage() {}
|
||||
|
||||
static MemoryAllocator getInstance() {
|
||||
final boolean hasLwjgl3ify = Launch.blackboard.get("lwjgl3ify:rfb-booted") == Boolean.TRUE;
|
||||
return hasLwjgl3ify ? CheckIntrinsics.getLwjgl3ifyAllocator() : new StdlibAllocator();
|
||||
}
|
||||
|
||||
/** stdlib memory allocator. */
|
||||
private static class StdlibAllocator implements MemoryAllocator {
|
||||
|
||||
static final sun.misc.Unsafe UNSAFE = getUnsafeInstance();
|
||||
|
||||
@Override
|
||||
public long malloc(long size) {
|
||||
return UNSAFE.allocateMemory(size);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long calloc(long num, long size) {
|
||||
final long totalSize = Math.multiplyExact(num, size);
|
||||
final long addr = UNSAFE.allocateMemory(totalSize);
|
||||
UNSAFE.setMemory(addr, totalSize, (byte) 0);
|
||||
return addr;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long realloc(long ptr, long size) {
|
||||
return UNSAFE.reallocateMemory(ptr, size);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void free(long ptr) {
|
||||
UNSAFE.freeMemory(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.UNSAFE;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCopyAligned64;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.Pointer.BITS64;
|
||||
|
||||
final class MultiReleaseMemCopy {
|
||||
|
||||
private MultiReleaseMemCopy() {}
|
||||
|
||||
public static int classVersion() {
|
||||
return 8;
|
||||
}
|
||||
|
||||
static void copy(long src, long dst, long bytes) {
|
||||
// A custom Java loop is fastest at small sizes, approximately up to 160 bytes.
|
||||
if (BITS64 && ((src | dst) & 7) == 0) {
|
||||
// both src and dst are aligned to 8 bytes
|
||||
memCopyAligned64(src, dst, (int) bytes & 0xFF);
|
||||
} else {
|
||||
// Unaligned fallback. Poor performance until Java 16.
|
||||
UNSAFE.copyMemory(null, src, null, dst, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.ARRAY_TLC_BYTE;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.ARRAY_TLC_CHAR;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.ARRAY_TLC_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.UNSAFE;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memByteBuffer;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* String decoding utilities.
|
||||
*
|
||||
* <p>
|
||||
* On Java 9 different implementations are used that work better with compact strings (JEP 254).
|
||||
* </p>
|
||||
*/
|
||||
final class MultiReleaseTextDecoding {
|
||||
|
||||
private MultiReleaseTextDecoding() {}
|
||||
|
||||
public static int classVersion() {
|
||||
return 8;
|
||||
}
|
||||
|
||||
/** @see MemoryUtilities#memUTF8(ByteBuffer, int, int) */
|
||||
static String decodeUTF8(long source, int length) {
|
||||
if (length <= 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
char[] string = length <= ARRAY_TLC_SIZE ? ARRAY_TLC_CHAR.get() : new char[length];
|
||||
|
||||
int i = 0, position = 0;
|
||||
|
||||
while (position < length) {
|
||||
char c;
|
||||
|
||||
int b0 = UNSAFE.getByte(null, source + position++) & 0xFF;
|
||||
if (b0 < 0x80) {
|
||||
c = (char) b0;
|
||||
} else {
|
||||
int b1 = UNSAFE.getByte(null, source + position++) & 0x3F;
|
||||
if ((b0 & 0xE0) == 0xC0) {
|
||||
c = (char) (((b0 & 0x1F) << 6) | b1);
|
||||
} else {
|
||||
int b2 = UNSAFE.getByte(null, source + position++) & 0x3F;
|
||||
if ((b0 & 0xF0) == 0xE0) {
|
||||
c = (char) (((b0 & 0x0F) << 12) | (b1 << 6) | b2);
|
||||
} else {
|
||||
int b3 = UNSAFE.getByte(null, source + position++) & 0x3F;
|
||||
int cp = ((b0 & 0x07) << 18) | (b1 << 12) | (b2 << 6) | b3;
|
||||
|
||||
if (i < length) {
|
||||
string[i++] = (char) ((cp >>> 10) + 0xD7C0);
|
||||
}
|
||||
c = (char) ((cp & 0x3FF) + 0xDC00);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (i < length) {
|
||||
string[i++] = c;
|
||||
}
|
||||
}
|
||||
|
||||
return new String(string, 0, Math.min(i, length));
|
||||
}
|
||||
|
||||
private static String jdkFallback(long source, int length) {
|
||||
byte[] bytes = length <= ARRAY_TLC_SIZE ? ARRAY_TLC_BYTE.get() : new byte[length];
|
||||
memByteBuffer(source, length).get(bytes, 0, length);
|
||||
return new String(bytes, 0, length, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.CHECKS;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.NULL;
|
||||
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.Sys;
|
||||
|
||||
/**
|
||||
* Pointer interface.
|
||||
*
|
||||
* <p>
|
||||
* LWJGL can run on both 32bit and 64bit architectures. Since LWJGL applications deal with native memory directly, this
|
||||
* interface provides necessary information about the underlying architecture of the running JVM process.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* When interacting with native functions, pointer values are mapped to Java {@code long}. LWJGL automatically converts
|
||||
* long values to the correct pointer addresses when used in native code. Native functions sometimes require arrays of
|
||||
* pointer values; the {@link PointerBuffer} class may be used for that purpose. It has an API similar to a
|
||||
* {@link java.nio.LongBuffer} but handles pointer casts automatically.
|
||||
* </p>
|
||||
*/
|
||||
public interface Pointer {
|
||||
|
||||
/** The pointer size in bytes. Will be 4 on a 32bit JVM and 8 on a 64bit one. */
|
||||
int POINTER_SIZE = Sys.is64Bit() ? 8 : 4;
|
||||
|
||||
/** The pointer size power-of-two. Will be 2 on a 32bit JVM and 3 on a 64bit one. */
|
||||
int POINTER_SHIFT = POINTER_SIZE == 8 ? 3 : 2;
|
||||
|
||||
/** The value of {@code sizeof(long)} for the current platform. */
|
||||
int CLONG_SIZE = POINTER_SIZE == 8 && SystemUtils.IS_OS_WINDOWS ? 4 : POINTER_SIZE;
|
||||
|
||||
/** The value of {@code sizeof(long)} as a power-of-two. */
|
||||
int CLONG_SHIFT = CLONG_SIZE == 8 ? 3 : 2;
|
||||
|
||||
/** Will be true on a 32bit JVM. */
|
||||
boolean BITS32 = POINTER_SIZE * 8 == 32;
|
||||
|
||||
/** Will be true on a 64bit JVM. */
|
||||
boolean BITS64 = POINTER_SIZE * 8 == 64;
|
||||
|
||||
/**
|
||||
* Returns the raw pointer address as a {@code long} value.
|
||||
*
|
||||
* @return the pointer address
|
||||
*/
|
||||
long address();
|
||||
|
||||
/** Default {@link Pointer} implementation. */
|
||||
abstract class Default implements Pointer {
|
||||
|
||||
// Removed final due to JDK-8139758. TODO: Restore if the fix is backported to JDK 8.
|
||||
protected long address;
|
||||
|
||||
protected Default(long address) {
|
||||
if (CHECKS && address == NULL) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long address() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public boolean equals(@Nullable Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof Pointer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Pointer that = (Pointer) o;
|
||||
|
||||
return address == that.address();
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return (int) (address ^ (address >>> 32));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s pointer [0x%X]", getClass().getSimpleName(), address);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license
|
||||
*/
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Stack-walking utilities.
|
||||
*
|
||||
* <p>
|
||||
* On Java 9 these methods are implemented using {@code java.lang.StackWalker}, which has much lower overhead.
|
||||
* </p>
|
||||
*/
|
||||
final class StackWalkUtil {
|
||||
|
||||
private StackWalkUtil() {}
|
||||
|
||||
public static int classVersion() {
|
||||
return 8;
|
||||
}
|
||||
|
||||
static StackTraceElement[] stackWalkArray(Object[] a) {
|
||||
return (StackTraceElement[]) a;
|
||||
}
|
||||
|
||||
static Object stackWalkGetMethod(Class<?> after) {
|
||||
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
||||
|
||||
for (int i = 3; i < stackTrace.length; i++) {
|
||||
if (!stackTrace[i].getClassName().startsWith(after.getName())) {
|
||||
return stackTrace[i];
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
private static boolean isSameMethod(StackTraceElement a, StackTraceElement b) {
|
||||
return isSameMethod(a, b, b.getMethodName());
|
||||
}
|
||||
|
||||
private static boolean isSameMethod(StackTraceElement a, StackTraceElement b, String methodName) {
|
||||
return a.getMethodName().equals(methodName) && a.getClassName().equals(b.getClassName())
|
||||
&& Objects.equals(a.getFileName(), b.getFileName());
|
||||
}
|
||||
|
||||
private static boolean isAutoCloseable(StackTraceElement element, StackTraceElement pushed) {
|
||||
// Java 9 try-with-resources: synthetic $closeResource
|
||||
if (isSameMethod(element, pushed, "$closeResource")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Kotlin T.use: kotlin.AutoCloseable::closeFinally
|
||||
if ("closeFinally".equals(element.getMethodName()) && "AutoCloseable.kt".equals(element.getFileName())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static @Nullable Object stackWalkCheckPop(Class<?> after, Object pushedObj) {
|
||||
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
||||
|
||||
for (int i = 3; i < stackTrace.length; i++) {
|
||||
StackTraceElement element = stackTrace[i];
|
||||
if (element.getClassName().startsWith(after.getName())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
StackTraceElement pushed = (StackTraceElement) pushedObj;
|
||||
if (isSameMethod(element, pushed)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isAutoCloseable(element, pushed) && i + 1 < stackTrace.length) {
|
||||
// Some runtimes use a separate method to call AutoCloseable::close in try-with-resources blocks.
|
||||
// That method suppresses any exceptions thrown by close if necessary.
|
||||
// When that happens, the pop is 1 level deeper than expected.
|
||||
element = stackTrace[i + 1];
|
||||
if (isSameMethod(pushed, stackTrace[i + 1])) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
static Object[] stackWalkGetTrace() {
|
||||
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
||||
|
||||
int i = 3;
|
||||
for (; i < stackTrace.length; i++) {
|
||||
if (!stackTrace[i].getClassName().startsWith("org.lwjgl.system.Memory")) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return Arrays.copyOfRange(stackTrace, i, stackTrace.length);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Utilities for more efficient ByteBuffer management, mostly ported over from LWJGL 3 sources. Intended for static
|
||||
* wildcard import usage, so you can use e.g. {@code stackPush()} unqualified.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
package com.gtnewhorizon.gtnhlib.bytebuf;
|
||||
|
||||
import org.jetbrains.annotations.NotNullByDefault;
|
||||
Reference in new issue
Block a user