Skip to content

Commit

Permalink
Merge branch 'main' into opengl
Browse files Browse the repository at this point in the history
  • Loading branch information
squid233 committed Sep 17, 2023
2 parents 105383f + ee0459f commit 9a93173
Show file tree
Hide file tree
Showing 13 changed files with 113 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package overrungl;

import overrungl.internal.Exceptions;
import overrungl.util.MemoryUtil;

import java.lang.foreign.FunctionDescriptor;
Expand All @@ -38,7 +39,7 @@
* case 'D' -> JAVA_DOUBLE;
* case 'P' -> ADDRESS;
* case 'p' -> MemoryUtil.ADDRESS_UNBOUNDED;
* default -> throw new IllegalStateException();
* default -> throw new IllegalArgumentException();
* }}
*
* @author squid233
Expand Down Expand Up @@ -124,9 +125,7 @@ public static ValueLayout ofValue(char c) throws IllegalArgumentException {
case 'P' -> ADDRESS;
case 'p' -> MemoryUtil.ADDRESS_UNBOUNDED;
default ->
throw new IllegalArgumentException(
STR."Invalid argument c: expected one of B, S, I, J, C, Z, F, D, P or p; got '\{c}'"
);
throw Exceptions.IAE. "Invalid argument c: expected one of B, S, I, J, C, Z, F, D, P or p; got '\{ c }'" ;
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* MIT License
*
* Copyright (c) 2023 Overrun Organization
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/

package overrungl.internal;

/**
* Quick create exceptions
*
* @author squid233
* @since 0.1.0
*/
public final class Exceptions {
/**
* {@link IllegalStateException}
*/
public static final StringTemplate.Processor<IllegalStateException, RuntimeException> ISE = stringTemplate ->
new IllegalStateException(stringTemplate.interpolate());

/**
* {@link IllegalArgumentException}
*/
public static final StringTemplate.Processor<IllegalArgumentException, RuntimeException> IAE = stringTemplate ->
new IllegalArgumentException(stringTemplate.interpolate());
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public static String unknownToken(int token) {
* @return the string is formatted in {@code STR."\{description} [0x\{toHexString(token)}]"}.
*/
public static String unknownToken(String description, int token) {
return description + "[0x" + Integer.toHexString(token) + "]";
return STR. "\{ description } [0x\{ Integer.toHexString(token) }]" ;
}

/**
Expand All @@ -161,7 +161,7 @@ public static SymbolLookup load(String module, String basename, String version)
uri = localFile.toURI();
} else {
// 2. Load from classpath
var file = new File(tmpdir, "overrungl" + System.getProperty("user.name"));
var file = new File(tmpdir, STR. "overrungl\{ System.getProperty("user.name") }" );
if (!file.exists()) {
// Create directory
file.mkdir();
Expand All @@ -171,15 +171,15 @@ public static SymbolLookup load(String module, String basename, String version)
// Create directory
file.mkdir();
}
var libFile = new File(file, basename + "-" + version + suffix);
var libFile = new File(file, STR. "\{ basename }-\{ version }\{ suffix }" );
if (!libFile.exists()) {
// Extract
try (var is = STACK_WALKER.getCallerClass().getClassLoader().getResourceAsStream(
module + "/" + os.familyName() + "/" + Architecture.current() + "/" + path
STR. "\{ module }/\{ os.familyName() }/\{ Architecture.current() }/\{ path }"
)) {
Files.copy(Objects.requireNonNull(is), Path.of(libFile.getAbsolutePath()));
} catch (Exception e) {
var exception = new IllegalStateException("File not found: " + file + "; try setting property -Doverrungl.natives to a valid path");
var exception = new IllegalStateException(STR. "File not found: \{ file }; try setting property -Doverrungl.natives to a valid path" );
exception.addSuppressed(e);
throw exception;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package overrungl.os;

import overrungl.internal.Exceptions;

import java.util.Locale;

/**
Expand All @@ -29,6 +31,8 @@ public enum Architecture {
ARM64,
ARM32;

private final String toStringValue = name().toLowerCase(Locale.ROOT);

/**
* {@return the current architecture of the current {@linkplain Platform platform}}
*/
Expand All @@ -45,7 +49,7 @@ class Holder {
X64;
case Platform.MacOSX _ -> arch.startsWith("aarch64") ? ARM64 : X64;
case Platform.Windows _ when arch.contains("64") -> arch.startsWith("aarch64") ? ARM64 : X64;
default -> throw new IllegalStateException("Unrecognized or unsupported architecture: " + arch);
default -> throw Exceptions.ISE. "Unrecognized or unsupported architecture: \{ arch }" ;
};
}
}
Expand All @@ -54,6 +58,6 @@ class Holder {

@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
return toStringValue;
}
}
23 changes: 20 additions & 3 deletions modules/overrungl.core/src/main/java/overrungl/os/Platform.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package overrungl.os;

