diff --git a/addon.gradle b/addon.gradle deleted file mode 100644 index 29106b4a..00000000 --- a/addon.gradle +++ /dev/null @@ -1,7 +0,0 @@ - -test { - useJUnitPlatform() - testLogging { - events "passed", "skipped", "failed" - } -} diff --git a/build.gradle.kts b/build.gradle.kts index e6c412be..67e2b30a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,6 +3,30 @@ plugins { id("com.gtnewhorizons.gtnhconvention") } +// Add a Java 17 sourceset for including code optimized for newer Java versions +val java17ToolchainSpec: JavaToolchainSpec.() -> Unit = { + vendor = JvmVendorSpec.AZUL + // Use a Java 21 compiler with a target of 17 + languageVersion = JavaLanguageVersion.of(21) +} +val main17 by sourceSets.creating { + compileClasspath = files(compileClasspath, configurations.lwjgl3Classpath.get(), sourceSets.main.get().compileClasspath.filter({ f -> !f.toString().contains("jabel-javac") }), sourceSets.main.get().output) + runtimeClasspath = files(runtimeClasspath, configurations.lwjgl3Classpath.get(), sourceSets.main.get().runtimeClasspath, sourceSets.main.get().output) +} +tasks.named(main17.compileJavaTaskName).configure { + javaCompiler = javaToolchains.compilerFor(java17ToolchainSpec) + options.release = 17 + sourceCompatibility = JavaVersion.VERSION_17.majorVersion + targetCompatibility = JavaVersion.VERSION_17.majorVersion +} +tasks.jar.configure { + dependsOn(main17.compileJavaTaskName) + into("META-INF/versions/17") { from(main17.output) } +} +tasks.sourcesJar.configure { + into("META-INF/versions/17") { from(main17.java.sourceDirectories) } +} + tasks.processResources { inputs.property("version", project.version.toString()) filesMatching("META-INF/rfb-plugin/*") { @@ -14,4 +38,26 @@ tasks.processResources { val shadowSources = configurations.getByName("shadowSources") tasks.sourcesJar { from(shadowSources.map { zipTree(it) }) + exclude("META-INF/versions/9/module-info.class") + exclude("META-INF/versions/9/module-info.java") +} + +tasks.shadowJar { + into("META-INF/versions/17") { from(main17.output) } + exclude("META-INF/versions/9/module-info.class") +} + +tasks.test { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") + } +} + +for (jarTask in listOf(tasks.jar, tasks.shadowJar, tasks.sourcesJar)) { + jarTask.configure { + manifest { + attributes("Multi-Release" to true) + } + } } diff --git a/dependencies.gradle b/dependencies.gradle index 87fbe36f..26598ad1 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -4,12 +4,12 @@ configurations { } dependencies { - shadowImplementation("it.unimi.dsi:fastutil:8.5.12") // Apache 2.0 - shadowImplementation("org.joml:joml:1.10.5") // MIT - shadowSources("it.unimi.dsi:fastutil:8.5.12:sources") - shadowSources("org.joml:joml:1.10.5:sources") + shadowImplementation("it.unimi.dsi:fastutil:8.5.15") // Apache 2.0 + shadowImplementation("org.joml:joml:1.10.8") { transitive = false } // MIT + shadowSources("it.unimi.dsi:fastutil:8.5.15:sources") + shadowSources("org.joml:joml:1.10.8:sources") { transitive = false } - testImplementation(platform("org.junit:junit-bom:5.9.2")) + testImplementation(platform("org.junit:junit-bom:5.11.4")) testImplementation("org.junit.jupiter:junit-jupiter") testRuntimeOnly("org.junit.platform:junit-platform-launcher") { because("Only needed to run tests in a version of IntelliJ IDEA that bundles older versions") @@ -17,12 +17,13 @@ dependencies { testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") testRuntimeOnly("org.junit.vintage:junit-vintage-engine") - compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:0.4.0") { transitive = false } + compileOnly("com.github.GTNewHorizons:lwjgl3ify:2.1.6") { transitive = false } + compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.0.7") { transitive = false } - compileOnly('org.jetbrains:annotations:24.0.1') - compileOnly("org.projectlombok:lombok:1.18.22") {transitive = false } - annotationProcessor("org.projectlombok:lombok:1.18.22") + compileOnly('org.jetbrains:annotations:26.0.1') + compileOnly("org.projectlombok:lombok:1.18.36") {transitive = false } + annotationProcessor("org.projectlombok:lombok:1.18.36") // For CapturingTesselator compat - compileOnly("com.falsepattern:falsetweaks-mc1.7.10:3.3.2:api") + compileOnly("com.falsepattern:falsetweaks-mc1.7.10:3.8.4:api") } diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/APIUtil.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/APIUtil.java new file mode 100644 index 00000000..dc680405 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/APIUtil.java @@ -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] + * + *

+ * Method names in this class are prefixed with {@code api} to avoid ambiguities when used with static imports. + *

+ * + */ +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 factory = (Supplier) Class.forName((String) state).getConstructor() + .newInstance(); + debugStream = factory.get(); + } catch (Exception e) { + e.printStackTrace(); + } + } else if (state instanceof Supplier) { + debugStream = ((Supplier) 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 { + + /** 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. + * + *

+ * 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). + *

+ * + * @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. + * + *

+ * This method is useful when debugging to quickly identify values returned from an API. + *

+ * + * @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 apiClassTokens(@Nullable BiPredicate filter, + @Nullable Map 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 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. + * + *

+ * The encoded buffers must be freed with {@link #apiArrayFree}. + *

+ * + * @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. + * + *

+ * The encoded buffers must be freed with {@link #apiArrayFree}. + *

+ * + * @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); + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/CheckIntrinsics.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/CheckIntrinsics.java new file mode 100644 index 00000000..b6048539 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/CheckIntrinsics.java @@ -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. + * + *

+ * On Java 9 these checks are replaced with the corresponding {@link java.util.Objects} methods, which perform better. + *

+ */ +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 dbb = (Class) Class + .forName("java.nio.DirectByteBuffer"); + final Constructor 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; + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/Checks.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/Checks.java new file mode 100644 index 00000000..3ff59c2c --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/Checks.java @@ -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. + * + *

+ * Internal class, don't use. + *

+ * + */ +final class Checks { + + /** + * Runtime checks flag. + * + *

+ * 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. + *

+ * + *

+ * If maximum performance is required, they can be disabled by setting to true. + *

+ */ + public static final boolean CHECKS = !Boolean.getBoolean("org.lwjgl.util.NoChecks"); + + /** + * Debug mode flag. + * + *

+ * 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. + *

+ * + *

+ * Can be enabled by setting to true. + *

+ */ + public static final boolean DEBUG = Boolean.getBoolean("org.lwjgl.util.Debug"); + + /** + * Debug functions flag. + * + *

+ * When enabled, a warning message will be output to the debug stream when LWJGL fails to retrieve a function + * pointer. + *

+ * + *

+ * Can be enabled by setting to true. + *

+ */ + 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); + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryManage.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryManage.java new file mode 100644 index 00000000..449e67c8 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryManage.java @@ -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); + } + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryStack.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryStack.java new file mode 100644 index 00000000..f0300d6a --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryStack.java @@ -0,0 +1,1426 @@ +/* + * Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license + */ +package com.gtnewhorizon.gtnhlib.bytebuf; + +import static com.gtnewhorizon.gtnhlib.bytebuf.APIUtil.DEBUG_STREAM; +import static com.gtnewhorizon.gtnhlib.bytebuf.APIUtil.apiLog; +import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.CHECKS; +import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.DEBUG; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.encodeASCIIUnsafe; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.encodeUTF16Unsafe; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.encodeUTF8Unsafe; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memLengthASCII; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memLengthUTF16; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memLengthUTF8; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPointerBuffer; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutAddress; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutByte; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutDouble; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutLong; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutShort; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memSet; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferByte; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferDouble; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferLong; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.wrapBufferShort; +import static com.gtnewhorizon.gtnhlib.bytebuf.StackWalkUtil.stackWalkCheckPop; +import static com.gtnewhorizon.gtnhlib.bytebuf.StackWalkUtil.stackWalkGetMethod; + +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; +import java.util.Arrays; + +import org.jetbrains.annotations.Nullable; +import org.lwjgl.BufferUtils; +import org.lwjgl.PointerBuffer; + +/** + * An off-heap memory stack. + * + *

+ * This class should be used in a thread-local manner for stack allocations. + *

+ * + */ +public class MemoryStack extends Pointer.Default implements AutoCloseable { + + public static final int DEFAULT_STACK_SIZE = 64 * 1024; + public static final int DEFAULT_STACK_FRAMES = 8; + public static final boolean DEBUG_STACK = Boolean.getBoolean("org.lwjgl.util.DebugStack"); + + private static final ThreadLocal TLS = ThreadLocal.withInitial(MemoryStack::create); + + static { + if (DEFAULT_STACK_SIZE < 0) { + throw new IllegalStateException("Invalid stack size."); + } + } + + @SuppressWarnings({ "FieldCanBeLocal", "unused" }) + private final @Nullable ByteBuffer container; + + private final int size; + + private int pointer; + + private int[] frames; + protected int frameIndex; + + /** + * Creates a new {@code MemoryStack} backed by the specified memory region. + * + *

+ * In the initial state, there is no active stack frame. The {@link #push} method must be used before any + * allocations. + *

+ * + * @param container the backing memory buffer, may be null + * @param address the backing memory address + * @param size the backing memory size + */ + protected MemoryStack(@Nullable ByteBuffer container, long address, int size) { + super(address); + this.container = container; + + this.size = size; + this.pointer = size; + + this.frames = new int[DEFAULT_STACK_FRAMES]; + } + + /** + * Creates a new {@code MemoryStack} with the default size. + * + *

+ * In the initial state, there is no active stack frame. The {@link #push} method must be used before any + * allocations. + *

+ */ + public static MemoryStack create() { + return create(DEFAULT_STACK_SIZE); + } + + /** + * Creates a new {@code MemoryStack} with the specified size. + * + *

+ * In the initial state, there is no active stack frame. The {@link #push} method must be used before any + * allocations. + *

+ * + * @param capacity the maximum number of bytes that may be allocated on the stack + */ + public static MemoryStack create(int capacity) { + return create(BufferUtils.createByteBuffer(capacity)); + } + + /** + * Creates a new {@code MemoryStack} backed by the specified memory buffer. + * + *

+ * In the initial state, there is no active stack frame. The {@link #push} method must be used before any + * allocations. + *

+ * + * @param buffer the backing memory buffer + */ + public static MemoryStack create(ByteBuffer buffer) { + long address = memAddress(buffer); + int size = buffer.remaining(); + return DEBUG_STACK ? new DebugMemoryStack(buffer, address, size) : new MemoryStack(buffer, address, size); + } + + /** + * Creates a new {@code MemoryStack} backed by the specified memory region. + * + *

+ * In the initial state, there is no active stack frame. The {@link #push} method must be used before any + * allocations. + *

+ * + * @param address the backing memory address + * @param size the backing memory size + */ + public static MemoryStack ncreate(long address, int size) { + return DEBUG_STACK ? new DebugMemoryStack(null, address, size) : new MemoryStack(null, address, size); + } + + /** + * Stores the current stack pointer and pushes a new frame to the stack. + * + *

+ * This method should be called when entering a method, before doing any stack allocations. When exiting a method, + * call the {@link #pop} method to restore the previous stack frame. + *

+ * + *

+ * Pairs of push/pop calls may be nested. Care must be taken to: + *

+ *
    + *
  • match every push with a pop
  • + *
  • not call pop before push has been called at least once
  • + *
  • not nest push calls to more than the maximum supported depth
  • + *
+ * + * @return this stack + */ + public MemoryStack push() { + if (frameIndex == frames.length) { + frameOverflow(); + } + + frames[frameIndex++] = pointer; + return this; + } + + private void frameOverflow() { + if (DEBUG) { + apiLog("[WARNING] Out of frame stack space (" + frames.length + ") in thread: " + Thread.currentThread()); + } + frames = Arrays.copyOf(frames, frames.length * 3 / 2); + } + + /** + * Pops the current stack frame and moves the stack pointer to the end of the previous stack frame. + * + * @return this stack + */ + public MemoryStack pop() { + pointer = frames[--frameIndex]; + return this; + } + + /** + * Calls {@link #pop} on this {@code MemoryStack}. + * + *

+ * This method should not be used directly. It is called automatically when the {@code MemoryStack} is used as a + * resource in a try-with-resources statement. + *

+ */ + @Override + public void close() { + // noinspection resource + pop(); + } + + /** Stores the method that pushed a frame and checks if it is the same method when the frame is popped. */ + private static class DebugMemoryStack extends MemoryStack { + + private @Nullable Object[] debugFrames; + + DebugMemoryStack(@Nullable ByteBuffer buffer, long address, int size) { + super(buffer, address, size); + debugFrames = new Object[DEFAULT_STACK_FRAMES]; + } + + @Override + public MemoryStack push() { + if (frameIndex == debugFrames.length) { + frameOverflow(); + } + + debugFrames[frameIndex] = stackWalkGetMethod(MemoryStack.class); + + return super.push(); + } + + private void frameOverflow() { + debugFrames = Arrays.copyOf(debugFrames, debugFrames.length * 3 / 2); + } + + @Override + public MemoryStack pop() { + Object pushed = debugFrames[frameIndex - 1]; + Object popped = stackWalkCheckPop(MemoryStack.class, pushed); + if (popped != null) { + reportAsymmetricPop(pushed, popped); + } + + debugFrames[frameIndex - 1] = null; + return super.pop(); + } + + // No need to check pop in try-with-resources + @Override + public void close() { + debugFrames[frameIndex - 1] = null; + super.pop(); + } + + private static void reportAsymmetricPop(Object pushed, Object popped) { + DEBUG_STREAM.format( + "[LWJGL] Asymmetric pop detected:\n\tPUSHED: %s\n\tPOPPED: %s\n\tTHREAD: %s\n", + pushed, + popped, + Thread.currentThread()); + } + + } + + /** + * Returns the address of the backing off-heap memory. + * + *

+ * The stack grows "downwards", so the bottom of the stack is at {@code address + size}, while the top is at + * {@code address}. + *

+ */ + public long getAddress() { + return address; + } + + /** + * Returns the size of the backing off-heap memory. + * + *

+ * This is the maximum number of bytes that may be allocated on the stack. + *

+ */ + public int getSize() { + return size; + } + + /** + * Returns the current frame index. + * + *

+ * This is the current number of nested {@link #push} calls. + *

+ */ + public int getFrameIndex() { + return frameIndex; + } + + /** Returns the memory address at the current stack pointer. */ + public long getPointerAddress() { + return address + (pointer & 0xFFFF_FFFFL); + } + + /** + * Returns the current stack pointer. + * + *

+ * The stack grows "downwards", so when the stack is empty {@code pointer} is equal to {@code size}. On every + * allocation {@code pointer} is reduced by the allocated size (after alignment) and {@code address + pointer} + * points to the first byte of the last allocation. + *

+ * + *

+ * Effectively, this methods returns how many more bytes may be allocated on the stack. + *

+ */ + public int getPointer() { + return pointer; + } + + /** + * Sets the current stack pointer. + * + *

+ * This method directly manipulates the stack pointer. Using it irresponsibly may break the internal state of the + * stack. It should only be used in rare cases or in auto-generated code. + *

+ */ + public void setPointer(int pointer) { + if (CHECKS) { + checkPointer(pointer); + } + + this.pointer = pointer; + } + + private void checkPointer(int pointer) { + if (pointer < 0 || size < pointer) { + throw new IndexOutOfBoundsException("Invalid stack pointer"); + } + } + + private static void checkAlignment(int alignment) { + if (Integer.bitCount(alignment) != 1) { + throw new IllegalArgumentException("Alignment must be a power-of-two value."); + } + } + + /** + * Calls {@link #nmalloc(int, int)} with {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + * + * @param size the allocation size + * + * @return the memory address on the stack for the requested allocation + */ + public long nmalloc(int size) { + return nmalloc(POINTER_SIZE, size); + } + + /** + * Allocates a block of {@code size} bytes of memory on the stack. The content of the newly allocated block of + * memory is not initialized, remaining with indeterminate values. + * + * @param alignment the required alignment + * @param size the allocation size + * + * @return the memory address on the stack for the requested allocation + */ + public long nmalloc(int alignment, int size) { + // Align address to the specified alignment + long address = (this.address + pointer - size) & ~Integer.toUnsignedLong(alignment - 1); + + pointer = (int) (address - this.address); + if (CHECKS && pointer < 0) { + throw new OutOfMemoryError("Out of stack space."); + } + + return address; + } + + /** + * Allocates a block of memory on the stack for an array of {@code num} elements, each of them {@code size} bytes + * long, and initializes all its bits to zero. + * + * @param alignment the required element alignment + * @param num num the number of elements to allocate + * @param size the size of each element + * + * @return the memory address on the stack for the requested allocation + */ + public long ncalloc(int alignment, int num, int size) { + int bytes = num * size; + long address = nmalloc(alignment, bytes); + memSet(address, 0, bytes); + return address; + } + + // ------------------------------------------------- + + /** + * 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) { + checkAlignment(alignment); + } + return wrapBufferByte(nmalloc(alignment, size), size); + } + + /** Calloc version of {@link #malloc(int, int)}. */ + public ByteBuffer calloc(int alignment, int size) { + if (DEBUG) { + checkAlignment(alignment); + } + return wrapBufferByte(ncalloc(alignment, size, 1), size); + } + + /** + * Allocates a {@link ByteBuffer} on the stack with {@code alignment} equal to {@link Pointer#POINTER_SIZE + * POINTER_SIZE}. + * + * @param size the number of elements in the buffer + * + * @return the allocated buffer + */ + public ByteBuffer malloc(int size) { + return wrapBufferByte(nmalloc(POINTER_SIZE, size), size); + } + + /** Calloc version of {@link #malloc(int)}. */ + public ByteBuffer calloc(int size) { + return wrapBufferByte(ncalloc(POINTER_SIZE, size, 1), size); + } + + /** Unsafe version of {@link #bytes(byte)}. */ + public long nbyte(byte value) { + long a = nmalloc(1, 1); + memPutByte(a, value); + return a; + } + + /** Single value version of {@link #malloc}. */ + public ByteBuffer bytes(byte x) { + return malloc(1, 1).put(0, x); + } + + /** Two value version of {@link #malloc}. */ + public ByteBuffer bytes(byte x, byte y) { + return malloc(1, 2).put(0, x).put(1, y); + } + + /** Three value version of {@link #malloc}. */ + public ByteBuffer bytes(byte x, byte y, byte z) { + return malloc(1, 3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #malloc}. */ + public ByteBuffer bytes(byte x, byte y, byte z, byte w) { + return malloc(1, 4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #malloc}. */ + public ByteBuffer bytes(byte... values) { + ByteBuffer buffer = malloc(1, values.length).put(values); + buffer.flip(); + return buffer; + } + + // ------------------------------------------------- + + /** Short version of {@link #malloc(int)}. */ + public ShortBuffer mallocShort(int size) { + return wrapBufferShort(nmalloc(2, size << 1), size); + } + + /** Short version of {@link #calloc(int)}. */ + public ShortBuffer callocShort(int size) { + int bytes = size * 2; + long address = nmalloc(2, bytes); + memSet(address, 0, bytes); + return wrapBufferShort(address, size); + } + + /** Unsafe version of {@link #shorts(short)}. */ + public long nshort(short value) { + long a = nmalloc(2, 2); + memPutShort(a, value); + return a; + } + + /** Single value version of {@link #mallocShort}. */ + public ShortBuffer shorts(short x) { + return mallocShort(1).put(0, x); + } + + /** Two value version of {@link #mallocShort}. */ + public ShortBuffer shorts(short x, short y) { + return mallocShort(2).put(0, x).put(1, y); + } + + /** Three value version of {@link #mallocShort}. */ + public ShortBuffer shorts(short x, short y, short z) { + return mallocShort(3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #mallocShort}. */ + public ShortBuffer shorts(short x, short y, short z, short w) { + return mallocShort(4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #mallocShort}. */ + public ShortBuffer shorts(short... values) { + ShortBuffer buffer = mallocShort(values.length).put(values); + buffer.flip(); + return buffer; + } + + // ------------------------------------------------- + + /** Int version of {@link #malloc(int)}. */ + public IntBuffer mallocInt(int size) { + return wrapBufferInt(nmalloc(4, size << 2), size); + } + + /** Int version of {@link #calloc(int)}. */ + public IntBuffer callocInt(int size) { + int bytes = size * 4; + long address = nmalloc(4, bytes); + memSet(address, 0, bytes); + return wrapBufferInt(address, size); + } + + /** Unsafe version of {@link #ints(int)}. */ + public long nint(int value) { + long a = nmalloc(4, 4); + memPutInt(a, value); + return a; + } + + /** Single value version of {@link #mallocInt}. */ + public IntBuffer ints(int x) { + return mallocInt(1).put(0, x); + } + + /** Two value version of {@link #mallocInt}. */ + public IntBuffer ints(int x, int y) { + return mallocInt(2).put(0, x).put(1, y); + } + + /** Three value version of {@link #mallocInt}. */ + public IntBuffer ints(int x, int y, int z) { + return mallocInt(3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #mallocInt}. */ + public IntBuffer ints(int x, int y, int z, int w) { + return mallocInt(4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #mallocInt}. */ + public IntBuffer ints(int... values) { + IntBuffer buffer = mallocInt(values.length).put(values); + buffer.flip(); + return buffer; + } + + // ------------------------------------------------- + + /** Long version of {@link #malloc(int)}. */ + public LongBuffer mallocLong(int size) { + return wrapBufferLong(nmalloc(8, size << 3), size); + } + + /** Long version of {@link #calloc(int)}. */ + public LongBuffer callocLong(int size) { + int bytes = size * 8; + long address = nmalloc(8, bytes); + memSet(address, 0, bytes); + return wrapBufferLong(address, size); + } + + /** Unsafe version of {@link #longs(long)}. */ + public long nlong(long value) { + long a = nmalloc(8, 8); + memPutLong(a, value); + return a; + } + + /** Single value version of {@link #mallocLong}. */ + public LongBuffer longs(long x) { + return mallocLong(1).put(0, x); + } + + /** Two value version of {@link #mallocLong}. */ + public LongBuffer longs(long x, long y) { + return mallocLong(2).put(0, x).put(1, y); + } + + /** Three value version of {@link #mallocLong}. */ + public LongBuffer longs(long x, long y, long z) { + return mallocLong(3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #mallocLong}. */ + public LongBuffer longs(long x, long y, long z, long w) { + return mallocLong(4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #mallocLong}. */ + public LongBuffer longs(long... more) { + LongBuffer buffer = mallocLong(more.length).put(more); + buffer.flip(); + return buffer; + } + + // ------------------------------------------------- + + /** Float version of {@link #malloc(int)}. */ + public FloatBuffer mallocFloat(int size) { + return wrapBufferFloat(nmalloc(4, size << 2), size); + } + + /** Float version of {@link #calloc(int)}. */ + public FloatBuffer callocFloat(int size) { + int bytes = size * 4; + long address = nmalloc(4, bytes); + memSet(address, 0, bytes); + return wrapBufferFloat(address, size); + } + + /** Unsafe version of {@link #floats(float)}. */ + public long nfloat(float value) { + long a = nmalloc(4, 4); + memPutFloat(a, value); + return a; + } + + /** Single value version of {@link #mallocFloat}. */ + public FloatBuffer floats(float x) { + return mallocFloat(1).put(0, x); + } + + /** Two value version of {@link #mallocFloat}. */ + public FloatBuffer floats(float x, float y) { + return mallocFloat(2).put(0, x).put(1, y); + } + + /** Three value version of {@link #mallocFloat}. */ + public FloatBuffer floats(float x, float y, float z) { + return mallocFloat(3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #mallocFloat}. */ + public FloatBuffer floats(float x, float y, float z, float w) { + return mallocFloat(4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #mallocFloat}. */ + public FloatBuffer floats(float... values) { + FloatBuffer buffer = mallocFloat(values.length).put(values); + buffer.flip(); + return buffer; + } + + // ------------------------------------------------- + + /** Double version of {@link #malloc(int)}. */ + public DoubleBuffer mallocDouble(int size) { + return wrapBufferDouble(nmalloc(8, size << 3), size); + } + + /** Double version of {@link #calloc(int)}. */ + public DoubleBuffer callocDouble(int size) { + int bytes = size * 8; + long address = nmalloc(8, bytes); + memSet(address, 0, bytes); + return wrapBufferDouble(address, size); + } + + /** Unsafe version of {@link #doubles(double)}. */ + public long ndouble(double value) { + long a = nmalloc(8, 8); + memPutDouble(a, value); + return a; + } + + /** Single value version of {@link #mallocDouble}. */ + public DoubleBuffer doubles(double x) { + return mallocDouble(1).put(0, x); + } + + /** Two value version of {@link #mallocDouble}. */ + public DoubleBuffer doubles(double x, double y) { + return mallocDouble(2).put(0, x).put(1, y); + } + + /** Three value version of {@link #mallocDouble}. */ + public DoubleBuffer doubles(double x, double y, double z) { + return mallocDouble(3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #mallocDouble}. */ + public DoubleBuffer doubles(double x, double y, double z, double w) { + return mallocDouble(4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #mallocDouble}. */ + public DoubleBuffer doubles(double... values) { + DoubleBuffer buffer = mallocDouble(values.length).put(values); + buffer.flip(); + return buffer; + } + + // ------------------------------------------------- + + /** Pointer version of {@link #malloc(int)}. */ + public PointerBuffer mallocPointer(int size) { + return memPointerBuffer(nmalloc(POINTER_SIZE, size << POINTER_SHIFT), size); + } + + /** Pointer version of {@link #calloc(int)}. */ + public PointerBuffer callocPointer(int size) { + int bytes = size * POINTER_SIZE; + long address = nmalloc(POINTER_SIZE, bytes); + memSet(address, 0, bytes); + return memPointerBuffer(address, size); + } + + /** Unsafe version of {@link #pointers(long)}. */ + public long npointer(long value) { + long a = nmalloc(POINTER_SIZE, POINTER_SIZE); + memPutAddress(a, value); + return a; + } + + /** Single value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(long x) { + return mallocPointer(1).put(0, x); + } + + /** Two value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(long x, long y) { + return mallocPointer(2).put(0, x).put(1, y); + } + + /** Three value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(long x, long y, long z) { + return mallocPointer(3).put(0, x).put(1, y).put(2, z); + } + + /** Four value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(long x, long y, long z, long w) { + return mallocPointer(4).put(0, x).put(1, y).put(2, z).put(3, w); + } + + /** Vararg version of {@link #mallocPointer}. */ + public PointerBuffer pointers(long... values) { + PointerBuffer buffer = mallocPointer(values.length).put(values); + buffer.flip(); + return buffer; + } + + /** Unsafe version of {@link #pointers(Pointer)}. */ + public long npointer(Pointer value) { + long a = nmalloc(POINTER_SIZE, POINTER_SIZE); + memPutAddress(a, value.address()); + return a; + } + + /** Single value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Pointer x) { + return mallocPointer(1).put(0, x.address()); + } + + /** Two value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Pointer x, Pointer y) { + return mallocPointer(2).put(0, x.address()).put(1, y.address()); + } + + /** Three value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Pointer x, Pointer y, Pointer z) { + return mallocPointer(3).put(0, x.address()).put(1, y.address()).put(2, z.address()); + } + + /** Four value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Pointer x, Pointer y, Pointer z, Pointer w) { + return mallocPointer(4).put(0, x.address()).put(1, y.address()).put(2, z.address()).put(3, w.address()); + } + + /** Vararg version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Pointer... values) { + PointerBuffer buffer = mallocPointer(values.length); + for (int i = 0; i < values.length; i++) { + buffer.put(i, values[i].address()); + } + return buffer; + } + + /** Unsafe version of {@link #pointers(Buffer)}. */ + public long npointer(Buffer value) { + long a = nmalloc(POINTER_SIZE, POINTER_SIZE); + memPutAddress(a, memAddress(value)); + return a; + } + + /** Single value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Buffer x) { + return mallocPointer(1).put(0, memAddress(x)); + } + + /** Two value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Buffer x, Buffer y) { + return mallocPointer(2).put(0, memAddress(x)).put(1, memAddress(y)); + } + + /** Three value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Buffer x, Buffer y, Buffer z) { + return mallocPointer(3).put(0, memAddress(x)).put(1, memAddress(y)).put(2, memAddress(z)); + } + + /** Four value version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Buffer x, Buffer y, Buffer z, Buffer w) { + return mallocPointer(4).put(0, memAddress(x)).put(1, memAddress(y)).put(2, memAddress(z)).put(3, memAddress(w)); + } + + /** Vararg version of {@link #mallocPointer}. */ + public PointerBuffer pointers(Buffer... values) { + PointerBuffer buffer = mallocPointer(values.length); + for (int i = 0; i < values.length; i++) { + buffer.put(i, memAddress(values[i])); + } + return buffer; + } + + // ------------------------------------------------- + + /** + * Encodes the specified text on the stack using ASCII encoding and returns a {@code ByteBuffer} that points to the + * encoded text, including a null-terminator. + * + *

+ * The buffer will have {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + */ + public ByteBuffer ASCII(CharSequence text) { + return ASCII(text, true); + } + + /** + * Encodes the specified text on the stack using ASCII encoding and returns a {@code ByteBuffer} that points to the + * encoded text. + * + *

+ * The buffer will have {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + * @param nullTerminated if true, a null-terminator is included at the end of the encoded text + */ + public ByteBuffer ASCII(CharSequence text, boolean nullTerminated) { + int length = memLengthASCII(text, nullTerminated); + long target = nmalloc(POINTER_SIZE, length); + encodeASCIIUnsafe(text, nullTerminated, target); + return wrapBufferByte(target, length); + } + + /** + * Encodes the specified text on the stack using ASCII encoding and returns the encoded text length, in bytes. + * + *

+ * Use {@link #getPointerAddress} immediately after this method to get the encoded text address, which will have + * {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + * @param nullTerminated if true, a null-terminator is included at the end of the encoded text + */ + public int nASCII(CharSequence text, boolean nullTerminated) { + long target = nmalloc(POINTER_SIZE, memLengthASCII(text, nullTerminated)); + return encodeASCIIUnsafe(text, nullTerminated, target); + } + + /** Like {@link #ASCII(CharSequence) ASCII}, but returns {@code null} if {@code text} is {@code null}. */ + public @Nullable ByteBuffer ASCIISafe(@Nullable CharSequence text) { + return ASCIISafe(text, true); + } + + /** Like {@link #ASCII(CharSequence, boolean) ASCII}, but returns {@code null} if {@code text} is {@code null}. */ + public @Nullable ByteBuffer ASCIISafe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? null : ASCII(text, nullTerminated); + } + + /** Like {@link #nASCII(CharSequence, boolean) nASCII}, but returns 0 if {@code text} is {@code null}. */ + public int nASCIISafe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? 0 : nASCII(text, nullTerminated); + } + + /** + * Encodes the specified text on the stack using UTF8 encoding and returns a {@code ByteBuffer} that points to the + * encoded text, including a null-terminator. + * + *

+ * The buffer will have {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + */ + public ByteBuffer UTF8(CharSequence text) { + return UTF8(text, true); + } + + /** + * Encodes the specified text on the stack using UTF8 encoding and returns a {@code ByteBuffer} that points to the + * encoded text. + * + *

+ * The buffer will have {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + * @param nullTerminated if true, a null-terminator is included at the end of the encoded text + */ + public ByteBuffer UTF8(CharSequence text, boolean nullTerminated) { + int length = memLengthUTF8(text, nullTerminated); + long target = nmalloc(POINTER_SIZE, length); + encodeUTF8Unsafe(text, nullTerminated, target); + return wrapBufferByte(target, length); + } + + /** + * Encodes the specified text on the stack using UTF8 encoding and returns the encoded text length, in bytes. + * + *

+ * Use {@link #getPointerAddress} immediately after this method to get the encoded text address, which will have + * {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + * @param nullTerminated if true, a null-terminator is included at the end of the encoded text + */ + public int nUTF8(CharSequence text, boolean nullTerminated) { + long target = nmalloc(POINTER_SIZE, memLengthUTF8(text, nullTerminated)); + return encodeUTF8Unsafe(text, nullTerminated, target); + } + + /** Like {@link #UTF8(CharSequence) UTF8}, but returns {@code null} if {@code text} is {@code null}. */ + public @Nullable ByteBuffer UTF8Safe(@Nullable CharSequence text) { + return UTF8Safe(text, true); + } + + /** Like {@link #UTF8(CharSequence, boolean) UTF8}, but returns {@code null} if {@code text} is {@code null}. */ + public @Nullable ByteBuffer UTF8Safe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? null : UTF8(text, nullTerminated); + } + + /** Like {@link #nUTF8(CharSequence, boolean) nUTF8}, but returns 0 if {@code text} is {@code null}. */ + public int nUTF8Safe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? 0 : nUTF8(text, nullTerminated); + } + + /** + * Encodes the specified text on the stack using UTF16 encoding and returns a {@code ByteBuffer} that points to the + * encoded text, including a null-terminator. + * + *

+ * The buffer will have {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + */ + public ByteBuffer UTF16(CharSequence text) { + return UTF16(text, true); + } + + /** + * Encodes the specified text on the stack using UTF16 encoding and returns a {@code ByteBuffer} that points to the + * encoded text. + * + *

+ * The buffer will have {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + * @param nullTerminated if true, a null-terminator is included at the end of the encoded text + */ + public ByteBuffer UTF16(CharSequence text, boolean nullTerminated) { + int length = memLengthUTF16(text, nullTerminated); + long target = nmalloc(POINTER_SIZE, length); + encodeUTF16Unsafe(text, nullTerminated, target); + return wrapBufferByte(target, length); + } + + /** + * Encodes the specified text on the stack using UTF16 encoding and returns the encoded text length, in bytes. + * + *

+ * Use {@link #getPointerAddress} immediately after this method to get the encoded text address, which will have + * {@code alignment} equal to {@link Pointer#POINTER_SIZE POINTER_SIZE}. + *

+ * + * @param text the text to encode + * @param nullTerminated if true, a null-terminator is included at the end of the encoded text + */ + public int nUTF16(CharSequence text, boolean nullTerminated) { + long target = nmalloc(POINTER_SIZE, memLengthUTF16(text, nullTerminated)); + return encodeUTF16Unsafe(text, nullTerminated, target); + } + + /** Like {@link #UTF16(CharSequence) UTF16}, but returns {@code null} if {@code text} is {@code null}. */ + public @Nullable ByteBuffer UTF16Safe(@Nullable CharSequence text) { + return UTF16Safe(text, true); + } + + /** Like {@link #UTF16(CharSequence, boolean) UTF16}, but returns {@code null} if {@code text} is {@code null}. */ + public @Nullable ByteBuffer UTF16Safe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? null : UTF16(text, nullTerminated); + } + + /** Like {@link #nUTF16(CharSequence, boolean) nUTF16}, but returns 0 if {@code text} is {@code null}. */ + public int nUTF16Safe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? 0 : nUTF16(text, nullTerminated); + } + + // ----------------------------------------------------- + // ----------------------------------------------------- + // ----------------------------------------------------- + + /** Returns the stack of the current thread. */ + public static MemoryStack stackGet() { + return TLS.get(); + } + + /** + * Calls {@link #push} on the stack of the current thread. + * + * @return the stack of the current thread. + */ + public static MemoryStack stackPush() { + return stackGet().push(); + } + + /** + * Calls {@link #pop} on the stack of the current thread. + * + * @return the stack of the current thread. + */ + public static MemoryStack stackPop() { + return stackGet().pop(); + } + + /** Thread-local version of {@link #nmalloc(int)}. */ + public static long nstackMalloc(int size) { + return stackGet().nmalloc(size); + } + + /** Thread-local version of {@link #nmalloc(int, int)}. */ + public static long nstackMalloc(int alignment, int size) { + return stackGet().nmalloc(alignment, size); + } + + /** Thread-local version of {@link #ncalloc}. */ + public static long nstackCalloc(int alignment, int num, int size) { + return stackGet().ncalloc(alignment, num, size); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #malloc(int) malloc}. */ + public static ByteBuffer stackMalloc(int size) { + return stackGet().malloc(size); + } + + /** Thread-local version of {@link #calloc(int) calloc}. */ + public static ByteBuffer stackCalloc(int size) { + return stackGet().calloc(size); + } + + /** Thread-local version of {@link #bytes(byte)}. */ + public static ByteBuffer stackBytes(byte x) { + return stackGet().bytes(x); + } + + /** Thread-local version of {@link #bytes(byte, byte)}. */ + public static ByteBuffer stackBytes(byte x, byte y) { + return stackGet().bytes(x, y); + } + + /** Thread-local version of {@link #bytes(byte, byte, byte)}. */ + public static ByteBuffer stackBytes(byte x, byte y, byte z) { + return stackGet().bytes(x, y, z); + } + + /** Thread-local version of {@link #bytes(byte, byte, byte, byte)}. */ + public static ByteBuffer stackBytes(byte x, byte y, byte z, byte w) { + return stackGet().bytes(x, y, z, w); + } + + /** Thread-local version of {@link #bytes(byte...)}. */ + public static ByteBuffer stackBytes(byte... values) { + return stackGet().bytes(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #mallocShort}. */ + public static ShortBuffer stackMallocShort(int size) { + return stackGet().mallocShort(size); + } + + /** Thread-local version of {@link #callocShort}. */ + public static ShortBuffer stackCallocShort(int size) { + return stackGet().callocShort(size); + } + + /** Thread-local version of {@link #shorts(short)}. */ + public static ShortBuffer stackShorts(short x) { + return stackGet().shorts(x); + } + + /** Thread-local version of {@link #shorts(short, short)}. */ + public static ShortBuffer stackShorts(short x, short y) { + return stackGet().shorts(x, y); + } + + /** Thread-local version of {@link #shorts(short, short, short)}. */ + public static ShortBuffer stackShorts(short x, short y, short z) { + return stackGet().shorts(x, y, z); + } + + /** Thread-local version of {@link #shorts(short, short, short, short)}. */ + public static ShortBuffer stackShorts(short x, short y, short z, short w) { + return stackGet().shorts(x, y, z, w); + } + + /** Thread-local version of {@link #shorts(short...)}. */ + public static ShortBuffer stackShorts(short... values) { + return stackGet().shorts(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #mallocInt}. */ + public static IntBuffer stackMallocInt(int size) { + return stackGet().mallocInt(size); + } + + /** Thread-local version of {@link #callocInt}. */ + public static IntBuffer stackCallocInt(int size) { + return stackGet().callocInt(size); + } + + /** Thread-local version of {@link #ints(int)}. */ + public static IntBuffer stackInts(int x) { + return stackGet().ints(x); + } + + /** Thread-local version of {@link #ints(int, int)}. */ + public static IntBuffer stackInts(int x, int y) { + return stackGet().ints(x, y); + } + + /** Thread-local version of {@link #ints(int, int, int)}. */ + public static IntBuffer stackInts(int x, int y, int z) { + return stackGet().ints(x, y, z); + } + + /** Thread-local version of {@link #ints(int, int, int, int)}. */ + public static IntBuffer stackInts(int x, int y, int z, int w) { + return stackGet().ints(x, y, z, w); + } + + /** Thread-local version of {@link #ints(int...)}. */ + public static IntBuffer stackInts(int... values) { + return stackGet().ints(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #mallocLong}. */ + public static LongBuffer stackMallocLong(int size) { + return stackGet().mallocLong(size); + } + + /** Thread-local version of {@link #callocLong}. */ + public static LongBuffer stackCallocLong(int size) { + return stackGet().callocLong(size); + } + + /** Thread-local version of {@link #longs(long)}. */ + public static LongBuffer stackLongs(long x) { + return stackGet().longs(x); + } + + /** Thread-local version of {@link #longs(long, long)}. */ + public static LongBuffer stackLongs(long x, long y) { + return stackGet().longs(x, y); + } + + /** Thread-local version of {@link #longs(long, long, long)}. */ + public static LongBuffer stackLongs(long x, long y, long z) { + return stackGet().longs(x, y, z); + } + + /** Thread-local version of {@link #longs(long, long, long, long)}. */ + public static LongBuffer stackLongs(long x, long y, long z, long w) { + return stackGet().longs(x, y, z, w); + } + + /** Thread-local version of {@link #longs(long...)}. */ + public static LongBuffer stackLongs(long... values) { + return stackGet().longs(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #mallocFloat}. */ + public static FloatBuffer stackMallocFloat(int size) { + return stackGet().mallocFloat(size); + } + + /** Thread-local version of {@link #callocFloat}. */ + public static FloatBuffer stackCallocFloat(int size) { + return stackGet().callocFloat(size); + } + + /** Thread-local version of {@link #floats(float)}. */ + public static FloatBuffer stackFloats(float x) { + return stackGet().floats(x); + } + + /** Thread-local version of {@link #floats(float, float)}. */ + public static FloatBuffer stackFloats(float x, float y) { + return stackGet().floats(x, y); + } + + /** Thread-local version of {@link #floats(float, float, float)}. */ + public static FloatBuffer stackFloats(float x, float y, float z) { + return stackGet().floats(x, y, z); + } + + /** Thread-local version of {@link #floats(float, float, float, float)}. */ + public static FloatBuffer stackFloats(float x, float y, float z, float w) { + return stackGet().floats(x, y, z, w); + } + + /** Thread-local version of {@link #floats(float...)}. */ + public static FloatBuffer stackFloats(float... values) { + return stackGet().floats(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #mallocDouble}. */ + public static DoubleBuffer stackMallocDouble(int size) { + return stackGet().mallocDouble(size); + } + + /** Thread-local version of {@link #callocDouble}. */ + public static DoubleBuffer stackCallocDouble(int size) { + return stackGet().callocDouble(size); + } + + /** Thread-local version of {@link #doubles(double)}. */ + public static DoubleBuffer stackDoubles(double x) { + return stackGet().doubles(x); + } + + /** Thread-local version of {@link #doubles(double, double)}. */ + public static DoubleBuffer stackDoubles(double x, double y) { + return stackGet().doubles(x, y); + } + + /** Thread-local version of {@link #doubles(double, double, double)}. */ + public static DoubleBuffer stackDoubles(double x, double y, double z) { + return stackGet().doubles(x, y, z); + } + + /** Thread-local version of {@link #doubles(double, double, double, double)}. */ + public static DoubleBuffer stackDoubles(double x, double y, double z, double w) { + return stackGet().doubles(x, y, z, w); + } + + /** Thread-local version of {@link #doubles(double...)}. */ + public static DoubleBuffer stackDoubles(double... values) { + return stackGet().doubles(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #mallocPointer}. */ + public static PointerBuffer stackMallocPointer(int size) { + return stackGet().mallocPointer(size); + } + + /** Thread-local version of {@link #callocPointer}. */ + public static PointerBuffer stackCallocPointer(int size) { + return stackGet().callocPointer(size); + } + + /** Thread-local version of {@link #pointers(long)}. */ + public static PointerBuffer stackPointers(long x) { + return stackGet().pointers(x); + } + + /** Thread-local version of {@link #pointers(long, long)}. */ + public static PointerBuffer stackPointers(long x, long y) { + return stackGet().pointers(x, y); + } + + /** Thread-local version of {@link #pointers(long, long, long)}. */ + public static PointerBuffer stackPointers(long x, long y, long z) { + return stackGet().pointers(x, y, z); + } + + /** Thread-local version of {@link #pointers(long, long, long, long)}. */ + public static PointerBuffer stackPointers(long x, long y, long z, long w) { + return stackGet().pointers(x, y, z, w); + } + + /** Thread-local version of {@link #pointers(long...)}. */ + public static PointerBuffer stackPointers(long... values) { + return stackGet().pointers(values); + } + + /** Thread-local version of {@link #pointers(Pointer)}. */ + public static PointerBuffer stackPointers(Pointer x) { + return stackGet().pointers(x); + } + + /** Thread-local version of {@link #pointers(Pointer, Pointer)}. */ + public static PointerBuffer stackPointers(Pointer x, Pointer y) { + return stackGet().pointers(x, y); + } + + /** Thread-local version of {@link #pointers(Pointer, Pointer, Pointer)}. */ + public static PointerBuffer stackPointers(Pointer x, Pointer y, Pointer z) { + return stackGet().pointers(x, y, z); + } + + /** Thread-local version of {@link #pointers(Pointer, Pointer, Pointer, Pointer)}. */ + public static PointerBuffer stackPointers(Pointer x, Pointer y, Pointer z, Pointer w) { + return stackGet().pointers(x, y, z, w); + } + + /** Thread-local version of {@link #pointers(Pointer...)}. */ + public static PointerBuffer stackPointers(Pointer... values) { + return stackGet().pointers(values); + } + + // ------------------------------------------------- + + /** Thread-local version of {@link #ASCII(CharSequence)}. */ + public static ByteBuffer stackASCII(CharSequence text) { + return stackGet().ASCII(text); + } + + /** Thread-local version of {@link #ASCII(CharSequence, boolean)}. */ + public static ByteBuffer stackASCII(CharSequence text, boolean nullTerminated) { + return stackGet().ASCII(text, nullTerminated); + } + + /** Thread-local version of {@link #UTF8(CharSequence)}. */ + public static ByteBuffer stackUTF8(CharSequence text) { + return stackGet().UTF8(text); + } + + /** Thread-local version of {@link #UTF8(CharSequence, boolean)}. */ + public static ByteBuffer stackUTF8(CharSequence text, boolean nullTerminated) { + return stackGet().UTF8(text, nullTerminated); + } + + /** Thread-local version of {@link #UTF16(CharSequence)}. */ + public static ByteBuffer stackUTF16(CharSequence text) { + return stackGet().UTF16(text); + } + + /** Thread-local version of {@link #UTF16(CharSequence, boolean)}. */ + public static ByteBuffer stackUTF16(CharSequence text, boolean nullTerminated) { + return stackGet().UTF16(text, nullTerminated); + } + + /** Thread-local version of {@link #ASCII(CharSequence)}. */ + public static @Nullable ByteBuffer stackASCIISafe(@Nullable CharSequence text) { + return stackGet().ASCIISafe(text); + } + + /** Thread-local version of {@link #ASCII(CharSequence, boolean)}. */ + public static @Nullable ByteBuffer stackASCIISafe(@Nullable CharSequence text, boolean nullTerminated) { + return stackGet().ASCIISafe(text, nullTerminated); + } + + /** Thread-local version of {@link #UTF8(CharSequence)}. */ + public static @Nullable ByteBuffer stackUTF8Safe(@Nullable CharSequence text) { + return stackGet().UTF8Safe(text); + } + + /** Thread-local version of {@link #UTF8(CharSequence, boolean)}. */ + public static @Nullable ByteBuffer stackUTF8Safe(@Nullable CharSequence text, boolean nullTerminated) { + return stackGet().UTF8Safe(text, nullTerminated); + } + + /** Thread-local version of {@link #UTF16(CharSequence)}. */ + public static @Nullable ByteBuffer stackUTF16Safe(@Nullable CharSequence text) { + return stackGet().UTF16Safe(text); + } + + /** Thread-local version of {@link #UTF16(CharSequence, boolean)}. */ + public static @Nullable ByteBuffer stackUTF16Safe(@Nullable CharSequence text, boolean nullTerminated) { + return stackGet().UTF16Safe(text, nullTerminated); + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryUtilities.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryUtilities.java new file mode 100644 index 00000000..f5f620c4 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MemoryUtilities.java @@ -0,0 +1,3429 @@ +/* + * Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license + */ +package com.gtnewhorizon.gtnhlib.bytebuf; + +import static com.gtnewhorizon.gtnhlib.bytebuf.APIUtil.apiCheckAllocation; +import static com.gtnewhorizon.gtnhlib.bytebuf.APIUtil.apiGetBytes; +import static com.gtnewhorizon.gtnhlib.bytebuf.CheckIntrinsics.NewDirectByteBuffer; +import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.CHECKS; +import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.DEBUG; +import static com.gtnewhorizon.gtnhlib.bytebuf.Checks.check; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.LazyInit.ALLOCATOR; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.LazyInit.ALLOCATOR_IMPL; +import static com.gtnewhorizon.gtnhlib.bytebuf.Pointer.BITS32; +import static com.gtnewhorizon.gtnhlib.bytebuf.Pointer.BITS64; +import static com.gtnewhorizon.gtnhlib.bytebuf.Pointer.CLONG_SIZE; +import static com.gtnewhorizon.gtnhlib.bytebuf.Pointer.POINTER_SHIFT; +import static java.lang.Character.isHighSurrogate; +import static java.lang.Character.toCodePoint; +import static java.lang.Math.min; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.Buffer; +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.DoubleBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.nio.LongBuffer; +import java.nio.ShortBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.function.LongPredicate; + +import org.jetbrains.annotations.Nullable; +import org.lwjgl.PointerBuffer; + +/** + * This class provides functionality for managing native memory. + * + *