import overrungl.internal.Exceptions;

/**
* The native platform, identifying the operating system and the architecture.
*
Expand All @@ -38,7 +40,7 @@ else if (os.startsWith("Mac OS X") || os.startsWith("Darwin"))
CURRENT = MacOSX.INSTANCE;
else if (os.startsWith("Windows"))
CURRENT = Windows.INSTANCE;
else throw new IllegalStateException("Unrecognized or unsupported platform: " + os);
else throw Exceptions.ISE. "Unrecognized or unsupported platform: \{ os }" ;
}
}
return Holder.CURRENT;
Expand Down Expand Up @@ -85,6 +87,11 @@ public String sharedLibrarySuffix() {
public String sharedLibraryName(String libraryName) {
return Platform.unixSharedLibraryName(libraryName, sharedLibrarySuffix());
}

@Override
public String toString() {
return familyName();
}
}

/**
Expand All @@ -110,6 +117,11 @@ public String sharedLibrarySuffix() {
public String sharedLibraryName(String libraryName) {
return Platform.unixSharedLibraryName(libraryName, sharedLibrarySuffix());
}

@Override
public String toString() {
return familyName();
}
}

/**
Expand All @@ -135,6 +147,11 @@ public String sharedLibrarySuffix() {
public String sharedLibraryName(String libraryName) {
return Platform.withExtension(libraryName, sharedLibrarySuffix());
}

@Override
public String toString() {
return familyName();
}
}

private static String unixSharedLibraryName(String libraryName, String suffix) {
Expand All @@ -143,9 +160,9 @@ private static String unixSharedLibraryName(String libraryName, String suffix) {
}
int pos = libraryName.lastIndexOf('/');
if (pos >= 0) {
return libraryName.substring(0, pos + 1) + "lib" + libraryName.substring(pos + 1) + suffix;
return STR. "\{ libraryName.substring(0, pos + 1) }lib\{ libraryName.substring(pos + 1) }\{ suffix }" ;
}
return "lib" + libraryName + suffix;
return STR. "lib\{ libraryName }\{ suffix }" ;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public static void check(boolean condition, String message) throws IllegalStateE
* @see #checkNotNullptr(MemorySegment, String)
*/
public static void checkNotNullptr(MemorySegment segment) throws IllegalStateException {
checkNotNullptr(segment, "condition == false");
checkNotNullptr(segment, "segment is NULL");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.jetbrains.annotations.Nullable;
import overrungl.Configurations;
import overrungl.OverrunGL;
import overrungl.internal.Exceptions;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
Expand All @@ -44,22 +45,16 @@ final class DebugAllocator {
for (Allocation allocation : ALLOCATIONS.keySet()) {
StringBuilder sb = new StringBuilder(512);

sb.append("[OverrunGL] ")
.append(allocation.size)
.append(" bytes leaked, thread ")
.append(allocation.threadId)
.append(" (")
.append(THREADS.get(allocation.threadId))
.append("), address: 0x")
.append(Long.toHexString(allocation.address).toUpperCase())
.append("\n");
sb.append(STR. """
[OverrunGL] \{ allocation.size } bytes leaked,\
thread \{ allocation.threadId } (\{ THREADS.get(allocation.threadId) }),\
address: 0x\{ Long.toHexString(allocation.address).toUpperCase() }
""" );

StackTraceElement[] stackTrace = allocation.getElements();
if (stackTrace != null) {
for (Object el : stackTrace) {
sb.append("\tat ")
.append(el.toString())
.append("\n");
sb.append(STR. "\tat \{ el.toString() }\n" );
}
} else {
missingStacktrace = true;
Expand Down Expand Up @@ -104,30 +99,22 @@ private static void trackAbort(long address, Allocation allocationOld, Allocatio
trackAbortPrint(allocationOld, "Old", addressHex);
trackAbortPrint(allocationNew, "New", addressHex);

throw new IllegalStateException(STR."The memory address specified is already being tracked: 0x\{addressHex}");
throw Exceptions.ISE. "The memory address specified is already being tracked: 0x\{ addressHex }" ;
}

private static void trackAbortPrint(Allocation allocation, String name, String address) {
StringBuilder sb = new StringBuilder(512);

sb.append("[OverrunGL] ")
.append(name)
.append(" allocation with size ")
.append(allocation.size)
.append(", thread ")
.append(allocation.threadId)
.append(" (")
.append(THREADS.get(allocation.threadId))
.append("), address: 0x")
.append(address)
.append("\n");
sb.append(STR. """
[OverrunGL] \{ name } allocation with size \{ allocation.size },\
thread \{ allocation.threadId } (\{ THREADS.get(allocation.threadId) }),\
address: 0x\{ address }
""" );

StackTraceElement[] stackTrace = allocation.getElements();
if (stackTrace != null) {
for (Object el : stackTrace) {
sb.append("\tat ")
.append(el.toString())
.append("\n");
sb.append(STR. "\tat \{ el.toString() }\n" );
}
}

Expand All @@ -151,7 +138,7 @@ static long untrack(long address) {
private static void untrackAbort(long address) {
String addressHex = Long.toHexString(address).toUpperCase();

throw new IllegalStateException(STR."The memory address specified is not being tracked: 0x\{addressHex}");
throw Exceptions.ISE. "The memory address specified is not being tracked: 0x\{ addressHex }" ;
}

private record Allocation(long address, long size, long threadId, @Nullable Object[] stacktrace) {
Expand Down
2 changes: 2 additions & 0 deletions modules/overrungl.glfw/src/main/java/overrungl/glfw/GLFW.java
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,8 @@ private GLFW() {

/**
* Converts the given error code to a readable string.
* <p>
* This method is created by OverrunGL and does not belong to the original GLFW library.
*
* @param errorCode the error code.
* @return the error string.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package overrungl.glfw;

import overrungl.OverrunGL;
import overrungl.internal.Exceptions;

import java.io.PrintStream;
import java.util.function.Consumer;
Expand All @@ -37,7 +38,7 @@ private GLFWErrorCallback() {
*/
public static IGLFWErrorFun createThrow() {
return (errorCode, description) -> {
throw new IllegalStateException(String.format("GLFW error [0x%X]: %s", errorCode, description));
throw Exceptions.ISE. "GLFW error [0x\{ Integer.toHexString(errorCode) }]: \{ description }" ;
};
}

Expand All @@ -49,16 +50,10 @@ public static IGLFWErrorFun createThrow() {
public static IGLFWErrorFun createLog(Consumer<String> logger) {
return (errorCode, description) -> {
var sb = new StringBuilder(512);
sb.append("[OverrunGL] GLFW ")
.append(GLFW.getErrorString(errorCode))
.append(" error: ")
.append(description)
.append("\n");
sb.append(STR. "[OverrunGL] GLFW \{ GLFW.getErrorString(errorCode) } error: \{ description }\n" );
var stack = Thread.currentThread().getStackTrace();
for (int i = 3; i < stack.length; i++) {
sb.append(" at ")
.append(stack[i])
.append("\n");
sb.append(STR. " at \{ stack[i] }\n" );
}
logger.accept(sb.toString());
};
Expand Down
4 changes: 2 additions & 2 deletions modules/overrungl.nfd/src/main/java/overrungl/nfd/NFD.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@
* new Pair<>("Image file", "png,jpg"));
* var result = NFD.openDialogN(outPath, filterItem, null);
* switch (result) {
* case ERROR -> System.err.println("Error: " + NFD.getError());
* case OKAY -> System.out.println("Success! " + outPath[0]);
* case ERROR -> System.err.println(STR. "Error: \{ NFD.getError() }" );
* case OKAY -> System.out.println(STR. "Success! \{ outPath[0] }" );
* case CANCEL -> System.out.println("User pressed cancel.");
* }
* }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public static Tuple2<NFDResult, NFDEnumerator> fromPathSetU8(SegmentAllocator al
}

private static IllegalStateException errorIterating() {
return new IllegalStateException("Error iterating: " + NFD.getError());
return new IllegalStateException(STR. "Error iterating: \{ NFD.getError() }" );
}

@NotNull
Expand Down
Loading

0 comments on commit 9a93173

Please sign in to comment.