+ * All methods in this class will make use of {@link sun.misc.Unsafe} if it's available, for performance. If Unsafe is + * not available, the fallback implementations make use of reflection and, in the worst-case, JNI. + *

+ * + *

+ * Method names in this class are prefixed with {@code mem} to avoid ambiguities when used with static imports. + *

+ * + *

Text encoding/decoding

+ * + * Three codecs are available, each with a different postfix: + *
    + *
  • UTF16 - Direct mapping of 2 bytes to Java char and vice versa
  • + *
  • UTF8 - custom UTF-8 codec without intermediate allocations
  • + *
  • ASCII - Not the original 7bit ASCII, but any character set with a single byte encoding (ISO 8859-1, Windows-1252, + * etc.)
  • + *
+ * + *

+ * The codec implementations do no codepoint validation, for improved performance. Therefore, if malformed input or + * unmappable characters are expected, the JDK {@link CharsetEncoder}/{@link CharsetDecoder} classes should be used + * instead. Methods in bindings that accept/return {@code CharSequence}/{@code String} also support {@code ByteBuffer}, + * so custom codecs can be used if necessary. + *

+ */ +public final class MemoryUtilities { + + /** + * Returns true if the specified integer {@code value} is a power-of-two number. + * + * @param value the value to test + * + * @return true if the value if a power-of-two number. + */ + public static boolean mathIsPoT(int value) { + return Integer.bitCount(value) == 1; + } + + /** + * Rounds the specified integer {@code value} up to the next power-of-two number. The returned value will be equal + * to {@code value} if it already is a power-of-two number. + * + * @param value the value to round-up. Must be a number between {@code 1} and 1 << 30. + * + * @return the power-of-two rounded value + */ + public static int mathRoundPoT(int value) { + return 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); + } + + public static boolean mathHasZeroByte(int value) { + return ((value - 0x01010101) & ~value & 0x80808080) != 0; + } + + public static boolean mathHasZeroByte(long value) { + return ((value - 0x0101010101010101L) & ~value & 0x8080808080808080L) != 0L; + } + + public static boolean mathHasZeroShort(int value) { + return ((value - 0x00010001) & ~value & 0x80008000) != 0; + } + + public static boolean mathHasZeroShort(long value) { + return ((value - 0x0001000100010001L) & ~value & 0x8000800080008000L) != 0L; + } + + /** Alias for the null pointer address. */ + public static final long NULL = 0L; + + /** The memory page size, in bytes. This value is always a power-of-two. */ + public static final int PAGE_SIZE; + + /** The cache-line size, in bytes. This value is always a power-of-two. */ + public static final int CACHE_LINE_SIZE; + + static final int ARRAY_TLC_SIZE = 8192; + + static final ThreadLocal ARRAY_TLC_BYTE = ThreadLocal.withInitial(() -> new byte[ARRAY_TLC_SIZE]); + static final ThreadLocal ARRAY_TLC_CHAR = ThreadLocal.withInitial(() -> new char[ARRAY_TLC_SIZE]); + + static final sun.misc.Unsafe UNSAFE; + + static final ByteOrder NATIVE_ORDER = ByteOrder.nativeOrder(); + + private static final Charset UTF16 = NATIVE_ORDER == ByteOrder.LITTLE_ENDIAN ? StandardCharsets.UTF_16LE + : StandardCharsets.UTF_16BE; + + static final Class BUFFER_BYTE; + static final Class BUFFER_SHORT; + static final Class BUFFER_CHAR; + static final Class BUFFER_INT; + static final Class BUFFER_LONG; + static final Class BUFFER_FLOAT; + static final Class BUFFER_DOUBLE; + + private static final long MARK; + private static final long POSITION; + private static final long LIMIT; + private static final long CAPACITY; + + private static final long ADDRESS; + + private static final long PARENT_BYTE; + private static final long PARENT_SHORT; + private static final long PARENT_CHAR; + private static final long PARENT_INT; + private static final long PARENT_LONG; + private static final long PARENT_FLOAT; + private static final long PARENT_DOUBLE; + + static { + ByteBuffer bb = ByteBuffer.allocateDirect(0).order(NATIVE_ORDER); + + BUFFER_BYTE = bb.getClass(); + BUFFER_SHORT = bb.asShortBuffer().getClass(); + BUFFER_CHAR = bb.asCharBuffer().getClass(); + BUFFER_INT = bb.asIntBuffer().getClass(); + BUFFER_LONG = bb.asLongBuffer().getClass(); + BUFFER_FLOAT = bb.asFloatBuffer().getClass(); + BUFFER_DOUBLE = bb.asDoubleBuffer().getClass(); + + UNSAFE = getUnsafeInstance(); + + try { + MARK = getMarkOffset(); + POSITION = getPositionOffset(); + LIMIT = getLimitOffset(); + CAPACITY = getCapacityOffset(); + + ADDRESS = getAddressOffset(); + + PARENT_BYTE = getFieldOffsetObject(bb.duplicate().order(bb.order()), bb); + PARENT_SHORT = getFieldOffsetObject(bb.asShortBuffer(), bb); + PARENT_CHAR = getFieldOffsetObject(bb.asCharBuffer(), bb); + PARENT_INT = getFieldOffsetObject(bb.asIntBuffer(), bb); + PARENT_LONG = getFieldOffsetObject(bb.asLongBuffer(), bb); + PARENT_FLOAT = getFieldOffsetObject(bb.asFloatBuffer(), bb); + PARENT_DOUBLE = getFieldOffsetObject(bb.asDoubleBuffer(), bb); + } catch (Throwable t) { + throw new UnsupportedOperationException(t); + } + + PAGE_SIZE = UNSAFE.pageSize(); + CACHE_LINE_SIZE = 64; + } + + static final class LazyInit { + + private LazyInit() {} + + static final MemoryAllocator ALLOCATOR_IMPL; + static final MemoryAllocator ALLOCATOR; + + static { + boolean debug = Boolean.getBoolean("org.lwjgl.util.DebugAllocator"); + + ALLOCATOR_IMPL = MemoryManage.getInstance(); + ALLOCATOR = ALLOCATOR_IMPL; + } + } + + private MemoryUtilities() {} + + /* + * ------------------------------------- ------------------------------------- EXPLICIT MEMORY MANAGEMENT API + * ------------------------------------- ------------------------------------- + */ + + /** + * The interface implemented by the memory allocator used by the explicit memory management API ({@link #memAlloc}, + * {@link #memFree}, etc). + */ + public interface MemoryAllocator { + + /** Called by {@link MemoryUtilities#memAlloc}. */ + long malloc(long size); + + /** Called by {@link MemoryUtilities#memCalloc}. */ + long calloc(long num, long size); + + /** Called by {@link MemoryUtilities#memRealloc}. */ + long realloc(long ptr, long size); + + /** Called by {@link MemoryUtilities#memFree}. */ + void free(long ptr); + } + + /** + * Returns the {@link MemoryAllocator} instance used internally by the explicit memory management API + * ({@link #memAlloc}, {@link #memFree}, etc). + * + *

+ * Allocations made through the returned instance will not be tracked for memory leaks, even if is enabled. This can + * be useful for {@code static final} allocations that live throughout the application's lifetime and will never be + * freed until the process is terminated. Normally such allocations would be reported as memory leaks by the debug + * allocator. + *

+ * + *

+ * The expectation is that this method will rarely be used, so it does not have the {@code mem} prefix to avoid + * pollution of auto-complete lists. + *

+ * + * @return the {@link MemoryAllocator} instance + */ + public static MemoryAllocator getAllocator() { + return getAllocator(false); + } + + /** + * Returns the {@link MemoryAllocator} instance used internally by the explicit memory management API + * ({@link #memAlloc}, {@link #memFree}, etc). + * + * @param tracked whether allocations will be tracked for memory leaks, if is enabled. + * + * @return the {@link MemoryAllocator} instance + */ + public static MemoryAllocator getAllocator(boolean tracked) { + return tracked ? ALLOCATOR : ALLOCATOR_IMPL; + } + + // --- [ memAlloc ] --- + + /** + * Unsafe version of {@link #memAlloc}. May return {@link #NULL} if {@code size} is zero or the allocation failed. + */ + public static long nmemAlloc(long size) { + return ALLOCATOR.malloc(size); + } + + /** + * Unsafe version of {@link #memAlloc} that checks the returned pointer. + * + * @return a pointer to the memory block allocated by the function on success. This pointer will never be + * {@link #NULL}, even if {@code size} is zero. + * + * @throws OutOfMemoryError if the function failed to allocate the requested block of memory + */ + public static long nmemAllocChecked(long size) { + long address = nmemAlloc(size != 0 ? size : 1L); + if (CHECKS && address == NULL) { + throw new OutOfMemoryError(); + } + return address; + } + + private static long getAllocationSize(int elements, int elementShift) { + return apiCheckAllocation( + elements, + Integer.toUnsignedLong(elements) << elementShift, + BITS64 ? Long.MAX_VALUE : 0xFFFF_FFFFL); + } + + /** + * The standard C malloc function. + * + *

+ * Allocates a block of {@code size} bytes of memory, returning a pointer to the beginning of the block. The content + * of the newly allocated block of memory is not initialized, remaining with indeterminate values. + *

+ * + *

+ * Memory allocated with this method must be freed with {@link #memFree}. + *

+ * + * @param size the size of the memory block to allocate, in bytes. If {@code size} is zero, the returned pointer + * shall not be dereferenced. + * + * @return on success, a pointer to the memory block allocated by the function + * + * @throws OutOfMemoryError if the function failed to allocate the requested block of memory + */ + public static ByteBuffer memAlloc(int size) { + return wrapBufferByte(nmemAllocChecked(size), size); + } + + /** + * ShortBuffer version of {@link #memAlloc}. + * + * @param size the number of short values to allocate. + */ + public static ShortBuffer memAllocShort(int size) { + return wrapBufferShort(nmemAllocChecked(getAllocationSize(size, 1)), size); + } + + /** + * IntBuffer version of {@link #memAlloc}. + * + * @param size the number of int values to allocate. + */ + public static IntBuffer memAllocInt(int size) { + return wrapBufferInt(nmemAllocChecked(getAllocationSize(size, 2)), size); + } + + /** + * FloatBuffer version of {@link #memAlloc}. + * + * @param size the number of float values to allocate. + */ + public static FloatBuffer memAllocFloat(int size) { + return wrapBufferFloat(nmemAllocChecked(getAllocationSize(size, 2)), size); + } + + /** + * LongBuffer version of {@link #memAlloc}. + * + * @param size the number of long values to allocate. + */ + public static LongBuffer memAllocLong(int size) { + return wrapBufferLong(nmemAllocChecked(getAllocationSize(size, 3)), size); + } + + /** + * DoubleBuffer version of {@link #memAlloc}. + * + * @param size the number of double values to allocate. + */ + public static DoubleBuffer memAllocDouble(int size) { + return wrapBufferDouble(nmemAllocChecked(getAllocationSize(size, 3)), size); + } + + /** + * PointerBuffer version of {@link #memAlloc}. + * + * @param size the number of pointer values to allocate. + */ + public static PointerBuffer memAllocPointer(int size) { + return new PointerBuffer(memAlloc(Math.toIntExact(getAllocationSize(size, POINTER_SHIFT)))); + } + + /** Unsafe version of {@link #memFree}. */ + public static void nmemFree(long ptr) { + ALLOCATOR.free(ptr); + } + + /** + * The standard C free function. + * + *

+ * A block of memory previously allocated by a call to {@link #memAlloc}, {@link #memCalloc} or {@link #memRealloc} + * is deallocated, making it available again for further allocations. + *

+ * + * @param ptr pointer to a memory block previously allocated with {@link #memAlloc}, {@link #memCalloc} or + * {@link #memRealloc}. If {@code ptr} does not point to a block of memory allocated with the above + * functions, it causes undefined behavior. If {@code ptr} is a {@link #NULL} pointer, the function does + * nothing. + */ + public static void memFree(@Nullable Buffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code ByteBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable ByteBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code ShortBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable ShortBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code CharBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable CharBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code IntBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable IntBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code LongBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable LongBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code FloatBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable FloatBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + /** {@code DoubleBuffer} version of {@link #memFree(Buffer)}. */ + public static void memFree(@Nullable DoubleBuffer ptr) { + if (ptr != null) { + nmemFree(UNSAFE.getLong(ptr, ADDRESS)); + } + } + + // --- [ memCalloc ] --- + + /** + * Unsafe version of {@link #memCalloc}. May return {@link #NULL} if {@code num} or {@code size} are zero or the + * allocation failed. + */ + public static long nmemCalloc(long num, long size) { + return ALLOCATOR.calloc(num, size); + } + + /** + * Unsafe version of {@link #memCalloc} that checks the returned pointer. + * + * @return a pointer to the memory block allocated by the function on success. This pointer will never be + * {@link #NULL}, even if {@code num} or {@code size} are zero. + * + * @throws OutOfMemoryError if the function failed to allocate the requested block of memory + */ + public static long nmemCallocChecked(long num, long size) { + if (num == 0L || size == 0L) { + num = 1L; + size = 1L; + } + + long address = nmemCalloc(num, size); + if (CHECKS && address == NULL) { + throw new OutOfMemoryError(); + } + return address; + } + + /** + * The standard C calloc function. + * + *

+ * Allocates a block of memory for an array of {@code num} elements, each of them {@code size} bytes long, and + * initializes all its bits to zero. The effective result is the allocation of a zero-initialized memory block of + * {@code (num*size)} bytes. + *

+ * + *

+ * Memory allocated with this method must be freed with {@link #memFree}. + *

+ * + * @param num the number of elements to allocate. + * @param size the size of each element. If {@code size} is zero, the return value depends on the particular library + * implementation (it may or may not be a null pointer), but the returned pointer shall not be + * dereferenced. + * + * @return on success, a pointer to the memory block allocated by the function + * + * @throws OutOfMemoryError if the function failed to allocate the requested block of memory + */ + public static ByteBuffer memCalloc(int num, int size) { + return wrapBufferByte(nmemCallocChecked(num, size), num * size); + } + + /** + * Alternative version of {@link #memCalloc}. + * + * @param num the number of bytes to allocate. + */ + public static ByteBuffer memCalloc(int num) { + return wrapBufferByte(nmemCallocChecked(num, 1), num); + } + + /** + * ShortBuffer version of {@link #memCalloc}. + * + * @param num the number of short values to allocate. + */ + public static ShortBuffer memCallocShort(int num) { + return wrapBufferShort(nmemCallocChecked(num, 2), num); + } + + /** + * IntBuffer version of {@link #memCalloc}. + * + * @param num the number of int values to allocate. + */ + public static IntBuffer memCallocInt(int num) { + return wrapBufferInt(nmemCallocChecked(num, 4), num); + } + + /** + * FloatBuffer version of {@link #memCalloc}. + * + * @param num the number of float values to allocate. + */ + public static FloatBuffer memCallocFloat(int num) { + return wrapBufferFloat(nmemCallocChecked(num, 4), num); + } + + /** + * LongBuffer version of {@link #memCalloc}. + * + * @param num the number of long values to allocate. + */ + public static LongBuffer memCallocLong(int num) { + return wrapBufferLong(nmemCallocChecked(num, 8), num); + } + + /** + * DoubleBuffer version of {@link #memCalloc}. + * + * @param num the number of double values to allocate. + */ + public static DoubleBuffer memCallocDouble(int num) { + return wrapBufferDouble(nmemCallocChecked(num, 8), num); + } + + /** + * PointerBuffer version of {@link #memCalloc}. + * + * @param num the number of pointer values to allocate. + */ + public static PointerBuffer memCallocPointer(int num) { + return new PointerBuffer(memCalloc(Math.toIntExact(getAllocationSize(num, POINTER_SHIFT)))); + } + + // --- [ memRealloc] --- + + /** + * Unsafe version of {@link #memRealloc}. May return {@link #NULL} if {@code size} is zero or the allocation failed. + */ + public static long nmemRealloc(long ptr, long size) { + return ALLOCATOR.realloc(ptr, size); + } + + /** + * Unsafe version of {@link #memRealloc} that checks the returned pointer. + * + * @return a pointer to the memory block reallocated by the function on success. This pointer will never be + * {@link #NULL}, even if {@code size} is zero. + * + * @throws OutOfMemoryError if the function failed to allocate the requested block of memory + */ + public static long nmemReallocChecked(long ptr, long size) { + long address = nmemRealloc(ptr, size != 0 ? size : 1L); + if (CHECKS && address == NULL) { + throw new OutOfMemoryError(); + } + return address; + } + + private static T realloc(@Nullable T old_p, T new_p, int size) { + if (old_p != null) { + new_p.position(min(old_p.position(), size)); + } + return new_p; + } + + /** + * The standard C realloc function. + * + *

+ * Changes the size of the memory block pointed to by {@code ptr}. The function may move the memory block to a new + * location (whose address is returned by the function). The content of the memory block is preserved up to the + * lesser of the new and old sizes, even if the block is moved to a new location. If the new size is larger, the + * value of the newly allocated portion is indeterminate. + *

+ * + *

+ * The memory address used is always the address at the start of {@code ptr}, so the current position of {@code ptr} + * does not need to be set to 0 for this function to work. The current position is preserved, even if the memory + * block is moved to a new location, unless {@code size} is less than the current position in which case position + * will be equal to capacity. The limit is set to the capacity, and the mark is discarded. + *

+ * + * @param ptr a pointer to a memory block previously allocated with {@link #memAlloc}, {@link #memCalloc} or + * {@link #memRealloc}. Alternatively, this can be a {@link #NULL} pointer, in which case a new block is + * allocated (as if {@link #memAlloc} was called). + * @param size the new size for the memory block, in bytes. + * + * @return a pointer to the reallocated memory block, which may be either the same as {@code ptr} or a new location + * + * @throws OutOfMemoryError if the function failed to allocate the requested block of memory. The memory block + * pointed to by argument {@code ptr} is not deallocated (it is still valid, and with its + * contents unchanged). + */ + public static ByteBuffer memRealloc(@Nullable ByteBuffer ptr, int size) { + return realloc( + ptr, + memByteBuffer(nmemReallocChecked(ptr == null ? NULL : UNSAFE.getLong(ptr, ADDRESS), size), size), + size); + } + + /** + * ShortBuffer version of {@link #memRealloc}. + * + * @param size the number of short values to allocate. + */ + public static ShortBuffer memRealloc(@Nullable ShortBuffer ptr, int size) { + return realloc( + ptr, + memShortBuffer( + nmemReallocChecked( + ptr == null ? NULL : UNSAFE.getLong(ptr, ADDRESS), + getAllocationSize(size, 1)), + size), + size); + } + + /** + * IntBuffer version of {@link #memRealloc}. + * + * @param size the number of int values to allocate. + */ + public static IntBuffer memRealloc(@Nullable IntBuffer ptr, int size) { + return realloc( + ptr, + memIntBuffer( + nmemReallocChecked( + ptr == null ? NULL : UNSAFE.getLong(ptr, ADDRESS), + getAllocationSize(size, 2)), + size), + size); + } + + /** + * LongBuffer version of {@link #memRealloc}. + * + * @param size the number of long values to allocate. + */ + public static LongBuffer memRealloc(@Nullable LongBuffer ptr, int size) { + return realloc( + ptr, + memLongBuffer( + nmemReallocChecked( + ptr == null ? NULL : UNSAFE.getLong(ptr, ADDRESS), + getAllocationSize(size, 3)), + size), + size); + } + + /** + * FloatBuffer version of {@link #memRealloc}. + * + * @param size the number of float values to allocate. + */ + public static FloatBuffer memRealloc(@Nullable FloatBuffer ptr, int size) { + return realloc( + ptr, + memFloatBuffer( + nmemReallocChecked( + ptr == null ? NULL : UNSAFE.getLong(ptr, ADDRESS), + getAllocationSize(size, 2)), + size), + size); + } + + /** + * DoubleBuffer version of {@link #memRealloc}. + * + * @param size the number of double values to allocate. + */ + public static DoubleBuffer memRealloc(@Nullable DoubleBuffer ptr, int size) { + return realloc( + ptr, + memDoubleBuffer( + nmemReallocChecked( + ptr == null ? NULL : UNSAFE.getLong(ptr, ADDRESS), + getAllocationSize(size, 3)), + size), + size); + } + + /** + * PointerBuffer version of {@link #memRealloc}. + * + * @param size the number of pointer values to allocate. + */ + public static PointerBuffer memRealloc(@Nullable PointerBuffer ptr, int size) { + // return new PointerBuffer(memCalloc(Math.toIntExact(getAllocationSize(num, POINTER_SHIFT)))); + + PointerBuffer buffer = memPointerBuffer( + nmemReallocChecked(ptr == null ? NULL : memAddress(ptr), getAllocationSize(size, POINTER_SHIFT)), + size); + if (ptr != null) { + buffer.position(min(ptr.position(), size)); + } + return buffer; + } + + /* + * ------------------------------------- ------------------------------------- BUFFER MANAGEMENT API + * ------------------------------------- ------------------------------------- + */ + + // --- [ memAddress0 ] --- + + /** + * Returns the memory address of the specified buffer. [INTERNAL USE ONLY] + * + * @param buffer the buffer + * + * @return the memory address + */ + public static long memAddress0(Buffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code ByteBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(ByteBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code ShortBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(ShortBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code CharBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(CharBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code IntBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(IntBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code LongBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(LongBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code FloatBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(FloatBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + /** {@code DoubleBuffer} version of {@link #memAddress0(Buffer)}. */ + public static long memAddress0(DoubleBuffer buffer) { + return UNSAFE.getLong(buffer, ADDRESS); + } + + // --- [ Buffer address ] --- + + /** + * Returns the memory address at the current position of the specified buffer. This is effectively a pointer value + * that can be used in native function calls. + * + * @param buffer the buffer + * + * @return the memory address + */ + public static long memAddress(ByteBuffer buffer) { + return buffer.position() + memAddress0(buffer); + } + + /** + * Returns the memory address at the specified position of the specified buffer. + * + * @param buffer the buffer + * @param position the buffer position + * + * @return the memory address + * + * @see #memAddress(ByteBuffer) + */ + public static long memAddress(ByteBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return memAddress0(buffer) + Integer.toUnsignedLong(position); + } + + private static long address(int position, int elementShift, long address) { + return address + ((position & 0xFFFF_FFFFL) << elementShift); + } + + /** ShortBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(ShortBuffer buffer) { + return address(buffer.position(), 1, memAddress0(buffer)); + } + + /** ShortBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(ShortBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, 1, memAddress0(buffer)); + } + + /** CharBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(CharBuffer buffer) { + return address(buffer.position(), 1, memAddress0(buffer)); + } + + /** CharBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(CharBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, 1, memAddress0(buffer)); + } + + /** IntBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(IntBuffer buffer) { + return address(buffer.position(), 2, memAddress0(buffer)); + } + + /** IntBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(IntBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, 2, memAddress0(buffer)); + } + + /** FloatBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(FloatBuffer buffer) { + return address(buffer.position(), 2, memAddress0(buffer)); + } + + /** FloatBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(FloatBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, 2, memAddress0(buffer)); + } + + /** LongBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(LongBuffer buffer) { + return address(buffer.position(), 3, memAddress0(buffer)); + } + + /** LongBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(LongBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, 3, memAddress0(buffer)); + } + + /** DoubleBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(DoubleBuffer buffer) { + return address(buffer.position(), 3, memAddress0(buffer)); + } + + /** DoubleBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(DoubleBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, 3, memAddress0(buffer)); + } + + /** PointerBuffer version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(PointerBuffer buffer) { + return address(buffer.position(), POINTER_SHIFT, memAddress0(buffer.getBuffer())); + } + + /** PointerBuffer version of {@link #memAddress(ByteBuffer, int)}. */ + public static long memAddress(PointerBuffer buffer, int position) { + Objects.requireNonNull(buffer); + return address(position, POINTER_SHIFT, memAddress0(buffer.getBuffer())); + } + + /** Polymorphic version of {@link #memAddress(ByteBuffer)}. */ + public static long memAddress(Buffer buffer) { + int elementShift; + if (buffer instanceof ByteBuffer) { + elementShift = 0; + } else if (buffer instanceof ShortBuffer || buffer instanceof CharBuffer) { + elementShift = 1; + } else if (buffer instanceof IntBuffer || buffer instanceof FloatBuffer) { + elementShift = 2; + } else { + elementShift = 3; + } + return address(buffer.position(), elementShift, UNSAFE.getLong(buffer, ADDRESS)); + } + + // --- [ Buffer address - Safe ] --- + + /** Null-safe version of {@link #memAddress(ByteBuffer)}. Returns {@link #NULL} if the specified buffer is null. */ + public static long memAddressSafe(@Nullable ByteBuffer buffer) { + return buffer == null ? NULL : memAddress0(buffer) + buffer.position(); + } + + /** ShortBuffer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable ShortBuffer buffer) { + return buffer == null ? NULL : address(buffer.position(), 1, memAddress0(buffer)); + } + + /** CharBuffer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable CharBuffer buffer) { + return buffer == null ? NULL : address(buffer.position(), 1, memAddress0(buffer)); + } + + /** IntBuffer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable IntBuffer buffer) { + return buffer == null ? NULL : address(buffer.position(), 2, memAddress0(buffer)); + } + + /** FloatBuffer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable FloatBuffer buffer) { + return buffer == null ? NULL : address(buffer.position(), 2, memAddress0(buffer)); + } + + /** LongBuffer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable LongBuffer buffer) { + return buffer == null ? NULL : address(buffer.position(), 3, memAddress0(buffer)); + } + + /** DoubleBuffer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable DoubleBuffer buffer) { + return buffer == null ? NULL : address(buffer.position(), 3, memAddress0(buffer)); + } + + /** Pointer version of {@link #memAddressSafe(ByteBuffer)}. */ + public static long memAddressSafe(@Nullable Pointer pointer) { + return pointer == null ? NULL : pointer.address(); + } + + // --- [ Buffer allocation ] --- + + /** + * Creates a new direct ByteBuffer that starts at the specified memory address and has the specified capacity. The + * returned ByteBuffer instance will be set to the native {@link ByteOrder}. + * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new ByteBuffer + */ + public static ByteBuffer memByteBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferByte(address, capacity); + } + + /** + * Like {@link #memByteBuffer(long, int) memByteBuffer}, but returns {@code null} if {@code address} is + * {@link #NULL}. + */ + public static @Nullable ByteBuffer memByteBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferByte(address, capacity); + } + + /** + * Creates a {@link ByteBuffer} instance as a view of the specified {@link ShortBuffer} between its current position + * and limit. + * + *

+ * This operation is the inverse of {@link ByteBuffer#asShortBuffer()}. The returned {@code ByteBuffer} instance + * will be set to the native {@link ByteOrder}. + *

+ * + * @param buffer the source buffer + * + * @return the {@code ByteBuffer} view + */ + public static ByteBuffer memByteBuffer(ShortBuffer buffer) { + if (CHECKS && (Integer.MAX_VALUE >> 1) < buffer.remaining()) { + throw new IllegalStateException("The source buffer range is too wide"); + } + return wrapBufferByte(memAddress(buffer), buffer.remaining() << 1); + } + + /** + * Creates a {@link ByteBuffer} instance as a view of the specified {@link CharBuffer} between its current position + * and limit. + * + *

+ * This operation is the inverse of {@link ByteBuffer#asCharBuffer()}. The returned {@code ByteBuffer} instance will + * be set to the native {@link ByteOrder}. + *

+ * + * @param buffer the source buffer + * + * @return the {@code ByteBuffer} view + */ + public static ByteBuffer memByteBuffer(CharBuffer buffer) { + if (CHECKS && (Integer.MAX_VALUE >> 1) < buffer.remaining()) { + throw new IllegalStateException("The source buffer range is too wide"); + } + return wrapBufferByte(memAddress(buffer), buffer.remaining() << 1); + } + + /** + * Creates a {@link ByteBuffer} instance as a view of the specified {@link IntBuffer} between its current position + * and limit. + * + *

+ * This operation is the inverse of {@link ByteBuffer#asIntBuffer()}. The returned {@code ByteBuffer} instance will + * be set to the native {@link ByteOrder}. + *

+ * + * @param buffer the source buffer + * + * @return the {@code ByteBuffer} view + */ + public static ByteBuffer memByteBuffer(IntBuffer buffer) { + if (CHECKS && (Integer.MAX_VALUE >> 2) < buffer.remaining()) { + throw new IllegalStateException("The source buffer range is too wide"); + } + return wrapBufferByte(memAddress(buffer), buffer.remaining() << 2); + } + + /** + * Creates a {@link ByteBuffer} instance as a view of the specified {@link LongBuffer} between its current position + * and limit. + * + *

+ * This operation is the inverse of {@link ByteBuffer#asLongBuffer()}. The returned {@code ByteBuffer} instance will + * be set to the native {@link ByteOrder}. + *

+ * + * @param buffer the source buffer + * + * @return the {@code ByteBuffer} view + */ + public static ByteBuffer memByteBuffer(LongBuffer buffer) { + if (CHECKS && (Integer.MAX_VALUE >> 3) < buffer.remaining()) { + throw new IllegalStateException("The source buffer range is too wide"); + } + return wrapBufferByte(memAddress(buffer), buffer.remaining() << 3); + } + + /** + * Creates a {@link ByteBuffer} instance as a view of the specified {@link FloatBuffer} between its current position + * and limit. + * + *

+ * This operation is the inverse of {@link ByteBuffer#asFloatBuffer()}. The returned {@code ByteBuffer} instance + * will be set to the native {@link ByteOrder}. + *

+ * + * @param buffer the source buffer + * + * @return the {@code ByteBuffer} view + */ + public static ByteBuffer memByteBuffer(FloatBuffer buffer) { + if (CHECKS && (Integer.MAX_VALUE >> 2) < buffer.remaining()) { + throw new IllegalStateException("The source buffer range is too wide"); + } + return wrapBufferByte(memAddress(buffer), buffer.remaining() << 2); + } + + /** + * Creates a {@link ByteBuffer} instance as a view of the specified {@link DoubleBuffer} between its current + * position and limit. + * + *

+ * This operation is the inverse of {@link ByteBuffer#asDoubleBuffer()}. The returned {@code ByteBuffer} instance + * will be set to the native {@link ByteOrder}. + *

+ * + * @param buffer the source buffer + * + * @return the {@code ByteBuffer} view + */ + public static ByteBuffer memByteBuffer(DoubleBuffer buffer) { + if (CHECKS && (Integer.MAX_VALUE >> 3) < buffer.remaining()) { + throw new IllegalStateException("The source buffer range is too wide"); + } + return wrapBufferByte(memAddress(buffer), buffer.remaining() << 3); + } + + /** + * Creates a new direct ShortBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to 2 bytes. If not, use + * {@code memByteBuffer(address, capacity * 2).asShortBuffer()}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new ShortBuffer + */ + public static ShortBuffer memShortBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferShort(address, capacity); + } + + /** Like {@link #memShortBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable ShortBuffer memShortBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferShort(address, capacity); + } + + /** + * Creates a new direct CharBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to 2 bytes. If not, use + * {@code memByteBuffer(address, capacity * 2).asCharBuffer()}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new CharBuffer + */ + public static CharBuffer memCharBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferChar(address, capacity); + } + + /** Like {@link #memCharBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable CharBuffer memCharBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferChar(address, capacity); + } + + /** + * Creates a new direct IntBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to 4 bytes. If not, use + * {@code memByteBuffer(address, capacity * 4).asIntBuffer()}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new IntBuffer + */ + public static IntBuffer memIntBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferInt(address, capacity); + } + + /** Like {@link #memIntBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable IntBuffer memIntBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferInt(address, capacity); + } + + /** + * Creates a new direct LongBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to 8 bytes. If not, use + * {@code memByteBuffer(address, capacity * 8).asLongBuffer()}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new LongBuffer + */ + public static LongBuffer memLongBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferLong(address, capacity); + } + + /** Like {@link #memLongBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable LongBuffer memLongBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferLong(address, capacity); + } + + /** + * Creates a new direct FloatBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to 4 bytes. If not, use + * {@code memByteBuffer(address, capacity * 4).asFloatBuffer()}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new FloatBuffer + */ + public static FloatBuffer memFloatBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferFloat(address, capacity); + } + + /** Like {@link #memFloatBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable FloatBuffer memFloatBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferFloat(address, capacity); + } + + /** + * Creates a new direct DoubleBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to 8 bytes. If not, use + * {@code memByteBuffer(address, capacity * 8).asDoubleBuffer()}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new DoubleBuffer + */ + public static DoubleBuffer memDoubleBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return wrapBufferDouble(address, capacity); + } + + /** Like {@link #memDoubleBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable DoubleBuffer memDoubleBufferSafe(long address, int capacity) { + return address == NULL ? null : wrapBufferDouble(address, capacity); + } + + /** + * Creates a new PointerBuffer that starts at the specified memory address and has the specified capacity. + * + *

+ * The {@code address} specified must be aligned to the pointer size. If not, use + * {@code PointerBuffer.create(memByteBuffer(address, capacity * + * POINTER_SIZE))}. + *

+ * + * @param address the starting memory address + * @param capacity the buffer capacity + * + * @return the new PointerBuffer + */ + public static PointerBuffer memPointerBuffer(long address, int capacity) { + if (CHECKS) { + check(address); + } + return new PointerBuffer(memByteBuffer(address, capacity)); + } + + /** Like {@link #memPointerBuffer}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable PointerBuffer memPointerBufferSafe(long address, int capacity) { + return address == NULL ? null : new PointerBuffer(memByteBuffer(address, capacity)); + } + + // --- [ Buffer duplication ] --- + + /** + * Duplicates the specified buffer. The returned buffer will have the same {@link ByteOrder} as the source buffer. + * + *

+ * This method should be preferred over {@link ByteBuffer#duplicate} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static ByteBuffer memDuplicate(ByteBuffer buffer) { + ByteBuffer target; + try { + target = (ByteBuffer) UNSAFE.allocateInstance(BUFFER_BYTE); + } catch (InstantiationException e) { + throw new UnsupportedOperationException(e); + } + + UNSAFE.putLong(target, ADDRESS, UNSAFE.getLong(buffer, ADDRESS)); + UNSAFE.putInt(target, MARK, UNSAFE.getInt(buffer, MARK)); + UNSAFE.putInt(target, POSITION, UNSAFE.getInt(buffer, POSITION)); + UNSAFE.putInt(target, LIMIT, UNSAFE.getInt(buffer, LIMIT)); + UNSAFE.putInt(target, CAPACITY, UNSAFE.getInt(buffer, CAPACITY)); + + Object attachment = UNSAFE.getObject(buffer, PARENT_BYTE); + UNSAFE.putObject(target, PARENT_BYTE, attachment == null ? buffer : attachment); + + return target.order(buffer.order()); + } + + /** + * Duplicates the specified buffer. + * + *

+ * This method should be preferred over {@link ShortBuffer#duplicate} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static ShortBuffer memDuplicate(ShortBuffer buffer) { + return duplicate(BUFFER_SHORT, buffer, PARENT_SHORT); + } + + /** + * Duplicates the specified buffer. + * + *

+ * This method should be preferred over {@link CharBuffer#duplicate} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static CharBuffer memDuplicate(CharBuffer buffer) { + return duplicate(BUFFER_CHAR, buffer, PARENT_CHAR); + } + + /** + * Duplicates the specified buffer. + * + *

+ * This method should be preferred over {@link IntBuffer#duplicate} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static IntBuffer memDuplicate(IntBuffer buffer) { + return duplicate(BUFFER_INT, buffer, PARENT_INT); + } + + /** + * Duplicates the specified buffer. + * + *

+ * This method should be preferred over {@link LongBuffer#duplicate} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static LongBuffer memDuplicate(LongBuffer buffer) { + return duplicate(BUFFER_LONG, buffer, PARENT_LONG); + } + + /** + * Duplicates the specified buffer. + * + *

+ * This method should be preferred over {@link FloatBuffer#duplicate} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static FloatBuffer memDuplicate(FloatBuffer buffer) { + return duplicate(BUFFER_FLOAT, buffer, PARENT_FLOAT); + } + + /** + * Duplicates the specified buffer. + * + *

+ * This method should be preferred over {@link DoubleBuffer#duplicate} because it has a much shorter call chain. + * Long call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement + * via Escape Analysis). + *

+ * + * @param buffer the buffer to duplicate + * + * @return the duplicated buffer + */ + public static DoubleBuffer memDuplicate(DoubleBuffer buffer) { + return duplicate(BUFFER_DOUBLE, buffer, PARENT_DOUBLE); + } + + // --- [ Buffer slicing ] --- + + /** + * Slices the specified buffer. The returned buffer will have the same {@link ByteOrder} as the source buffer. + * + *

+ * This method should be preferred over {@link ByteBuffer#slice} because it has a much shorter call chain. Long call + * chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static ByteBuffer memSlice(ByteBuffer buffer) { + return slice(buffer, memAddress0(buffer) + buffer.position(), buffer.remaining()); + } + + /** + * Slices the specified buffer. + * + *

+ * This method should be preferred over {@link ShortBuffer#slice} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static ShortBuffer memSlice(ShortBuffer buffer) { + return slice( + BUFFER_SHORT, + buffer, + address(buffer.position(), 1, memAddress0(buffer)), + buffer.remaining(), + PARENT_SHORT); + } + + /** + * Slices the specified buffer. + * + *

+ * This method should be preferred over {@link CharBuffer#slice} because it has a much shorter call chain. Long call + * chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static CharBuffer memSlice(CharBuffer buffer) { + return slice( + BUFFER_CHAR, + buffer, + address(buffer.position(), 1, memAddress0(buffer)), + buffer.remaining(), + PARENT_CHAR); + } + + /** + * Slices the specified buffer. + * + *

+ * This method should be preferred over {@link IntBuffer#slice} because it has a much shorter call chain. Long call + * chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static IntBuffer memSlice(IntBuffer buffer) { + return slice( + BUFFER_INT, + buffer, + address(buffer.position(), 2, memAddress0(buffer)), + buffer.remaining(), + PARENT_INT); + } + + /** + * Slices the specified buffer. + * + *

+ * This method should be preferred over {@link LongBuffer#slice} because it has a much shorter call chain. Long call + * chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static LongBuffer memSlice(LongBuffer buffer) { + return slice( + BUFFER_LONG, + buffer, + address(buffer.position(), 3, memAddress0(buffer)), + buffer.remaining(), + PARENT_LONG); + } + + /** + * Slices the specified buffer. + * + *

+ * This method should be preferred over {@link FloatBuffer#slice} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static FloatBuffer memSlice(FloatBuffer buffer) { + return slice( + BUFFER_FLOAT, + buffer, + address(buffer.position(), 2, memAddress0(buffer)), + buffer.remaining(), + PARENT_FLOAT); + } + + /** + * Slices the specified buffer. + * + *

+ * This method should be preferred over {@link DoubleBuffer#slice} because it has a much shorter call chain. Long + * call chains may fail to inline due to JVM limits, disabling important optimizations (e.g. scalar replacement via + * Escape Analysis). + *

+ * + * @param buffer the buffer to slice + * + * @return the sliced buffer + */ + public static DoubleBuffer memSlice(DoubleBuffer buffer) { + return slice( + BUFFER_DOUBLE, + buffer, + address(buffer.position(), 3, memAddress0(buffer)), + buffer.remaining(), + PARENT_DOUBLE); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. The returned buffer will have the same {@link ByteOrder} as the + * original buffer. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static ByteBuffer memSlice(ByteBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(buffer, memAddress0(buffer) + position, capacity); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static ShortBuffer memSlice(ShortBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(BUFFER_SHORT, buffer, address(position, 1, memAddress0(buffer)), capacity, PARENT_SHORT); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static CharBuffer memSlice(CharBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(BUFFER_CHAR, buffer, address(position, 1, memAddress0(buffer)), capacity, PARENT_CHAR); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static IntBuffer memSlice(IntBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(BUFFER_INT, buffer, address(position, 2, memAddress0(buffer)), capacity, PARENT_INT); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static LongBuffer memSlice(LongBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(BUFFER_LONG, buffer, address(position, 3, memAddress0(buffer)), capacity, PARENT_LONG); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static FloatBuffer memSlice(FloatBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(BUFFER_FLOAT, buffer, address(position, 2, memAddress0(buffer)), capacity, PARENT_FLOAT); + } + + /** + * Returns a slice of the specified buffer between {@code (buffer.position() + offset)} and + * {@code (buffer.position() + offset + capacity)}. + * + *

+ * The position and limit of the original buffer are preserved after a call to this method. + *

+ * + * @param buffer the buffer to slice + * @param offset the slice offset, it must be ≤ {@code buffer.remaining()} + * @param capacity the slice length, it must be ≤ {@code buffer.capacity() - (buffer.position() + offset)} + * + * @return the sliced buffer + */ + public static DoubleBuffer memSlice(DoubleBuffer buffer, int offset, int capacity) { + int position = buffer.position() + offset; + if (offset < 0 || buffer.limit() < position) { + throw new IllegalArgumentException(); + } + if (capacity < 0 || buffer.capacity() - position < capacity) { + throw new IllegalArgumentException(); + } + return slice(BUFFER_DOUBLE, buffer, address(position, 3, memAddress0(buffer)), capacity, PARENT_DOUBLE); + } + + // --- [ memset ] --- + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(ByteBuffer ptr, int value) { + memSet(memAddress(ptr), value, ptr.remaining()); + } + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(ShortBuffer ptr, int value) { + memSet(memAddress(ptr), value, apiGetBytes(ptr.remaining(), 1)); + } + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(CharBuffer ptr, int value) { + memSet(memAddress(ptr), value, apiGetBytes(ptr.remaining(), 1)); + } + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(IntBuffer ptr, int value) { + memSet(memAddress(ptr), value, apiGetBytes(ptr.remaining(), 2)); + } + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(LongBuffer ptr, int value) { + memSet(memAddress(ptr), value, apiGetBytes(ptr.remaining(), 3)); + } + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(FloatBuffer ptr, int value) { + memSet(memAddress(ptr), value, apiGetBytes(ptr.remaining(), 2)); + } + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + */ + public static void memSet(DoubleBuffer ptr, int value) { + memSet(memAddress(ptr), value, apiGetBytes(ptr.remaining(), 3)); + } + + // --- [ memcpy ] --- + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(ByteBuffer src, ByteBuffer dst) { + if (CHECKS) { + check(dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), src.remaining()); + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(ShortBuffer src, ShortBuffer dst) { + if (CHECKS) { + check(dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), apiGetBytes(src.remaining(), 1)); + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(CharBuffer src, CharBuffer dst) { + if (CHECKS) { + check((Buffer) dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), apiGetBytes(src.remaining(), 1)); + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(IntBuffer src, IntBuffer dst) { + if (CHECKS) { + check(dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), apiGetBytes(src.remaining(), 2)); + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(LongBuffer src, LongBuffer dst) { + if (CHECKS) { + check(dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), apiGetBytes(src.remaining(), 3)); + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(FloatBuffer src, FloatBuffer dst) { + if (CHECKS) { + check(dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), apiGetBytes(src.remaining(), 2)); + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + */ + public static void memCopy(DoubleBuffer src, DoubleBuffer dst) { + if (CHECKS) { + check(dst, src.remaining()); + } + MultiReleaseMemCopy.copy(memAddress(src), memAddress(dst), apiGetBytes(src.remaining(), 3)); + } + + /* + * ------------------------------------- ------------------------------------- UNSAFE MEMORY ACCESS API + * ------------------------------------- ------------------------------------- + */ + + private static final int FILL_PATTERN_32 = Integer.divideUnsigned(-1, 255); + private static final long FILL_PATTERN_64 = Long.divideUnsigned(-1L, 255L); + + /** + * Sets all bytes in a specified block of memory to a fixed value (usually zero). + * + * @param ptr the starting memory address + * @param value the value to set (memSet will convert it to unsigned byte) + * @param bytes the number of bytes to set + */ + public static void memSet(long ptr, int value, long bytes) { + if (DEBUG && (ptr == NULL || bytes < 0)) { + throw new IllegalArgumentException(); + } + + /* + * - Unsafe.setMemory is very slow. - A custom Java loop is fastest at small sizes, approximately up to 256 + * bytes. - The native memset becomes fastest at bigger sizes, when the JNI overhead becomes negligible. + */ + + // UNSAFE.setMemory(ptr, bytes, (byte)(value & 0xFF)); + if (bytes < 256L) { + int p = (int) ptr; + if (BITS64) { + if ((p & 7) == 0) { + memSet64(ptr, value, (int) bytes & 0xFF); + return; + } + } else { + if ((p & 3) == 0) { + memSet32(p, value, (int) bytes & 0xFF); + return; + } + } + } + UNSAFE.setMemory(ptr, bytes, (byte) (value & 0xFF)); + } + + private static void memSet64(long ptr, int value, int bytes) { + int aligned = bytes & ~7; + + // Aligned body + long valuel = (value & 0xFF) * FILL_PATTERN_64; + for (int i = 0; i < aligned; i += 8) { + UNSAFE.putLong(null, ptr + i, valuel); + } + + // Unaligned tail + byte valueb = (byte) (value & 0xFF); + for (int i = aligned; i < bytes; i++) { + UNSAFE.putByte(null, ptr + i, valueb); + } + } + + private static void memSet32(int ptr, int value, int bytes) { + int aligned = bytes & ~3; + + // Aligned body + int vi = (value & 0xFF) * FILL_PATTERN_32; + for (int i = 0; i < aligned; i += 4) { + UNSAFE.putInt(null, (ptr + i) & 0xFFFF_FFFFL, vi); + } + + // Unaligned tail + byte vb = (byte) (value & 0xFF); + for (int i = aligned; i < bytes; i++) { + UNSAFE.putByte(null, (ptr + i) & 0xFFFF_FFFFL, vb); + } + } + + /** + * Sets all bytes in a specified block of memory to a copy of another block. + * + * @param src the source memory address + * @param dst the destination memory address + * @param bytes the number of bytes to copy + */ + public static void memCopy(long src, long dst, long bytes) { + if (DEBUG && (src == NULL || dst == NULL || bytes < 0)) { + throw new IllegalArgumentException(); + } + + MultiReleaseMemCopy.copy(src, dst, bytes); + } + + static void memCopyAligned64(long src, long dst, int bytes) { + int aligned = bytes & ~7; + + // Aligned body + for (int i = 0; i < aligned; i += 8) { + UNSAFE.putLong(null, dst + i, UNSAFE.getLong(null, src + i)); + } + + // Unaligned tail + for (int i = aligned; i < bytes; i++) { + UNSAFE.putByte(null, dst + i, UNSAFE.getByte(null, src + i)); + } + } + + static void memCopyAligned32(int src, int dst, int bytes) { + int aligned = bytes & ~3; + + // Aligned body + for (int i = 0; i < aligned; i += 4) { + UNSAFE.putInt(null, (dst + i) & 0xFFFF_FFFFL, UNSAFE.getInt(null, (src + i) & 0xFFFF_FFFFL)); + } + + // Unaligned tail + for (int i = aligned; i < bytes; i++) { + UNSAFE.putByte(null, (dst + i) & 0xFFFF_FFFFL, UNSAFE.getByte(null, (src + i) & 0xFFFF_FFFFL)); + } + } + + public static boolean memGetBoolean(long ptr) { + return UNSAFE.getByte(null, ptr) != 0; + } + + public static byte memGetByte(long ptr) { + return UNSAFE.getByte(null, ptr); + } + + public static short memGetShort(long ptr) { + return UNSAFE.getShort(null, ptr); + } + + public static int memGetInt(long ptr) { + return UNSAFE.getInt(null, ptr); + } + + public static long memGetLong(long ptr) { + return UNSAFE.getLong(null, ptr); + } + + public static float memGetFloat(long ptr) { + return UNSAFE.getFloat(null, ptr); + } + + public static double memGetDouble(long ptr) { + return UNSAFE.getDouble(null, ptr); + } + + public static long memGetCLong(long ptr) { + return CLONG_SIZE == 8 ? UNSAFE.getLong(null, ptr) : UNSAFE.getInt(null, ptr); + } + + public static long memGetAddress(long ptr) { + return BITS64 ? UNSAFE.getLong(null, ptr) : UNSAFE.getInt(null, ptr) & 0xFFFF_FFFFL; + } + + public static void memPutByte(long ptr, byte value) { + UNSAFE.putByte(null, ptr, value); + } + + public static void memPutShort(long ptr, short value) { + UNSAFE.putShort(null, ptr, value); + } + + public static void memPutInt(long ptr, int value) { + UNSAFE.putInt(null, ptr, value); + } + + public static void memPutLong(long ptr, long value) { + UNSAFE.putLong(null, ptr, value); + } + + public static void memPutFloat(long ptr, float value) { + UNSAFE.putFloat(null, ptr, value); + } + + public static void memPutDouble(long ptr, double value) { + UNSAFE.putDouble(null, ptr, value); + } + + public static void memPutCLong(long ptr, long value) { + if (CLONG_SIZE == 8) { + UNSAFE.putLong(null, ptr, value); + } else { + UNSAFE.putInt(null, ptr, (int) value); + } + } + + public static void memPutAddress(long ptr, long value) { + if (BITS64) { + UNSAFE.putLong(null, ptr, value); + } else { + UNSAFE.putInt(null, ptr, (int) value); + } + } + + /* + * ------------------------------------- ------------------------------------- JNI UTILITIES API + * ------------------------------------- ------------------------------------- + */ + + /** + * Returns the object that the specified global reference points to. + * + * @param globalRef the global reference + * @param the object type + * + * @return the object pointed to by {@code globalRef} + */ + public static native T memGlobalRefToObject(long globalRef); + + /* + * ------------------------------------- ------------------------------------- TEXT ENCODING API + * ------------------------------------- ------------------------------------- + */ + + private static int write8(long target, int offset, int value) { + UNSAFE.putByte(null, target + Integer.toUnsignedLong(offset), (byte) value); + return offset + 1; + } + + private static int write8Safe(long target, int offset, int maxLength, int value) { + if (offset == maxLength) { + throw new BufferOverflowException(); + } + UNSAFE.putByte(null, target + Integer.toUnsignedLong(offset), (byte) value); + return offset + 1; + } + + private static int write16(long target, int offset, char value) { + UNSAFE.putShort(null, target + Integer.toUnsignedLong(offset), (short) value); + return offset + 2; + } + + /** + * Returns a ByteBuffer containing the specified text ASCII encoded and null-terminated. + * + * @param text the text to encode + * + * @return the encoded text. The returned buffer must be deallocated manually with {@link #memFree}. + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static ByteBuffer memASCII(CharSequence text) { + return memASCII(text, true); + } + + /** Like {@link #memASCII(CharSequence) memASCII}, but returns {@code null} if {@code text} is {@code null}. */ + public static @Nullable ByteBuffer memASCIISafe(@Nullable CharSequence text) { + return text == null ? null : memASCII(text, true); + } + + /** + * Returns a {@link ByteBuffer} containing the specified text ASCII encoded and optionally null-terminated. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * + * @return the encoded text. The returned buffer must be deallocated manually with {@link #memFree}. + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static ByteBuffer memASCII(CharSequence text, boolean nullTerminated) { + int length = memLengthASCII(text, nullTerminated); + long target = nmemAlloc(length); + if (CHECKS && target == NULL) { + throw new OutOfMemoryError(); + } + encodeASCIIUnsafe(text, nullTerminated, target); + return wrapBufferByte(target, length); + } + + /** + * Like {@link #memASCII(CharSequence, boolean) memASCII}, but returns {@code null} if {@code text} is {@code null}. + */ + public static @Nullable ByteBuffer memASCIISafe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? null : memASCII(text, nullTerminated); + } + + /** + * Encodes and optionally null-terminates the specified text using ASCII encoding. The encoded text is stored in the + * specified {@link ByteBuffer}, at the current buffer position. The current buffer position is not modified by this + * operation. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0' + * @param target the buffer where the encoded text should be stored + * + * @return the number of bytes of the encoded string + * + * @throws BufferOverflowException if more than {@code target.remaining()} bytes are required to encode the text. + */ + public static int memASCII(CharSequence text, boolean nullTerminated, ByteBuffer target) { + if (target.remaining() < memLengthASCII(text, nullTerminated)) { + throw new BufferOverflowException(); + } + long address = memAddress(target); + return encodeASCIIUnsafe(text, nullTerminated, address); + } + + /** + * Encodes and optionally null-terminates the specified text using ASCII encoding. The encoded text is stored in the + * specified {@link ByteBuffer} at the specified {@code position} offset. The current buffer position is not + * modified by this operation. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * @param offset the buffer position to which the string will be encoded + * + * @return the number of bytes of the encoded string + * + * @throws BufferOverflowException if more than {@code target.capacity() - offset} bytes are required to encode the + * text. + */ + public static int memASCII(CharSequence text, boolean nullTerminated, ByteBuffer target, int offset) { + if (target.capacity() - offset < memLengthASCII(text, nullTerminated)) { + throw new BufferOverflowException(); + } + return encodeASCIIUnsafe(text, nullTerminated, memAddress(target, offset)); + } + + static int encodeASCIIUnsafe(CharSequence text, boolean nullTerminated, long target) { + int i = 0, len = text.length(); + + while (i < len) { + i = write8(target, i, text.charAt(i)); + } + + if (nullTerminated) { + i = write8(target, i, 0); + } + + return i; + } + + /** + * Returns the number of bytes required to encode the specified text in the ASCII encoding. + * + * @param value the text to encode + * @param nullTerminated if true, add the number of bytes required for null-termination + * + * @return the number of bytes + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static int memLengthASCII(CharSequence value, boolean nullTerminated) { + int len = value.length() + (nullTerminated ? 1 : 0); + if (len < 0) { + throw new BufferOverflowException(); + } + return len; + } + + /** + * Returns a ByteBuffer containing the specified text UTF-8 encoded and null-terminated. + * + * @param text the text to encode + * + * @return the encoded text. The returned buffer must be deallocated manually with {@link #memFree}. + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static ByteBuffer memUTF8(CharSequence text) { + return memUTF8(text, true); + } + + /** Like {@link #memUTF8(CharSequence) memUTF8}, but returns {@code null} if {@code text} is {@code null}. */ + public static @Nullable ByteBuffer memUTF8Safe(@Nullable CharSequence text) { + return text == null ? null : memUTF8(text, true); + } + + /** + * Returns a ByteBuffer containing the specified text UTF-8 encoded and optionally null-terminated. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * + * @return the encoded text. The returned buffer must be deallocated manually with {@link #memFree}. + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static ByteBuffer memUTF8(CharSequence text, boolean nullTerminated) { + int length = memLengthUTF8(text, nullTerminated); + long target = nmemAlloc(length); + if (CHECKS && target == NULL) { + throw new OutOfMemoryError(); + } + encodeUTF8Unsafe(text, nullTerminated, target); + return wrapBufferByte(target, length); + } + + /** + * Like {@link #memUTF8(CharSequence, boolean) memUTF8}, but returns {@code null} if {@code text} is {@code null}. + */ + public static @Nullable ByteBuffer memUTF8Safe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? null : memUTF8(text, nullTerminated); + } + + /** + * Encodes and optionally null-terminates the specified text using UTF-8 encoding. The encoded text is stored in the + * specified {@link ByteBuffer}, at the current buffer position. The current buffer position is not modified by this + * operation. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * @param target the buffer in which to store the encoded text + * + * @return the number of bytes of the encoded string + * + * @throws BufferOverflowException if more than {@code target.remaining} bytes are required to encode the text. + */ + public static int memUTF8(CharSequence text, boolean nullTerminated, ByteBuffer target) { + if (target.remaining() < memLengthASCII(text, nullTerminated)) { + throw new BufferOverflowException(); + } + return encodeUTF8Safe(text, nullTerminated, memAddress(target), target.remaining()); + } + + /** + * Encodes and optionally null-terminates the specified text using UTF-8 encoding. The encoded text is stored in the + * specified {@link ByteBuffer}, at the specified {@code position} offset. The current buffer position is not + * modified by this operation. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * @param target the buffer in which to store the encoded text + * @param offset the buffer position to which the string will be encoded + * + * @return the number of bytes of the encoded string + * + * @throws BufferOverflowException if more than {@code target.capacity() - offset} bytes are required to encode the + * text. + */ + public static int memUTF8(CharSequence text, boolean nullTerminated, ByteBuffer target, int offset) { + if (target.capacity() - offset < memLengthASCII(text, nullTerminated)) { + throw new BufferOverflowException(); + } + return encodeUTF8Safe(text, nullTerminated, memAddress(target, offset), target.capacity() - offset); + } + + static int encodeUTF8Unsafe(CharSequence text, boolean nullTerminated, long target) { + int p = 0, i = 0, len = text.length(); + + while (i < len) { + char c = text.charAt(i++); + if (c < 0x80) { + p = write8(target, p, c); + } else { + int cp = c; + if (c < 0x800) { + p = write8(target, p, 0xC0 | cp >> 6); + } else { + if (!isHighSurrogate(c)) { + p = write8(target, p, 0xE0 | cp >> 12); + } else { + cp = toCodePoint(c, text.charAt(i++)); + + p = write8(target, p, 0xF0 | cp >> 18); + p = write8(target, p, 0x80 | cp >> 12 & 0x3F); + } + p = write8(target, p, 0x80 | cp >> 6 & 0x3F); + } + p = write8(target, p, 0x80 | cp & 0x3F); + } + } + + if (nullTerminated) { + p = write8(target, p, 0); + } + + return p; + } + + static int encodeUTF8Safe(CharSequence text, boolean nullTerminated, long target, int maxLength) { + int p = 0, i = 0, length = text.length(); + + // ASCII fast path + while (i < length) { + char c = text.charAt(i); + if (0x80 <= c) { + break; + } + p = write8(target, p, c); // have already checked that text.length() <= maxLength + i++; + } + + // Slow path + while (i < length) { + char c = text.charAt(i++); + if (c < 0x80) { + p = write8Safe(target, p, maxLength, c); + } else { + int cp = c; + if (c < 0x800) { + p = write8Safe(target, p, maxLength, 0xC0 | cp >> 6); + } else { + if (!isHighSurrogate(c)) { + p = write8Safe(target, p, maxLength, 0xE0 | cp >> 12); + } else { + cp = toCodePoint(c, text.charAt(i++)); + + p = write8Safe(target, p, maxLength, 0xF0 | cp >> 18); + p = write8Safe(target, p, maxLength, 0x80 | cp >> 12 & 0x3F); + } + p = write8Safe(target, p, maxLength, 0x80 | cp >> 6 & 0x3F); + } + p = write8Safe(target, p, maxLength, 0x80 | cp & 0x3F); + } + } + + if (nullTerminated) { + p = write8Safe(target, p, maxLength, 0); + } + + return p; + } + + /** + * Returns the number of bytes required to encode the specified text in the UTF-8 encoding. + * + * @param value the text to encode + * @param nullTerminated if true, add the number of bytes required for null-termination + * + * @return the number of bytes + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static int memLengthUTF8(CharSequence value, boolean nullTerminated) { + int len = value.length(); + int bytes = len + (nullTerminated ? 1 : 0); // start with 1:1 + + for (int i = 0; i < len; i++) { + char c = value.charAt(i); + + if (c < 0x80) { + // 1 input char -> 1 output byte + } else { + if (c < 0x800) { + // c <= 127: 0 (1 input char -> 1 output byte) + // c >= 128: 1 (1 input char -> 2 output bytes) + bytes += (0x7F - c) >>> 31; + } else { + // non-high-surrogate: 1 input char -> 3 output bytes + // surrogate-pair: 2 input chars -> 4 output bytes + bytes += 2; + if (isHighSurrogate(c)) { + i++; + } + } + if (bytes < 0) { + throw new BufferOverflowException(); + } + } + } + + if (bytes < 0) { + throw new BufferOverflowException(); + } + + return bytes; + } + + /** + * Returns a ByteBuffer containing the specified text UTF-16 encoded and null-terminated. + * + * @param text the text to encode + * + * @return the encoded text. The returned buffer must be deallocated manually with {@link #memFree}. + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static ByteBuffer memUTF16(CharSequence text) { + return memUTF16(text, true); + } + + /** Like {@link #memUTF16(CharSequence) memUTF16}, but returns {@code null} if {@code text} is {@code null}. */ + public static @Nullable ByteBuffer memUTF16Safe(@Nullable CharSequence text) { + return text == null ? null : memUTF16(text, true); + } + + /** + * Returns a ByteBuffer containing the specified text UTF-16 encoded and optionally null-terminated. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * + * @return the encoded text. The returned buffer must be deallocated manually with {@link #memFree}. + * + * @throws BufferOverflowException if more than {@link Integer#MAX_VALUE} bytes are required to encode the text. + */ + public static ByteBuffer memUTF16(CharSequence text, boolean nullTerminated) { + int length = memLengthUTF16(text, nullTerminated); + long target = nmemAlloc(length); + if (CHECKS && target == NULL) { + throw new OutOfMemoryError(); + } + encodeUTF16Unsafe(text, nullTerminated, target); + return wrapBufferByte(target, length); + } + + /** + * Like {@link #memUTF16(CharSequence, boolean) memUTF16}, but returns {@code null} if {@code text} is {@code null}. + */ + public static @Nullable ByteBuffer memUTF16Safe(@Nullable CharSequence text, boolean nullTerminated) { + return text == null ? null : memUTF16(text, nullTerminated); + } + + /** + * Encodes and optionally null-terminates the specified text using UTF-16 encoding. The encoded text is stored in + * the specified {@link ByteBuffer}, at the current buffer position. The current buffer position is not modified by + * this operation. The {@code target} buffer is assumed to have enough remaining space to store the encoded text. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * @param target the buffer in which to store the encoded text + * + * @return the number of bytes of the encoded string + * + * @throws BufferOverflowException if more than {@code target.remaining()} bytes are required to encode the text. + */ + public static int memUTF16(CharSequence text, boolean nullTerminated, ByteBuffer target) { + if (target.remaining() < memLengthUTF16(text, nullTerminated)) { + throw new BufferOverflowException(); + } + long address = memAddress(target); + return encodeUTF16Unsafe(text, nullTerminated, address); + } + + /** + * Encodes and optionally null-terminates the specified text using UTF-16 encoding. The encoded text is stored in + * the specified {@link ByteBuffer} at the specified {@code position} offset. The current buffer position is not + * modified by this operation. The {@code target} buffer is assumed to have enough remaining space to store the + * encoded text. + * + * @param text the text to encode + * @param nullTerminated if true, the text will be terminated with a '\0'. + * @param target the buffer in which to store the encoded text + * @param offset the buffer position to which the string will be encoded + * + * @return the number of bytes of the encoded string + * + * @throws BufferOverflowException if more than {@code target.capacity() - offset} bytes are required to encode the + * text. + */ + public static int memUTF16(CharSequence text, boolean nullTerminated, ByteBuffer target, int offset) { + if (target.capacity() - offset < memLengthUTF16(text, nullTerminated)) { + throw new BufferOverflowException(); + } + long address = memAddress(target, offset); + return encodeUTF16Unsafe(text, nullTerminated, address); + } + + static int encodeUTF16Unsafe(CharSequence text, boolean nullTerminated, long target) { + int p = 0, i = 0, len = text.length(); + + while (i < len) { + p = write16(target, p, text.charAt(i++)); + } + + if (nullTerminated) { + p = write16(target, p, '\0'); + } + + return p; + } + + /** + * Returns the number of bytes required to encode the specified text in the UTF-16 encoding. + * + * @param value the text to encode + * @param nullTerminated if true, add the number of bytes required for null-termination + * + * @return the number of bytes + */ + public static int memLengthUTF16(CharSequence value, boolean nullTerminated) { + int len = value.length() + (nullTerminated ? 1 : 0); + if (len < 0 || 0x3FFFFFFF < len) { + throw new BufferOverflowException(); + } + return len << 1; + } + + /* + * ------------------------------------- ------------------------------------- TEXT DECODING API + * ------------------------------------- ------------------------------------- + */ + + private static int memLengthNT1(long address, int maxLength) { + if (CHECKS) { + check(address); + } + return BITS64 ? strlen64NT1(address, maxLength) : strlen32NT1(address, maxLength); + } + + private static int strlen64NT1(long address, int maxLength) { + int i = 0; + + if (8 <= maxLength) { + int misalignment = (int) address & 7; + if (misalignment != 0) { + // Align to 8 bytes + for (int len = 8 - misalignment; i < len; i++) { + if (UNSAFE.getByte(null, address + i) == 0) { + return i; + } + } + } + + // Aligned longs for performance + for (; i <= maxLength - 8; i += 8) { + if (mathHasZeroByte(UNSAFE.getLong(null, address + i))) { + break; + } + } + } + + // Tail + for (; i < maxLength; i++) { + if (UNSAFE.getByte(null, address + i) == 0) { + break; + } + } + + return i; + } + + private static int strlen32NT1(long address, int maxLength) { + int i = 0; + + if (4 <= maxLength) { + int misalignment = (int) address & 3; + if (misalignment != 0) { + // Align to 4 bytes + for (int len = 4 - misalignment; i < len; i++) { + if (UNSAFE.getByte(null, address + i) == 0) { + return i; + } + } + } + + // Aligned ints for performance + for (; i <= maxLength - 4; i += 4) { + if (mathHasZeroByte(UNSAFE.getInt(null, address + i))) { + break; + } + } + } + + // Tail + for (; i < maxLength; i++) { + if (UNSAFE.getByte(null, address + i) == 0) { + break; + } + } + + return i; + } + + /** + * Calculates the length, in bytes, of the null-terminated string that starts at the current position of the + * specified buffer. A single \0 character will terminate the string. The returned length will NOT include the \0 + * byte. + * + *

+ * This method is useful for reading ASCII and UTF8 encoded text. + *

+ * + * @param buffer the buffer containing the null-terminated string + * + * @return the string length, in bytes + */ + public static int memLengthNT1(ByteBuffer buffer) { + return memLengthNT1(memAddress(buffer), buffer.remaining()); + } + + private static int memLengthNT2(long address, int maxLength) { + if (CHECKS) { + check(address); + } + return BITS64 ? strlen64NT2(address, maxLength) : strlen32NT2((int) address, maxLength); + } + + private static int strlen64NT2(long address, int maxLength) { + int i = 0; + + if (8 <= maxLength) { + int misalignment = (int) address & 7; + if (misalignment != 0) { + // Align to 8 bytes + for (int len = 8 - misalignment; i < len; i += 2) { + if (UNSAFE.getShort(null, address + i) == 0) { + return i; + } + } + } + + // Aligned longs for performance + for (; i <= maxLength - 8; i += 8) { + if (mathHasZeroShort(UNSAFE.getLong(null, address + i))) { + break; + } + } + } + + // Tail + for (; i < maxLength; i += 2) { + if (UNSAFE.getShort(null, address + i) == 0) { + break; + } + } + + return i; + } + + private static int strlen32NT2(long address, int maxLength) { + int i = 0; + + if (4 <= maxLength) { + int misalignment = (int) address & 3; + if (misalignment != 0) { + // Align to 4 bytes + for (int len = 4 - misalignment; i < len; i += 2) { + if (UNSAFE.getShort(null, address + i) == 0) { + return i; + } + } + } + + // Aligned longs for performance + while (i <= maxLength - 4) { + if (mathHasZeroShort(UNSAFE.getInt(null, address + i))) { + break; + } + i += 4; + } + } + + // Tail + for (; i < maxLength; i += 2) { + if (UNSAFE.getShort(null, address + i) == 0) { + break; + } + } + + return i; + } + + /** + * Calculates the length, in bytes, of the null-terminated string that starts at the current position of the + * specified buffer. Two \0 characters will terminate the string. The returned buffer will NOT include the \0 bytes. + * + *

+ * This method is useful for reading UTF16 encoded text. + *

+ * + * @param buffer the buffer containing the null-terminated string + * + * @return the string length, in bytes + */ + public static int memLengthNT2(ByteBuffer buffer) { + return memLengthNT2(memAddress(buffer), buffer.remaining()); + } + + /** + * Creates a new direct ByteBuffer that starts at the specified memory address and has capacity equal to the + * null-terminated string starting at that address. A single \0 character will terminate the string. The returned + * buffer will NOT include the \0 byte. + * + *

+ * This method is useful for reading ASCII and UTF8 encoded text. + *

+ * + * @param address the starting memory address + * + * @return the new ByteBuffer + */ + public static ByteBuffer memByteBufferNT1(long address) { + return memByteBuffer(address, memLengthNT1(address, Integer.MAX_VALUE)); + } + + /** + * Creates a new direct ByteBuffer that starts at the specified memory address and has capacity equal to the + * null-terminated string starting at that address, up to a maximum of {@code maxLength} bytes. A single \0 + * character will terminate the string. The returned buffer will NOT include the \0 byte. + * + *

+ * This method is useful for reading ASCII and UTF8 encoded text. + *

+ * + * @param address the starting memory address + * @param maxLength the maximum string length, in bytes + * + * @return the new ByteBuffer + */ + public static ByteBuffer memByteBufferNT1(long address, int maxLength) { + return memByteBuffer(address, memLengthNT1(address, maxLength)); + } + + /** + * Like {@link #memByteBufferNT1(long) memByteBufferNT1}, but returns {@code null} if {@code address} is + * {@link #NULL}. + */ + public static @Nullable ByteBuffer memByteBufferNT1Safe(long address) { + return address == NULL ? null : memByteBuffer(address, memLengthNT1(address, Integer.MAX_VALUE)); + } + + /** + * Like {@link #memByteBufferNT1(long, int) memByteBufferNT1}, but returns {@code null} if {@code address} is + * {@link #NULL}. + */ + public static @Nullable ByteBuffer memByteBufferNT1Safe(long address, int maxLength) { + return address == NULL ? null : memByteBuffer(address, memLengthNT1(address, maxLength)); + } + + /** + * Creates a new direct ByteBuffer that starts at the specified memory address and has capacity equal to the + * null-terminated string starting at that address. Two \0 characters will terminate the string. The returned buffer + * will NOT include the \0 bytes. + * + *

+ * This method is useful for reading UTF16 encoded text. + *

+ * + * @param address the starting memory address + * + * @return the new ByteBuffer + */ + public static ByteBuffer memByteBufferNT2(long address) { + return memByteBufferNT2(address, Integer.MAX_VALUE - 1); + } + + /** + * Creates a new direct ByteBuffer that starts at the specified memory address and has capacity equal to the + * null-terminated string starting at that address, up to a maximum of {@code maxLength} bytes. Two \0 characters + * will terminate the string. The returned buffer will NOT include the \0 bytes. + * + *

+ * This method is useful for reading UTF16 encoded text. + *

+ * + * @param address the starting memory address + * + * @return the new ByteBuffer + */ + public static ByteBuffer memByteBufferNT2(long address, int maxLength) { + if (DEBUG) { + if ((maxLength & 1) != 0) { + throw new IllegalArgumentException("The maximum length must be an even number."); + } + } + return memByteBuffer(address, memLengthNT2(address, maxLength)); + } + + /** + * Like {@link #memByteBufferNT2(long) memByteBufferNT2}, but returns {@code null} if {@code address} is + * {@link #NULL}. + */ + public static @Nullable ByteBuffer memByteBufferNT2Safe(long address) { + return address == NULL ? null : memByteBufferNT2(address, Integer.MAX_VALUE - 1); + } + + /** + * Like {@link #memByteBufferNT2(long, int) memByteBufferNT2}, but returns {@code null} if {@code address} is + * {@link #NULL}. + */ + public static @Nullable ByteBuffer memByteBufferNT2Safe(long address, int maxLength) { + return address == NULL ? null : memByteBufferNT2(address, maxLength); + } + + /** + * Converts the null-terminated ASCII encoded string at the specified memory address to a {@link String}. + * + * @param address the string memory address + * + * @return the decoded {@link String} + */ + public static String memASCII(long address) { + return memASCII(address, memLengthNT1(address, Integer.MAX_VALUE)); + } + + /** + * Converts the ASCII encoded string at the specified memory address to a {@link String}. + * + * @param address the string memory address + * @param length the number of bytes to decode + * + * @return the decoded {@link String} + */ + @SuppressWarnings("deprecation") + public static String memASCII(long address, int length) { + if (length <= 0) { + return ""; + } + + byte[] ascii = length <= ARRAY_TLC_SIZE ? ARRAY_TLC_BYTE.get() : new byte[length]; + memByteBuffer(address, length).get(ascii, 0, length); + return new String(ascii, 0, 0, length); + } + + /** + * Decodes the bytes with index {@code [position(), position()+remaining()}) in {@code buffer}, as an ASCII string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * + * @return the decoded {@link String} + */ + public static String memASCII(ByteBuffer buffer) { + return memASCII(memAddress(buffer), buffer.remaining()); + } + + /** Like {@link #memASCII(long) memASCII}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable String memASCIISafe(long address) { + return address == NULL ? null : memASCII(address, memLengthNT1(address, Integer.MAX_VALUE)); + } + + /** Like {@link #memASCII(long, int) memASCII}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable String memASCIISafe(long address, int length) { + return address == NULL ? null : memASCII(address, length); + } + + /** Like {@link #memASCII(ByteBuffer) memASCII}, but returns {@code null} if {@code buffer} is {@code null}. */ + public static @Nullable String memASCIISafe(@Nullable ByteBuffer buffer) { + return buffer == null ? null : memASCII(memAddress(buffer), buffer.remaining()); + } + + /** + * Decodes the bytes with index {@code [position(), position()+length}) in {@code buffer}, as an ASCII string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * @param length the number of bytes to decode + * + * @return the decoded {@link String} + */ + public static String memASCII(ByteBuffer buffer, int length) { + return memASCII(memAddress(buffer), length); + } + + /** + * Decodes the bytes with index {@code [offset, offset+length}) in {@code buffer}, as an ASCII string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * @param length the number of bytes to decode + * @param offset the offset at which to start decoding. + * + * @return the decoded {@link String} + */ + public static String memASCII(ByteBuffer buffer, int length, int offset) { + return memASCII(memAddress(buffer, offset), length); + } + + /** + * Converts the null-terminated UTF-8 encoded string at the specified memory address to a {@link String}. + * + * @param address the string memory address + * + * @return the decoded {@link String} + */ + public static String memUTF8(long address) { + return MultiReleaseTextDecoding.decodeUTF8(address, memLengthNT1(address, Integer.MAX_VALUE)); + } + + /** + * Converts the UTF-8 encoded string at the specified memory address to a {@link String}. + * + * @param address the string memory address + * @param length the number of bytes to decode + * + * @return the decoded {@link String} + */ + public static String memUTF8(long address, int length) { + return MultiReleaseTextDecoding.decodeUTF8(address, length); + } + + /** + * Decodes the bytes with index {@code [position(), position()+remaining()}) in {@code buffer}, as a UTF-8 string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * + * @return the decoded {@link String} + */ + public static String memUTF8(ByteBuffer buffer) { + return MultiReleaseTextDecoding.decodeUTF8(memAddress(buffer), buffer.remaining()); + } + + /** Like {@link #memUTF8(long) memUTF8}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable String memUTF8Safe(long address) { + return address == NULL ? null + : MultiReleaseTextDecoding.decodeUTF8(address, memLengthNT1(address, Integer.MAX_VALUE)); + } + + /** Like {@link #memUTF8(long, int) memUTF8}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable String memUTF8Safe(long address, int length) { + return address == NULL ? null : MultiReleaseTextDecoding.decodeUTF8(address, length); + } + + /** Like {@link #memUTF8(ByteBuffer) memUTF8}, but returns {@code null} if {@code buffer} is {@code null}. */ + public static @Nullable String memUTF8Safe(@Nullable ByteBuffer buffer) { + return buffer == null ? null : MultiReleaseTextDecoding.decodeUTF8(memAddress(buffer), buffer.remaining()); + } + + /** + * Decodes the bytes with index {@code [position(), position()+length}) in {@code buffer}, as a UTF-8 string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * @param length the number of bytes to decode + * + * @return the decoded {@link String} + */ + public static String memUTF8(ByteBuffer buffer, int length) { + return MultiReleaseTextDecoding.decodeUTF8(memAddress(buffer), length); + } + + /** + * Decodes the bytes with index {@code [offset, offset+length}) in {@code buffer}, as a UTF-8 string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * @param length the number of bytes to decode + * @param offset the offset at which to start decoding. + * + * @return the decoded {@link String} + */ + public static String memUTF8(ByteBuffer buffer, int length, int offset) { + return MultiReleaseTextDecoding.decodeUTF8(memAddress(buffer, offset), length); + } + + /** + * Converts the null-terminated UTF-16 encoded string at the specified memory address to a {@link String}. + * + * @param address the string memory address + * + * @return the decoded {@link String} + */ + public static String memUTF16(long address) { + return memUTF16(address, memLengthNT2(address, Integer.MAX_VALUE - 1) >> 1); + } + + /** + * Converts the UTF-16 encoded string at the specified memory address to a {@link String}. + * + * @param address the string memory address + * @param length the number of characters to decode + * + * @return the decoded {@link String} + */ + public static String memUTF16(long address, int length) { + if (length <= 0) { + return ""; + } + + if (DEBUG) { + // The implementation below does no codepoint validation. + int len = length << 1; + byte[] bytes = len <= ARRAY_TLC_SIZE ? ARRAY_TLC_BYTE.get() : new byte[len]; + memByteBuffer(address, len).get(bytes, 0, len); + return new String(bytes, 0, len, UTF16); + } + + char[] chars = length <= ARRAY_TLC_SIZE ? ARRAY_TLC_CHAR.get() : new char[length]; + memCharBuffer(address, length).get(chars, 0, length); + return new String(chars, 0, length); + } + + /** + * Decodes the bytes with index {@code [position(), position()+remaining()}) in {@code buffer}, as a UTF-16 string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * + * @return the decoded {@link String} + */ + public static String memUTF16(ByteBuffer buffer) { + return memUTF16(memAddress(buffer), buffer.remaining() >> 1); + } + + /** Like {@link #memUTF16(long) memUTF16}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable String memUTF16Safe(long address) { + return address == NULL ? null : memUTF16(address, memLengthNT2(address, Integer.MAX_VALUE - 1) >> 1); + } + + /** Like {@link #memUTF16(long, int) memUTF16}, but returns {@code null} if {@code address} is {@link #NULL}. */ + public static @Nullable String memUTF16Safe(long address, int length) { + return address == NULL ? null : memUTF16(address, length); + } + + /** Like {@link #memUTF16(ByteBuffer) memUTF16}, but returns {@code null} if {@code buffer} is {@code null}. */ + public static @Nullable String memUTF16Safe(@Nullable ByteBuffer buffer) { + return buffer == null ? null : memUTF16(memAddress(buffer), buffer.remaining() >> 1); + } + + /** + * Decodes the bytes with index {@code [position(), position()+(length*2)}) in {@code buffer}, as a UTF-16 string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * @param length the number of characters to decode + * + * @return the decoded {@link String} + */ + public static String memUTF16(ByteBuffer buffer, int length) { + return memUTF16(memAddress(buffer), length); + } + + /** + * Decodes the bytes with index {@code [offset, offset+(length*2)}) in {@code buffer}, as a UTF-16 string. + * + *

+ * The current {@code position} and {@code limit} of the specified {@code buffer} are not affected by this + * operation. + *

+ * + * @param buffer the {@link ByteBuffer} to decode + * @param length the number of characters to decode + * @param offset the offset at which to start decoding, in bytes. + * + * @return the decoded {@link String} + */ + public static String memUTF16(ByteBuffer buffer, int length, int offset) { + return memUTF16(memAddress(buffer, offset), length); + } + + // ------------------------------------------------- + // ------------------------------------------------- + // ------------------------------------------------- + + static sun.misc.Unsafe getUnsafeInstance() { + java.lang.reflect.Field[] fields = sun.misc.Unsafe.class.getDeclaredFields(); + + /* + * Different runtimes use different names for the Unsafe singleton, so we cannot use .getDeclaredField and we + * scan instead. For example: Oracle: theUnsafe PERC : m_unsafe_instance Android: THE_ONE + */ + for (java.lang.reflect.Field field : fields) { + if (!field.getType().equals(sun.misc.Unsafe.class)) { + continue; + } + + int modifiers = field.getModifiers(); + if (!(java.lang.reflect.Modifier.isStatic(modifiers) && java.lang.reflect.Modifier.isFinal(modifiers))) { + continue; + } + + try { + field.setAccessible(true); + return (sun.misc.Unsafe) field.get(null); + } catch (Exception ignored) {} + break; + } + + throw new UnsupportedOperationException("LWJGL requires sun.misc.Unsafe to be available."); + } + + private static long getFieldOffset(Class containerType, Class fieldType, LongPredicate predicate) { + Class c = containerType; + while (c != Object.class) { + Field[] fields = c.getDeclaredFields(); + for (Field field : fields) { + if (!field.getType().isAssignableFrom(fieldType) || Modifier.isStatic(field.getModifiers()) + || field.isSynthetic()) { + continue; + } + + long offset = UNSAFE.objectFieldOffset(field); + if (predicate.test(offset)) { + return offset; + } + } + c = c.getSuperclass(); + } + throw new UnsupportedOperationException("Failed to find field offset in class."); + } + + private static long getFieldOffsetInt(Object container, int value) { + return getFieldOffset(container.getClass(), int.class, offset -> UNSAFE.getInt(container, offset) == value); + } + + private static long getFieldOffsetObject(Object container, Object value) { + return getFieldOffset( + container.getClass(), + value.getClass(), + offset -> UNSAFE.getObject(container, offset) == value); + } + + private static long getAddressOffset() { + long MAGIC_ADDRESS = 0xDEADBEEF8BADF00DL & (BITS32 ? 0xFFFF_FFFFL : 0xFFFF_FFFF_FFFF_FFFFL); + + ByteBuffer bb = Objects.requireNonNull(NewDirectByteBuffer(MAGIC_ADDRESS, 0)); + + return getFieldOffset(bb.getClass(), long.class, offset -> UNSAFE.getLong(bb, offset) == MAGIC_ADDRESS); + } + + private static final int MAGIC_CAPACITY = 0x0D15EA5E; + private static final int MAGIC_POSITION = 0x00FACADE; + + private static long getMarkOffset() { + ByteBuffer bb = Objects.requireNonNull(NewDirectByteBuffer(1L, 0)); + return getFieldOffsetInt(bb, -1); + } + + private static long getPositionOffset() { + ByteBuffer bb = Objects.requireNonNull(NewDirectByteBuffer(-1L, MAGIC_CAPACITY)); + bb.position(MAGIC_POSITION); + return getFieldOffsetInt(bb, MAGIC_POSITION); + } + + private static long getLimitOffset() { + ByteBuffer bb = Objects.requireNonNull(NewDirectByteBuffer(-1L, MAGIC_CAPACITY)); + bb.limit(MAGIC_POSITION); + return getFieldOffsetInt(bb, MAGIC_POSITION); + } + + private static long getCapacityOffset() { + ByteBuffer bb = Objects.requireNonNull(NewDirectByteBuffer(-1L, MAGIC_CAPACITY)); + bb.limit(0); + 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 ShortBuffer wrapBufferShort(long address, int capacity) { + ShortBuffer buffer; + try { + buffer = (ShortBuffer) UNSAFE.allocateInstance(BUFFER_SHORT); + } 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; + } + + static CharBuffer wrapBufferChar(long address, int capacity) { + CharBuffer buffer; + try { + buffer = (CharBuffer) UNSAFE.allocateInstance(BUFFER_CHAR); + } 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; + } + + static IntBuffer wrapBufferInt(long address, int capacity) { + IntBuffer buffer; + try { + buffer = (IntBuffer) UNSAFE.allocateInstance(BUFFER_INT); + } 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; + } + + static LongBuffer wrapBufferLong(long address, int capacity) { + LongBuffer buffer; + try { + buffer = (LongBuffer) UNSAFE.allocateInstance(BUFFER_LONG); + } 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; + } + + static FloatBuffer wrapBufferFloat(long address, int capacity) { + FloatBuffer buffer; + try { + buffer = (FloatBuffer) UNSAFE.allocateInstance(BUFFER_FLOAT); + } 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; + } + + static DoubleBuffer wrapBufferDouble(long address, int capacity) { + DoubleBuffer buffer; + try { + buffer = (DoubleBuffer) UNSAFE.allocateInstance(BUFFER_DOUBLE); + } 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; + } + + static ByteBuffer slice(ByteBuffer source, long address, int capacity) { + ByteBuffer target; + try { + target = (ByteBuffer) UNSAFE.allocateInstance(BUFFER_BYTE); + } catch (InstantiationException e) { + throw new UnsupportedOperationException(e); + } + + UNSAFE.putLong(target, ADDRESS, address); + UNSAFE.putInt(target, MARK, -1); + UNSAFE.putInt(target, LIMIT, capacity); + UNSAFE.putInt(target, CAPACITY, capacity); + + Object attachment = UNSAFE.getObject(source, PARENT_BYTE); + UNSAFE.putObject(target, PARENT_BYTE, attachment == null ? source : attachment); + + return target.order(source.order()); + } + + @SuppressWarnings("unchecked") + static T slice(Class clazz, T source, long address, int capacity, + long attachmentOffset) { + T target; + try { + target = (T) UNSAFE.allocateInstance(clazz); + } catch (InstantiationException e) { + throw new UnsupportedOperationException(e); + } + + UNSAFE.putLong(target, ADDRESS, address); + UNSAFE.putInt(target, MARK, -1); + UNSAFE.putInt(target, LIMIT, capacity); + UNSAFE.putInt(target, CAPACITY, capacity); + + UNSAFE.putObject(target, attachmentOffset, UNSAFE.getObject(source, attachmentOffset)); + + return target; + } + + @SuppressWarnings("unchecked") + static T duplicate(Class clazz, T source, long attachmentOffset) { + T target; + try { + target = (T) UNSAFE.allocateInstance(clazz); + } catch (InstantiationException e) { + throw new UnsupportedOperationException(e); + } + + UNSAFE.putLong(target, ADDRESS, UNSAFE.getLong(source, ADDRESS)); + UNSAFE.putInt(target, MARK, UNSAFE.getInt(source, MARK)); + UNSAFE.putInt(target, POSITION, UNSAFE.getInt(source, POSITION)); + UNSAFE.putInt(target, LIMIT, UNSAFE.getInt(source, LIMIT)); + UNSAFE.putInt(target, CAPACITY, UNSAFE.getInt(source, CAPACITY)); + + UNSAFE.putObject(target, attachmentOffset, UNSAFE.getObject(source, attachmentOffset)); + + return target; + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseMemCopy.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseMemCopy.java new file mode 100644 index 00000000..72581e36 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseMemCopy.java @@ -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); + } + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseTextDecoding.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseTextDecoding.java new file mode 100644 index 00000000..b9d50f2a --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseTextDecoding.java @@ -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. + * + *

+ * On Java 9 different implementations are used that work better with compact strings (JEP 254). + *

+ */ +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); + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/Pointer.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/Pointer.java new file mode 100644 index 00000000..4b953496 --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/Pointer.java @@ -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. + * + *

+ * 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. + *

+ * + *

+ * 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. + *

+ */ +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); + } + + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/StackWalkUtil.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/StackWalkUtil.java new file mode 100644 index 00000000..c997118a --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/StackWalkUtil.java @@ -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. + * + *

+ * On Java 9 these methods are implemented using {@code java.lang.StackWalker}, which has much lower overhead. + *

+ */ +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); + } + +} diff --git a/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/package-info.java b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/package-info.java new file mode 100644 index 00000000..92f4b9ed --- /dev/null +++ b/src/main/java/com/gtnewhorizon/gtnhlib/bytebuf/package-info.java @@ -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; diff --git a/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/CheckIntrinsics.java b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/CheckIntrinsics.java new file mode 100644 index 00000000..faa84b81 --- /dev/null +++ b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/CheckIntrinsics.java @@ -0,0 +1,68 @@ +/* + * Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license + */ +package com.gtnewhorizon.gtnhlib.bytebuf; + +import java.nio.ByteBuffer; +import java.util.Objects; + +import org.jetbrains.annotations.NotNullByDefault; + +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; + +/** Java 9 version of {@code CheckIntrinsics}. */ +@NotNullByDefault +@Lwjgl3Aware +public final class CheckIntrinsics { + + private CheckIntrinsics() {} + + public static int classVersion() { + return 17; + } + + public static int checkIndex(int index, int length) { + return Objects.checkIndex(index, length); + } + + public static int checkFromToIndex(int fromIndex, int toIndex, int length) { + return Objects.checkFromToIndex(fromIndex, toIndex, length); + } + + public static int checkFromIndexSize(int fromIndex, int size, int length) { + return Objects.checkFromIndexSize(fromIndex, size, length); + } + + public static ByteBuffer NewDirectByteBuffer(long address, int capacity) { + return org.lwjgl.system.jni.JNINativeInterface.NewDirectByteBuffer(address, capacity); + } + + public static MemoryUtilities.MemoryAllocator getLwjgl3ifyAllocator() { + return new Lwjgl3ifyAllocator(); + } + + @Lwjgl3Aware + private static final class Lwjgl3ifyAllocator implements MemoryUtilities.MemoryAllocator { + + @Override + public long malloc(long size) { + return org.lwjgl.system.MemoryUtil.nmemAlloc(size); + } + + @Override + public long calloc(long num, long size) { + return org.lwjgl.system.MemoryUtil.nmemCalloc(num, size); + } + + @Override + public long realloc(long ptr, long size) { + return org.lwjgl.system.MemoryUtil.nmemRealloc(ptr, size); + } + + @Override + public void free(long ptr) { + org.lwjgl.system.MemoryUtil.nmemFree(ptr); + } + } + +} diff --git a/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseMemCopy.java b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseMemCopy.java new file mode 100644 index 00000000..c039f996 --- /dev/null +++ b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseMemCopy.java @@ -0,0 +1,20 @@ +/* + * Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license + */ +package com.gtnewhorizon.gtnhlib.bytebuf; + +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; + +@Lwjgl3Aware +final class MultiReleaseMemCopy { + + private MultiReleaseMemCopy() {} + + public static int classVersion() { + return 17; + } + + static void copy(long src, long dst, long bytes) { + org.lwjgl.system.MemoryUtil.memCopy(src, dst, bytes); + } +} diff --git a/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseTextDecoding.java b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseTextDecoding.java new file mode 100644 index 00000000..6eed3b1a --- /dev/null +++ b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/MultiReleaseTextDecoding.java @@ -0,0 +1,28 @@ +package com.gtnewhorizon.gtnhlib.bytebuf; + +import java.nio.ByteBuffer; + +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; + +/** + * String decoding utilities. + * + *

+ * On Java 9 different implementations are used that work better with compact strings (JEP 254). + *

+ */ +@Lwjgl3Aware +final class MultiReleaseTextDecoding { + + private MultiReleaseTextDecoding() {} + + public static int classVersion() { + return 17; + } + + /** @see MemoryUtilities#memUTF8(ByteBuffer, int, int) */ + static String decodeUTF8(long source, int length) { + return org.lwjgl.system.MemoryUtil.memUTF8(source, length); + } + +} diff --git a/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/StackWalkUtil.java b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/StackWalkUtil.java new file mode 100644 index 00000000..8ef4ff4e --- /dev/null +++ b/src/main17/java/com/gtnewhorizon/gtnhlib/bytebuf/StackWalkUtil.java @@ -0,0 +1,111 @@ +/* + * Copyright LWJGL. All rights reserved. License terms: https://www.lwjgl.org/license + */ +package com.gtnewhorizon.gtnhlib.bytebuf; + +import static org.lwjgl.system.APIUtil.apiLog; + +import java.util.Arrays; +import java.util.Iterator; + +import org.jetbrains.annotations.Nullable; + +import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware; + +/** Java 9 version of {@code {@link StackWalkUtil }}. */ +@Lwjgl3Aware +final class StackWalkUtil { + + private static final StackWalker STACKWALKER = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); + + static { + apiLog("Java 11 stack walker enabled"); + } + + private StackWalkUtil() {} + + public static int classVersion() { + return 17; + } + + static StackTraceElement[] stackWalkArray(Object[] a) { + return Arrays.stream(((StackWalker.StackFrame[]) a)).map(StackWalker.StackFrame::toStackTraceElement) + .toArray(StackTraceElement[]::new); + } + + static Object stackWalkGetMethod(Class after) { + return STACKWALKER.walk(s -> { + Iterator iter = s.iterator(); + iter.next(); // skip this method + iter.next(); // skip MemoryStack::pop + + StackWalker.StackFrame frame; + do { + frame = iter.next(); + } while (frame.getDeclaringClass() == after && iter.hasNext()); + + return frame; + }); + } + + private static boolean isSameMethod(StackWalker.StackFrame a, StackWalker.StackFrame b) { + return isSameMethod(a, b, b.getMethodName()); + } + + private static boolean isSameMethod(StackWalker.StackFrame a, StackWalker.StackFrame b, String methodName) { + return a.getDeclaringClass() == b.getDeclaringClass() && a.getMethodName().equals(methodName); + } + + private static boolean isAutoCloseable(StackWalker.StackFrame element, StackWalker.StackFrame pushed) { + // Java 9 try-with-resources: synthetic $closeResource + if (isSameMethod(element, pushed, "$closeResource")) { + return true; + } + + // Kotlin T.use: kotlin.AutoCloseable::closeFinally + if ("kotlin.jdk7.AutoCloseableKt".equals(element.getClassName()) + && "closeFinally".equals(element.getMethodName())) { + return true; + } + + return false; + } + + static @Nullable Object stackWalkCheckPop(Class after, Object pushedObj) { + StackWalker.StackFrame pushed = (StackWalker.StackFrame) pushedObj; + + return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(s -> { + Iterator iter = s.iterator(); + iter.next(); + iter.next(); + + StackWalker.StackFrame element; + do { + element = iter.next(); + } while (element.getDeclaringClass() == after && iter.hasNext()); + + if (isSameMethod(element, pushed)) { + return null; + } + + if (iter.hasNext() && isAutoCloseable(element, pushed)) { + // 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 = iter.next(); + if (isSameMethod(element, pushed)) { + return null; + } + } + + return element; + }); + } + + static Object[] stackWalkGetTrace() { + return StackWalker.getInstance().walk( + s -> s.skip(2).dropWhile(f -> f.getClassName().startsWith("org.lwjgl.system.Memory")) + .toArray(StackWalker.StackFrame[]::new)); + } + +}