Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package com.jcraft.jzlib;
|
||||
|
||||
/**
|
||||
* Starts a jzlib stream over in place, keeping the buffers it allocated. jzlib can do this (zlib's
|
||||
* {@code inflateReset} and {@code deflateReset}), but only from its own package: its public API
|
||||
* offers only {@code init}, which allocates a new state (an inflate's 32 KB window and Huffman
|
||||
* tables, a deflate's 64 KB window, hash chains and pending buffer). The game resets its inflater
|
||||
* and deflater after every compressed packet, so without this each packet allocated and cleared
|
||||
* that state anew.
|
||||
*
|
||||
* <p>An Incari class (web-classlib's {@code Inflater} and {@code Deflater} substitutes call it),
|
||||
* placed in jzlib's package only to reach those two methods. jzlib's jar isn't sealed.
|
||||
*/
|
||||
public final class StreamResets {
|
||||
|
||||
private StreamResets() {}
|
||||
|
||||
/**
|
||||
* Resets an inflate stream to read a new stream of the same kind (zlib-wrapped or raw).
|
||||
*
|
||||
* @return false if it has no state to reset (ended, or never started)
|
||||
*/
|
||||
public static boolean inflate(Inflater stream) {
|
||||
Inflate state = stream.istate;
|
||||
return state != null && state.inflateReset() == JZlib.Z_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets a deflate stream to write a new stream with the level and strategy it has now.
|
||||
*
|
||||
* @return false if it has no state to reset (ended, or never started)
|
||||
*/
|
||||
public static boolean deflate(Deflater stream) {
|
||||
Deflate state = stream.dstate;
|
||||
return state != null && state.deflateReset() == JZlib.Z_OK;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package incari.classlib;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks a method in an {@code incari.classlib.additions} class that the web build adds to its
|
||||
* target class as a constructor with the same parameters. The constructor passes what the method
|
||||
* returns to the class's own one-argument constructor for that type, so the addition only works
|
||||
* out the argument ({@code String(byte[], int, int, int)} becomes {@code this(char[])}). The web
|
||||
* build refers to this annotation by name.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Constructor {}
|
||||
@@ -0,0 +1,15 @@
|
||||
package incari.classlib;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks a method in an {@code incari.classlib.additions} class that the web build adds to its
|
||||
* target class as an instance method; the first parameter is the receiver. Unmarked additions are
|
||||
* added as static methods. The web build refers to this annotation by name.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface InstanceMethod {}
|
||||
@@ -0,0 +1,40 @@
|
||||
package incari.classlib;
|
||||
|
||||
/**
|
||||
* What code the browser build strips turns into. The web build's link step replaces each
|
||||
* reference to a removed class or member (a desktop-only library, a native API) with a call to
|
||||
* {@link #reference}, so reaching it at run time fails loudly instead of the compile failing.
|
||||
*
|
||||
* <p>The web build refers to this class by name; keep its name and members stable.
|
||||
*/
|
||||
public final class Removed {
|
||||
|
||||
private Removed() {}
|
||||
|
||||
/**
|
||||
* Always throws: the calling code reached something the browser build doesn't include.
|
||||
*
|
||||
* @param symbol the class or member, as {@code pkg.Class} or {@code pkg.Class#member}
|
||||
*/
|
||||
public static void reference(String symbol) {
|
||||
throw new UnsupportedOperationException(symbol + " isn't part of the browser build");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stands in for a removed class in class literals ({@code InetAddress.class}): nothing is an
|
||||
* instance of it, so type checks against it answer no.
|
||||
*/
|
||||
public static final class Absent {
|
||||
private Absent() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stands in for an exception type the build removed, in {@code catch} clauses: nothing can
|
||||
* throw one, so the handler never runs.
|
||||
*/
|
||||
public static final class Never extends RuntimeException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Never() {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package incari.classlib;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks an addition that replaces the method TeaVM's class of the same name already has, where
|
||||
* TeaVM's behaves differently from what the browser build needs (resources from the class path
|
||||
* read from the page's file system instead of from data compiled into the module). The web build
|
||||
* refers to this annotation by name.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Replaces {}
|
||||
@@ -0,0 +1,124 @@
|
||||
package incari.classlib;
|
||||
|
||||
import incari.classlib.concurrent.Waits;
|
||||
import java.util.Arrays;
|
||||
import org.teavm.interop.PlatformMarker;
|
||||
import org.teavm.interop.Platforms;
|
||||
import org.teavm.jso.JSBody;
|
||||
|
||||
/**
|
||||
* Counts the program's throws in a build compiled with {@code -Pteavm.throwCensus} (the web build's
|
||||
* {@code ThrowCensus} transformer calls {@link #thrown} before every {@code throw}). In the page a
|
||||
* throw off the main thread costs about ten times one on it (ADR 0033), so the census counts each
|
||||
* site's throws on and off the render thread and, every ten seconds that something throws, logs
|
||||
* the busiest sites: {@code [Incari] Throws <off>/<on> at site <n> (<exception>)}, the sites'
|
||||
* methods in the build's {@code throw-sites.txt}. Development only. The web build refers to this
|
||||
* class by name.
|
||||
*/
|
||||
public final class ThrowCensus {
|
||||
|
||||
private static final long INTERVAL_MILLIS = 10_000;
|
||||
private static final int SHOWN = 15;
|
||||
|
||||
private static int[] off = new int[0];
|
||||
private static int[] on = new int[0];
|
||||
private static String[] types = new String[0];
|
||||
private static long reportAt;
|
||||
private static long totalOff;
|
||||
private static long totalOn;
|
||||
// A throw while counting one (the report's printing) isn't counted.
|
||||
private static boolean counting;
|
||||
|
||||
private ThrowCensus() {}
|
||||
|
||||
/** Before a throw at {@code site}, of {@code exception}. */
|
||||
@SuppressWarnings("ReferenceEquality") // threads are compared by identity
|
||||
public static void thrown(Object exception, int site) {
|
||||
if (counting) {
|
||||
return;
|
||||
}
|
||||
counting = true;
|
||||
try {
|
||||
count(exception, site);
|
||||
} finally {
|
||||
counting = false;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("ReferenceEquality") // threads are compared by identity
|
||||
private static void count(Object exception, int site) {
|
||||
if (site >= off.length) {
|
||||
int length = Math.max(site + 1, off.length * 2);
|
||||
off = Arrays.copyOf(off, length);
|
||||
on = Arrays.copyOf(on, length);
|
||||
types = Arrays.copyOf(types, length);
|
||||
}
|
||||
if (Thread.currentThread() == Waits.watched()) {
|
||||
on[site]++;
|
||||
totalOn++;
|
||||
} else {
|
||||
off[site]++;
|
||||
totalOff++;
|
||||
}
|
||||
if (types[site] == null) {
|
||||
types[site] = exception.getClass().getName();
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
if (reportAt == 0) {
|
||||
reportAt = now + INTERVAL_MILLIS;
|
||||
} else if (now >= reportAt) {
|
||||
report();
|
||||
reportAt = now + INTERVAL_MILLIS;
|
||||
}
|
||||
}
|
||||
|
||||
private static void report() {
|
||||
StringBuilder line = new StringBuilder(
|
||||
"[Incari] Throws in the last 10 s, off/on the render thread (since start ")
|
||||
.append(totalOff)
|
||||
.append('/')
|
||||
.append(totalOn)
|
||||
.append("):");
|
||||
boolean[] shown = new boolean[off.length];
|
||||
for (int n = 0; n < SHOWN; n++) {
|
||||
int best = -1;
|
||||
for (int site = 0; site < off.length; site++) {
|
||||
if (!shown[site]
|
||||
&& (off[site] + on[site]) > 0
|
||||
&& (best < 0 || off[site] * 10 + on[site] > off[best] * 10 + on[best])) {
|
||||
best = site;
|
||||
}
|
||||
}
|
||||
if (best < 0) {
|
||||
break;
|
||||
}
|
||||
shown[best] = true;
|
||||
line.append("\n[Incari] Throws ")
|
||||
.append(off[best])
|
||||
.append('/')
|
||||
.append(on[best])
|
||||
.append(" at site ")
|
||||
.append(best)
|
||||
.append(" (")
|
||||
.append(types[best])
|
||||
.append(')');
|
||||
}
|
||||
// To the page's console directly: the game routes System.out through its own logging.
|
||||
if (inPage()) {
|
||||
log(line.toString());
|
||||
} else {
|
||||
System.out.println(line);
|
||||
}
|
||||
Arrays.fill(off, 0);
|
||||
Arrays.fill(on, 0);
|
||||
}
|
||||
|
||||
/** True in the WebAssembly build; TeaVM replaces calls to it with the constant. */
|
||||
@PlatformMarker(Platforms.WEBASSEMBLY_GC)
|
||||
private static boolean inPage() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@JSBody(params = "message", script = "console.log(message);")
|
||||
private static native void log(String message);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package incari.classlib;
|
||||
|
||||
/**
|
||||
* What {@code StackWalker.getCallerClass} answers in the browser build, which can't see the call
|
||||
* stack's classes. Loggers named after their caller get this name instead; the game's log format
|
||||
* doesn't print logger names.
|
||||
*/
|
||||
public final class UnknownCaller {
|
||||
|
||||
private UnknownCaller() {}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package incari.classlib.additions.io.netty.util.concurrent;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.Replaces;
|
||||
|
||||
/**
|
||||
* Netty's cancellation exception for promises, {@code DefaultPromise.LeanCancellationException},
|
||||
* with a {@code fillInStackTrace} that leaves the stack empty. The class name carries the
|
||||
* nested class's binary name, as the additions transformer looks it up.
|
||||
*
|
||||
* <p>Netty's version sets a shared one-frame stack held in a {@code DefaultPromise} static. That
|
||||
* one read keeps every exception constructor in the browser build from being plain code:
|
||||
* {@code Throwable}'s constructors call {@code fillInStackTrace} virtually, TeaVM follows the call
|
||||
* to this override, then into {@code DefaultPromise}'s class initializer, which makes loggers,
|
||||
* signals and system property lookups through hot map calls that can suspend. So every exception
|
||||
* constructor became a coroutine, and with them {@code String.charAt} and the JavaScript interop's
|
||||
* string conversion, which the page calls from JavaScript while it loads: the module crashed
|
||||
* ("dereferencing a null pointer" in {@code Fiber.isResuming}). The exception is only made inside
|
||||
* {@code DefaultPromise.cancel}, so its stack is never needed to find anything.
|
||||
*/
|
||||
public final class DefaultPromise$LeanCancellationExceptionAdditions {
|
||||
|
||||
private DefaultPromise$LeanCancellationExceptionAdditions() {}
|
||||
|
||||
/** Replaces Netty's override, which reads {@code DefaultPromise}'s shared stack. */
|
||||
@Replaces
|
||||
@InstanceMethod
|
||||
public static Throwable fillInStackTrace(Throwable self) {
|
||||
return self;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package incari.classlib.additions.io.netty.util.internal.logging;
|
||||
|
||||
import incari.classlib.Replaces;
|
||||
import io.netty.util.internal.logging.InternalLoggerFactory;
|
||||
import io.netty.util.internal.logging.Slf4JLoggerFactory;
|
||||
|
||||
/**
|
||||
* Netty's logger lookup, bound to SLF4J (which the browser build binds to the console) instead of
|
||||
* probing for Log4j 2 first.
|
||||
*
|
||||
* <p>Not only tidier: Netty's first logger is made in {@code DefaultPromise}'s static initializer,
|
||||
* which one of its exceptions' {@code fillInStackTrace} triggers. Log4j's provider lookup takes a
|
||||
* lock, so with it reachable, TeaVM compiled every exception constructor, and with them
|
||||
* {@code String.charAt} and the JavaScript interop's string conversion, as coroutines, and the page
|
||||
* crashed while loading. SLF4J's binding takes no lock.
|
||||
*/
|
||||
public final class InternalLoggerFactoryAdditions {
|
||||
|
||||
private InternalLoggerFactoryAdditions() {}
|
||||
|
||||
/** Replaces Netty's private probe for a logging library. */
|
||||
@Replaces
|
||||
@SuppressWarnings("deprecation") // INSTANCE skips the NOP-binding check, which is moot here.
|
||||
public static InternalLoggerFactory newDefaultFactory(String name) {
|
||||
return Slf4JLoggerFactory.INSTANCE;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package incari.classlib.additions.java.io;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/** {@code java.io.File} methods TeaVM lacks. Both views share TeaVM's one virtual file system. */
|
||||
public final class FileAdditions {
|
||||
|
||||
private FileAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
public static Path toPath(File self) {
|
||||
return Paths.get(self.getPath());
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package incari.classlib.additions.java.io;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.Replaces;
|
||||
import incari.classlib.nio.FileChannels;
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileChannel;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
/** {@code java.io.FileInputStream} methods TeaVM lacks, or has wrong. */
|
||||
public final class FileInputStreamAdditions {
|
||||
|
||||
private FileInputStreamAdditions() {}
|
||||
|
||||
/**
|
||||
* The stream's channel, which reads through the stream and so shares its position. TeaVM's
|
||||
* stream hides its file handle, so the channel can't seek or size the file (see
|
||||
* {@code incari.classlib.nio.StreamFileChannel}).
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static TFileChannel getChannel(FileInputStream self) {
|
||||
return FileChannels.of(self);
|
||||
}
|
||||
|
||||
/**
|
||||
* The next byte, 0 to 255, or -1 at the end. TeaVM's returns the byte signed, so a byte
|
||||
* of 0x80 or more reads as negative: a {@code DataInputStream} straight over the file (the
|
||||
* game's {@code NbtIo.read(Path)}, which reads {@code servers.dat}) took it for the end.
|
||||
*/
|
||||
@InstanceMethod
|
||||
@Replaces
|
||||
public static int read(FileInputStream self) throws IOException {
|
||||
byte[] one = new byte[1];
|
||||
return self.read(one, 0, 1) == 1 ? one[0] & 0xFF : -1;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package incari.classlib.additions.java.io;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.nio.FileChannels;
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileChannel;
|
||||
import java.io.FileOutputStream;
|
||||
|
||||
/** {@code java.io.FileOutputStream} methods TeaVM lacks. */
|
||||
public final class FileOutputStreamAdditions {
|
||||
|
||||
private FileOutputStreamAdditions() {}
|
||||
|
||||
/**
|
||||
* The stream's channel, which writes through the stream and so shares its position. TeaVM's
|
||||
* stream hides its file handle, so the channel can't seek or size the file (see
|
||||
* {@code incari.classlib.nio.StreamFileChannel}); locking works.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static TFileChannel getChannel(FileOutputStream self) {
|
||||
return FileChannels.of(self);
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package incari.classlib.additions.java.io;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.nio.FileChannels;
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileChannel;
|
||||
import java.io.RandomAccessFile;
|
||||
|
||||
/** {@code java.io.RandomAccessFile} methods TeaVM lacks. */
|
||||
public final class RandomAccessFileAdditions {
|
||||
|
||||
private RandomAccessFileAdditions() {}
|
||||
|
||||
/**
|
||||
* The file's channel, whose position is the file's pointer. Closing the channel closes the
|
||||
* file; closing the file is only noticed by the channel's next operation, which fails.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static TFileChannel getChannel(RandomAccessFile self) {
|
||||
return FileChannels.of(self);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package incari.classlib.additions.java.io;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
|
||||
/** {@code java.io.Reader} methods TeaVM lacks. */
|
||||
public final class ReaderAdditions {
|
||||
|
||||
private ReaderAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
public static long transferTo(Reader self, Writer out) throws IOException {
|
||||
char[] buffer = new char[8192];
|
||||
long total = 0;
|
||||
int read;
|
||||
while ((read = self.read(buffer)) >= 0) {
|
||||
out.write(buffer, 0, read);
|
||||
total += read;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static String readAllAsString(Reader self) throws IOException {
|
||||
StringBuilder text = new StringBuilder();
|
||||
char[] buffer = new char[8192];
|
||||
int read;
|
||||
while ((read = self.read(buffer)) >= 0) {
|
||||
text.append(buffer, 0, read);
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
/** {@code java.lang.Character} methods TeaVM lacks. */
|
||||
public final class CharacterAdditions {
|
||||
|
||||
private CharacterAdditions() {}
|
||||
|
||||
public static String toString(int codePoint) {
|
||||
return new String(Character.toChars(codePoint));
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks a character up by its Unicode name. The browser build carries no Unicode name table, so
|
||||
* every name is unknown; SNBT's {@code \N{...}} escapes fail to parse, as an unknown name would.
|
||||
*/
|
||||
public static int codePointOf(String name) {
|
||||
throw new IllegalArgumentException("Unrecognized character name: " + name);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.reflect.GenericSuperclasses;
|
||||
import incari.classlib.resources.ClassPathResources;
|
||||
import incari.classlib.substitutes.java.lang.TModule;
|
||||
import java.lang.reflect.Type;
|
||||
import java.net.URL;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* {@code java.lang.Class} methods TeaVM lacks. The browser build keeps no signers and few generic
|
||||
* signatures, so these answer as a class without them would; resources come from
|
||||
* {@link ClassPathResources}.
|
||||
*/
|
||||
public final class ClassAdditions {
|
||||
|
||||
private ClassAdditions() {}
|
||||
|
||||
/**
|
||||
* The generic superclass where the build kept it (type capture: {@link GenericSuperclasses}),
|
||||
* otherwise the raw one.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static @Nullable Type getGenericSuperclass(Class<?> self) {
|
||||
Type kept = GenericSuperclasses.of(self);
|
||||
return kept != null ? kept : self.getSuperclass();
|
||||
}
|
||||
|
||||
/**
|
||||
* The one module a page has ({@link TModule}). The game's profiler asks for {@code jdk.jfr}
|
||||
* through it, which it doesn't find (the first packet sent reaches the profiler).
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static TModule getModule(Class<?> self) {
|
||||
return TModule.PROGRAM;
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static Type[] getGenericInterfaces(Class<?> self) {
|
||||
return self.getInterfaces();
|
||||
}
|
||||
|
||||
/** A {@code file:} URL into the page's copy of the class path's resources. */
|
||||
@InstanceMethod
|
||||
public static @Nullable URL getResource(Class<?> self, String name) {
|
||||
return ClassPathResources.url(ClassPathResources.find(self, name));
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static Object @Nullable [] getSigners(Class<?> self) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static boolean isAnonymousClass(Class<?> self) {
|
||||
return self.getSimpleName().isEmpty();
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.Replaces;
|
||||
import incari.classlib.resources.ClassPathResources;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* {@code java.lang.ClassLoader} methods TeaVM lacks. A compiled page has one fixed set of classes,
|
||||
* so classes can't be looked up by name; resources come from {@link ClassPathResources}.
|
||||
*/
|
||||
public final class ClassLoaderAdditions {
|
||||
|
||||
private ClassLoaderAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
public static @Nullable URL getResource(ClassLoader self, String name) {
|
||||
return ClassPathResources.url(ClassPathResources.find(name));
|
||||
}
|
||||
|
||||
public static @Nullable URL getSystemResource(String name) {
|
||||
return ClassPathResources.url(ClassPathResources.find(name));
|
||||
}
|
||||
|
||||
/** TeaVM's reads resources compiled into the module; the game's are in the file system. */
|
||||
@InstanceMethod
|
||||
@Replaces
|
||||
public static @Nullable InputStream getResourceAsStream(ClassLoader self, String name) {
|
||||
return ClassPathResources.open(ClassPathResources.find(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing: the game looks for extra resource roots this way and uses only {@code file:} ones,
|
||||
* while on desktop it finds the jar's ({@code jar:}), so the answer that matches is none. The
|
||||
* jar's own root comes through {@link #getResource}.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static Enumeration<URL> getResources(ClassLoader self, String name) {
|
||||
return Collections.emptyEnumeration();
|
||||
}
|
||||
|
||||
public static Enumeration<URL> getSystemResources(String name) {
|
||||
return Collections.emptyEnumeration();
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static Class<?> loadClass(ClassLoader self, String name) throws ClassNotFoundException {
|
||||
throw new ClassNotFoundException(name + " (classes can't be loaded by name in the browser build)");
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
/** {@code java.lang.Integer} methods TeaVM lacks. */
|
||||
public final class IntegerAdditions {
|
||||
|
||||
private IntegerAdditions() {}
|
||||
|
||||
public static int parseUnsignedInt(String text, int radix) {
|
||||
if (text.startsWith("-")) {
|
||||
throw new NumberFormatException("Illegal leading minus sign on unsigned string " + text + ".");
|
||||
}
|
||||
long value = Long.parseLong(text, radix);
|
||||
if ((value & 0xFFFF_FFFF_0000_0000L) != 0) {
|
||||
throw new NumberFormatException("String value " + text + " exceeds range of unsigned int.");
|
||||
}
|
||||
return (int) value;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
/** {@code java.lang.Long} methods TeaVM lacks. */
|
||||
public final class LongAdditions {
|
||||
|
||||
private LongAdditions() {}
|
||||
|
||||
private static final BigInteger LIMIT = BigInteger.ONE.shiftLeft(64);
|
||||
|
||||
public static long parseUnsignedLong(String text, int radix) {
|
||||
if (text.startsWith("-")) {
|
||||
throw new NumberFormatException("Illegal leading minus sign on unsigned string " + text + ".");
|
||||
}
|
||||
BigInteger value = new BigInteger(text, radix);
|
||||
if (value.compareTo(LIMIT) >= 0) {
|
||||
throw new NumberFormatException("String value " + text + " exceeds range of unsigned long.");
|
||||
}
|
||||
return value.longValue();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
/** {@code java.lang.Math} methods TeaVM lacks. */
|
||||
public final class MathAdditions {
|
||||
|
||||
private MathAdditions() {}
|
||||
|
||||
/**
|
||||
* {@code a * b + c}. Not fused: WebAssembly has no fused multiply-add, so this rounds twice. The
|
||||
* callers (JOML) use it for speed, not for the single rounding.
|
||||
*/
|
||||
public static double fma(double a, double b, double c) {
|
||||
return a * b + c;
|
||||
}
|
||||
|
||||
/** {@code a * b + c}, computed in double, which is exact for the product of two floats. */
|
||||
public static float fma(float a, float b, float c) {
|
||||
return (float) ((double) a * (double) b + (double) c);
|
||||
}
|
||||
|
||||
public static int powExact(int base, int exponent) {
|
||||
if (exponent < 0) {
|
||||
throw new ArithmeticException("negative exponent");
|
||||
}
|
||||
int result = 1;
|
||||
for (int i = 0; i < exponent; i++) {
|
||||
result = Math.multiplyExact(result, base);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.Replaces;
|
||||
import incari.classlib.memory.PageHeap;
|
||||
|
||||
/** {@code java.lang.Runtime} methods TeaVM lacks, and its memory figures from the page's heap. */
|
||||
public final class RuntimeAdditions {
|
||||
|
||||
private RuntimeAdditions() {}
|
||||
|
||||
/** A page has no shutdown to hook; closing the tab just stops it. The hook never runs. */
|
||||
@InstanceMethod
|
||||
public static void addShutdownHook(Runtime self, Thread hook) {}
|
||||
|
||||
/** The heap's ceiling, where the browser reports it ({@link PageHeap}). */
|
||||
@InstanceMethod
|
||||
public static long maxMemory(Runtime self) {
|
||||
return PageHeap.max();
|
||||
}
|
||||
|
||||
/** TeaVM reports {@link Integer#MAX_VALUE} on WebAssembly GC; the page's heap is known. */
|
||||
@InstanceMethod
|
||||
@Replaces
|
||||
public static long totalMemory(Runtime self) {
|
||||
return PageHeap.total();
|
||||
}
|
||||
|
||||
/** TeaVM reports {@link Integer#MAX_VALUE} (all of it free); the page's heap is known. */
|
||||
@InstanceMethod
|
||||
@Replaces
|
||||
public static long freeMemory(Runtime self) {
|
||||
return PageHeap.free();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
|
||||
/** {@code java.lang.SecurityManager} methods TeaVM lacks. */
|
||||
@SuppressWarnings("removal") // The libraries that still call it are what this serves.
|
||||
public final class SecurityManagerAdditions {
|
||||
|
||||
private SecurityManagerAdditions() {}
|
||||
|
||||
/** The browser build can't see the call stack's classes; callers treat none as unknown. */
|
||||
@InstanceMethod
|
||||
public static Class<?>[] getClassContext(SecurityManager self) {
|
||||
return new Class<?>[0];
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import incari.classlib.Constructor;
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** {@code java.lang.String} methods TeaVM lacks. */
|
||||
public final class StringAdditions {
|
||||
|
||||
private StringAdditions() {}
|
||||
|
||||
/**
|
||||
* {@code String(byte[] ascii, int hibyte, int offset, int count)}: each byte is a character's
|
||||
* low eight bits and {@code hibyte} the high eight. Deprecated in the JDK, but Netty's
|
||||
* {@code ByteBufUtil} decodes ASCII and Latin-1 with it.
|
||||
*/
|
||||
@Constructor
|
||||
public static char[] characters(byte[] ascii, int hibyte, int offset, int count) {
|
||||
if (offset < 0 || count < 0 || offset > ascii.length - count) {
|
||||
throw new StringIndexOutOfBoundsException(
|
||||
"offset " + offset + ", count " + count + ", length " + ascii.length);
|
||||
}
|
||||
char high = (char) ((hibyte & 0xFF) << 8);
|
||||
char[] characters = new char[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
characters[i] = (char) (high | (ascii[offset + i] & 0xFF));
|
||||
}
|
||||
return characters;
|
||||
}
|
||||
|
||||
/** The lines of the string, split at {@code \n}, {@code \r} or {@code \r\n}. */
|
||||
@InstanceMethod
|
||||
public static Stream<String> lines(String self) {
|
||||
if (self.isEmpty()) {
|
||||
return Stream.empty();
|
||||
}
|
||||
String[] parts = self.split("\r\n|\r|\n", -1);
|
||||
char last = self.charAt(self.length() - 1);
|
||||
// A trailing line terminator ends the last line rather than starting an empty one.
|
||||
int count = last == '\n' || last == '\r' ? parts.length - 1 : parts.length;
|
||||
return Arrays.stream(parts, 0, count);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
/** {@code java.lang.System} methods TeaVM lacks. */
|
||||
public final class SystemAdditions {
|
||||
|
||||
private SystemAdditions() {}
|
||||
|
||||
/**
|
||||
* A page can't end its own process. Exiting stops the calling thread for good (the game's main
|
||||
* thread, in practice), which halts the game where a desktop JVM would have exited; the page
|
||||
* stays open with the console log.
|
||||
*/
|
||||
@SuppressWarnings("InfiniteLoopStatement") // Never returning is the point.
|
||||
public static void exit(int status) {
|
||||
// tools/webbuild's BrowserCheck watches for this line.
|
||||
System.err.println("Java exited with status " + status);
|
||||
Object never = new Object();
|
||||
synchronized (never) {
|
||||
while (true) {
|
||||
try {
|
||||
never.wait();
|
||||
} catch (InterruptedException e) {
|
||||
// Still exited.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** No native libraries in a page; the name is only ever logged or compared. */
|
||||
public static String mapLibraryName(String name) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package incari.classlib.additions.java.lang;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.time.Duration;
|
||||
|
||||
/** {@code java.lang.Thread} methods TeaVM lacks. */
|
||||
public final class ThreadAdditions {
|
||||
|
||||
private ThreadAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
@SuppressWarnings("deprecation") // getId is the same number; threadId is what callers use now.
|
||||
public static long threadId(Thread self) {
|
||||
return self.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* A spin-wait hint. In a page, threads are coroutines that only switch when one yields, so a
|
||||
* spinning thread must yield or the thread it waits for never runs.
|
||||
*/
|
||||
@SuppressWarnings("ThreadPriorityCheck") // Yielding is the only way another coroutine runs.
|
||||
public static void onSpinWait() {
|
||||
Thread.yield();
|
||||
}
|
||||
|
||||
public static void sleep(Duration duration) throws InterruptedException {
|
||||
Thread.sleep(Math.max(0L, duration.toMillis()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing to set: a page has one class loader, which every thread already uses. Netty sets it
|
||||
* on its helper threads.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static void setContextClassLoader(Thread self, ClassLoader loader) {}
|
||||
|
||||
/**
|
||||
* Whether the thread is alive is all TeaVM's {@code Thread} tracks: a live one is runnable (a
|
||||
* coroutine is either running or ready to), any other terminated, including one never started.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static Thread.State getState(Thread self) {
|
||||
return self.isAlive() ? Thread.State.RUNNABLE : Thread.State.TERMINATED;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package incari.classlib.additions.java.lang.reflect;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
/** {@code java.lang.reflect.Array} methods TeaVM lacks. */
|
||||
public final class ArrayAdditions {
|
||||
|
||||
private ArrayAdditions() {}
|
||||
|
||||
/** A multi-dimensional array, built one dimension at a time from the one-dimensional form. */
|
||||
public static Object newInstance(Class<?> componentType, int... dimensions) {
|
||||
if (dimensions.length == 0) {
|
||||
throw new IllegalArgumentException("Empty dimensions array");
|
||||
}
|
||||
return create(componentType, dimensions, 0);
|
||||
}
|
||||
|
||||
private static Object create(Class<?> componentType, int[] dimensions, int index) {
|
||||
if (index == dimensions.length - 1) {
|
||||
return Array.newInstance(componentType, dimensions[index]);
|
||||
}
|
||||
Class<?> elementType = componentType;
|
||||
for (int i = index + 1; i < dimensions.length; i++) {
|
||||
elementType = Array.newInstance(elementType, 0).getClass();
|
||||
}
|
||||
Object array = Array.newInstance(elementType, dimensions[index]);
|
||||
for (int i = 0; i < dimensions[index]; i++) {
|
||||
Array.set(array, i, create(componentType, dimensions, index + 1));
|
||||
}
|
||||
return array;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package incari.classlib.additions.java.nio;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/** {@code java.nio.ByteBuffer} methods TeaVM lacks. */
|
||||
public final class ByteBufferAdditions {
|
||||
|
||||
private ByteBufferAdditions() {}
|
||||
|
||||
/** The {@code length} bytes from {@code index}, sharing content; this buffer is unchanged. */
|
||||
@InstanceMethod
|
||||
public static ByteBuffer slice(ByteBuffer self, int index, int length) {
|
||||
ByteBuffer view = self.duplicate();
|
||||
view.limit(index + length).position(index);
|
||||
return view.slice();
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package incari.classlib.additions.java.nio.file;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.util.Globs;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.PathMatcher;
|
||||
import java.nio.file.WatchService;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** {@code java.nio.file.FileSystem} methods TeaVM lacks. */
|
||||
public final class FileSystemAdditions {
|
||||
|
||||
private FileSystemAdditions() {}
|
||||
|
||||
/** Matches paths against {@code glob:} or {@code regex:} patterns, as the JDK documents. */
|
||||
@InstanceMethod
|
||||
public static PathMatcher getPathMatcher(FileSystem self, String syntaxAndPattern) {
|
||||
int colon = syntaxAndPattern.indexOf(':');
|
||||
if (colon <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
String syntax = syntaxAndPattern.substring(0, colon);
|
||||
String pattern = syntaxAndPattern.substring(colon + 1);
|
||||
Pattern regex;
|
||||
if (syntax.equalsIgnoreCase("glob")) {
|
||||
regex = Pattern.compile(Globs.toRegex(pattern));
|
||||
} else if (syntax.equalsIgnoreCase("regex")) {
|
||||
regex = Pattern.compile(pattern);
|
||||
} else {
|
||||
throw new UnsupportedOperationException("Syntax '" + syntax + "' not recognized");
|
||||
}
|
||||
return path -> regex.matcher(path.toString()).matches();
|
||||
}
|
||||
|
||||
/** Nothing outside the page changes its files, so there's nothing to watch for. */
|
||||
@InstanceMethod
|
||||
public static WatchService newWatchService(FileSystem self) throws IOException {
|
||||
throw new IOException("The browser's file system can't be watched");
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package incari.classlib.additions.java.nio.file;
|
||||
|
||||
import incari.classlib.Replaces;
|
||||
import incari.classlib.nio.FileChannels;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
import java.nio.file.FileStore;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.nio.file.attribute.FileAttributeView;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.UserPrincipal;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* {@code java.nio.file.Files} methods TeaVM lacks. The browser's storage is TeaVM's virtual file
|
||||
* system: files and directories with modification times, and nothing more (no stores, links,
|
||||
* owners or permissions), so those answer as a file system without them does.
|
||||
*/
|
||||
public final class FilesAdditions {
|
||||
|
||||
private FilesAdditions() {}
|
||||
|
||||
/** The page's storage isn't a disk with stores; callers report the space as unknown. */
|
||||
public static FileStore getFileStore(Path path) throws IOException {
|
||||
throw new IOException("No file stores in the browser");
|
||||
}
|
||||
|
||||
/**
|
||||
* The files under {@code start}, depth first, that {@code matcher} accepts. Replaces TeaVM's,
|
||||
* which fails with a {@code NullPointerException} when a directory itself doesn't match and
|
||||
* lists matching subtrees twice. The page's file system has no links to follow.
|
||||
*/
|
||||
@Replaces
|
||||
public static Stream<Path> find(
|
||||
Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption... options)
|
||||
throws IOException {
|
||||
BasicFileAttributes attributes = Files.readAttributes(start, BasicFileAttributes.class);
|
||||
Stream<Path> self = matcher.test(start, attributes) ? Stream.of(start) : Stream.empty();
|
||||
if (maxDepth <= 0 || !attributes.isDirectory()) {
|
||||
return self;
|
||||
}
|
||||
List<Path> children;
|
||||
try (Stream<Path> listing = Files.list(start)) {
|
||||
children = listing.collect(Collectors.toList());
|
||||
}
|
||||
return Stream.concat(self, children.stream().flatMap(child -> {
|
||||
try {
|
||||
return find(child, maxDepth - 1, matcher);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/** Files in the page's storage have no owners; callers treat that as an unreadable property. */
|
||||
public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException {
|
||||
throw new IOException("No file owners in the browser");
|
||||
}
|
||||
|
||||
public static @Nullable String probeContentType(Path path) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A {@code FileChannel} over TeaVM's virtual file system (see {@link FileChannels}). */
|
||||
public static SeekableByteChannel newByteChannel(
|
||||
Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
|
||||
return FileChannels.open(path, options, attrs);
|
||||
}
|
||||
|
||||
public static SeekableByteChannel newByteChannel(Path path, OpenOption... options) throws IOException {
|
||||
return FileChannels.open(path, new HashSet<>(Arrays.asList(options)));
|
||||
}
|
||||
|
||||
public static Path setLastModifiedTime(Path path, FileTime time) throws IOException {
|
||||
if (!path.toFile().setLastModified(time.toMillis())) {
|
||||
throw new IOException("Couldn't set the modification time of " + path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public static Path createLink(Path link, Path existing) throws IOException {
|
||||
throw new UnsupportedOperationException("The browser's file system has no links");
|
||||
}
|
||||
|
||||
public static Set<PosixFilePermission> getPosixFilePermissions(Path path, LinkOption... options) {
|
||||
throw new UnsupportedOperationException("The browser's file system has no permissions");
|
||||
}
|
||||
|
||||
public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> permissions) {
|
||||
throw new UnsupportedOperationException("The browser's file system has no permissions");
|
||||
}
|
||||
|
||||
/** Only the basic attributes exist; views of any kind aren't available. */
|
||||
public static <V extends FileAttributeView> @Nullable V getFileAttributeView(
|
||||
Path path, Class<V> type, LinkOption... options) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The basic attributes by name ({@code basic:size}, {@code lastModifiedTime}...). */
|
||||
public static @Nullable Object getAttribute(Path path, String attribute, LinkOption... options) throws IOException {
|
||||
int colon = attribute.indexOf(':');
|
||||
String view = colon < 0 ? "basic" : attribute.substring(0, colon);
|
||||
String name = attribute.substring(colon + 1);
|
||||
if (!view.equals("basic")) {
|
||||
throw new UnsupportedOperationException("View '" + view + "' not available");
|
||||
}
|
||||
return switch (name) {
|
||||
case "size" -> Files.size(path);
|
||||
case "lastModifiedTime", "lastAccessTime", "creationTime" -> Files.getLastModifiedTime(path);
|
||||
case "isDirectory" -> Files.isDirectory(path);
|
||||
case "isRegularFile" -> Files.isRegularFile(path);
|
||||
case "isSymbolicLink" -> false;
|
||||
case "isOther" -> false;
|
||||
case "fileKey" -> null;
|
||||
default -> throw new IllegalArgumentException("'" + name + "' not recognized");
|
||||
};
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package incari.classlib.additions.java.nio.file;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.WatchEvent;
|
||||
import java.nio.file.WatchKey;
|
||||
import java.nio.file.WatchService;
|
||||
|
||||
/** {@code java.nio.file.Path} methods TeaVM lacks. */
|
||||
public final class PathAdditions {
|
||||
|
||||
private PathAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
public static Path resolve(Path self, String first, String... more) {
|
||||
Path result = self.resolve(first);
|
||||
for (String part : more) {
|
||||
result = result.resolve(part);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** No watch service exists in the browser build to register with. */
|
||||
@InstanceMethod
|
||||
public static WatchKey register(Path self, WatchService watcher, WatchEvent.Kind<?>... events) throws IOException {
|
||||
throw new IOException("The browser's file system can't be watched");
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package incari.classlib.additions.java.time;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.time.Duration;
|
||||
|
||||
/** {@code java.time.Duration} methods newer than ThreeTen Backport, which the browser build uses. */
|
||||
public final class DurationAdditions {
|
||||
|
||||
private DurationAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
public static boolean isPositive(Duration self) {
|
||||
return !self.isNegative() && !self.isZero();
|
||||
}
|
||||
|
||||
/** The whole seconds, as {@code getSeconds} (the game's world-unload telemetry). */
|
||||
@InstanceMethod
|
||||
@SuppressWarnings("JavaDurationGetSecondsToToSeconds") // This is toSeconds, for a library without it.
|
||||
public static long toSeconds(Duration self) {
|
||||
return self.getSeconds();
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package incari.classlib.additions.java.util;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* {@code java.util.Base64} methods TeaVM lacks. Approximate: the MIME coders here are the basic
|
||||
* ones, without line breaks and without skipping them when decoding. Their only callers are the
|
||||
* online-mode key parsing the browser build doesn't use.
|
||||
*/
|
||||
public final class Base64Additions {
|
||||
|
||||
private Base64Additions() {}
|
||||
|
||||
public static Base64.Decoder getMimeDecoder() {
|
||||
return Base64.getDecoder();
|
||||
}
|
||||
|
||||
public static Base64.Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) {
|
||||
return Base64.getEncoder();
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package incari.classlib.additions.java.util;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.SortedSet;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** {@code java.util.Collections} methods TeaVM lacks. */
|
||||
public final class CollectionsAdditions {
|
||||
|
||||
private CollectionsAdditions() {}
|
||||
|
||||
public static <K, V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> map) {
|
||||
return new UnmodifiableSortedMap<>(map);
|
||||
}
|
||||
|
||||
public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> set) {
|
||||
return new UnmodifiableSortedSet<>(set);
|
||||
}
|
||||
|
||||
/** A read-only view of a sorted set; its subsets are read-only views too. */
|
||||
private static final class UnmodifiableSortedSet<T> extends java.util.AbstractSet<T> implements SortedSet<T> {
|
||||
private final SortedSet<T> set;
|
||||
|
||||
UnmodifiableSortedSet(SortedSet<T> set) {
|
||||
this.set = set;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Comparator<? super T> comparator() {
|
||||
return set.comparator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedSet<T> subSet(T fromElement, T toElement) {
|
||||
return new UnmodifiableSortedSet<>(set.subSet(fromElement, toElement));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedSet<T> headSet(T toElement) {
|
||||
return new UnmodifiableSortedSet<>(set.headSet(toElement));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedSet<T> tailSet(T fromElement) {
|
||||
return new UnmodifiableSortedSet<>(set.tailSet(fromElement));
|
||||
}
|
||||
|
||||
@Override
|
||||
public T first() {
|
||||
return set.first();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T last() {
|
||||
return set.last();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return set.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(@Nullable Object element) {
|
||||
return set.contains(element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.Iterator<T> iterator() {
|
||||
return Collections.unmodifiableCollection(set).iterator();
|
||||
}
|
||||
}
|
||||
|
||||
/** A read-only view of a sorted map; its sub-maps are read-only views too. */
|
||||
private static final class UnmodifiableSortedMap<K, V> extends java.util.AbstractMap<K, V>
|
||||
implements SortedMap<K, V> {
|
||||
private final SortedMap<K, ? extends V> map;
|
||||
|
||||
UnmodifiableSortedMap(SortedMap<K, ? extends V> map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Comparator<? super K> comparator() {
|
||||
return map.comparator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedMap<K, V> subMap(K fromKey, K toKey) {
|
||||
return new UnmodifiableSortedMap<>(map.subMap(fromKey, toKey));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedMap<K, V> headMap(K toKey) {
|
||||
return new UnmodifiableSortedMap<>(map.headMap(toKey));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SortedMap<K, V> tailMap(K fromKey) {
|
||||
return new UnmodifiableSortedMap<>(map.tailMap(fromKey));
|
||||
}
|
||||
|
||||
@Override
|
||||
public K firstKey() {
|
||||
return map.firstKey();
|
||||
}
|
||||
|
||||
@Override
|
||||
public K lastKey() {
|
||||
return map.lastKey();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return map.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsKey(@Nullable Object key) {
|
||||
return map.containsKey(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable V get(@Nullable Object key) {
|
||||
return map.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<K> keySet() {
|
||||
return Collections.unmodifiableSet(map.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<V> values() {
|
||||
return Collections.unmodifiableCollection(map.values());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked") // Read-only, so widening the value type is safe.
|
||||
public Set<Map.Entry<K, V>> entrySet() {
|
||||
return Collections.unmodifiableMap((Map<K, V>) map).entrySet();
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package incari.classlib.additions.java.util;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
/** {@code java.util.Date} methods TeaVM lacks: the bridges to {@code java.time}. */
|
||||
@SuppressWarnings("JavaUtilDate") // These are Date's own methods.
|
||||
public final class DateAdditions {
|
||||
|
||||
private DateAdditions() {}
|
||||
|
||||
public static Date from(Instant instant) {
|
||||
return new Date(instant.toEpochMilli());
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static Instant toInstant(Date self) {
|
||||
return Instant.ofEpochMilli(self.getTime());
|
||||
}
|
||||
|
||||
/** {@code EEE MMM dd HH:mm:ss zzz yyyy}, as the JDK prints a date. */
|
||||
@InstanceMethod
|
||||
public static String toString(Date self) {
|
||||
return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).format(self);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package incari.classlib.additions.java.util;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.util.Locale;
|
||||
|
||||
/** {@code java.util.Locale} methods TeaVM lacks. */
|
||||
public final class LocaleAdditions {
|
||||
|
||||
private LocaleAdditions() {}
|
||||
|
||||
/**
|
||||
* The language, region and variant of a BCP 47 tag ({@code en-US}); extensions and private-use
|
||||
* parts are dropped, and {@code und} is the root locale.
|
||||
*/
|
||||
public static Locale forLanguageTag(String tag) {
|
||||
String[] parts = tag.split("[-_]", -1);
|
||||
String language = parts.length > 0 && !parts[0].equals("und") ? parts[0] : "";
|
||||
String country = "";
|
||||
String variant = "";
|
||||
int i = 1;
|
||||
if (i < parts.length && parts[i].length() == 4 && Character.isLetter(parts[i].charAt(0))) {
|
||||
i++; // A script subtag, which TeaVM's Locale doesn't carry.
|
||||
}
|
||||
if (i < parts.length && (parts[i].length() == 2 || (parts[i].length() == 3 && isDigits(parts[i])))) {
|
||||
country = parts[i++];
|
||||
}
|
||||
// BCP 47 variants: five to eight characters, or four starting with a digit.
|
||||
if (i < parts.length
|
||||
&& (parts[i].length() >= 5 || (parts[i].length() == 4 && Character.isDigit(parts[i].charAt(0))))) {
|
||||
variant = parts[i];
|
||||
}
|
||||
return Locale.of(language, country, variant);
|
||||
}
|
||||
|
||||
/** The browser build carries no ISO 3166 table; callers treat an empty code as unknown. */
|
||||
@InstanceMethod
|
||||
public static String getISO3Country(Locale self) {
|
||||
return "";
|
||||
}
|
||||
|
||||
private static boolean isDigits(String text) {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
if (!Character.isDigit(text.charAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package incari.classlib.additions.java.util;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.PrimitiveIterator;
|
||||
import java.util.Spliterator;
|
||||
import java.util.function.IntConsumer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** {@code java.util.Spliterators} methods TeaVM lacks. */
|
||||
public final class SpliteratorsAdditions {
|
||||
|
||||
private SpliteratorsAdditions() {}
|
||||
|
||||
public static <T> Spliterator<T> emptySpliterator() {
|
||||
return java.util.Spliterators.spliterator(new Object[0], Spliterator.SIZED | Spliterator.SUBSIZED);
|
||||
}
|
||||
|
||||
public static <T extends @Nullable Object> Iterator<T> iterator(Spliterator<? extends T> spliterator) {
|
||||
return new Iterator<>() {
|
||||
private boolean ready;
|
||||
private @Nullable T next;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if (!ready) {
|
||||
ready = spliterator.tryAdvance(value -> next = value);
|
||||
}
|
||||
return ready;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("NullAway") // next holds what tryAdvance gave, which is a T.
|
||||
public T next() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
ready = false;
|
||||
return next;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static PrimitiveIterator.OfInt iterator(Spliterator.OfInt spliterator) {
|
||||
return new PrimitiveIterator.OfInt() {
|
||||
private boolean ready;
|
||||
private int next;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if (!ready) {
|
||||
ready = spliterator.tryAdvance((IntConsumer) this::take);
|
||||
}
|
||||
return ready;
|
||||
}
|
||||
|
||||
private void take(int value) {
|
||||
next = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int nextInt() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
ready = false;
|
||||
return next;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package incari.classlib.additions.java.util.concurrent;
|
||||
|
||||
import incari.classlib.substitutes.java.util.concurrent.TConcurrentHashMap$KeySetView;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* {@code java.util.concurrent.ConcurrentHashMap} methods TeaVM lacks. They name the class library's
|
||||
* {@code KeySetView} directly; the web build maps that name to the JDK's in this class too.
|
||||
*/
|
||||
public final class ConcurrentHashMapAdditions {
|
||||
|
||||
private ConcurrentHashMapAdditions() {}
|
||||
|
||||
public static <K> TConcurrentHashMap$KeySetView<K, Boolean> newKeySet() {
|
||||
return new TConcurrentHashMap$KeySetView<>(new ConcurrentHashMap<>(), Boolean.TRUE);
|
||||
}
|
||||
|
||||
public static <K> TConcurrentHashMap$KeySetView<K, Boolean> newKeySet(int initialCapacity) {
|
||||
return new TConcurrentHashMap$KeySetView<>(new ConcurrentHashMap<>(initialCapacity), Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package incari.classlib.additions.java.util.concurrent;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** {@code java.util.concurrent.TimeUnit} methods TeaVM lacks. */
|
||||
public final class TimeUnitAdditions {
|
||||
|
||||
private static final long NANOS_PER_SECOND = 1_000_000_000L;
|
||||
|
||||
private TimeUnitAdditions() {}
|
||||
|
||||
/**
|
||||
* {@code duration} in {@code self}'s unit, truncated toward zero and saturated at
|
||||
* {@code Long.MIN_VALUE} or {@code Long.MAX_VALUE}, as {@code TimeUnit.convert(Duration)}.
|
||||
*/
|
||||
@InstanceMethod
|
||||
public static long convert(TimeUnit self, Duration duration) {
|
||||
long seconds = duration.getSeconds();
|
||||
long nanos = duration.getNano();
|
||||
// Negative durations keep a positive nano part; move it so both parts share a sign and
|
||||
// each converts toward zero.
|
||||
if (seconds < 0 && nanos > 0) {
|
||||
seconds++;
|
||||
nanos -= NANOS_PER_SECOND;
|
||||
}
|
||||
long whole = self.convert(seconds, TimeUnit.SECONDS);
|
||||
if (whole == Long.MAX_VALUE || whole == Long.MIN_VALUE) {
|
||||
return whole;
|
||||
}
|
||||
long part = self.convert(nanos, TimeUnit.NANOSECONDS);
|
||||
long sum = whole + part;
|
||||
// Overflow happened if both operands share a sign the sum doesn't.
|
||||
if (((whole ^ sum) & (part ^ sum)) < 0) {
|
||||
return whole < 0 ? Long.MIN_VALUE : Long.MAX_VALUE;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package incari.classlib.additions.java.util.regex;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** {@code java.util.regex.Pattern} methods TeaVM lacks. */
|
||||
public final class PatternAdditions {
|
||||
|
||||
private PatternAdditions() {}
|
||||
|
||||
@InstanceMethod
|
||||
public static Predicate<String> asPredicate(Pattern self) {
|
||||
return text -> self.matcher(text).find();
|
||||
}
|
||||
|
||||
@InstanceMethod
|
||||
public static Predicate<String> asMatchPredicate(Pattern self) {
|
||||
return text -> self.matcher(text).matches();
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package incari.classlib.additions.java.util.stream;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
/**
|
||||
* {@code java.util.stream.StreamSupport} methods TeaVM lacks: primitive streams, built over the
|
||||
* boxed stream TeaVM supports. Sequential only; a page has no parallel streams.
|
||||
*/
|
||||
public final class StreamSupportAdditions {
|
||||
|
||||
private StreamSupportAdditions() {}
|
||||
|
||||
public static IntStream intStream(Spliterator.OfInt spliterator, boolean parallel) {
|
||||
return StreamSupport.stream(spliterator, false).mapToInt(Integer::intValue);
|
||||
}
|
||||
|
||||
public static LongStream longStream(Spliterator.OfLong spliterator, boolean parallel) {
|
||||
return StreamSupport.stream(spliterator, false).mapToLong(Long::longValue);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package incari.classlib.additions.java.util.zip;
|
||||
|
||||
import incari.classlib.InstanceMethod;
|
||||
import incari.classlib.Replaces;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.InflaterInputStream;
|
||||
|
||||
/** {@code java.util.zip.InflaterInputStream} methods TeaVM has but gets wrong. */
|
||||
public final class InflaterInputStreamAdditions {
|
||||
|
||||
/** Inflated bytes a skip reads at most at a time. */
|
||||
private static final int SKIP_CHUNK = 512;
|
||||
|
||||
private InflaterInputStreamAdditions() {}
|
||||
|
||||
/**
|
||||
* Skips {@code n} inflated bytes by reading them into a scratch array of its own. TeaVM's read
|
||||
* them into the stream's {@code buf}, the compressed input the inflater was still taking from
|
||||
* (it holds the array, not a copy): every skip overwrote compressed data not yet inflated, and
|
||||
* the next read failed (zlib's -3). The game skips the NBT it doesn't need when it scans a
|
||||
* chunk, so every scan of a saved chunk failed.
|
||||
*/
|
||||
@Replaces
|
||||
@InstanceMethod
|
||||
public static long skip(InflaterInputStream self, long n) throws IOException {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("negative skip length");
|
||||
}
|
||||
byte[] scratch = new byte[(int) Math.min(n, SKIP_CHUNK)];
|
||||
long skipped = 0;
|
||||
while (skipped < n) {
|
||||
int read = self.read(scratch, 0, (int) Math.min(n - skipped, scratch.length));
|
||||
if (read < 0) {
|
||||
break;
|
||||
}
|
||||
skipped += read;
|
||||
}
|
||||
return skipped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package incari.classlib.concurrent;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
/**
|
||||
* Where the browser build's non-waiting lock acquisitions go. The web build's
|
||||
* {@code MonitorElision} routes {@code lock()} calls here in methods that never suspend otherwise:
|
||||
* in the page such a method runs exclusively, so the lock is free, or already the current
|
||||
* thread's, whenever it's reached, and taking it needn't wait. A lock held by another thread here
|
||||
* means that thread suspended while holding it, which the analysis rules out; failing loudly is
|
||||
* better than proceeding without it. The web build refers to this class by name.
|
||||
*/
|
||||
public final class Locks {
|
||||
|
||||
private Locks() {}
|
||||
|
||||
public static void lockNow(Lock lock) {
|
||||
if (!lock.tryLock()) {
|
||||
throw new IllegalStateException(
|
||||
"Lock held by a suspended thread; the browser build can't wait for it here");
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package incari.classlib.concurrent;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Helpers for the {@code java.util.concurrent} substitutes, which all block on plain monitors.
|
||||
*
|
||||
* <p>It lives outside {@code incari.classlib.substitutes} because every top-level {@code T}-class
|
||||
* there is taken for a JDK substitute.
|
||||
*/
|
||||
public final class Monitors {
|
||||
|
||||
private Monitors() {}
|
||||
|
||||
/**
|
||||
* Waits on {@code monitor}, which the caller holds, for at most {@code nanos} and returns the time
|
||||
* left (zero or less once it has run out). Wakes early on a notify or spuriously, so callers loop.
|
||||
*
|
||||
* <p>Object.wait only takes milliseconds in the browser, so the wait is rounded up: rounding down
|
||||
* would turn a sub-millisecond wait into {@code wait(0)}, which never times out.
|
||||
*/
|
||||
@SuppressWarnings("WaitNotInLoop") // callers loop on their own condition
|
||||
public static long awaitNanos(Object monitor, long nanos) throws InterruptedException {
|
||||
if (nanos <= 0) {
|
||||
return nanos;
|
||||
}
|
||||
long start = System.nanoTime();
|
||||
long millis = nanos / 1_000_000L;
|
||||
if (millis * 1_000_000L < nanos) {
|
||||
millis++;
|
||||
}
|
||||
monitor.wait(millis);
|
||||
return nanos - (System.nanoTime() - start);
|
||||
}
|
||||
|
||||
/** Throws {@link InterruptedException} (clearing the flag) if the current thread is interrupted. */
|
||||
public static void checkInterrupt() throws InterruptedException {
|
||||
if (Thread.interrupted()) {
|
||||
throw new InterruptedException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An unchecked cast that may produce {@code null}, for results stored as {@code Object}.
|
||||
*
|
||||
* <p>The callers only pass values they stored as a {@code T}, or {@code null} where {@code T}
|
||||
* admits it; the compiler can't see that through the {@code Object} field.
|
||||
*/
|
||||
// See above: the value was stored as a T, and inferring T at the call site is the point.
|
||||
@SuppressWarnings({"unchecked", "NullAway", "TypeParameterUnusedInFormals"})
|
||||
public static <T extends @Nullable Object> T cast(@Nullable Object value) {
|
||||
return (T) value;
|
||||
}
|
||||
|
||||
/** Rethrows an unchecked throwable as is and wraps a checked one, for code that can't declare it. */
|
||||
public static RuntimeException rethrow(Throwable t) {
|
||||
if (t instanceof RuntimeException e) {
|
||||
throw e;
|
||||
}
|
||||
if (t instanceof Error e) {
|
||||
throw e;
|
||||
}
|
||||
throw new RuntimeException(t);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package incari.classlib.concurrent;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* The iterator the concurrent collection substitutes hand out: it walks a copy taken when it was
|
||||
* made, so it never throws {@code ConcurrentModificationException} (the JDK's weakly consistent
|
||||
* iterators promise that), and its {@code remove} asks the collection to drop that exact element.
|
||||
*/
|
||||
public final class SnapshotIterator<E> implements Iterator<E> {
|
||||
|
||||
private final Object[] items;
|
||||
private final Consumer<Object> remover;
|
||||
private int next;
|
||||
private int last = -1;
|
||||
|
||||
/** Iterates {@code items}; {@code remover} removes one of them from the backing collection. */
|
||||
public SnapshotIterator(Object[] items, Consumer<Object> remover) {
|
||||
this.items = items;
|
||||
this.remover = remover;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return next < items.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E next() {
|
||||
if (next >= items.length) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
last = next;
|
||||
return Monitors.cast(items[next++]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
if (last < 0) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
remover.accept(items[last]);
|
||||
last = -1;
|
||||
}
|
||||
|
||||
/** Removes the element that is {@code o} itself (not merely equal) from {@code it}'s source. */
|
||||
@SuppressWarnings("ReferenceEquality") // identity is the point
|
||||
public static void removeExact(Iterator<?> it, Object o) {
|
||||
while (it.hasNext()) {
|
||||
if (it.next() == o) {
|
||||
it.remove();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package incari.classlib.concurrent;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.interop.PlatformMarker;
|
||||
import org.teavm.interop.Platforms;
|
||||
import org.teavm.jso.JSBody;
|
||||
|
||||
/**
|
||||
* Where the browser build's waits go. The web build's {@code MonitorElision} routes every
|
||||
* {@code Object.wait} in the program here, as it routes notifications to {@link Wakeups}. On the
|
||||
* render thread a wait holds back the game's frame (the page goes on, the game doesn't), so its
|
||||
* length is added to the page's frame monitor ({@code window.__incariFrames.waitMillis}, platform-web),
|
||||
* and a wait of 50 ms or more prints where it was: every blocking call in the class library ends in
|
||||
* {@code wait} (the threading audit, ADR 0015). Other threads wait as they would anyway. The web build
|
||||
* refers to this class by name.
|
||||
*/
|
||||
public final class Waits {
|
||||
|
||||
/** A wait this long holds back the page's frame visibly: the budget for a stall. */
|
||||
static final double REPORT_MILLIS = 50;
|
||||
|
||||
private static @Nullable Thread watched;
|
||||
private static @Nullable Runnable beforeWait;
|
||||
|
||||
private Waits() {}
|
||||
|
||||
/** The render thread, whose waits are timed; the entry point names it before the game starts. */
|
||||
public static void watch(Thread thread) {
|
||||
watched = thread;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs just before every wait off the render thread. The page's background pool gives itself up
|
||||
* there when one of its tasks blocks (platform-web's {@code IdleTimeExecutor}): the work it
|
||||
* waits for may be queued behind it.
|
||||
*/
|
||||
public static void beforeWait(Runnable hook) {
|
||||
beforeWait = hook;
|
||||
}
|
||||
|
||||
/** The render thread, or null before the entry point names it ({@code ThrowCensus} reads it). */
|
||||
public static @Nullable Thread watched() {
|
||||
return watched;
|
||||
}
|
||||
|
||||
public static void wait(Object monitor) throws InterruptedException {
|
||||
wait(monitor, 0L);
|
||||
}
|
||||
|
||||
public static void wait(Object monitor, long timeout, int nanos) throws InterruptedException {
|
||||
wait(monitor, nanos > 0 && timeout < Long.MAX_VALUE ? timeout + 1 : timeout);
|
||||
}
|
||||
|
||||
// The caller loops on its own condition; and threads are compared by identity, which is what
|
||||
// Thread.equals does too, without a virtual call.
|
||||
@SuppressWarnings({"WaitNotInLoop", "ReferenceEquality"})
|
||||
public static void wait(Object monitor, long timeout) throws InterruptedException {
|
||||
if (Thread.currentThread() != watched) {
|
||||
Runnable hook = beforeWait;
|
||||
if (hook != null) {
|
||||
hook.run();
|
||||
}
|
||||
monitor.wait(timeout);
|
||||
return;
|
||||
}
|
||||
long start = System.nanoTime();
|
||||
try {
|
||||
monitor.wait(timeout);
|
||||
} finally {
|
||||
waited((System.nanoTime() - start) / 1_000_000.0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reports a render-thread wait of {@code millis}; package-private for tests. */
|
||||
static void waited(double millis) {
|
||||
if (inPage()) {
|
||||
addToFrame(millis);
|
||||
}
|
||||
if (millis >= REPORT_MILLIS) {
|
||||
String message = "[Incari] The render thread waited " + Math.round(millis) + " ms";
|
||||
if (inPage()) {
|
||||
// The browser's own stack: a release build's Java stack has no names, but its
|
||||
// module's frames do when it keeps them (-Pteavm.names).
|
||||
warnWithStack(message);
|
||||
} else {
|
||||
new Throwable(message).printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True in the WebAssembly build, false on a JVM (where the tests run). TeaVM replaces calls to
|
||||
* it with the constant.
|
||||
*/
|
||||
@PlatformMarker(Platforms.WEBASSEMBLY_GC)
|
||||
private static boolean inPage() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@JSBody(
|
||||
params = "message",
|
||||
script = "var limit = Error.stackTraceLimit; Error.stackTraceLimit = 200;"
|
||||
+ " console.warn(message + '\\n' + new Error().stack); Error.stackTraceLimit = limit;")
|
||||
private static native void warnWithStack(String message);
|
||||
|
||||
@JSBody(params = "millis", script = "var f = window.__incariFrames; if (f) f.waitMillis += millis;")
|
||||
private static native void addToFrame(double millis);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package incari.classlib.concurrent;
|
||||
|
||||
/**
|
||||
* Where the browser build's notifications go. The web build's {@code MonitorElision} drops the
|
||||
* monitors of methods that notify but never wait (their bodies can't suspend, so they already run
|
||||
* exclusively in the page) and routes each {@code notify}/{@code notifyAll} here, where the monitor
|
||||
* is taken just for the call, as {@code notify} requires. The build takes these two monitors
|
||||
* without suspending, so a method that only notifies stays an ordinary function. The web build
|
||||
* refers to this class by name.
|
||||
*/
|
||||
public final class Wakeups {
|
||||
|
||||
private Wakeups() {}
|
||||
|
||||
public static void notify(Object monitor) {
|
||||
synchronized (monitor) {
|
||||
monitor.notify();
|
||||
}
|
||||
}
|
||||
|
||||
public static void notifyAll(Object monitor) {
|
||||
synchronized (monitor) {
|
||||
monitor.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package incari.classlib.image;
|
||||
|
||||
/**
|
||||
* Resizes 8-bit images, behind the substitute for LWJGL's {@code STBImageResize}: what the game
|
||||
* uses it for is shrinking a frame to a world's 64x64 icon. Each output pixel is the average of the
|
||||
* source area it covers, weighted by how much of each source pixel falls inside it, one axis after
|
||||
* the other; growing an image repeats source pixels. Values are averaged as they are, with no
|
||||
* colour-space conversion (STB's "linear" entry point). With an alpha channel, colours are weighted
|
||||
* by their alpha, so fully transparent pixels don't bleed their colour into their neighbours.
|
||||
*/
|
||||
public final class ImageResize {
|
||||
|
||||
private ImageResize() {}
|
||||
|
||||
/**
|
||||
* Resizes {@code source}, packed rows of {@code components} bytes a pixel, to {@code width} by
|
||||
* {@code height}.
|
||||
*
|
||||
* @param components 1 to 4 channels a pixel
|
||||
* @param alpha whether the last channel is alpha, weighting the others
|
||||
*/
|
||||
public static byte[] resize(
|
||||
byte[] source, int sourceWidth, int sourceHeight, int components, boolean alpha, int width, int height) {
|
||||
if (sourceWidth <= 0 || sourceHeight <= 0 || width <= 0 || height <= 0) {
|
||||
throw new IllegalArgumentException("Empty image");
|
||||
}
|
||||
if (components < 1 || components > 4) {
|
||||
throw new IllegalArgumentException("Unsupported channel count: " + components);
|
||||
}
|
||||
// Colours premultiplied by alpha, in floats, for both passes.
|
||||
float[] pixels = new float[sourceWidth * sourceHeight * components];
|
||||
for (int p = 0; p < sourceWidth * sourceHeight; p++) {
|
||||
int base = p * components;
|
||||
float weight = alpha ? (source[base + components - 1] & 0xFF) / 255f : 1f;
|
||||
for (int c = 0; c < components; c++) {
|
||||
float value = source[base + c] & 0xFF;
|
||||
pixels[base + c] = alpha && c < components - 1 ? value * weight : value;
|
||||
}
|
||||
}
|
||||
float[] wide = resizeRows(pixels, sourceWidth, sourceHeight, components, width);
|
||||
float[] done = resizeColumns(wide, width, sourceHeight, components, height);
|
||||
byte[] result = new byte[width * height * components];
|
||||
for (int p = 0; p < width * height; p++) {
|
||||
int base = p * components;
|
||||
float weight = alpha ? done[base + components - 1] / 255f : 1f;
|
||||
for (int c = 0; c < components; c++) {
|
||||
float value = done[base + c];
|
||||
if (alpha && c < components - 1) {
|
||||
value = weight > 0 ? value / weight : 0;
|
||||
}
|
||||
result[base + c] = (byte) Math.clamp(Math.round(value), 0, 255);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Each row from {@code sourceWidth} to {@code width} pixels. */
|
||||
private static float[] resizeRows(float[] source, int sourceWidth, int rows, int components, int width) {
|
||||
float[] result = new float[width * rows * components];
|
||||
Span[] spans = spans(sourceWidth, width);
|
||||
for (int y = 0; y < rows; y++) {
|
||||
int sourceRow = y * sourceWidth;
|
||||
int row = y * width;
|
||||
for (int x = 0; x < width; x++) {
|
||||
Span span = spans[x];
|
||||
int out = (row + x) * components;
|
||||
for (int s = span.first; s <= span.last; s++) {
|
||||
float weight = span.weight(s);
|
||||
int in = (sourceRow + s) * components;
|
||||
for (int c = 0; c < components; c++) {
|
||||
result[out + c] += source[in + c] * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Each column from {@code sourceHeight} to {@code height} pixels. */
|
||||
private static float[] resizeColumns(float[] source, int width, int sourceHeight, int components, int height) {
|
||||
float[] result = new float[width * height * components];
|
||||
Span[] spans = spans(sourceHeight, height);
|
||||
for (int y = 0; y < height; y++) {
|
||||
Span span = spans[y];
|
||||
for (int s = span.first; s <= span.last; s++) {
|
||||
float weight = span.weight(s);
|
||||
int in = s * width * components;
|
||||
int out = y * width * components;
|
||||
for (int i = 0; i < width * components; i++) {
|
||||
result[out + i] += source[in + i] * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** For each output pixel along an axis, the source pixels it covers and how much of each. */
|
||||
private static Span[] spans(int sourceSize, int size) {
|
||||
Span[] spans = new Span[size];
|
||||
double scale = (double) sourceSize / size;
|
||||
for (int i = 0; i < size; i++) {
|
||||
double start = i * scale;
|
||||
double end = (i + 1) * scale;
|
||||
spans[i] = new Span(start, end);
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/** A stretch {@code [start, end)} of source pixels along one axis. */
|
||||
private static final class Span {
|
||||
final double start;
|
||||
final double end;
|
||||
final int first;
|
||||
final int last;
|
||||
|
||||
Span(double start, double end) {
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.first = (int) Math.floor(start);
|
||||
// The last pixel the stretch reaches into; one that only touches its edge doesn't count.
|
||||
this.last = Math.max(first, (int) Math.ceil(end) - 1);
|
||||
}
|
||||
|
||||
/** The share of the stretch that source pixel {@code s} covers; the shares add up to 1. */
|
||||
float weight(int s) {
|
||||
double covered = Math.min(end, s + 1) - Math.max(start, s);
|
||||
return (float) (covered / (end - start));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package incari.classlib.image;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.DataFormatException;
|
||||
import java.util.zip.Inflater;
|
||||
|
||||
/**
|
||||
* Decodes PNG images to 8-bit RGBA, for the browser build's stand-in of LWJGL's STB image
|
||||
* decoder. Every color type and bit depth, palette and {@code tRNS} transparency, and Adam7
|
||||
* interlacing; gamma and color-space chunks are ignored, as STB ignores them.
|
||||
*/
|
||||
public final class PngDecoder {
|
||||
|
||||
private static final byte[] SIGNATURE = {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};
|
||||
private static final int[][] ADAM7 = {
|
||||
{0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4}, {0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2}
|
||||
};
|
||||
|
||||
/** A decoded image: {@code width * height * 4} RGBA bytes, and how many channels the file had. */
|
||||
public static final class Image {
|
||||
private final int width;
|
||||
private final int height;
|
||||
private final int channels;
|
||||
private final byte[] rgba;
|
||||
|
||||
Image(int width, int height, int channels, byte[] rgba) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.channels = channels;
|
||||
this.rgba = rgba;
|
||||
}
|
||||
|
||||
public int width() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public int height() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public int channels() {
|
||||
return channels;
|
||||
}
|
||||
|
||||
/** The pixels, not copied. */
|
||||
public byte[] rgba() {
|
||||
return rgba;
|
||||
}
|
||||
}
|
||||
|
||||
private final byte[] data;
|
||||
private int width;
|
||||
private int height;
|
||||
private int bitDepth;
|
||||
private int colorType;
|
||||
private boolean interlaced;
|
||||
private byte[] palette = new byte[0];
|
||||
private byte[] paletteAlpha = new byte[0];
|
||||
private int transparentGray = -1;
|
||||
private int transparentRed = -1;
|
||||
private int transparentGreen = -1;
|
||||
private int transparentBlue = -1;
|
||||
|
||||
private PngDecoder(byte[] data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static Image decode(byte[] data) throws IOException {
|
||||
return new PngDecoder(data).decode();
|
||||
}
|
||||
|
||||
private Image decode() throws IOException {
|
||||
for (int i = 0; i < SIGNATURE.length; i++) {
|
||||
if (data.length < SIGNATURE.length || data[i] != SIGNATURE[i]) {
|
||||
StringBuilder start = new StringBuilder();
|
||||
for (int j = 0; j < Math.min(8, data.length); j++) {
|
||||
start.append(j == 0 ? "" : " ").append(Integer.toHexString(data[j] & 0xFF));
|
||||
}
|
||||
throw new IOException("Not a PNG file (" + data.length + " bytes, starting " + start + ")");
|
||||
}
|
||||
}
|
||||
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
|
||||
int position = SIGNATURE.length;
|
||||
boolean header = false;
|
||||
while (true) {
|
||||
if (position + 8 > data.length) {
|
||||
throw new IOException("Truncated PNG file");
|
||||
}
|
||||
int length = readInt(position);
|
||||
String type = new String(data, position + 4, 4, StandardCharsets.US_ASCII);
|
||||
int start = position + 8;
|
||||
if (length < 0 || start + length + 4 > data.length) {
|
||||
throw new IOException("Truncated PNG chunk " + type);
|
||||
}
|
||||
switch (type) {
|
||||
case "IHDR" -> {
|
||||
readHeader(start, length);
|
||||
header = true;
|
||||
}
|
||||
case "PLTE" -> palette = copy(start, length);
|
||||
case "tRNS" -> readTransparency(start, length);
|
||||
case "IDAT" -> compressed.write(data, start, length);
|
||||
case "IEND" -> {
|
||||
if (!header) {
|
||||
throw new IOException("PNG file without a header");
|
||||
}
|
||||
return new Image(width, height, channelsInFile(), toRgba(inflate(compressed.toByteArray())));
|
||||
}
|
||||
default -> {
|
||||
// Ancillary chunks (gamma, text, times) don't change the pixels STB returns.
|
||||
}
|
||||
}
|
||||
position = start + length + 4;
|
||||
}
|
||||
}
|
||||
|
||||
private void readHeader(int start, int length) throws IOException {
|
||||
if (length < 13) {
|
||||
throw new IOException("Bad PNG header");
|
||||
}
|
||||
width = readInt(start);
|
||||
height = readInt(start + 4);
|
||||
bitDepth = data[start + 8] & 0xFF;
|
||||
colorType = data[start + 9] & 0xFF;
|
||||
interlaced = data[start + 12] == 1;
|
||||
if (width <= 0 || height <= 0 || (long) width * height > (1 << 28)) {
|
||||
throw new IOException("Unsupported PNG size " + width + "x" + height);
|
||||
}
|
||||
boolean valid =
|
||||
switch (colorType) {
|
||||
case 0 -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8 || bitDepth == 16;
|
||||
case 3 -> bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8;
|
||||
case 2, 4, 6 -> bitDepth == 8 || bitDepth == 16;
|
||||
default -> false;
|
||||
};
|
||||
if (!valid) {
|
||||
throw new IOException("Bad PNG color type " + colorType + " with bit depth " + bitDepth);
|
||||
}
|
||||
}
|
||||
|
||||
private void readTransparency(int start, int length) {
|
||||
switch (colorType) {
|
||||
case 0 -> transparentGray = length >= 2 ? readShort(start) : -1;
|
||||
case 2 -> {
|
||||
if (length >= 6) {
|
||||
transparentRed = readShort(start);
|
||||
transparentGreen = readShort(start + 2);
|
||||
transparentBlue = readShort(start + 4);
|
||||
}
|
||||
}
|
||||
case 3 -> paletteAlpha = copy(start, length);
|
||||
default -> {}
|
||||
}
|
||||
}
|
||||
|
||||
private int channelsInFile() {
|
||||
boolean keyed = transparentGray >= 0 || transparentRed >= 0 || paletteAlpha.length > 0;
|
||||
return switch (colorType) {
|
||||
case 0 -> keyed ? 2 : 1;
|
||||
case 4 -> 2;
|
||||
case 2 -> keyed ? 4 : 3;
|
||||
case 3 -> keyed ? 4 : 3;
|
||||
default -> 4;
|
||||
};
|
||||
}
|
||||
|
||||
private int samplesPerPixel() {
|
||||
return switch (colorType) {
|
||||
case 2 -> 3;
|
||||
case 4 -> 2;
|
||||
case 6 -> 4;
|
||||
default -> 1;
|
||||
};
|
||||
}
|
||||
|
||||
private byte[] inflate(byte[] compressed) throws IOException {
|
||||
Inflater inflater = new Inflater();
|
||||
try {
|
||||
inflater.setInput(compressed);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(compressed.length * 4);
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
while (!inflater.finished()) {
|
||||
int count = inflater.inflate(buffer);
|
||||
if (count == 0 && (inflater.needsInput() || inflater.needsDictionary())) {
|
||||
throw new IOException("Truncated PNG image data");
|
||||
}
|
||||
out.write(buffer, 0, count);
|
||||
}
|
||||
return out.toByteArray();
|
||||
} catch (DataFormatException e) {
|
||||
throw new IOException("Corrupt PNG image data", e);
|
||||
} finally {
|
||||
inflater.end();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] toRgba(byte[] raw) throws IOException {
|
||||
byte[] rgba = new byte[width * height * 4];
|
||||
int offset = 0;
|
||||
if (!interlaced) {
|
||||
offset = pass(raw, offset, rgba, 0, 0, 1, 1);
|
||||
} else {
|
||||
for (int[] pass : ADAM7) {
|
||||
offset = pass(raw, offset, rgba, pass[0], pass[1], pass[2], pass[3]);
|
||||
}
|
||||
}
|
||||
return rgba;
|
||||
}
|
||||
|
||||
/** Unfilters one pass of the image and writes its pixels; returns where the next pass starts. */
|
||||
private int pass(byte[] raw, int offset, byte[] rgba, int x0, int y0, int dx, int dy) throws IOException {
|
||||
int columns = (width - x0 + dx - 1) / dx;
|
||||
int rows = (height - y0 + dy - 1) / dy;
|
||||
if (columns <= 0 || rows <= 0) {
|
||||
return offset;
|
||||
}
|
||||
int bitsPerPixel = samplesPerPixel() * bitDepth;
|
||||
int stride = (columns * bitsPerPixel + 7) / 8;
|
||||
int bytesPerPixel = Math.max(1, bitsPerPixel / 8);
|
||||
byte[] previous = new byte[stride];
|
||||
byte[] current = new byte[stride];
|
||||
for (int row = 0; row < rows; row++) {
|
||||
if (offset + 1 + stride > raw.length) {
|
||||
throw new IOException("Truncated PNG image data");
|
||||
}
|
||||
int filter = raw[offset] & 0xFF;
|
||||
System.arraycopy(raw, offset + 1, current, 0, stride);
|
||||
offset += 1 + stride;
|
||||
unfilter(filter, current, previous, bytesPerPixel);
|
||||
int y = y0 + row * dy;
|
||||
for (int column = 0; column < columns; column++) {
|
||||
writePixel(current, column, rgba, ((y * width) + x0 + column * dx) * 4);
|
||||
}
|
||||
byte[] swap = previous;
|
||||
previous = current;
|
||||
current = swap;
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
private static void unfilter(int filter, byte[] line, byte[] above, int bpp) throws IOException {
|
||||
switch (filter) {
|
||||
case 0 -> {}
|
||||
case 1 -> {
|
||||
for (int i = bpp; i < line.length; i++) {
|
||||
line[i] += line[i - bpp];
|
||||
}
|
||||
}
|
||||
case 2 -> {
|
||||
for (int i = 0; i < line.length; i++) {
|
||||
line[i] += above[i];
|
||||
}
|
||||
}
|
||||
case 3 -> {
|
||||
for (int i = 0; i < line.length; i++) {
|
||||
int left = i >= bpp ? line[i - bpp] & 0xFF : 0;
|
||||
line[i] += (byte) ((left + (above[i] & 0xFF)) >>> 1);
|
||||
}
|
||||
}
|
||||
case 4 -> {
|
||||
for (int i = 0; i < line.length; i++) {
|
||||
int a = i >= bpp ? line[i - bpp] & 0xFF : 0;
|
||||
int b = above[i] & 0xFF;
|
||||
int c = i >= bpp ? above[i - bpp] & 0xFF : 0;
|
||||
int p = a + b - c;
|
||||
int pa = Math.abs(p - a);
|
||||
int pb = Math.abs(p - b);
|
||||
int pc = Math.abs(p - c);
|
||||
line[i] += (byte) (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
|
||||
}
|
||||
}
|
||||
default -> throw new IOException("Bad PNG filter " + filter);
|
||||
}
|
||||
}
|
||||
|
||||
private void writePixel(byte[] line, int column, byte[] rgba, int target) {
|
||||
switch (colorType) {
|
||||
case 0 -> {
|
||||
int gray = sample(line, column, 0, 1);
|
||||
int level = scale(gray);
|
||||
rgba[target] = (byte) level;
|
||||
rgba[target + 1] = (byte) level;
|
||||
rgba[target + 2] = (byte) level;
|
||||
rgba[target + 3] = (byte) (gray == transparentGray ? 0 : 255);
|
||||
}
|
||||
case 2 -> {
|
||||
int r = sample(line, column, 0, 3);
|
||||
int g = sample(line, column, 1, 3);
|
||||
int b = sample(line, column, 2, 3);
|
||||
rgba[target] = (byte) scale(r);
|
||||
rgba[target + 1] = (byte) scale(g);
|
||||
rgba[target + 2] = (byte) scale(b);
|
||||
boolean clear = r == transparentRed && g == transparentGreen && b == transparentBlue;
|
||||
rgba[target + 3] = (byte) (clear ? 0 : 255);
|
||||
}
|
||||
case 3 -> {
|
||||
int index = sample(line, column, 0, 1);
|
||||
if (index * 3 + 2 < palette.length) {
|
||||
rgba[target] = palette[index * 3];
|
||||
rgba[target + 1] = palette[index * 3 + 1];
|
||||
rgba[target + 2] = palette[index * 3 + 2];
|
||||
}
|
||||
rgba[target + 3] = index < paletteAlpha.length ? paletteAlpha[index] : (byte) 255;
|
||||
}
|
||||
case 4 -> {
|
||||
int level = scale(sample(line, column, 0, 2));
|
||||
rgba[target] = (byte) level;
|
||||
rgba[target + 1] = (byte) level;
|
||||
rgba[target + 2] = (byte) level;
|
||||
rgba[target + 3] = (byte) scale(sample(line, column, 1, 2));
|
||||
}
|
||||
default -> {
|
||||
for (int channel = 0; channel < 4; channel++) {
|
||||
rgba[target + channel] = (byte) scale(sample(line, column, channel, 4));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One sample, at its bit depth (not yet scaled to 8 bits). */
|
||||
private int sample(byte[] line, int column, int channel, int samples) {
|
||||
int index = column * samples + channel;
|
||||
return switch (bitDepth) {
|
||||
case 16 -> ((line[index * 2] & 0xFF) << 8) | (line[index * 2 + 1] & 0xFF);
|
||||
case 8 -> line[index] & 0xFF;
|
||||
default -> {
|
||||
int bit = index * bitDepth;
|
||||
int shift = 8 - bitDepth - (bit & 7);
|
||||
yield (line[bit >> 3] >> shift) & ((1 << bitDepth) - 1);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** A sample scaled to 8 bits; palette indices are never scaled. */
|
||||
private int scale(int sample) {
|
||||
return switch (bitDepth) {
|
||||
case 16 -> sample >>> 8;
|
||||
case 8 -> sample;
|
||||
default -> colorType == 3 ? sample : sample * 255 / ((1 << bitDepth) - 1);
|
||||
};
|
||||
}
|
||||
|
||||
private int readInt(int at) {
|
||||
return (data[at] & 0xFF) << 24
|
||||
| (data[at + 1] & 0xFF) << 16
|
||||
| (data[at + 2] & 0xFF) << 8
|
||||
| (data[at + 3] & 0xFF);
|
||||
}
|
||||
|
||||
private int readShort(int at) {
|
||||
return (data[at] & 0xFF) << 8 | (data[at + 1] & 0xFF);
|
||||
}
|
||||
|
||||
private byte[] copy(int start, int length) {
|
||||
byte[] result = new byte[length];
|
||||
System.arraycopy(data, start, result, 0, length);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package incari.classlib.image;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Deflater;
|
||||
|
||||
/**
|
||||
* Encodes 8-bit images as PNG, for the browser build's stand-in of LWJGL's STB image writer (the
|
||||
* game's screenshots). Written from the PNG specification: one IDAT chunk, and for each row the
|
||||
* filter whose output has the smallest sum of absolute values, the heuristic the specification
|
||||
* suggests.
|
||||
*/
|
||||
public final class PngEncoder {
|
||||
|
||||
private static final byte[] SIGNATURE = {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};
|
||||
|
||||
private PngEncoder() {}
|
||||
|
||||
/**
|
||||
* The PNG file of an image.
|
||||
*
|
||||
* @param channels 1 (gray), 2 (gray and alpha), 3 (RGB) or 4 (RGBA)
|
||||
* @param pixels {@code width * height * channels} bytes, rows top to bottom, no padding
|
||||
*/
|
||||
public static byte[] encode(int width, int height, int channels, byte[] pixels) {
|
||||
if (width <= 0 || height <= 0 || channels < 1 || channels > 4) {
|
||||
throw new IllegalArgumentException(width + "x" + height + " with " + channels + " channels");
|
||||
}
|
||||
int stride = width * channels;
|
||||
if (pixels.length < (long) stride * height) {
|
||||
throw new IllegalArgumentException("Too few pixels for " + width + "x" + height);
|
||||
}
|
||||
ByteArrayOutputStream file = new ByteArrayOutputStream();
|
||||
file.write(SIGNATURE, 0, SIGNATURE.length);
|
||||
|
||||
byte[] header = new byte[13];
|
||||
putInt(header, 0, width);
|
||||
putInt(header, 4, height);
|
||||
header[8] = 8;
|
||||
header[9] = (byte) colorType(channels);
|
||||
chunk(file, "IHDR", header, header.length);
|
||||
|
||||
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
|
||||
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
|
||||
byte[] chunkBuffer = new byte[64 * 1024];
|
||||
byte[][] candidates = new byte[5][stride + 1];
|
||||
try {
|
||||
for (int y = 0; y < height; y++) {
|
||||
int row = y * stride;
|
||||
byte[] best = filterRow(pixels, row, y == 0 ? -1 : row - stride, stride, channels, candidates);
|
||||
deflater.setInput(best, 0, stride + 1);
|
||||
drain(deflater, compressed, chunkBuffer);
|
||||
}
|
||||
deflater.finish();
|
||||
while (!deflater.finished()) {
|
||||
int count = deflater.deflate(chunkBuffer);
|
||||
compressed.write(chunkBuffer, 0, count);
|
||||
}
|
||||
} finally {
|
||||
deflater.end();
|
||||
}
|
||||
byte[] data = compressed.toByteArray();
|
||||
chunk(file, "IDAT", data, data.length);
|
||||
chunk(file, "IEND", new byte[0], 0);
|
||||
return file.toByteArray();
|
||||
}
|
||||
|
||||
private static void drain(Deflater deflater, ByteArrayOutputStream out, byte[] buffer) {
|
||||
while (!deflater.needsInput()) {
|
||||
int count = deflater.deflate(buffer);
|
||||
if (count == 0) {
|
||||
break;
|
||||
}
|
||||
out.write(buffer, 0, count);
|
||||
}
|
||||
}
|
||||
|
||||
/** The filtered row (filter type first) with the smallest sum of absolute values. */
|
||||
private static byte[] filterRow(byte[] pixels, int row, int above, int stride, int channels, byte[][] candidates) {
|
||||
byte[] best = candidates[0];
|
||||
long bestSum = Long.MAX_VALUE;
|
||||
for (int type = 0; type < 5; type++) {
|
||||
byte[] out = candidates[type];
|
||||
out[0] = (byte) type;
|
||||
long sum = 0;
|
||||
for (int i = 0; i < stride; i++) {
|
||||
int x = pixels[row + i] & 0xFF;
|
||||
int a = i >= channels ? pixels[row + i - channels] & 0xFF : 0;
|
||||
int b = above >= 0 ? pixels[above + i] & 0xFF : 0;
|
||||
int c = above >= 0 && i >= channels ? pixels[above + i - channels] & 0xFF : 0;
|
||||
int predicted =
|
||||
switch (type) {
|
||||
case 0 -> 0;
|
||||
case 1 -> a;
|
||||
case 2 -> b;
|
||||
case 3 -> (a + b) >>> 1;
|
||||
default -> paeth(a, b, c);
|
||||
};
|
||||
byte filtered = (byte) (x - predicted);
|
||||
out[i + 1] = filtered;
|
||||
sum += Math.abs(filtered);
|
||||
}
|
||||
if (sum < bestSum) {
|
||||
bestSum = sum;
|
||||
best = out;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static int paeth(int a, int b, int c) {
|
||||
int p = a + b - c;
|
||||
int pa = Math.abs(p - a);
|
||||
int pb = Math.abs(p - b);
|
||||
int pc = Math.abs(p - c);
|
||||
if (pa <= pb && pa <= pc) {
|
||||
return a;
|
||||
}
|
||||
return pb <= pc ? b : c;
|
||||
}
|
||||
|
||||
private static int colorType(int channels) {
|
||||
return switch (channels) {
|
||||
case 1 -> 0;
|
||||
case 2 -> 4;
|
||||
case 3 -> 2;
|
||||
default -> 6;
|
||||
};
|
||||
}
|
||||
|
||||
private static void chunk(ByteArrayOutputStream file, String type, byte[] data, int length) {
|
||||
byte[] name = type.getBytes(StandardCharsets.US_ASCII);
|
||||
byte[] number = new byte[4];
|
||||
putInt(number, 0, length);
|
||||
file.write(number, 0, number.length);
|
||||
file.write(name, 0, name.length);
|
||||
file.write(data, 0, length);
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(name);
|
||||
crc.update(data, 0, length);
|
||||
putInt(number, 0, (int) crc.getValue());
|
||||
file.write(number, 0, number.length);
|
||||
}
|
||||
|
||||
private static void putInt(byte[] bytes, int at, int value) {
|
||||
bytes[at] = (byte) (value >>> 24);
|
||||
bytes[at + 1] = (byte) (value >>> 16);
|
||||
bytes[at + 2] = (byte) (value >>> 8);
|
||||
bytes[at + 3] = (byte) value;
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package incari.classlib.logging;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.slf4j.Marker;
|
||||
import org.slf4j.event.Level;
|
||||
import org.slf4j.helpers.LegacyAbstractLogger;
|
||||
import org.slf4j.helpers.MessageFormatter;
|
||||
|
||||
/**
|
||||
* An SLF4J logger that prints to the browser console in the game's desktop log format:
|
||||
* {@code [12:34:56] [Render thread/INFO]: message}. Warnings and errors go to standard error,
|
||||
* which the browser shows as console errors. Debug and trace are off.
|
||||
*/
|
||||
public final class ConsoleLogger extends LegacyAbstractLogger {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
// The console as it was when logging started. The game's Bootstrap.wrapStreams later points
|
||||
// System.out and System.err at loggers; printing to those would log each line forever.
|
||||
private static final PrintStream OUT = System.out;
|
||||
private static final PrintStream ERR = System.err;
|
||||
|
||||
ConsoleLogger(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTraceEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInfoEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isWarnEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isErrorEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @Nullable String getFullyQualifiedCallerName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void handleNormalizedLoggingCall(
|
||||
Level level,
|
||||
@Nullable Marker marker,
|
||||
@Nullable String messagePattern,
|
||||
@Nullable Object @Nullable [] arguments,
|
||||
@Nullable Throwable throwable) {
|
||||
String message = MessageFormatter.basicArrayFormat(messagePattern, arguments);
|
||||
PrintStream out = level.toInt() >= Level.WARN.toInt() ? ERR : OUT;
|
||||
Calendar now = Calendar.getInstance();
|
||||
out.println("[" + twoDigits(now.get(Calendar.HOUR_OF_DAY)) + ":" + twoDigits(now.get(Calendar.MINUTE)) + ":"
|
||||
+ twoDigits(now.get(Calendar.SECOND)) + "] ["
|
||||
+ Thread.currentThread().getName() + "/" + level + "]: "
|
||||
+ message);
|
||||
if (throwable != null) {
|
||||
printWithCauses(throwable, out);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a throwable and its causes, each found through {@code getCause()}. TeaVM's
|
||||
* {@code printStackTrace} reads the cause field instead, so it left out the cause of the game's
|
||||
* {@code ReportedException}, which overrides {@code getCause()} to answer its crash report's
|
||||
* exception: every crash logged without the error that caused it.
|
||||
*/
|
||||
static void printWithCauses(Throwable throwable, PrintStream out) {
|
||||
Set<Throwable> printed = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
String heading = "";
|
||||
for (Throwable current = throwable; current != null && printed.add(current); current = current.getCause()) {
|
||||
out.println(heading + current);
|
||||
for (StackTraceElement element : current.getStackTrace()) {
|
||||
out.println("\tat " + element);
|
||||
}
|
||||
heading = "Caused by: ";
|
||||
}
|
||||
}
|
||||
|
||||
private static String twoDigits(int value) {
|
||||
return value < 10 ? "0" + value : Integer.toString(value);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package incari.classlib.logging;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.slf4j.ILoggerFactory;
|
||||
import org.slf4j.IMarkerFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.helpers.BasicMDCAdapter;
|
||||
import org.slf4j.helpers.BasicMarkerFactory;
|
||||
import org.slf4j.spi.MDCAdapter;
|
||||
import org.slf4j.spi.SLF4JServiceProvider;
|
||||
|
||||
/**
|
||||
* The SLF4J provider behind the browser build's {@code LoggerFactory}: {@link ConsoleLogger}s, bound
|
||||
* directly rather than found by SLF4J's service lookup, which relies on class loading a compiled
|
||||
* page doesn't have.
|
||||
*/
|
||||
public final class ConsoleLogging implements SLF4JServiceProvider, ILoggerFactory {
|
||||
|
||||
public static final ConsoleLogging INSTANCE = new ConsoleLogging();
|
||||
|
||||
private final Map<String, Logger> loggers = new ConcurrentHashMap<>();
|
||||
private final IMarkerFactory markers = new BasicMarkerFactory();
|
||||
private final MDCAdapter mdc = new BasicMDCAdapter();
|
||||
|
||||
private ConsoleLogging() {}
|
||||
|
||||
@Override
|
||||
public Logger getLogger(String name) {
|
||||
return loggers.computeIfAbsent(name, ConsoleLogger::new);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ILoggerFactory getLoggerFactory() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IMarkerFactory getMarkerFactory() {
|
||||
return markers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MDCAdapter getMDCAdapter() {
|
||||
return mdc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRequestedApiVersion() {
|
||||
return "2.0.99";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package incari.classlib.memory;
|
||||
|
||||
import java.nio.Buffer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.IntBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import org.teavm.interop.PlatformMarker;
|
||||
import org.teavm.interop.Platforms;
|
||||
import org.teavm.jso.JSBody;
|
||||
|
||||
/**
|
||||
* Off-heap memory for LWJGL's {@code MemoryUtil}, {@code MemoryStack} and {@code BufferUtils},
|
||||
* with addresses as the game's vertex builders and images use them.
|
||||
*
|
||||
* <p>In the browser, memory is the module's linear memory (the {@code ArrayBuffer} JavaScript
|
||||
* sees). Each allocation is a TeaVM direct buffer, its address is its real offset, and a read or
|
||||
* write is one WebAssembly load or store ({@link LinearMemory}). A view ({@code memByteBuffer}) is
|
||||
* a slice of its block, so WebGL uploads it from linear memory without a copy.
|
||||
*
|
||||
* <p>On a JVM (the tests), the same bookkeeping runs over heap buffers with made-up addresses, and
|
||||
* {@code malloc} memory is filled with junk, as reused linear memory would be, so tests catch code
|
||||
* that forgets to clear it.
|
||||
*
|
||||
* <p>Blocks are kept by start address; views and the JVM's accesses find a block from an address
|
||||
* inside it with a floor lookup. One thread at a time: the page's, where Java threads are
|
||||
* coroutines and nothing here suspends.
|
||||
*/
|
||||
public final class Heap {
|
||||
|
||||
/** What the JVM backend fills unzeroed memory with. */
|
||||
static final byte JUNK = (byte) 0xA5;
|
||||
|
||||
private static final TreeMap<Long, ByteBuffer> blocks = new TreeMap<>();
|
||||
|
||||
// The JVM backend's addresses: block starts by backing array, and int views by identity.
|
||||
private static final IdentityHashMap<byte[], Long> jvmStarts = new IdentityHashMap<>();
|
||||
private static final Map<Long, byte[]> jvmArrays = new HashMap<>();
|
||||
private static final IdentityHashMap<IntBuffer, Long> jvmInts = new IdentityHashMap<>();
|
||||
private static long jvmNext = 1L << 32;
|
||||
|
||||
// Bytes in blocks not yet freed: the profiler's "linear memory in use". Linear memory
|
||||
// itself only grows, so its size is a high-water mark and says little about what's held now.
|
||||
private static long live;
|
||||
|
||||
private Heap() {}
|
||||
|
||||
/** Bytes in blocks allocated and not yet freed (buffers the collector frees aren't counted). */
|
||||
public static long liveBytes() {
|
||||
return live;
|
||||
}
|
||||
|
||||
/**
|
||||
* True in the WebAssembly build, false on a JVM. TeaVM replaces calls to it with the constant,
|
||||
* so each branch on it costs nothing and the other backend isn't compiled in.
|
||||
*/
|
||||
@PlatformMarker(Platforms.WEBASSEMBLY_GC)
|
||||
static boolean linear() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Allocates {@code size} bytes, zeroed if {@code zeroed} ({@code calloc}), else not ({@code malloc}). */
|
||||
public static long allocate(long size, boolean zeroed) {
|
||||
if (size < 0 || size > Integer.MAX_VALUE - 8) {
|
||||
throw new OutOfMemoryError("Can't allocate " + size + " bytes");
|
||||
}
|
||||
// Never zero bytes, so every block has its own start address.
|
||||
int capacity = (int) Math.max(size, 1);
|
||||
ByteBuffer block;
|
||||
long address;
|
||||
if (linear()) {
|
||||
block = ByteBuffer.allocateDirect(capacity);
|
||||
address = LinearMemory.address(block);
|
||||
if (zeroed) {
|
||||
// TeaVM's allocator hands out freed memory as it was.
|
||||
LinearMemory.fill(address, (byte) 0, capacity);
|
||||
}
|
||||
} else {
|
||||
byte[] array = new byte[capacity];
|
||||
if (!zeroed) {
|
||||
Arrays.fill(array, JUNK);
|
||||
}
|
||||
block = ByteBuffer.wrap(array);
|
||||
address = jvmNext;
|
||||
jvmNext += (capacity + 15L) & -16L;
|
||||
jvmStarts.put(array, address);
|
||||
jvmArrays.put(address, array);
|
||||
}
|
||||
blocks.put(address, block.order(ByteOrder.LITTLE_ENDIAN));
|
||||
counted(capacity);
|
||||
return address;
|
||||
}
|
||||
|
||||
/** Frees the block {@code address} starts; 0 is ignored, as {@code free(NULL)} is. */
|
||||
public static void free(long address) {
|
||||
if (address == 0) {
|
||||
return;
|
||||
}
|
||||
ByteBuffer block = blocks.remove(address);
|
||||
if (block == null) {
|
||||
throw new IllegalArgumentException("Not the start of a block: " + Long.toHexString(address));
|
||||
}
|
||||
counted(-block.capacity());
|
||||
if (linear()) {
|
||||
// Now rather than when the collector gets to the buffer: linear memory never shrinks.
|
||||
LinearMemory.release(block);
|
||||
} else {
|
||||
jvmStarts.remove(jvmArrays.remove(address));
|
||||
}
|
||||
}
|
||||
|
||||
private static void counted(long bytes) {
|
||||
live += bytes;
|
||||
if (linear()) {
|
||||
publish((double) live);
|
||||
}
|
||||
}
|
||||
|
||||
// Where the benchmark runner reads it (window.__incariLinear.live), with the peak beside it.
|
||||
@JSBody(
|
||||
params = "live",
|
||||
script = "var c = self.__incariLinear || (self.__incariLinear = {live: 0, peak: 0});"
|
||||
+ " c.live = live; if (live > c.peak) c.peak = live;")
|
||||
private static native void publish(double live);
|
||||
|
||||
/** Moves the block {@code address} starts into a new one of {@code size} bytes; 0 allocates. */
|
||||
public static long reallocate(long address, long size) {
|
||||
long moved = allocate(size, false);
|
||||
if (address != 0) {
|
||||
copy(address, moved, Math.min(block(address).capacity(), size));
|
||||
free(address);
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/** The {@code size} bytes at {@code address}, which must lie in one block, as a little-endian buffer. */
|
||||
public static ByteBuffer buffer(long address, int size) {
|
||||
Map.Entry<Long, ByteBuffer> entry = blocks.floorEntry(address);
|
||||
long offset = entry == null ? -1 : address - entry.getKey();
|
||||
if (entry == null || size < 0 || offset + size > entry.getValue().capacity()) {
|
||||
throw new IllegalArgumentException("Not allocated: " + size + " bytes at " + Long.toHexString(address));
|
||||
}
|
||||
return entry.getValue().slice((int) offset, size).order(ByteOrder.LITTLE_ENDIAN);
|
||||
}
|
||||
|
||||
/** A new block as a buffer. */
|
||||
public static ByteBuffer allocateBuffer(int size, boolean zeroed) {
|
||||
return buffer(allocate(size, zeroed), size);
|
||||
}
|
||||
|
||||
/**
|
||||
* A zeroed buffer the collector frees, as LWJGL's {@code BufferUtils} gives: never passed to
|
||||
* {@link #free}, so the heap doesn't keep it. Its address is still valid while it lives.
|
||||
*/
|
||||
public static ByteBuffer collectedBuffer(int size) {
|
||||
ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.LITTLE_ENDIAN);
|
||||
if (linear()) {
|
||||
LinearMemory.fill(LinearMemory.address(buffer), (byte) 0, size);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/** The address of {@code buffer}'s position. */
|
||||
public static long address(ByteBuffer buffer) {
|
||||
if (linear()) {
|
||||
if (!buffer.isDirect()) {
|
||||
throw new IllegalArgumentException("Not a buffer in linear memory: " + buffer);
|
||||
}
|
||||
return LinearMemory.address(buffer) + buffer.position();
|
||||
}
|
||||
Long start = buffer.hasArray() ? jvmStarts.get(buffer.array()) : null;
|
||||
if (start == null) {
|
||||
throw new IllegalArgumentException("Not a buffer from MemoryUtil: " + buffer);
|
||||
}
|
||||
return start + buffer.arrayOffset() + buffer.position();
|
||||
}
|
||||
|
||||
/** An int view of a new block. */
|
||||
public static IntBuffer allocateInts(int count, boolean zeroed) {
|
||||
return ints(allocate((long) count * Integer.BYTES, zeroed), count);
|
||||
}
|
||||
|
||||
/** An int view of {@code count} ints at {@code address}. */
|
||||
public static IntBuffer ints(long address, int count) {
|
||||
IntBuffer ints = buffer(address, count * Integer.BYTES).asIntBuffer();
|
||||
if (!linear()) {
|
||||
// A JVM's int views don't say what they view; remembered so memAddress finds it (tests only).
|
||||
jvmInts.put(ints, address);
|
||||
}
|
||||
return ints;
|
||||
}
|
||||
|
||||
/** The address of an int buffer's position: any in linear memory, or one from {@link #ints} on a JVM. */
|
||||
public static long address(IntBuffer buffer) {
|
||||
long start;
|
||||
if (linear()) {
|
||||
if (!buffer.isDirect()) {
|
||||
throw new IllegalArgumentException("Not a buffer in linear memory: " + buffer);
|
||||
}
|
||||
start = LinearMemory.address(buffer);
|
||||
} else {
|
||||
Long known = jvmInts.get(buffer);
|
||||
if (known == null) {
|
||||
throw new IllegalArgumentException("Not a buffer from MemoryUtil.memAllocInt: " + buffer);
|
||||
}
|
||||
start = known;
|
||||
}
|
||||
return start + (long) buffer.position() * Integer.BYTES;
|
||||
}
|
||||
|
||||
/** Frees the block a buffer from this heap starts at its position 0. */
|
||||
public static void free(Buffer buffer) {
|
||||
if (buffer instanceof ByteBuffer bytes) {
|
||||
free(address(bytes) - bytes.position());
|
||||
} else if (buffer instanceof IntBuffer ints) {
|
||||
long start = address(ints) - (long) ints.position() * Integer.BYTES;
|
||||
if (!linear()) {
|
||||
jvmInts.remove(ints);
|
||||
}
|
||||
free(start);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Can't free " + buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reads and writes: one load or store in the browser -----------------------------------
|
||||
|
||||
/** Copies {@code count} bytes; the ranges may overlap, as {@code memmove}'s may. */
|
||||
public static void copy(long source, long target, long count) {
|
||||
if (count <= 0) {
|
||||
return;
|
||||
}
|
||||
if (linear()) {
|
||||
LinearMemory.copy(source, target, (int) count);
|
||||
} else {
|
||||
// Views of blocks: ByteBuffer.put copies as if through a temporary, so overlaps are safe.
|
||||
int length = (int) count;
|
||||
buffer(target, length).put(0, buffer(source, length), 0, length);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets {@code count} bytes to {@code value}. */
|
||||
public static void fill(long address, byte value, long count) {
|
||||
if (count <= 0) {
|
||||
return;
|
||||
}
|
||||
if (linear()) {
|
||||
LinearMemory.fill(address, value, (int) count);
|
||||
} else {
|
||||
ByteBuffer view = buffer(address, (int) count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
view.put(i, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte getByte(long address) {
|
||||
if (linear()) {
|
||||
return LinearMemory.getByte(address);
|
||||
}
|
||||
return buffer(address, 1).get(0);
|
||||
}
|
||||
|
||||
public static void putByte(long address, byte value) {
|
||||
if (linear()) {
|
||||
LinearMemory.putByte(address, value);
|
||||
} else {
|
||||
buffer(address, 1).put(0, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static short getShort(long address) {
|
||||
if (linear()) {
|
||||
return LinearMemory.getShort(address);
|
||||
}
|
||||
return buffer(address, 2).getShort(0);
|
||||
}
|
||||
|
||||
public static void putShort(long address, short value) {
|
||||
if (linear()) {
|
||||
LinearMemory.putShort(address, value);
|
||||
} else {
|
||||
buffer(address, 2).putShort(0, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static int getInt(long address) {
|
||||
if (linear()) {
|
||||
return LinearMemory.getInt(address);
|
||||
}
|
||||
return buffer(address, 4).getInt(0);
|
||||
}
|
||||
|
||||
public static void putInt(long address, int value) {
|
||||
if (linear()) {
|
||||
LinearMemory.putInt(address, value);
|
||||
} else {
|
||||
buffer(address, 4).putInt(0, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static long getLong(long address) {
|
||||
if (linear()) {
|
||||
return LinearMemory.getLong(address);
|
||||
}
|
||||
return buffer(address, 8).getLong(0);
|
||||
}
|
||||
|
||||
public static void putLong(long address, long value) {
|
||||
if (linear()) {
|
||||
LinearMemory.putLong(address, value);
|
||||
} else {
|
||||
buffer(address, 8).putLong(0, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static float getFloat(long address) {
|
||||
if (linear()) {
|
||||
return LinearMemory.getFloat(address);
|
||||
}
|
||||
return buffer(address, 4).getFloat(0);
|
||||
}
|
||||
|
||||
public static void putFloat(long address, float value) {
|
||||
if (linear()) {
|
||||
LinearMemory.putFloat(address, value);
|
||||
} else {
|
||||
buffer(address, 4).putFloat(0, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static double getDouble(long address) {
|
||||
if (linear()) {
|
||||
return LinearMemory.getDouble(address);
|
||||
}
|
||||
return buffer(address, 8).getDouble(0);
|
||||
}
|
||||
|
||||
public static void putDouble(long address, double value) {
|
||||
if (linear()) {
|
||||
LinearMemory.putDouble(address, value);
|
||||
} else {
|
||||
buffer(address, 8).putDouble(0, value);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Strings -------------------------------------------------------------------------------
|
||||
|
||||
/** A zero-terminated string starting at {@code address}. */
|
||||
public static String string(long address, boolean ascii) {
|
||||
int length = 0;
|
||||
while (getByte(address + length) != 0) {
|
||||
length++;
|
||||
}
|
||||
byte[] bytes = new byte[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
bytes[i] = getByte(address + i);
|
||||
}
|
||||
return new String(bytes, ascii ? StandardCharsets.US_ASCII : StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** {@code text} encoded in a new block, followed by a zero if {@code terminated}. */
|
||||
public static ByteBuffer encode(CharSequence text, boolean terminated, boolean ascii) {
|
||||
byte[] bytes = text.toString().getBytes(ascii ? StandardCharsets.US_ASCII : StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = allocateBuffer(bytes.length + (terminated ? 1 : 0), false);
|
||||
buffer.put(bytes);
|
||||
if (terminated) {
|
||||
buffer.put((byte) 0);
|
||||
}
|
||||
buffer.flip();
|
||||
// The terminator is in memory but, as in LWJGL, outside the buffer.
|
||||
buffer.limit(bytes.length);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
// --- Blocks --------------------------------------------------------------------------------
|
||||
|
||||
/** The block {@code address} starts. */
|
||||
private static ByteBuffer block(long address) {
|
||||
ByteBuffer block = blocks.get(address);
|
||||
if (block == null) {
|
||||
throw new IllegalArgumentException("Not the start of a block: " + Long.toHexString(address));
|
||||
}
|
||||
return block;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package incari.classlib.memory;
|
||||
|
||||
import incari.classlib.substitutes.java.nio.TNativeBuffer;
|
||||
import incari.classlib.substitutes.java.nio.file.TAddressBasedBuffer;
|
||||
import java.nio.Buffer;
|
||||
import org.teavm.interop.Address;
|
||||
|
||||
/**
|
||||
* {@link Heap}'s browser backend: the WebAssembly module's linear memory, read and written through
|
||||
* TeaVM's {@link Address} intrinsics, which compile to single loads and stores (little-endian, and
|
||||
* unaligned access is allowed). Only reached when {@link Heap#linear()} holds, so a JVM never loads
|
||||
* it. Hot path: nothing here allocates.
|
||||
*/
|
||||
final class LinearMemory {
|
||||
|
||||
private LinearMemory() {}
|
||||
|
||||
/** Where a direct buffer's contents start in linear memory (its position isn't counted). */
|
||||
static long address(Buffer buffer) {
|
||||
// WebAssembly addresses are 32-bit and unsigned.
|
||||
return ((TAddressBasedBuffer) (Object) buffer).getDataAddress().toInt() & 0xFFFFFFFFL;
|
||||
}
|
||||
|
||||
/** Frees a direct buffer's memory now, and stops the collector from freeing it again later. */
|
||||
static void release(Buffer buffer) {
|
||||
((TNativeBuffer) (Object) buffer).release();
|
||||
}
|
||||
|
||||
static void copy(long source, long target, int count) {
|
||||
Address.moveMemoryBlock(at(source), at(target), count);
|
||||
}
|
||||
|
||||
static void fill(long address, byte value, int count) {
|
||||
Address.fill(at(address), value, count);
|
||||
}
|
||||
|
||||
static byte getByte(long address) {
|
||||
return at(address).getByte();
|
||||
}
|
||||
|
||||
static void putByte(long address, byte value) {
|
||||
at(address).putByte(value);
|
||||
}
|
||||
|
||||
static short getShort(long address) {
|
||||
return at(address).getShort();
|
||||
}
|
||||
|
||||
static void putShort(long address, short value) {
|
||||
at(address).putShort(value);
|
||||
}
|
||||
|
||||
static int getInt(long address) {
|
||||
return at(address).getInt();
|
||||
}
|
||||
|
||||
static void putInt(long address, int value) {
|
||||
at(address).putInt(value);
|
||||
}
|
||||
|
||||
static long getLong(long address) {
|
||||
return at(address).getLong();
|
||||
}
|
||||
|
||||
static void putLong(long address, long value) {
|
||||
at(address).putLong(value);
|
||||
}
|
||||
|
||||
static float getFloat(long address) {
|
||||
return at(address).getFloat();
|
||||
}
|
||||
|
||||
static void putFloat(long address, float value) {
|
||||
at(address).putFloat(value);
|
||||
}
|
||||
|
||||
static double getDouble(long address) {
|
||||
return at(address).getDouble();
|
||||
}
|
||||
|
||||
static void putDouble(long address, double value) {
|
||||
at(address).putDouble(value);
|
||||
}
|
||||
|
||||
private static Address at(long address) {
|
||||
return Address.fromInt((int) address);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package incari.classlib.memory;
|
||||
|
||||
import org.teavm.jso.JSBody;
|
||||
|
||||
/**
|
||||
* The page's JavaScript heap, as {@code Runtime}'s memory figures. WebAssembly GC objects live in
|
||||
* that heap, so it is the game's Java heap. Chromium reports it in {@code performance.memory}
|
||||
* (coarse and refreshed slowly unless Chrome runs with precise memory info, but real numbers).
|
||||
* Other browsers don't; there the figures stay TeaVM's own, {@link Integer#MAX_VALUE} for all
|
||||
* three, which reads as an empty heap.
|
||||
*/
|
||||
public final class PageHeap {
|
||||
|
||||
/** TeaVM's figure for all three when a browser reports nothing. */
|
||||
static final long UNKNOWN = Integer.MAX_VALUE;
|
||||
|
||||
private PageHeap() {}
|
||||
|
||||
/** {@code Runtime.maxMemory()}: the most the heap may grow to. */
|
||||
public static long max() {
|
||||
return figures(jsHeapSizeLimit(), totalJsHeapSize(), usedJsHeapSize())[0];
|
||||
}
|
||||
|
||||
/** {@code Runtime.totalMemory()}: what the heap holds now, used or not. */
|
||||
public static long total() {
|
||||
return figures(jsHeapSizeLimit(), totalJsHeapSize(), usedJsHeapSize())[1];
|
||||
}
|
||||
|
||||
/** {@code Runtime.freeMemory()}: the part of {@link #total()} not in use. */
|
||||
public static long free() {
|
||||
return figures(jsHeapSizeLimit(), totalJsHeapSize(), usedJsHeapSize())[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* Max, total and free from what the browser reports (negative for nothing), kept in the order
|
||||
* {@code Runtime} promises and callers divide by: {@code 0 <= free <= total <= max}, max > 0.
|
||||
*/
|
||||
static long[] figures(double limit, double total, double used) {
|
||||
if (!(limit > 0) || !(total > 0) || !(used >= 0)) {
|
||||
return new long[] {UNKNOWN, UNKNOWN, UNKNOWN};
|
||||
}
|
||||
long t = (long) total;
|
||||
long m = Math.max((long) limit, t);
|
||||
long f = Math.max(0, t - Math.min((long) used, t));
|
||||
return new long[] {m, t, f};
|
||||
}
|
||||
|
||||
// Each reads one figure, or -1 where the browser has none (not Chromium, or a worker without it).
|
||||
@JSBody(
|
||||
script = "var m = self.performance && self.performance.memory;"
|
||||
+ " return m && m.jsHeapSizeLimit > 0 ? m.jsHeapSizeLimit : -1;")
|
||||
private static native double jsHeapSizeLimit();
|
||||
|
||||
@JSBody(
|
||||
script = "var m = self.performance && self.performance.memory;"
|
||||
+ " return m && m.totalJSHeapSize > 0 ? m.totalJSHeapSize : -1;")
|
||||
private static native double totalJsHeapSize();
|
||||
|
||||
@JSBody(
|
||||
script = "var m = self.performance && self.performance.memory;"
|
||||
+ " return m && m.usedJSHeapSize >= 0 ? m.usedJSHeapSize : -1;")
|
||||
private static native double usedJsHeapSize();
|
||||
}
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
package incari.classlib.nio;
|
||||
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileChannel;
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileLock;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.ClosedChannelException;
|
||||
import java.nio.channels.NonReadableChannelException;
|
||||
import java.nio.channels.NonWritableChannelException;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.nio.channels.WritableByteChannel;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The {@code FileChannel} contract (argument checks, access modes, closed state, scattering and
|
||||
* gathering, transfers, locks) over a handful of primitive operations a subclass supplies.
|
||||
*
|
||||
* <p>Every primitive runs holding one lock, so each operation is atomic with respect to the
|
||||
* others and to the position, as the JDK requires. On the page, operations never suspend while
|
||||
* holding it: the virtual file system answers synchronously.
|
||||
*/
|
||||
abstract class BaseFileChannel extends TFileChannel {
|
||||
|
||||
/** The chunk size for transfers and for copying through buffers without a backing array. */
|
||||
static final int CHUNK = 8192;
|
||||
|
||||
private final boolean readable;
|
||||
private final boolean writable;
|
||||
// What LockTable groups locks by: the file's path, or the channel itself when it has none.
|
||||
private final Object lockKey;
|
||||
private final Object ioLock = new Object();
|
||||
|
||||
BaseFileChannel(boolean readable, boolean writable, Object lockKey) {
|
||||
this.readable = readable;
|
||||
this.writable = writable;
|
||||
this.lockKey = lockKey;
|
||||
}
|
||||
|
||||
// --- Primitives, each called holding the I/O lock on an open channel ----------------------------
|
||||
|
||||
/** Reads at the position into {@code dst}, which has room; -1 at the end of the file. */
|
||||
abstract int implRead(ByteBuffer dst) throws IOException;
|
||||
|
||||
/** Writes all of {@code src} at the position (at the end, in append mode). */
|
||||
abstract void implWrite(ByteBuffer src) throws IOException;
|
||||
|
||||
/** Reads at {@code position} into {@code dst}, which has room; -1 at or past the end. */
|
||||
abstract int implRead(ByteBuffer dst, long position) throws IOException;
|
||||
|
||||
/** Writes all of {@code src} at {@code position}, leaving the channel's position alone. */
|
||||
abstract void implWrite(ByteBuffer src, long position) throws IOException;
|
||||
|
||||
abstract long implPosition() throws IOException;
|
||||
|
||||
abstract void implPosition(long newPosition) throws IOException;
|
||||
|
||||
abstract long implSize() throws IOException;
|
||||
|
||||
/** Shrinks the file to {@code size}, which is below its current size. */
|
||||
abstract void implTruncate(long size) throws IOException;
|
||||
|
||||
abstract void implForce() throws IOException;
|
||||
|
||||
/** Releases what the channel holds; called once. */
|
||||
abstract void implClose() throws IOException;
|
||||
|
||||
// --- The contract ------------------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public int read(ByteBuffer dst) throws IOException {
|
||||
checkReadInto(dst);
|
||||
if (!dst.hasRemaining()) {
|
||||
return 0;
|
||||
}
|
||||
return (int) io(() -> implRead(dst));
|
||||
}
|
||||
|
||||
@Override
|
||||
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
|
||||
Objects.checkFromIndexSize(offset, length, dsts.length);
|
||||
ensureOpen();
|
||||
for (int i = offset; i < offset + length; i++) {
|
||||
checkReadInto(dsts[i]);
|
||||
}
|
||||
return io(() -> {
|
||||
long total = 0;
|
||||
for (int i = offset; i < offset + length; i++) {
|
||||
ByteBuffer dst = dsts[i];
|
||||
if (!dst.hasRemaining()) {
|
||||
continue;
|
||||
}
|
||||
int n = implRead(dst);
|
||||
if (n < 0) {
|
||||
return total == 0 ? -1 : total;
|
||||
}
|
||||
total += n;
|
||||
if (dst.hasRemaining()) {
|
||||
break; // A short read: the file has nothing more for the next buffer yet.
|
||||
}
|
||||
}
|
||||
return total;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public int write(ByteBuffer src) throws IOException {
|
||||
checkWriteFrom(src);
|
||||
return (int) io(() -> {
|
||||
int n = src.remaining();
|
||||
if (n > 0) {
|
||||
implWrite(src);
|
||||
}
|
||||
return n;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException {
|
||||
Objects.checkFromIndexSize(offset, length, srcs.length);
|
||||
ensureOpen();
|
||||
for (int i = offset; i < offset + length; i++) {
|
||||
checkWriteFrom(srcs[i]);
|
||||
}
|
||||
return io(() -> {
|
||||
long total = 0;
|
||||
for (int i = offset; i < offset + length; i++) {
|
||||
ByteBuffer src = srcs[i];
|
||||
int n = src.remaining();
|
||||
if (n > 0) {
|
||||
implWrite(src);
|
||||
total += n;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public long position() throws IOException {
|
||||
ensureOpen();
|
||||
return io(this::implPosition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TFileChannel position(long newPosition) throws IOException {
|
||||
ensureOpen();
|
||||
if (newPosition < 0) {
|
||||
throw new IllegalArgumentException("Negative position");
|
||||
}
|
||||
io(() -> {
|
||||
implPosition(newPosition);
|
||||
return 0;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long size() throws IOException {
|
||||
ensureOpen();
|
||||
return io(this::implSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TFileChannel truncate(long size) throws IOException {
|
||||
ensureOpen();
|
||||
if (size < 0) {
|
||||
throw new IllegalArgumentException("Negative size");
|
||||
}
|
||||
if (!writable) {
|
||||
throw new NonWritableChannelException();
|
||||
}
|
||||
io(() -> {
|
||||
if (size < implSize()) {
|
||||
implTruncate(size);
|
||||
}
|
||||
if (implPosition() > size) {
|
||||
implPosition(size);
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void force(boolean metaData) throws IOException {
|
||||
ensureOpen();
|
||||
io(() -> {
|
||||
implForce();
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public long transferTo(long position, long count, WritableByteChannel target) throws IOException {
|
||||
ensureOpen();
|
||||
if (!target.isOpen()) {
|
||||
throw new ClosedChannelException();
|
||||
}
|
||||
if (!readable) {
|
||||
throw new NonReadableChannelException();
|
||||
}
|
||||
checkRange(position, count);
|
||||
// Chunk by chunk, without holding the I/O lock across the target's writes: the target
|
||||
// may be another channel with its own lock, or this one.
|
||||
ByteBuffer buffer = ByteBuffer.allocate((int) Math.min(CHUNK, Math.max(count, 1)));
|
||||
long total = 0;
|
||||
while (total < count) {
|
||||
buffer.clear().limit((int) Math.min(buffer.capacity(), count - total));
|
||||
int n = read(buffer, position + total);
|
||||
if (n <= 0) {
|
||||
break;
|
||||
}
|
||||
buffer.flip();
|
||||
while (buffer.hasRemaining()) {
|
||||
if (target.write(buffer) <= 0) {
|
||||
break; // A target that takes nothing now (non-blocking) ends the transfer.
|
||||
}
|
||||
}
|
||||
total += n - buffer.remaining();
|
||||
if (buffer.hasRemaining()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
|
||||
ensureOpen();
|
||||
if (!src.isOpen()) {
|
||||
throw new ClosedChannelException();
|
||||
}
|
||||
if (!writable) {
|
||||
throw new NonWritableChannelException();
|
||||
}
|
||||
checkRange(position, count);
|
||||
if (position > size()) {
|
||||
return 0;
|
||||
}
|
||||
ByteBuffer buffer = ByteBuffer.allocate((int) Math.min(CHUNK, Math.max(count, 1)));
|
||||
long total = 0;
|
||||
while (total < count) {
|
||||
buffer.clear().limit((int) Math.min(buffer.capacity(), count - total));
|
||||
int n = src.read(buffer);
|
||||
if (n <= 0) {
|
||||
break;
|
||||
}
|
||||
buffer.flip();
|
||||
write(buffer, position + total);
|
||||
total += n;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(ByteBuffer dst, long position) throws IOException {
|
||||
if (position < 0) {
|
||||
throw new IllegalArgumentException("Negative position");
|
||||
}
|
||||
checkReadInto(dst);
|
||||
if (!dst.hasRemaining()) {
|
||||
return 0;
|
||||
}
|
||||
return (int) io(() -> implRead(dst, position));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int write(ByteBuffer src, long position) throws IOException {
|
||||
if (position < 0) {
|
||||
throw new IllegalArgumentException("Negative position");
|
||||
}
|
||||
checkWriteFrom(src);
|
||||
return (int) io(() -> {
|
||||
int n = src.remaining();
|
||||
if (n > 0) {
|
||||
implWrite(src, position);
|
||||
}
|
||||
return n;
|
||||
});
|
||||
}
|
||||
|
||||
/** A page has no way to map a file into memory. */
|
||||
@Override
|
||||
public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException {
|
||||
throw new UnsupportedOperationException("Memory-mapped files are not available in the browser");
|
||||
}
|
||||
|
||||
@Override
|
||||
public TFileLock lock(long position, long size, boolean shared) throws IOException {
|
||||
return tryLock(position, size, shared);
|
||||
}
|
||||
|
||||
/**
|
||||
* Grants the lock at once: one page is one process, so the only locks that could conflict are
|
||||
* this program's own, and the contract makes those an {@code OverlappingFileLockException}
|
||||
* rather than a wait.
|
||||
*/
|
||||
@Override
|
||||
public TFileLock tryLock(long position, long size, boolean shared) throws IOException {
|
||||
ensureOpen();
|
||||
checkRange(position, size);
|
||||
if (position + size < 0) {
|
||||
throw new IllegalArgumentException("Negative position + size");
|
||||
}
|
||||
if (shared && !readable) {
|
||||
throw new NonReadableChannelException();
|
||||
}
|
||||
if (!shared && !writable) {
|
||||
throw new NonWritableChannelException();
|
||||
}
|
||||
// A size of zero locks from the position to the end of the file, however it grows.
|
||||
long lockSize = size == 0 ? Long.MAX_VALUE - position : size;
|
||||
return LockTable.acquire(this, lockKey, position, lockSize, shared);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void implCloseChannel() throws IOException {
|
||||
LockTable.releaseAll(lockKey, this);
|
||||
synchronized (ioLock) {
|
||||
implClose();
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers -----------------------------------------------------------------------------------
|
||||
|
||||
/** An I/O primitive, run by {@link #io}. */
|
||||
@FunctionalInterface
|
||||
interface Primitive {
|
||||
long run() throws IOException;
|
||||
}
|
||||
|
||||
/** Runs {@code primitive} holding the I/O lock, inside the interruptible-channel bracket. */
|
||||
private long io(Primitive primitive) throws IOException {
|
||||
boolean completed = false;
|
||||
begin();
|
||||
try {
|
||||
synchronized (ioLock) {
|
||||
// Checked again under the lock: another thread may have closed the channel.
|
||||
ensureOpen();
|
||||
long result = primitive.run();
|
||||
completed = true;
|
||||
return result;
|
||||
}
|
||||
} finally {
|
||||
end(completed);
|
||||
}
|
||||
}
|
||||
|
||||
final void ensureOpen() throws ClosedChannelException {
|
||||
if (!isOpen()) {
|
||||
throw new ClosedChannelException();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkReadInto(ByteBuffer dst) throws ClosedChannelException {
|
||||
Objects.requireNonNull(dst);
|
||||
ensureOpen();
|
||||
if (!readable) {
|
||||
throw new NonReadableChannelException();
|
||||
}
|
||||
if (dst.isReadOnly()) {
|
||||
throw new IllegalArgumentException("Read-only buffer");
|
||||
}
|
||||
}
|
||||
|
||||
private void checkWriteFrom(ByteBuffer src) throws ClosedChannelException {
|
||||
Objects.requireNonNull(src);
|
||||
ensureOpen();
|
||||
if (!writable) {
|
||||
throw new NonWritableChannelException();
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkRange(long position, long count) {
|
||||
if (position < 0) {
|
||||
throw new IllegalArgumentException("Negative position");
|
||||
}
|
||||
if (count < 0) {
|
||||
throw new IllegalArgumentException("Negative size");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package incari.classlib.nio;
|
||||
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileChannel;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.AccessDeniedException;
|
||||
import java.nio.file.FileAlreadyExistsException;
|
||||
import java.nio.file.FileSystemException;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.function.Function;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Opens {@code FileChannel}s for the browser build, over {@link RandomAccessFile} and TeaVM's
|
||||
* virtual file system, and gives the file streams their channels.
|
||||
*
|
||||
* <p>Differences from the JDK, all forced by the page:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Initial file attributes can't be set: the virtual file system has none. Passing any throws
|
||||
* {@link UnsupportedOperationException}, as the JDK does for attributes it can't set.
|
||||
* <li>{@code SYNC} and {@code DSYNC} open the file in {@code "rws"}/{@code "rwd"} mode, and
|
||||
* {@code force} does nothing: there is no disk cache between the page and its storage.
|
||||
* <li>{@code NOFOLLOW_LINKS} and {@code SPARSE} are accepted and ignored (no links, no sparse
|
||||
* files). {@code DELETE_ON_CLOSE} deletes the file when the channel closes, best effort.
|
||||
* <li>A directory opened for reading gives a channel whose reads fail, as on Linux.
|
||||
* </ul>
|
||||
*/
|
||||
public final class FileChannels {
|
||||
|
||||
private static final int UNKNOWN = 0;
|
||||
private static final int PRESERVES = 1;
|
||||
private static final int TRUNCATES = 2;
|
||||
|
||||
// Whether opening an existing file "rw" empties it: TeaVM's RandomAccessFile does, the
|
||||
// JDK's doesn't. Found out once, by trying (readWriteOpenTruncates).
|
||||
private static volatile int readWriteOpen = UNKNOWN;
|
||||
|
||||
// Each stream's channel, so getChannel() keeps returning the same one. Weak both ways: the
|
||||
// channel refers to its stream, so a strong value would keep the key alive forever.
|
||||
// Guarded by the map itself.
|
||||
private static final Map<Object, WeakReference<TFileChannel>> STREAM_CHANNELS = new WeakHashMap<>();
|
||||
|
||||
private FileChannels() {}
|
||||
|
||||
/** {@code FileChannel.open(Path, Set, FileAttribute...)}. */
|
||||
public static TFileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
|
||||
throws IOException {
|
||||
Objects.requireNonNull(path);
|
||||
boolean read = false;
|
||||
boolean write = false;
|
||||
boolean append = false;
|
||||
boolean truncate = false;
|
||||
boolean create = false;
|
||||
boolean createNew = false;
|
||||
boolean deleteOnClose = false;
|
||||
boolean sync = false;
|
||||
boolean dsync = false;
|
||||
for (OpenOption option : options) {
|
||||
Objects.requireNonNull(option);
|
||||
if (option instanceof StandardOpenOption standard) {
|
||||
switch (standard) {
|
||||
case READ -> read = true;
|
||||
case WRITE -> write = true;
|
||||
case APPEND -> append = true;
|
||||
case TRUNCATE_EXISTING -> truncate = true;
|
||||
case CREATE -> create = true;
|
||||
case CREATE_NEW -> createNew = true;
|
||||
case DELETE_ON_CLOSE -> deleteOnClose = true;
|
||||
case SYNC -> sync = true;
|
||||
case DSYNC -> dsync = true;
|
||||
case SPARSE -> {
|
||||
// Files in the page have no holes to leave; a hint the JDK may ignore too.
|
||||
}
|
||||
}
|
||||
} else if (option != LinkOption.NOFOLLOW_LINKS) {
|
||||
// The virtual file system has no links, so not following them changes nothing.
|
||||
throw new UnsupportedOperationException(option + " not supported");
|
||||
}
|
||||
}
|
||||
if (attrs.length > 0) {
|
||||
throw new UnsupportedOperationException(
|
||||
"'" + attrs[0].name() + "' not supported as initial attribute in the browser");
|
||||
}
|
||||
if (append) {
|
||||
if (read) {
|
||||
throw new IllegalArgumentException("READ + APPEND not allowed");
|
||||
}
|
||||
if (truncate) {
|
||||
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
|
||||
}
|
||||
write = true;
|
||||
}
|
||||
if (!read && !write) {
|
||||
read = true;
|
||||
}
|
||||
|
||||
File file = path.toFile();
|
||||
if (file.isDirectory()) {
|
||||
if (write) {
|
||||
throw new FileSystemException(path.toString(), null, "Is a directory");
|
||||
}
|
||||
return new DirectoryChannel(path.toString());
|
||||
}
|
||||
if (write && createNew) {
|
||||
if (!createFile(file, path)) {
|
||||
throw new FileAlreadyExistsException(path.toString());
|
||||
}
|
||||
} else if (!file.exists()) {
|
||||
if (!write || !create) {
|
||||
throw new NoSuchFileException(path.toString());
|
||||
}
|
||||
createFile(file, path);
|
||||
}
|
||||
|
||||
RandomAccessFile raf;
|
||||
try {
|
||||
if (!write) {
|
||||
raf = new RandomAccessFile(file, "r");
|
||||
} else {
|
||||
raf = openForWriting(file, sync ? "rws" : dsync ? "rwd" : "rw", truncate);
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
// The file exists by now, so the platform refused it.
|
||||
IOException refused = file.exists()
|
||||
? new AccessDeniedException(path.toString(), null, e.getMessage())
|
||||
: new NoSuchFileException(path.toString());
|
||||
refused.initCause(e);
|
||||
throw refused;
|
||||
}
|
||||
Object lockKey = path.toAbsolutePath().normalize().toString();
|
||||
return new RandomAccessFileChannel(raf, read, write, append, deleteOnClose ? file : null, lockKey);
|
||||
}
|
||||
|
||||
/** {@code RandomAccessFile.getChannel()}: a channel sharing the file's pointer. */
|
||||
public static TFileChannel of(RandomAccessFile file) {
|
||||
// Whether the file was opened read-only is private to it, so the channel allows both and
|
||||
// the file itself refuses writes it can't do.
|
||||
return channelOf(file, f -> new RandomAccessFileChannel(f, true, true, false, null, new Object()));
|
||||
}
|
||||
|
||||
/** {@code FileInputStream.getChannel()}. See {@link StreamFileChannel} for its limits. */
|
||||
public static TFileChannel of(FileInputStream in) {
|
||||
return channelOf(in, StreamFileChannel::reading);
|
||||
}
|
||||
|
||||
/** {@code FileOutputStream.getChannel()}. See {@link StreamFileChannel} for its limits. */
|
||||
public static TFileChannel of(FileOutputStream out) {
|
||||
return channelOf(out, StreamFileChannel::writing);
|
||||
}
|
||||
|
||||
private static <T> TFileChannel channelOf(T owner, Function<T, TFileChannel> factory) {
|
||||
synchronized (STREAM_CHANNELS) {
|
||||
WeakReference<TFileChannel> ref = STREAM_CHANNELS.get(owner);
|
||||
TFileChannel channel = ref == null ? null : ref.get();
|
||||
if (channel == null) {
|
||||
channel = factory.apply(owner);
|
||||
STREAM_CHANNELS.put(owner, new WeakReference<>(channel));
|
||||
}
|
||||
return channel;
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates {@code file}; false if it already exists. */
|
||||
private static boolean createFile(File file, Path path) throws IOException {
|
||||
File parent = file.getAbsoluteFile().getParentFile();
|
||||
if (parent == null || !parent.isDirectory()) {
|
||||
throw new NoSuchFileException(path.toString());
|
||||
}
|
||||
return file.createNewFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens {@code file} for reading and writing, keeping its content unless {@code truncate}.
|
||||
* Where opening "rw" empties the file (TeaVM), the content is read first and put back.
|
||||
*/
|
||||
private static RandomAccessFile openForWriting(File file, String mode, boolean truncate) throws IOException {
|
||||
long length = file.length();
|
||||
byte @Nullable [] content = null;
|
||||
if (!truncate && length > 0 && readWriteOpenTruncates()) {
|
||||
content = new byte[(int) length];
|
||||
try (RandomAccessFile original = new RandomAccessFile(file, "r")) {
|
||||
original.readFully(content);
|
||||
}
|
||||
}
|
||||
RandomAccessFile raf = new RandomAccessFile(file, mode);
|
||||
try {
|
||||
if (truncate) {
|
||||
raf.setLength(0);
|
||||
} else if (content != null && raf.length() != content.length) {
|
||||
raf.setLength(0);
|
||||
raf.write(content);
|
||||
raf.seek(0);
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
try {
|
||||
raf.close();
|
||||
} catch (IOException suppressed) {
|
||||
e.addSuppressed(suppressed);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return raf;
|
||||
}
|
||||
|
||||
private static boolean readWriteOpenTruncates() {
|
||||
int state = readWriteOpen;
|
||||
if (state == UNKNOWN) {
|
||||
state = probeReadWriteOpen() ? TRUNCATES : PRESERVES;
|
||||
readWriteOpen = state;
|
||||
}
|
||||
return state == TRUNCATES;
|
||||
}
|
||||
|
||||
private static boolean probeReadWriteOpen() {
|
||||
try {
|
||||
File probe = File.createTempFile("incari-", ".probe");
|
||||
try {
|
||||
try (RandomAccessFile out = new RandomAccessFile(probe, "rw")) {
|
||||
out.write(1);
|
||||
}
|
||||
try (RandomAccessFile again = new RandomAccessFile(probe, "rw")) {
|
||||
return again.length() == 0;
|
||||
}
|
||||
} finally {
|
||||
probe.delete();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Assume the worst: keeping content wrongly costs a copy, losing it costs the file.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A directory opened for reading. The JDK allows the open (so a directory can be forced) and
|
||||
* fails the reads.
|
||||
*/
|
||||
private static final class DirectoryChannel extends BaseFileChannel {
|
||||
|
||||
private final String path;
|
||||
|
||||
DirectoryChannel(String path) {
|
||||
super(true, false, new Object());
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
@Override
|
||||
int implRead(ByteBuffer dst) throws IOException {
|
||||
throw isDirectory();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implWrite(ByteBuffer src) throws IOException {
|
||||
throw isDirectory();
|
||||
}
|
||||
|
||||
@Override
|
||||
int implRead(ByteBuffer dst, long position) throws IOException {
|
||||
throw isDirectory();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implWrite(ByteBuffer src, long position) throws IOException {
|
||||
throw isDirectory();
|
||||
}
|
||||
|
||||
@Override
|
||||
long implPosition() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
void implPosition(long newPosition) {}
|
||||
|
||||
@Override
|
||||
long implSize() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
void implTruncate(long size) {}
|
||||
|
||||
@Override
|
||||
void implForce() {}
|
||||
|
||||
@Override
|
||||
void implClose() {}
|
||||
|
||||
private IOException isDirectory() {
|
||||
return new IOException(path + ": Is a directory");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package incari.classlib.nio;
|
||||
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileChannel;
|
||||
import incari.classlib.substitutes.java.nio.channels.TFileLock;
|
||||
import incari.classlib.substitutes.java.nio.channels.TOverlappingFileLockException;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.ClosedChannelException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The file locks this program holds, by file. The JDK refuses a lock that overlaps one already
|
||||
* held on the same file anywhere in the program, through any channel; with one page as the only
|
||||
* process, that refusal is all locking has left to do.
|
||||
*/
|
||||
final class LockTable {
|
||||
|
||||
// Guarded by LockTable.class.
|
||||
private static final Map<Object, List<ChannelLock>> HELD = new HashMap<>();
|
||||
|
||||
private LockTable() {}
|
||||
|
||||
static synchronized TFileLock acquire(TFileChannel channel, Object key, long position, long size, boolean shared) {
|
||||
List<ChannelLock> held = HELD.get(key);
|
||||
if (held == null) {
|
||||
held = new ArrayList<>();
|
||||
HELD.put(key, held);
|
||||
}
|
||||
for (ChannelLock lock : held) {
|
||||
if (lock.overlaps(position, size)) {
|
||||
throw new TOverlappingFileLockException();
|
||||
}
|
||||
}
|
||||
ChannelLock lock = new ChannelLock(channel, key, position, size, shared);
|
||||
held.add(lock);
|
||||
return lock;
|
||||
}
|
||||
|
||||
/** Releases every lock {@code channel} holds, as closing it does. */
|
||||
static synchronized void releaseAll(Object key, TFileChannel channel) {
|
||||
List<ChannelLock> held = HELD.get(key);
|
||||
if (held == null) {
|
||||
return;
|
||||
}
|
||||
held.removeIf(lock -> {
|
||||
if (!lock.channel().equals(channel)) {
|
||||
return false;
|
||||
}
|
||||
lock.valid = false;
|
||||
return true;
|
||||
});
|
||||
if (held.isEmpty()) {
|
||||
HELD.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized void release(ChannelLock lock) {
|
||||
if (!lock.valid) {
|
||||
return;
|
||||
}
|
||||
lock.valid = false;
|
||||
List<ChannelLock> held = HELD.get(lock.key);
|
||||
if (held != null) {
|
||||
held.remove(lock);
|
||||
if (held.isEmpty()) {
|
||||
HELD.remove(lock.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ChannelLock extends TFileLock {
|
||||
|
||||
private final Object key;
|
||||
// Written under LockTable's lock; read without it by isValid.
|
||||
volatile boolean valid = true;
|
||||
|
||||
ChannelLock(TFileChannel channel, Object key, long position, long size, boolean shared) {
|
||||
super(channel, position, size, shared);
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid() {
|
||||
return valid && channel().isOpen();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release() throws IOException {
|
||||
if (!channel().isOpen()) {
|
||||
throw new ClosedChannelException();
|
||||
}
|
||||
LockTable.release(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package incari.classlib.nio;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A file channel over a {@link RandomAccessFile}, which TeaVM keeps in its virtual file system.
|
||||
* The channel's position is the file's pointer, so a channel from
|
||||
* {@code RandomAccessFile.getChannel()} shares it with the file as the JDK requires.
|
||||
*/
|
||||
final class RandomAccessFileChannel extends BaseFileChannel {
|
||||
|
||||
private final RandomAccessFile file;
|
||||
private final boolean append;
|
||||
private final @Nullable File deleteOnClose;
|
||||
// Copies through buffers with no backing array (direct ones); guarded by the I/O lock.
|
||||
private byte @Nullable [] scratch;
|
||||
|
||||
RandomAccessFileChannel(
|
||||
RandomAccessFile file,
|
||||
boolean readable,
|
||||
boolean writable,
|
||||
boolean append,
|
||||
@Nullable File deleteOnClose,
|
||||
Object lockKey) {
|
||||
super(readable, writable, lockKey);
|
||||
this.file = file;
|
||||
this.append = append;
|
||||
this.deleteOnClose = deleteOnClose;
|
||||
}
|
||||
|
||||
@Override
|
||||
int implRead(ByteBuffer dst) throws IOException {
|
||||
// Never asks the file for zero bytes: TeaVM's RandomAccessFile reports that as the end.
|
||||
int length = dst.remaining();
|
||||
if (dst.hasArray()) {
|
||||
int n = file.read(dst.array(), dst.arrayOffset() + dst.position(), length);
|
||||
if (n > 0) {
|
||||
dst.position(dst.position() + n);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
byte[] buffer = scratch();
|
||||
int n = file.read(buffer, 0, Math.min(length, buffer.length));
|
||||
if (n > 0) {
|
||||
dst.put(buffer, 0, n);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@Override
|
||||
void implWrite(ByteBuffer src) throws IOException {
|
||||
if (append) {
|
||||
file.seek(file.length());
|
||||
}
|
||||
writeAll(src);
|
||||
}
|
||||
|
||||
@Override
|
||||
int implRead(ByteBuffer dst, long position) throws IOException {
|
||||
if (position >= file.length()) {
|
||||
return -1;
|
||||
}
|
||||
long saved = file.getFilePointer();
|
||||
try {
|
||||
file.seek(position);
|
||||
return implRead(dst);
|
||||
} finally {
|
||||
file.seek(saved);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
void implWrite(ByteBuffer src, long position) throws IOException {
|
||||
long saved = file.getFilePointer();
|
||||
try {
|
||||
file.seek(position);
|
||||
writeAll(src);
|
||||
} finally {
|
||||
file.seek(saved);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
long implPosition() throws IOException {
|
||||
// In append mode every write lands at the end, and the JDK reports the position there.
|
||||
return append ? file.length() : file.getFilePointer();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implPosition(long newPosition) throws IOException {
|
||||
file.seek(newPosition);
|
||||
}
|
||||
|
||||
@Override
|
||||
long implSize() throws IOException {
|
||||
return file.length();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implTruncate(long size) throws IOException {
|
||||
file.setLength(size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing to do: the page's virtual file system has no write cache between the channel and
|
||||
* the storage behind it.
|
||||
*/
|
||||
@Override
|
||||
void implForce() {}
|
||||
|
||||
@Override
|
||||
void implClose() throws IOException {
|
||||
try {
|
||||
file.close();
|
||||
} finally {
|
||||
if (deleteOnClose != null) {
|
||||
// Best effort, as in the JDK: a file that can't be deleted stays.
|
||||
deleteOnClose.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void writeAll(ByteBuffer src) throws IOException {
|
||||
if (src.hasArray()) {
|
||||
file.write(src.array(), src.arrayOffset() + src.position(), src.remaining());
|
||||
src.position(src.limit());
|
||||
return;
|
||||
}
|
||||
byte[] buffer = scratch();
|
||||
while (src.hasRemaining()) {
|
||||
int n = Math.min(src.remaining(), buffer.length);
|
||||
src.get(buffer, 0, n);
|
||||
file.write(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] scratch() {
|
||||
byte[] buffer = scratch;
|
||||
if (buffer == null) {
|
||||
buffer = new byte[CHUNK];
|
||||
scratch = buffer;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package incari.classlib.nio;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The channel of a {@code FileInputStream} or {@code FileOutputStream} in the browser build.
|
||||
*
|
||||
* <p>TeaVM's file streams keep their file handle to themselves, and nothing outside them can
|
||||
* reach it, so this channel reads and writes through the stream. That keeps the JDK's rule that
|
||||
* the stream and its channel share one position, but the position can't be read or moved: the
|
||||
* operations that need it or the file's size ({@code position}, {@code size}, {@code truncate},
|
||||
* positional reads and writes, transfers) throw an {@link IOException}. To use those, open the
|
||||
* file with {@code FileChannel.open} or {@code RandomAccessFile}.
|
||||
*/
|
||||
final class StreamFileChannel extends BaseFileChannel {
|
||||
|
||||
private final @Nullable InputStream in;
|
||||
private final @Nullable OutputStream out;
|
||||
private byte @Nullable [] scratch;
|
||||
|
||||
private StreamFileChannel(@Nullable InputStream in, @Nullable OutputStream out) {
|
||||
super(in != null, out != null, new Object());
|
||||
this.in = in;
|
||||
this.out = out;
|
||||
}
|
||||
|
||||
static StreamFileChannel reading(InputStream in) {
|
||||
return new StreamFileChannel(in, null);
|
||||
}
|
||||
|
||||
static StreamFileChannel writing(OutputStream out) {
|
||||
return new StreamFileChannel(null, out);
|
||||
}
|
||||
|
||||
@Override
|
||||
int implRead(ByteBuffer dst) throws IOException {
|
||||
InputStream stream = in();
|
||||
int length = dst.remaining();
|
||||
if (dst.hasArray()) {
|
||||
int n = stream.read(dst.array(), dst.arrayOffset() + dst.position(), length);
|
||||
if (n > 0) {
|
||||
dst.position(dst.position() + n);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
byte[] buffer = scratch();
|
||||
int n = stream.read(buffer, 0, Math.min(length, buffer.length));
|
||||
if (n > 0) {
|
||||
dst.put(buffer, 0, n);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@Override
|
||||
void implWrite(ByteBuffer src) throws IOException {
|
||||
OutputStream stream = out();
|
||||
if (src.hasArray()) {
|
||||
stream.write(src.array(), src.arrayOffset() + src.position(), src.remaining());
|
||||
src.position(src.limit());
|
||||
return;
|
||||
}
|
||||
byte[] buffer = scratch();
|
||||
while (src.hasRemaining()) {
|
||||
int n = Math.min(src.remaining(), buffer.length);
|
||||
src.get(buffer, 0, n);
|
||||
stream.write(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
int implRead(ByteBuffer dst, long position) throws IOException {
|
||||
throw unseekable();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implWrite(ByteBuffer src, long position) throws IOException {
|
||||
throw unseekable();
|
||||
}
|
||||
|
||||
@Override
|
||||
long implPosition() throws IOException {
|
||||
throw unseekable();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implPosition(long newPosition) throws IOException {
|
||||
throw unseekable();
|
||||
}
|
||||
|
||||
@Override
|
||||
long implSize() throws IOException {
|
||||
throw unseekable();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implTruncate(long size) throws IOException {
|
||||
throw unseekable();
|
||||
}
|
||||
|
||||
@Override
|
||||
void implForce() throws IOException {
|
||||
if (out != null) {
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/** Closing a stream's channel closes the stream, as in the JDK. */
|
||||
@Override
|
||||
void implClose() throws IOException {
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
private InputStream in() {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("Not a reading channel");
|
||||
}
|
||||
return in;
|
||||
}
|
||||
|
||||
private OutputStream out() {
|
||||
if (out == null) {
|
||||
throw new IllegalStateException("Not a writing channel");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static IOException unseekable() {
|
||||
return new IOException("A file stream's channel can't seek or size its file in the browser;"
|
||||
+ " open the file with FileChannel.open or RandomAccessFile instead");
|
||||
}
|
||||
|
||||
private byte[] scratch() {
|
||||
byte[] buffer = scratch;
|
||||
if (buffer == null) {
|
||||
buffer = new byte[CHUNK];
|
||||
scratch = buffer;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package incari.classlib.nio;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.channels.SeekableByteChannel;
|
||||
import java.nio.file.AccessMode;
|
||||
import java.nio.file.CopyOption;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.FileStore;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.nio.file.attribute.FileAttributeView;
|
||||
import java.nio.file.spi.FileSystemProvider;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The browser build's {@code jar} file system provider, which the game looks up at startup
|
||||
* ({@code Util.ZIP_FILE_SYSTEM_PROVIDER}) for writing zip files (world exports, debug reports).
|
||||
* There's no zip file system: every operation refuses, so profiling reports can't be written
|
||||
* (ADR 0011). Resource packs in zips are read through {@code ZipFile}, which works.
|
||||
*/
|
||||
public final class ZipFileSystemProvider extends FileSystemProvider {
|
||||
|
||||
@Override
|
||||
public String getScheme() {
|
||||
return "jar";
|
||||
}
|
||||
|
||||
private static UnsupportedOperationException unsupported() {
|
||||
return new UnsupportedOperationException("Zip files aren't supported in the browser build yet");
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileSystem newFileSystem(URI uri, Map<String, ?> env) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileSystem newFileSystem(Path path, Map<String, ?> env) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileSystem getFileSystem(URI uri) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path getPath(URI uri) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createDirectory(Path dir, FileAttribute<?>... attrs) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Path path) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copy(Path source, Path target, CopyOption... options) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void move(Path source, Path target, CopyOption... options) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSameFile(Path path, Path path2) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden(Path path) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileStore getFileStore(Path path) throws IOException {
|
||||
throw new IOException("Zip files aren't supported in the browser build yet");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkAccess(Path path, AccessMode... modes) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V extends FileAttributeView> @Nullable V getFileAttributeView(
|
||||
Path path, Class<V> type, LinkOption... options) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) {
|
||||
throw unsupported();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* The JDK as the browser build needs it: classes and methods TeaVM's class library lacks, written
|
||||
* for a single-threaded page where Java threads are coroutines.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code incari.classlib.substitutes.<package>.T<Name>} stands in for {@code <package>.<Name>};
|
||||
* <li>{@code incari.classlib.additions.<package>.<Name>Additions} adds methods to a class TeaVM
|
||||
* has ({@link incari.classlib.InstanceMethod});
|
||||
* <li>{@link incari.classlib.Removed} is what code the build strips turns into.
|
||||
* </ul>
|
||||
*
|
||||
* <p>The code runs on a desktop JVM too, which is how its tests run. Nothing here may be copied
|
||||
* from the JDK: it's written fresh against the documented behaviour.
|
||||
*/
|
||||
@NullMarked
|
||||
package incari.classlib;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package incari.classlib.reflect;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Generic superclasses the browser build keeps, for {@code Class.getGenericSuperclass}. A
|
||||
* compiled page has no generic signatures, but "type capture" relies on them: an anonymous
|
||||
* {@code new TypeToken<Map<String, Integer>>() {}} (Guava's and Gson's) reads its type argument
|
||||
* from its superclass, and DataFixerUpper and the game use such tokens. {@code tools/webbuild}
|
||||
* fills in {@link #of} for the direct subclasses of those bases; other classes answer null.
|
||||
*/
|
||||
public final class GenericSuperclasses {
|
||||
|
||||
private GenericSuperclasses() {}
|
||||
|
||||
/**
|
||||
* The generic superclass the build recorded for {@code cls}, or null. The web build replaces
|
||||
* this body; the web build refers to this class and method by name.
|
||||
*/
|
||||
public static @Nullable Type of(Class<?> cls) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package incari.classlib.reflect;
|
||||
|
||||
import java.lang.reflect.GenericArrayType;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.WildcardType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Builds {@link Type}s from the compact form {@code tools/webbuild} records them in: a string of
|
||||
* one-letter tags, and the classes it names in order of appearance (class literals, since a page
|
||||
* can't look classes up by name).
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code C}: the next class;
|
||||
* <li>{@code P} owner count args...: a parameterized type of the next class; owner is {@code N}
|
||||
* (none) or a type; count is one digit;
|
||||
* <li>{@code A} component: a generic array;
|
||||
* <li>{@code U} bound / {@code L} bound: a wildcard with that upper / lower bound ({@code ?} is
|
||||
* {@code U} of {@code Object}).
|
||||
* </ul>
|
||||
*
|
||||
* <p>Equality and hash codes follow the JDK's contracts, so these compare equal to the JDK's own
|
||||
* (and Guava's, and Gson's) types for the same thing.
|
||||
*/
|
||||
public final class GenericTypes {
|
||||
|
||||
private final String code;
|
||||
private final Class<?>[] classes;
|
||||
private int position;
|
||||
private int nextClass;
|
||||
|
||||
private GenericTypes(String code, Class<?>[] classes) {
|
||||
this.code = code;
|
||||
this.classes = classes;
|
||||
}
|
||||
|
||||
/** The type {@code code} describes; the web build calls this from {@link GenericSuperclasses}. */
|
||||
public static Type parse(String code, Class<?>[] classes) {
|
||||
GenericTypes parser = new GenericTypes(code, classes);
|
||||
Type type = parser.type();
|
||||
if (parser.position != code.length() || parser.nextClass != classes.length) {
|
||||
throw new IllegalArgumentException("Malformed type code " + code);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private Type type() {
|
||||
char tag = code.charAt(position++);
|
||||
return switch (tag) {
|
||||
case 'C' -> classes[nextClass++];
|
||||
case 'P' -> {
|
||||
Class<?> raw = classes[nextClass++];
|
||||
Type owner = code.charAt(position) == 'N' ? skipNone() : type();
|
||||
Type[] arguments = new Type[code.charAt(position++) - '0'];
|
||||
for (int i = 0; i < arguments.length; i++) {
|
||||
arguments[i] = type();
|
||||
}
|
||||
yield new Parameterized(raw, owner, arguments);
|
||||
}
|
||||
case 'A' -> new GenericArray(type());
|
||||
case 'U' -> new Wildcard(new Type[] {type()}, new Type[0]);
|
||||
case 'L' -> new Wildcard(new Type[] {Object.class}, new Type[] {type()});
|
||||
default -> throw new IllegalArgumentException("Malformed type code " + code);
|
||||
};
|
||||
}
|
||||
|
||||
private @Nullable Type skipNone() {
|
||||
position++;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String name(Type type) {
|
||||
return type instanceof Class<?> cls ? cls.getName() : type.toString();
|
||||
}
|
||||
|
||||
private static final class Parameterized implements ParameterizedType {
|
||||
private final Class<?> raw;
|
||||
private final @Nullable Type owner;
|
||||
private final Type[] arguments;
|
||||
|
||||
Parameterized(Class<?> raw, @Nullable Type owner, Type[] arguments) {
|
||||
this.raw = raw;
|
||||
this.owner = owner;
|
||||
this.arguments = arguments;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type[] getActualTypeArguments() {
|
||||
return arguments.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type getRawType() {
|
||||
return raw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable Type getOwnerType() {
|
||||
return owner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object o) {
|
||||
return o instanceof ParameterizedType that
|
||||
&& raw.equals(that.getRawType())
|
||||
&& Objects.equals(owner, that.getOwnerType())
|
||||
&& Arrays.equals(arguments, that.getActualTypeArguments());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Arrays.hashCode(arguments) ^ Objects.hashCode(owner) ^ raw.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder text = new StringBuilder(raw.getName()).append('<');
|
||||
for (int i = 0; i < arguments.length; i++) {
|
||||
text.append(i == 0 ? "" : ", ").append(name(arguments[i]));
|
||||
}
|
||||
return text.append('>').toString();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class GenericArray implements GenericArrayType {
|
||||
private final Type component;
|
||||
|
||||
GenericArray(Type component) {
|
||||
this.component = component;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type getGenericComponentType() {
|
||||
return component;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object o) {
|
||||
return o instanceof GenericArrayType that && component.equals(that.getGenericComponentType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return component.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name(component) + "[]";
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Wildcard implements WildcardType {
|
||||
private final Type[] upper;
|
||||
private final Type[] lower;
|
||||
|
||||
Wildcard(Type[] upper, Type[] lower) {
|
||||
this.upper = upper;
|
||||
this.lower = lower;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type[] getUpperBounds() {
|
||||
return upper.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type[] getLowerBounds() {
|
||||
return lower.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object o) {
|
||||
return o instanceof WildcardType that
|
||||
&& Arrays.equals(upper, that.getUpperBounds())
|
||||
&& Arrays.equals(lower, that.getLowerBounds());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Arrays.hashCode(upper) ^ Arrays.hashCode(lower);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (lower.length > 0) {
|
||||
return "? super " + name(lower[0]);
|
||||
}
|
||||
return upper[0] == Object.class ? "?" : "? extends " + name(upper[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package incari.classlib.resources;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The class path's resources in the browser build: files under {@link #ROOT} in the page's file
|
||||
* system, then under any root an entry point adds. The build compiles classes only, so whatever
|
||||
* the game reads with {@code Class.getResource} (its language file, {@code version.json}, the
|
||||
* vanilla resource and data packs) is mounted there from the client jar before the game starts, by
|
||||
* the entry point; libraries' resources (Via's mapping data) come from the build's asset pack.
|
||||
*/
|
||||
public final class ClassPathResources {
|
||||
|
||||
/** The directory that stands in for the class path's root. */
|
||||
public static final String ROOT = "/incari/classpath";
|
||||
|
||||
/** More directories searched after {@link #ROOT}, in order; set up before the game starts. */
|
||||
private static final List<String> MORE_ROOTS = new ArrayList<>();
|
||||
|
||||
private ClassPathResources() {}
|
||||
|
||||
/** Makes {@code directory} part of the class path, after the roots before it. */
|
||||
public static void addRoot(String directory) {
|
||||
MORE_ROOTS.add(directory);
|
||||
}
|
||||
|
||||
/**
|
||||
* The file for a resource, as {@code Class.getResource} names it: absolute with a leading
|
||||
* slash, otherwise relative to the class's package.
|
||||
*/
|
||||
public static @Nullable File find(Class<?> caller, String name) {
|
||||
return find(qualified(caller, name));
|
||||
}
|
||||
|
||||
/** The file for a resource named from the class path's root, as class loaders name them. */
|
||||
public static @Nullable File find(String name) {
|
||||
File file = new File(ROOT, name);
|
||||
if (file.isFile() || file.isDirectory()) {
|
||||
return file;
|
||||
}
|
||||
for (String root : MORE_ROOTS) {
|
||||
File other = new File(root, name);
|
||||
if (other.isFile() || other.isDirectory()) {
|
||||
return other;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A {@code file:} URL for the resource, which {@code Paths.get(URI)} turns into a path. */
|
||||
public static @Nullable URL url(@Nullable File file) {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return file.toURI().toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static @Nullable InputStream open(@Nullable File file) {
|
||||
if (file == null || !file.isFile()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new FileInputStream(file);
|
||||
} catch (FileNotFoundException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String qualified(Class<?> caller, String name) {
|
||||
if (name.startsWith("/")) {
|
||||
return name.substring(1);
|
||||
}
|
||||
String className = caller.getName();
|
||||
int lastDot = className.lastIndexOf('.');
|
||||
return lastDot < 0 ? name : className.substring(0, lastDot).replace('.', '/') + "/" + name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package incari.classlib.security;
|
||||
|
||||
import java.util.Locale;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* MD5 (RFC 1321), SHA-1 and SHA-256 (FIPS 180-4), written from their specifications, behind the
|
||||
* browser build's {@code MessageDigest}. All three work on 64-byte blocks padded with a bit length
|
||||
* at the end (little-endian for MD5, big-endian for SHA); only the state, the byte order and the
|
||||
* compression function differ.
|
||||
*/
|
||||
public final class Digest {
|
||||
|
||||
private static final int MD5 = 0;
|
||||
private static final int SHA1 = 1;
|
||||
private static final int SHA256 = 2;
|
||||
|
||||
// MD5's per-round shifts and its constants (the integer part of 2^32 * |sin(i + 1)|).
|
||||
private static final int[] MD5_SHIFT = {7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21};
|
||||
private static final int[] MD5_K = new int[64];
|
||||
|
||||
static {
|
||||
for (int i = 0; i < 64; i++) {
|
||||
MD5_K[i] = (int) (long) Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296.0);
|
||||
}
|
||||
}
|
||||
|
||||
private static final int[] SHA256_K = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
};
|
||||
|
||||
private final int kind;
|
||||
private final int[] state;
|
||||
// The message schedule: 80 words for SHA-1, 64 for SHA-256.
|
||||
private final int[] words = new int[80];
|
||||
private final byte[] block = new byte[64];
|
||||
private int buffered;
|
||||
private long length;
|
||||
|
||||
private Digest(int kind) {
|
||||
this.kind = kind;
|
||||
this.state = new int[kind == SHA256 ? 8 : kind == SHA1 ? 5 : 4];
|
||||
reset();
|
||||
}
|
||||
|
||||
/** A digest for {@code algorithm} ("MD5", "SHA-1", "SHA-256", with or without the dash), or null. */
|
||||
public static @Nullable Digest create(String algorithm) {
|
||||
return switch (algorithm.toUpperCase(Locale.ROOT).replace("-", "")) {
|
||||
case "MD5" -> new Digest(MD5);
|
||||
case "SHA1", "SHA" -> new Digest(SHA1);
|
||||
case "SHA256" -> new Digest(SHA256);
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return kind == SHA256 ? 32 : kind == SHA1 ? 20 : 16;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
int[] initial = kind == SHA256
|
||||
? new int[] {
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
|
||||
}
|
||||
: kind == SHA1
|
||||
? new int[] {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0}
|
||||
: new int[] {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476};
|
||||
System.arraycopy(initial, 0, state, 0, state.length);
|
||||
buffered = 0;
|
||||
length = 0;
|
||||
}
|
||||
|
||||
public void update(byte[] input, int offset, int count) {
|
||||
length += count;
|
||||
for (int i = 0; i < count; i++) {
|
||||
block[buffered++] = input[offset + i];
|
||||
if (buffered == 64) {
|
||||
compress();
|
||||
buffered = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The hash of everything given since the last reset; resets afterwards. */
|
||||
public byte[] finish() {
|
||||
long bits = length * 8;
|
||||
byte[] one = {(byte) 0x80};
|
||||
update(one, 0, 1);
|
||||
byte[] zero = {0};
|
||||
while (buffered != 56) {
|
||||
update(zero, 0, 1);
|
||||
}
|
||||
byte[] tail = new byte[8];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
tail[i] = (byte) (kind == MD5 ? bits >>> (8 * i) : bits >>> (56 - 8 * i));
|
||||
}
|
||||
update(tail, 0, 8);
|
||||
byte[] out = new byte[length()];
|
||||
for (int i = 0; i < out.length; i++) {
|
||||
int shift = kind == MD5 ? 8 * (i % 4) : 24 - 8 * (i % 4);
|
||||
out[i] = (byte) (state[i / 4] >>> shift);
|
||||
}
|
||||
reset();
|
||||
return out;
|
||||
}
|
||||
|
||||
public Digest copy() {
|
||||
Digest copy = new Digest(kind);
|
||||
System.arraycopy(state, 0, copy.state, 0, state.length);
|
||||
System.arraycopy(block, 0, copy.block, 0, block.length);
|
||||
copy.buffered = buffered;
|
||||
copy.length = length;
|
||||
return copy;
|
||||
}
|
||||
|
||||
private void compress() {
|
||||
if (kind == MD5) {
|
||||
compressMd5();
|
||||
return;
|
||||
}
|
||||
for (int t = 0; t < 16; t++) {
|
||||
words[t] = (block[4 * t] & 0xff) << 24
|
||||
| (block[4 * t + 1] & 0xff) << 16
|
||||
| (block[4 * t + 2] & 0xff) << 8
|
||||
| (block[4 * t + 3] & 0xff);
|
||||
}
|
||||
if (kind == SHA256) {
|
||||
compress256();
|
||||
} else {
|
||||
compress1();
|
||||
}
|
||||
}
|
||||
|
||||
private void compressMd5() {
|
||||
for (int t = 0; t < 16; t++) {
|
||||
words[t] = (block[4 * t] & 0xff)
|
||||
| (block[4 * t + 1] & 0xff) << 8
|
||||
| (block[4 * t + 2] & 0xff) << 16
|
||||
| (block[4 * t + 3] & 0xff) << 24;
|
||||
}
|
||||
int a = state[0];
|
||||
int b = state[1];
|
||||
int c = state[2];
|
||||
int d = state[3];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
int f;
|
||||
int g;
|
||||
if (i < 16) {
|
||||
f = (b & c) | (~b & d);
|
||||
g = i;
|
||||
} else if (i < 32) {
|
||||
f = (d & b) | (~d & c);
|
||||
g = (5 * i + 1) % 16;
|
||||
} else if (i < 48) {
|
||||
f = b ^ c ^ d;
|
||||
g = (3 * i + 5) % 16;
|
||||
} else {
|
||||
f = c ^ (b | ~d);
|
||||
g = (7 * i) % 16;
|
||||
}
|
||||
int rotated = Integer.rotateLeft(a + f + MD5_K[i] + words[g], MD5_SHIFT[(i / 16) * 4 + i % 4]);
|
||||
a = d;
|
||||
d = c;
|
||||
c = b;
|
||||
b = b + rotated;
|
||||
}
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
}
|
||||
|
||||
private void compress1() {
|
||||
for (int t = 16; t < 80; t++) {
|
||||
words[t] = Integer.rotateLeft(words[t - 3] ^ words[t - 8] ^ words[t - 14] ^ words[t - 16], 1);
|
||||
}
|
||||
int a = state[0];
|
||||
int b = state[1];
|
||||
int c = state[2];
|
||||
int d = state[3];
|
||||
int e = state[4];
|
||||
for (int t = 0; t < 80; t++) {
|
||||
int f;
|
||||
int k;
|
||||
if (t < 20) {
|
||||
f = (b & c) | (~b & d);
|
||||
k = 0x5a827999;
|
||||
} else if (t < 40) {
|
||||
f = b ^ c ^ d;
|
||||
k = 0x6ed9eba1;
|
||||
} else if (t < 60) {
|
||||
f = (b & c) | (b & d) | (c & d);
|
||||
k = 0x8f1bbcdc;
|
||||
} else {
|
||||
f = b ^ c ^ d;
|
||||
k = 0xca62c1d6;
|
||||
}
|
||||
int temp = Integer.rotateLeft(a, 5) + f + e + k + words[t];
|
||||
e = d;
|
||||
d = c;
|
||||
c = Integer.rotateLeft(b, 30);
|
||||
b = a;
|
||||
a = temp;
|
||||
}
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
state[4] += e;
|
||||
}
|
||||
|
||||
private void compress256() {
|
||||
for (int t = 16; t < 64; t++) {
|
||||
int s0 = Integer.rotateRight(words[t - 15], 7)
|
||||
^ Integer.rotateRight(words[t - 15], 18)
|
||||
^ (words[t - 15] >>> 3);
|
||||
int s1 = Integer.rotateRight(words[t - 2], 17)
|
||||
^ Integer.rotateRight(words[t - 2], 19)
|
||||
^ (words[t - 2] >>> 10);
|
||||
words[t] = words[t - 16] + s0 + words[t - 7] + s1;
|
||||
}
|
||||
int a = state[0];
|
||||
int b = state[1];
|
||||
int c = state[2];
|
||||
int d = state[3];
|
||||
int e = state[4];
|
||||
int f = state[5];
|
||||
int g = state[6];
|
||||
int h = state[7];
|
||||
for (int t = 0; t < 64; t++) {
|
||||
int sum1 = Integer.rotateRight(e, 6) ^ Integer.rotateRight(e, 11) ^ Integer.rotateRight(e, 25);
|
||||
int choose = (e & f) ^ (~e & g);
|
||||
int temp1 = h + sum1 + choose + SHA256_K[t] + words[t];
|
||||
int sum0 = Integer.rotateRight(a, 2) ^ Integer.rotateRight(a, 13) ^ Integer.rotateRight(a, 22);
|
||||
int majority = (a & b) ^ (a & c) ^ (b & c);
|
||||
int temp2 = sum0 + majority;
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + temp1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = temp1 + temp2;
|
||||
}
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
state[4] += e;
|
||||
state[5] += f;
|
||||
state[6] += g;
|
||||
state[7] += h;
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package incari.classlib.security;
|
||||
|
||||
import incari.classlib.substitutes.java.security.TPrivateKey;
|
||||
import java.util.Arrays;
|
||||
import org.bouncycastle.crypto.params.RSAKeyParameters;
|
||||
|
||||
/**
|
||||
* An RSA private key for the browser build's {@code KeyFactory} and {@code Signature} (ADR 0070):
|
||||
* Bouncy Castle's parameters and the PKCS#8 encoding it came from. Never printed.
|
||||
*/
|
||||
public final class RsaPrivateKey implements TPrivateKey {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final transient RSAKeyParameters parameters;
|
||||
private final byte[] encoded;
|
||||
|
||||
public RsaPrivateKey(RSAKeyParameters parameters, byte[] encoded) {
|
||||
if (!parameters.isPrivate()) {
|
||||
throw new IllegalArgumentException("Not a private key");
|
||||
}
|
||||
this.parameters = parameters;
|
||||
this.encoded = encoded.clone();
|
||||
}
|
||||
|
||||
public RSAKeyParameters parameters() {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAlgorithm() {
|
||||
return "RSA";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFormat() {
|
||||
return "PKCS#8";
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getEncoded() {
|
||||
return encoded.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof RsaPrivateKey that && Arrays.equals(encoded, that.encoded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Arrays.hashCode(encoded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RSA private key";
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package incari.classlib.security;
|
||||
|
||||
import incari.classlib.substitutes.java.security.TPublicKey;
|
||||
import java.util.Arrays;
|
||||
import org.bouncycastle.crypto.params.RSAKeyParameters;
|
||||
|
||||
/**
|
||||
* An RSA public key for the browser build's {@code KeyFactory}, {@code Cipher} and
|
||||
* {@code Signature} (ADR 0070): Bouncy Castle's parameters and the X.509 encoding it came from.
|
||||
* {@link #getEncoded} hands back exactly those bytes, since the login handshake hashes the
|
||||
* server's key as the server sent it.
|
||||
*/
|
||||
public final class RsaPublicKey implements TPublicKey {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final transient RSAKeyParameters parameters;
|
||||
private final byte[] encoded;
|
||||
|
||||
public RsaPublicKey(RSAKeyParameters parameters, byte[] encoded) {
|
||||
if (parameters.isPrivate()) {
|
||||
throw new IllegalArgumentException("Not a public key");
|
||||
}
|
||||
this.parameters = parameters;
|
||||
this.encoded = encoded.clone();
|
||||
}
|
||||
|
||||
public RSAKeyParameters parameters() {
|
||||
return parameters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAlgorithm() {
|
||||
return "RSA";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFormat() {
|
||||
return "X.509";
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getEncoded() {
|
||||
return encoded.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof RsaPublicKey that && Arrays.equals(encoded, that.encoded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Arrays.hashCode(encoded);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RSA public key, " + parameters.getModulus().bitLength() + " bits";
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.lang;
|
||||
|
||||
/**
|
||||
* ICU's {@code UCharacter} for the browser build, with the one method the game uses: the
|
||||
* mirror image of a bracket-like character in right-to-left text. Covers the ASCII and common
|
||||
* typographic pairs; other characters mirror to themselves.
|
||||
*/
|
||||
public final class TUCharacter {
|
||||
|
||||
private static final String PAIRS = "()[]{}<>«»‹›⁅⁆⁽⁾₍₎≤≥";
|
||||
|
||||
private TUCharacter() {}
|
||||
|
||||
public static int getMirror(int ch) {
|
||||
int at = PAIRS.indexOf(ch);
|
||||
if (at < 0) {
|
||||
return ch;
|
||||
}
|
||||
return PAIRS.charAt(at % 2 == 0 ? at + 1 : at - 1);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
/**
|
||||
* ICU's {@code ArabicShaping} for the browser build: no shaping, the text comes back as given
|
||||
* (see {@link TBidi}). The constants are ICU's option bits, which callers combine.
|
||||
*/
|
||||
public final class TArabicShaping {
|
||||
|
||||
public static final int LETTERS_SHAPE = 8;
|
||||
public static final int LETTERS_UNSHAPE = 16;
|
||||
public static final int DIGITS_EN2AN = 32;
|
||||
public static final int TEXT_DIRECTION_VISUAL_LTR = 4;
|
||||
public static final int LENGTH_GROW_SHRINK = 0;
|
||||
|
||||
public TArabicShaping(int options) {}
|
||||
|
||||
public String shape(String text) throws TArabicShapingException {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/** ICU's {@code ArabicShapingException}; {@link TArabicShaping} never throws it. */
|
||||
public class TArabicShapingException extends Exception {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public TArabicShapingException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
/**
|
||||
* ICU's {@code Bidi} for the browser build, which leaves ICU out. Minimal: every text is one
|
||||
* left-to-right run, so right-to-left languages (Arabic, Hebrew) show in logical order until a
|
||||
* real bidi shim over the browser's own text layout replaces this.
|
||||
*/
|
||||
public class TBidi {
|
||||
|
||||
public static final byte LTR = 0;
|
||||
public static final byte RTL = 1;
|
||||
public static final byte LEVEL_DEFAULT_LTR = 0x7E;
|
||||
public static final byte LEVEL_DEFAULT_RTL = 0x7F;
|
||||
public static final short REORDER_DEFAULT = 0;
|
||||
public static final short KEEP_BASE_COMBINING = 1;
|
||||
public static final short DO_MIRRORING = 2;
|
||||
public static final short INSERT_LRM_FOR_NUMERIC = 4;
|
||||
public static final short REMOVE_BIDI_CONTROLS = 8;
|
||||
public static final short OUTPUT_REVERSE = 16;
|
||||
|
||||
private final String text;
|
||||
|
||||
public TBidi(String paragraph, int flags) {
|
||||
this.text = paragraph;
|
||||
}
|
||||
|
||||
public void setReorderingMode(int reorderingMode) {}
|
||||
|
||||
public int countRuns() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
public TBidiRun getVisualRun(int runIndex) {
|
||||
return new TBidiRun(0, text.length(), false);
|
||||
}
|
||||
|
||||
public String writeReordered(int options) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
/** ICU's {@code BidiRun}: one run of a {@link TBidi}. */
|
||||
public class TBidiRun {
|
||||
|
||||
private final int start;
|
||||
private final int length;
|
||||
private final boolean odd;
|
||||
|
||||
TBidiRun(int start, int length, boolean odd) {
|
||||
this.start = start;
|
||||
this.length = length;
|
||||
this.odd = odd;
|
||||
}
|
||||
|
||||
public int getStart() {
|
||||
return start;
|
||||
}
|
||||
|
||||
public int getLength() {
|
||||
return length;
|
||||
}
|
||||
|
||||
public boolean isOddRun() {
|
||||
return odd;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* ICU's {@code Collator} for the browser build, which has neither ICU nor {@code java.text.Collator}:
|
||||
* orders strings ignoring case first, then by exact text, for any locale. Close enough for the
|
||||
* sorted lists in the game's screens; a locale-aware order can come from the browser's Intl later.
|
||||
*/
|
||||
public final class TCollator implements Comparator<Object> {
|
||||
|
||||
private static final TCollator INSTANCE = new TCollator();
|
||||
|
||||
private TCollator() {}
|
||||
|
||||
public static TCollator getInstance(Locale locale) {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public static TCollator getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public int compare(String source, String target) {
|
||||
int folded = source.compareToIgnoreCase(target);
|
||||
return folded != 0 ? folded : source.compareTo(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compare(Object source, Object target) {
|
||||
return compare((String) source, (String) target);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/** ICU's {@code DateFormat} for the browser build; see {@link TSimpleDateFormat}. */
|
||||
public abstract class TDateFormat {
|
||||
|
||||
public abstract String format(Date date);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.text;
|
||||
|
||||
import incari.classlib.substitutes.com.ibm.icu.util.TCalendar;
|
||||
import incari.classlib.substitutes.com.ibm.icu.util.TULocale;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* ICU's {@code SimpleDateFormat} for the browser build, over {@link java.text.SimpleDateFormat},
|
||||
* whose pattern letters agree with ICU's for the common fields.
|
||||
*/
|
||||
public class TSimpleDateFormat extends TDateFormat {
|
||||
|
||||
private final SimpleDateFormat format;
|
||||
|
||||
public TSimpleDateFormat(String pattern, TULocale locale) {
|
||||
this.format = new SimpleDateFormat(pattern, locale.toLocale());
|
||||
}
|
||||
|
||||
public void setCalendar(TCalendar calendar) {
|
||||
format.setCalendar(calendar.toJava());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format(Date date) {
|
||||
return format.format(date);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.util;
|
||||
|
||||
import java.util.Calendar;
|
||||
|
||||
/** ICU's {@code Calendar} for the browser build: a zone and a locale for a date format to use. */
|
||||
public final class TCalendar {
|
||||
|
||||
private final TTimeZone zone;
|
||||
private final TULocale locale;
|
||||
|
||||
private TCalendar(TTimeZone zone, TULocale locale) {
|
||||
this.zone = zone;
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
public static TCalendar getInstance(TTimeZone zone, TULocale locale) {
|
||||
return new TCalendar(zone, locale);
|
||||
}
|
||||
|
||||
public static TCalendar getInstance(TULocale locale) {
|
||||
return new TCalendar(TTimeZone.getDefault(), locale);
|
||||
}
|
||||
|
||||
public TTimeZone getTimeZone() {
|
||||
return zone;
|
||||
}
|
||||
|
||||
/** The equivalent {@link Calendar}, for {@code TSimpleDateFormat}. */
|
||||
public Calendar toJava() {
|
||||
return Calendar.getInstance(zone.toJava(), locale.toLocale());
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.util;
|
||||
|
||||
import java.util.TimeZone;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** ICU's {@code TimeZone} for the browser build, over {@link java.util.TimeZone}. */
|
||||
public final class TTimeZone {
|
||||
|
||||
public static final TTimeZone UNKNOWN_ZONE = new TTimeZone(TimeZone.getTimeZone("GMT"), "Etc/Unknown");
|
||||
|
||||
private final TimeZone zone;
|
||||
private final String id;
|
||||
|
||||
private TTimeZone(TimeZone zone, String id) {
|
||||
this.zone = zone;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/** The zone with this id, or {@link #UNKNOWN_ZONE}. */
|
||||
public static TTimeZone getTimeZone(String id) {
|
||||
TimeZone zone = TimeZone.getTimeZone(id);
|
||||
// java.util answers GMT for ids it doesn't know; ICU answers the unknown zone.
|
||||
if (zone.getID().equals("GMT") && !id.equals("GMT")) {
|
||||
return UNKNOWN_ZONE;
|
||||
}
|
||||
return new TTimeZone(zone, id);
|
||||
}
|
||||
|
||||
public static TTimeZone getDefault() {
|
||||
TimeZone zone = TimeZone.getDefault();
|
||||
return new TTimeZone(zone, zone.getID());
|
||||
}
|
||||
|
||||
public String getID() {
|
||||
return id;
|
||||
}
|
||||
|
||||
TimeZone toJava() {
|
||||
return zone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object other) {
|
||||
return other instanceof TTimeZone that && that.id.equals(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package incari.classlib.substitutes.com.ibm.icu.util;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* ICU's {@code ULocale}, for the browser build, which leaves ICU out. Only what the game uses (item
|
||||
* models that show the local time), over {@link Locale}.
|
||||
*/
|
||||
public final class TULocale {
|
||||
|
||||
private final Locale locale;
|
||||
|
||||
public TULocale(String localeId) {
|
||||
this.locale = Locale.forLanguageTag(localeId.replace('_', '-'));
|
||||
}
|
||||
|
||||
private TULocale(Locale locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
public static TULocale getDefault() {
|
||||
return new TULocale(Locale.getDefault());
|
||||
}
|
||||
|
||||
public static TULocale forLocale(Locale locale) {
|
||||
return new TULocale(locale);
|
||||
}
|
||||
|
||||
public Locale toLocale() {
|
||||
return locale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return locale.toString();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package incari.classlib.substitutes.com.mojang.text2speech;
|
||||
|
||||
import java.io.Serial;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Mojang's text-to-speech {@code Narrator} for the browser build, which leaves out its native
|
||||
* speech engines. Until the Web Speech API version (the survey's narrator shim), there's no
|
||||
* narrator: {@link #getNarrator} is the inactive one, and the game shows narration as unavailable.
|
||||
*/
|
||||
public interface TNarrator {
|
||||
|
||||
Logger LOGGER = LoggerFactory.getLogger("Narrator");
|
||||
|
||||
TNarrator EMPTY = new TNarrator() {
|
||||
@Override
|
||||
public void say(String message, boolean interrupt, float volume) {}
|
||||
|
||||
@Override
|
||||
public void clear() {}
|
||||
|
||||
@Override
|
||||
public boolean active() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {}
|
||||
};
|
||||
|
||||
void say(String message, boolean interrupt, float volume);
|
||||
|
||||
void clear();
|
||||
|
||||
default boolean active() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void destroy();
|
||||
|
||||
static TNarrator getNarrator() {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
/** A narrator that couldn't start. */
|
||||
class InitializeException extends Exception {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public InitializeException(String message, @Nullable Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public InitializeException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package incari.classlib.substitutes.com.viaversion.viaversion.util;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.handler.codec.ByteToMessageDecoder;
|
||||
import io.netty.handler.codec.MessageToByteEncoder;
|
||||
import io.netty.handler.codec.MessageToMessageDecoder;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Via's {@code PipelineUtil} for the browser build (ADR 0017). Via's own looks up methods of
|
||||
* Netty's codecs reflectively when the class loads, for server platforms that wrap other codecs;
|
||||
* the browser can't reflect on methods, so the class failed to load, and with it the cause checks
|
||||
* Via runs whenever a packet it drops on purpose comes through an error path. This one has the
|
||||
* same methods, written for the build: the checks and pipeline lookups work, and calling another
|
||||
* codec, which the client never asks for, says so.
|
||||
*/
|
||||
@SuppressWarnings({"rawtypes", "unused"}) // Via's signatures take raw codec types
|
||||
public final class TPipelineUtil {
|
||||
|
||||
private TPipelineUtil() {}
|
||||
|
||||
public static List<Object> callDecode(ByteToMessageDecoder decoder, ChannelHandlerContext ctx, Object input) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
public static void callEncode(MessageToByteEncoder encoder, ChannelHandlerContext ctx, Object msg, ByteBuf output) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
public static List<Object> callDecode(MessageToMessageDecoder decoder, ChannelHandlerContext ctx, Object msg) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
/** Whether {@code failure} or one of its causes is a {@code type}. */
|
||||
public static boolean containsCause(Throwable failure, Class<?> type) {
|
||||
return getCause(failure, type) != null;
|
||||
}
|
||||
|
||||
/** The first of {@code failure} and its causes that is a {@code type}, or null. */
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> @Nullable T getCause(@Nullable Throwable failure, Class<T> type) {
|
||||
for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
|
||||
if (type.isInstance(cause)) {
|
||||
return (T) cause;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The context of the handler that comes after the one named {@code name} (any case). */
|
||||
public static @Nullable ChannelHandlerContext getContextBefore(String name, ChannelPipeline pipeline) {
|
||||
List<String> names = pipeline.names();
|
||||
for (int i = 0; i < names.size() - 1; i++) {
|
||||
if (names.get(i).equalsIgnoreCase(name)) {
|
||||
return pipeline.context(names.get(i + 1));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The context of the handler that comes before the one named {@code name}. */
|
||||
public static @Nullable ChannelHandlerContext getPreviousContext(String name, ChannelPipeline pipeline) {
|
||||
String before = null;
|
||||
for (String current : pipeline.toMap().keySet()) {
|
||||
if (current.equals(name)) {
|
||||
return before == null ? null : pipeline.context(before);
|
||||
}
|
||||
before = current;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static UnsupportedOperationException unsupported() {
|
||||
return new UnsupportedOperationException("Calling another Netty codec isn't part of the browser build");
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package incari.classlib.substitutes.java.io;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* {@code java.io.ObjectInputStream}: present only so libraries that probe for it by reflection
|
||||
* link (Gson looks for its instance allocator and falls back when the lookup fails), and so Bouncy
|
||||
* Castle's key factories link (their XMSS keys deserialize; sign-in's TLS never meets one, ADR
|
||||
* 0070). The browser build has no Java serialization: opening one fails.
|
||||
*/
|
||||
public class TObjectInputStream extends InputStream {
|
||||
|
||||
protected TObjectInputStream() {}
|
||||
|
||||
public TObjectInputStream(InputStream in) throws IOException {
|
||||
throw new IOException("The browser build has no Java serialization");
|
||||
}
|
||||
|
||||
public final Object readObject() throws IOException, ClassNotFoundException {
|
||||
throw new IOException("The browser build has no Java serialization");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] buffer, int offset, int length) {
|
||||
throw unsupported();
|
||||
}
|
||||
|
||||
private static UnsupportedOperationException unsupported() {
|
||||
return new UnsupportedOperationException("The browser build has no Java serialization");
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package incari.classlib.substitutes.java.io;
|
||||
|
||||
/** {@code java.io.ObjectStreamClass}: present only so reflective probes link (see {@link TObjectInputStream}). */
|
||||
public class TObjectStreamClass {
|
||||
|
||||
private TObjectStreamClass() {}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
import java.io.Serial;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** {@code java.lang.ExceptionInInitializerError}, which TeaVM lacks. */
|
||||
public class TExceptionInInitializerError extends LinkageError {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1521711792217232256L;
|
||||
|
||||
public TExceptionInInitializerError() {
|
||||
super(null, null);
|
||||
}
|
||||
|
||||
public TExceptionInInitializerError(@Nullable Throwable thrown) {
|
||||
super(null, thrown);
|
||||
}
|
||||
|
||||
public TExceptionInInitializerError(@Nullable String message) {
|
||||
super(message, null);
|
||||
}
|
||||
|
||||
public @Nullable Throwable getException() {
|
||||
return getCause();
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
/**
|
||||
* {@code java.lang.Module}, which TeaVM lacks. A page is one program with no module system: every
|
||||
* class is in this one module, in the boot layer, which holds no named modules. So a check for an
|
||||
* optional JDK module ({@code jdk.jfr} for the game's profiler) finds none, as on a runtime
|
||||
* without it.
|
||||
*/
|
||||
public final class TModule {
|
||||
|
||||
/** The module every class is in; public for {@code ClassAdditions.getModule}. */
|
||||
public static final TModule PROGRAM = new TModule();
|
||||
|
||||
private TModule() {}
|
||||
|
||||
/** The boot layer, which this one module stands for. */
|
||||
public TModuleLayer getLayer() {
|
||||
return TModuleLayer.boot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "module (browser build)";
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* {@code java.lang.ModuleLayer}, which TeaVM lacks: the boot layer only, with no named modules in
|
||||
* it ({@link TModule}).
|
||||
*/
|
||||
public final class TModuleLayer {
|
||||
|
||||
private static final TModuleLayer BOOT = new TModuleLayer();
|
||||
|
||||
private TModuleLayer() {}
|
||||
|
||||
public static TModuleLayer boot() {
|
||||
return BOOT;
|
||||
}
|
||||
|
||||
/** Always empty: the browser build has no named modules to find. */
|
||||
public Optional<TModule> findModule(String name) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "boot layer (browser build)";
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.function.Supplier;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* {@code java.lang.ScopedValue} (Java 25), which TeaVM lacks: a value bound for the extent of a
|
||||
* call on one thread. Bindings are an immutable list per thread; a {@link Carrier} pushes its
|
||||
* bindings for the call and restores the previous ones after.
|
||||
*/
|
||||
public final class TScopedValue<T extends @Nullable Object> {
|
||||
|
||||
private static final ThreadLocal<@Nullable Binding> BINDINGS = new ThreadLocal<>();
|
||||
|
||||
private TScopedValue() {}
|
||||
|
||||
public static <T extends @Nullable Object> TScopedValue<T> newInstance() {
|
||||
return new TScopedValue<>();
|
||||
}
|
||||
|
||||
public static <T extends @Nullable Object> Carrier where(TScopedValue<T> key, T value) {
|
||||
return new Carrier(new Binding(key, value, null));
|
||||
}
|
||||
|
||||
public T get() {
|
||||
Binding binding = find(this);
|
||||
if (binding == null) {
|
||||
throw new NoSuchElementException("ScopedValue not bound");
|
||||
}
|
||||
return binding.valueOf(this);
|
||||
}
|
||||
|
||||
public boolean isBound() {
|
||||
return find(this) != null;
|
||||
}
|
||||
|
||||
public T orElse(T other) {
|
||||
Binding binding = find(this);
|
||||
return binding == null ? other : binding.valueOf(this);
|
||||
}
|
||||
|
||||
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
|
||||
Binding binding = find(this);
|
||||
if (binding == null) {
|
||||
throw exceptionSupplier.get();
|
||||
}
|
||||
return binding.valueOf(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ScopedValue@" + Integer.toHexString(hashCode());
|
||||
}
|
||||
|
||||
private static @Nullable Binding find(TScopedValue<?> key) {
|
||||
for (Binding binding = BINDINGS.get(); binding != null; binding = binding.next) {
|
||||
if (binding.key == key) {
|
||||
return binding;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** An operation run with bindings in effect, returning a result. */
|
||||
@FunctionalInterface
|
||||
public interface CallableOp<T extends @Nullable Object, X extends Throwable> {
|
||||
T call() throws X;
|
||||
}
|
||||
|
||||
/** Bindings waiting to be put in effect for a call. */
|
||||
public static final class Carrier {
|
||||
private final Binding bindings;
|
||||
|
||||
private Carrier(Binding bindings) {
|
||||
this.bindings = bindings;
|
||||
}
|
||||
|
||||
public <T extends @Nullable Object> Carrier where(TScopedValue<T> key, T value) {
|
||||
return new Carrier(new Binding(key, value, bindings));
|
||||
}
|
||||
|
||||
public <T extends @Nullable Object> T get(TScopedValue<T> key) {
|
||||
for (Binding binding = bindings; binding != null; binding = binding.next) {
|
||||
if (binding.key == key) {
|
||||
return binding.valueOf(key);
|
||||
}
|
||||
}
|
||||
throw new NoSuchElementException("key not bound");
|
||||
}
|
||||
|
||||
public <R extends @Nullable Object, X extends Throwable> R call(CallableOp<? extends R, X> op) throws X {
|
||||
@Nullable Binding previous = BINDINGS.get();
|
||||
BINDINGS.set(stack(previous));
|
||||
try {
|
||||
return op.call();
|
||||
} finally {
|
||||
BINDINGS.set(previous);
|
||||
}
|
||||
}
|
||||
|
||||
public void run(Runnable op) {
|
||||
@Nullable Binding previous = BINDINGS.get();
|
||||
BINDINGS.set(stack(previous));
|
||||
try {
|
||||
op.run();
|
||||
} finally {
|
||||
BINDINGS.set(previous);
|
||||
}
|
||||
}
|
||||
|
||||
// This carrier's bindings on top of the ones already in effect; the newest wins lookups.
|
||||
private Binding stack(@Nullable Binding below) {
|
||||
Binding result = below;
|
||||
java.util.ArrayList<Binding> mine = new java.util.ArrayList<>();
|
||||
for (Binding binding = bindings; binding != null; binding = binding.next) {
|
||||
mine.add(binding);
|
||||
}
|
||||
for (int i = mine.size() - 1; i >= 0; i--) {
|
||||
result = new Binding(mine.get(i).key, mine.get(i).value, result);
|
||||
}
|
||||
return java.util.Objects.requireNonNull(result);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Binding {
|
||||
final TScopedValue<?> key;
|
||||
final @Nullable Object value;
|
||||
final @Nullable Binding next;
|
||||
|
||||
Binding(TScopedValue<?> key, @Nullable Object value, @Nullable Binding next) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
// Only where(key, value) makes bindings, so the value is the key's T, and null only when
|
||||
// T allows it; neither the compiler nor NullAway can see that link.
|
||||
@SuppressWarnings({"unchecked", "NullAway"})
|
||||
<V extends @Nullable Object> V valueOf(TScopedValue<V> owner) {
|
||||
if (owner != key) {
|
||||
throw new IllegalArgumentException("not this binding's key");
|
||||
}
|
||||
return (V) value;
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
import incari.classlib.UnknownCaller;
|
||||
import java.lang.invoke.MethodType;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* {@code java.lang.StackWalker}, which TeaVM lacks. The browser build can't see its own call stack
|
||||
* as classes and methods, so every walk sees no frames and the caller class is
|
||||
* {@link UnknownCaller}.
|
||||
*/
|
||||
public final class TStackWalker {
|
||||
|
||||
private static final TStackWalker DEFAULT = new TStackWalker(EnumSet.noneOf(Option.class));
|
||||
|
||||
private final Set<Option> options;
|
||||
|
||||
private TStackWalker(Set<Option> options) {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
public static TStackWalker getInstance() {
|
||||
return DEFAULT;
|
||||
}
|
||||
|
||||
public static TStackWalker getInstance(Option option) {
|
||||
return new TStackWalker(EnumSet.of(option));
|
||||
}
|
||||
|
||||
public static TStackWalker getInstance(Set<Option> options) {
|
||||
return new TStackWalker(options.isEmpty() ? EnumSet.noneOf(Option.class) : EnumSet.copyOf(options));
|
||||
}
|
||||
|
||||
public static TStackWalker getInstance(Set<Option> options, int estimateDepth) {
|
||||
if (estimateDepth <= 0) {
|
||||
throw new IllegalArgumentException("estimateDepth must be > 0");
|
||||
}
|
||||
return getInstance(options);
|
||||
}
|
||||
|
||||
public <T> T walk(Function<? super Stream<StackFrame>, ? extends T> function) {
|
||||
return function.apply(Stream.empty());
|
||||
}
|
||||
|
||||
public void forEach(Consumer<? super StackFrame> action) {
|
||||
// No frames to visit.
|
||||
}
|
||||
|
||||
public Class<?> getCallerClass() {
|
||||
if (!options.contains(Option.RETAIN_CLASS_REFERENCE)) {
|
||||
throw new UnsupportedOperationException("This stack walker does not have RETAIN_CLASS_REFERENCE access");
|
||||
}
|
||||
return UnknownCaller.class;
|
||||
}
|
||||
|
||||
Set<Option> options() {
|
||||
return Collections.unmodifiableSet(options);
|
||||
}
|
||||
|
||||
/** What a walk shows and keeps. */
|
||||
public enum Option {
|
||||
RETAIN_CLASS_REFERENCE,
|
||||
SHOW_REFLECT_FRAMES,
|
||||
SHOW_HIDDEN_FRAMES,
|
||||
DROP_METHOD_INFO
|
||||
}
|
||||
|
||||
/** One frame of a walk; none are ever produced here. */
|
||||
public interface StackFrame {
|
||||
String getClassName();
|
||||
|
||||
String getMethodName();
|
||||
|
||||
Class<?> getDeclaringClass();
|
||||
|
||||
default MethodType getMethodType() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
default String getDescriptor() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
int getByteCodeIndex();
|
||||
|
||||
String getFileName();
|
||||
|
||||
int getLineNumber();
|
||||
|
||||
boolean isNativeMethod();
|
||||
|
||||
StackTraceElement toStackTraceElement();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
/**
|
||||
* {@code java.lang.Thread.State}, which TeaVM's {@code Thread} lacks. A top-level class named for
|
||||
* the nested one, so it takes the JDK name {@code java.lang.Thread$State}; {@code Thread.getState}
|
||||
* comes from {@code ThreadAdditions}.
|
||||
*/
|
||||
@SuppressWarnings("TypeName") // The name is the JDK's nested class, as the class library maps it.
|
||||
public enum TThread$State {
|
||||
NEW,
|
||||
RUNNABLE,
|
||||
BLOCKED,
|
||||
WAITING,
|
||||
TIMED_WAITING,
|
||||
TERMINATED
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package incari.classlib.substitutes.java.lang;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.function.Supplier;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* {@code java.lang.ThreadLocal}. Replaces TeaVM's, which keeps every thread's value but the main
|
||||
* thread's in a {@code WeakHashMap} keyed by thread: each {@code get()} on any other thread looked
|
||||
* its thread up through a weak reference, and on WebAssembly GC every weak reference read is a
|
||||
* call out to JavaScript ({@code WeakRef.deref}). The background pool's meshing reads the block tint
|
||||
* cache's thread-local and {@code IdleTimeExecutor}'s for every block, and Netty's event loop its
|
||||
* own for every message: about 8,000 calls out a second in a singleplayer world.
|
||||
*
|
||||
* <p>Here each thread's value lives in a {@link Slot} only that thread reads or writes. The slots
|
||||
* sit in a {@code WeakHashMap} by thread, so a finished thread's values can go, but a thread-local
|
||||
* also remembers the last thread that used it and that thread's slot, so a run of uses on one
|
||||
* thread (meshing a section, decoding a packet) compares one field. Only a switch of threads looks
|
||||
* in the map. The last thread stays reachable until another thread uses the thread-local.
|
||||
*/
|
||||
public class TThreadLocal<T extends @Nullable Object> {
|
||||
|
||||
/** A slot's value before {@link #initialValue()} has run, or after {@link #remove()}. */
|
||||
private static final Object UNSET = new Object();
|
||||
|
||||
/** One thread's value. Only that thread reads or writes it. */
|
||||
private static final class Slot {
|
||||
@Nullable
|
||||
Object value = UNSET;
|
||||
}
|
||||
|
||||
/** The last thread to use this thread-local and its slot, replaced as one so threads see a pair. */
|
||||
private record Last(Thread thread, Slot slot) {}
|
||||
|
||||
/** Every thread's slot. The slots never refer to their threads, so the keys can go. */
|
||||
private final Map<Thread, Slot> slots = new WeakHashMap<>();
|
||||
|
||||
private volatile @Nullable Last last;
|
||||
|
||||
public TThreadLocal() {}
|
||||
|
||||
public static <S extends @Nullable Object> TThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
|
||||
return new TThreadLocal<>() {
|
||||
@Override
|
||||
protected S initialValue() {
|
||||
return supplier.get();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected @Nullable T initialValue() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The marker is compared by identity, and the slot holds what set or initialValue gave, a T.
|
||||
@SuppressWarnings({"unchecked", "ReferenceEquality", "NullAway"})
|
||||
public T get() {
|
||||
Slot slot = slot();
|
||||
if (slot.value == UNSET) {
|
||||
// Outside any lock: the supplier may do anything, block included.
|
||||
slot.value = initialValue();
|
||||
}
|
||||
return (T) slot.value;
|
||||
}
|
||||
|
||||
public void set(T value) {
|
||||
slot().value = value;
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
slot().value = UNSET;
|
||||
}
|
||||
|
||||
/** The current thread's slot: the last one's if it's the same thread, else the map's. */
|
||||
@SuppressWarnings("ReferenceEquality") // the same thread, not an equal one
|
||||
private Slot slot() {
|
||||
Thread thread = Thread.currentThread();
|
||||
Last remembered = last;
|
||||
if (remembered != null && remembered.thread() == thread) {
|
||||
return remembered.slot();
|
||||
}
|
||||
Slot slot;
|
||||
synchronized (slots) {
|
||||
slot = slots.get(thread);
|
||||
if (slot == null) {
|
||||
slot = new Slot();
|
||||
slots.put(thread, slot);
|
||||
}
|
||||
}
|
||||
last = new Last(thread, slot);
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package incari.classlib.substitutes.java.lang.invoke;
|
||||
|
||||
/**
|
||||
* {@code java.lang.invoke.MethodHandle}. No instance can exist in the browser build, since
|
||||
* {@link TMethodHandles$Lookup} finds nothing; the type is here so the lookup's signatures match
|
||||
* the JDK's. Invocations are signature-polymorphic and stay removed by the build.
|
||||
*/
|
||||
public abstract class TMethodHandle {
|
||||
|
||||
/** Public, as TeaVM's placeholder had it. */
|
||||
public TMethodHandle() {}
|
||||
|
||||
public TMethodType type() {
|
||||
throw new UnsupportedOperationException("No method handles in the browser build");
|
||||
}
|
||||
|
||||
public TMethodHandle asType(TMethodType newType) {
|
||||
throw new UnsupportedOperationException("No method handles in the browser build");
|
||||
}
|
||||
|
||||
public TMethodHandle bindTo(Object value) {
|
||||
throw new UnsupportedOperationException("No method handles in the browser build");
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package incari.classlib.substitutes.java.lang.invoke;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* {@code java.lang.invoke.MethodHandles.Lookup} that finds nothing (see {@link TMethodHandles}).
|
||||
* A top-level class named for the nested one, so it takes the name
|
||||
* {@code java.lang.invoke.MethodHandles$Lookup}.
|
||||
*/
|
||||
@SuppressWarnings({"TypeName", "unused"}) // The JDK's nested name; parameters match JDK signatures.
|
||||
public final class TMethodHandles$Lookup {
|
||||
|
||||
static final TMethodHandles$Lookup NOTHING = new TMethodHandles$Lookup();
|
||||
|
||||
/** Public, as TeaVM's placeholder had it. */
|
||||
public TMethodHandles$Lookup() {}
|
||||
|
||||
public Class<?> lookupClass() {
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
public TMethodHandles$Lookup in(Class<?> requestedLookupClass) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public TMethodHandle findStatic(Class<?> owner, String name, TMethodType type)
|
||||
throws NoSuchMethodException, IllegalAccessException {
|
||||
throw noMethod(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle findVirtual(Class<?> owner, String name, TMethodType type)
|
||||
throws NoSuchMethodException, IllegalAccessException {
|
||||
throw noMethod(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle findConstructor(Class<?> owner, TMethodType type)
|
||||
throws NoSuchMethodException, IllegalAccessException {
|
||||
throw noMethod(owner, "<init>");
|
||||
}
|
||||
|
||||
public TMethodHandle findSpecial(Class<?> owner, String name, TMethodType type, Class<?> caller)
|
||||
throws NoSuchMethodException, IllegalAccessException {
|
||||
throw noMethod(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle findGetter(Class<?> owner, String name, Class<?> type)
|
||||
throws NoSuchFieldException, IllegalAccessException {
|
||||
throw noField(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle findSetter(Class<?> owner, String name, Class<?> type)
|
||||
throws NoSuchFieldException, IllegalAccessException {
|
||||
throw noField(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle findStaticGetter(Class<?> owner, String name, Class<?> type)
|
||||
throws NoSuchFieldException, IllegalAccessException {
|
||||
throw noField(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle findStaticSetter(Class<?> owner, String name, Class<?> type)
|
||||
throws NoSuchFieldException, IllegalAccessException {
|
||||
throw noField(owner, name);
|
||||
}
|
||||
|
||||
public TMethodHandle unreflect(Method method) throws IllegalAccessException {
|
||||
throw unavailable();
|
||||
}
|
||||
|
||||
public TMethodHandle unreflectConstructor(Constructor<?> constructor) throws IllegalAccessException {
|
||||
throw unavailable();
|
||||
}
|
||||
|
||||
public TMethodHandle unreflectGetter(Field field) throws IllegalAccessException {
|
||||
throw unavailable();
|
||||
}
|
||||
|
||||
public TMethodHandle unreflectSetter(Field field) throws IllegalAccessException {
|
||||
throw unavailable();
|
||||
}
|
||||
|
||||
private static NoSuchMethodException noMethod(Class<?> owner, String name) {
|
||||
return new NoSuchMethodException(owner.getName() + "." + name + ": no method handles in the browser build");
|
||||
}
|
||||
|
||||
private static NoSuchFieldException noField(Class<?> owner, String name) {
|
||||
return new NoSuchFieldException(owner.getName() + "." + name + ": no method handles in the browser build");
|
||||
}
|
||||
|
||||
private static IllegalAccessException unavailable() {
|
||||
return new IllegalAccessException("Method handles aren't available in the browser build");
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package incari.classlib.substitutes.java.lang.invoke;
|
||||
|
||||
/**
|
||||
* {@code java.lang.invoke.MethodHandles}: a lookup exists, but nothing can be found through it.
|
||||
* TeaVM compiles a closed world with no method handles at run time, and its own class is an empty
|
||||
* placeholder, so a library's first {@code MethodHandles.lookup()} failed outright. Libraries that
|
||||
* probe for faster paths (Netty's {@code PlatformDependent0} calls {@code lookup()} before any of
|
||||
* its guarded probes) are written for platforms where a lookup finds nothing: every {@code find}
|
||||
* and {@code unreflect} throws the checked exception the JDK documents, and they fall back as they
|
||||
* would there.
|
||||
*/
|
||||
public class TMethodHandles {
|
||||
|
||||
/** Public, as TeaVM's placeholder had it. */
|
||||
public TMethodHandles() {}
|
||||
|
||||
public static TMethodHandles$Lookup lookup() {
|
||||
return TMethodHandles$Lookup.NOTHING;
|
||||
}
|
||||
|
||||
public static TMethodHandles$Lookup publicLookup() {
|
||||
return TMethodHandles$Lookup.NOTHING;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused") // The parameters exist to match the JDK signature.
|
||||
public static TMethodHandles$Lookup privateLookupIn(Class<?> target, TMethodHandles$Lookup caller)
|
||||
throws IllegalAccessException {
|
||||
throw new IllegalAccessException("Method handles aren't available in the browser build");
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package incari.classlib.substitutes.java.lang.invoke;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@code java.lang.invoke.MethodType}: a return type and parameter types, which libraries build
|
||||
* before a lookup (that then finds nothing, see {@link TMethodHandles}), sometimes outside the
|
||||
* guard around it.
|
||||
*/
|
||||
public final class TMethodType implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Class<?>[] NONE = {};
|
||||
|
||||
private final Class<?> returnType;
|
||||
private final Class<?>[] parameterTypes;
|
||||
|
||||
/** Public, as TeaVM's placeholder had it: a {@code void()} type. */
|
||||
public TMethodType() {
|
||||
this(void.class, NONE);
|
||||
}
|
||||
|
||||
private TMethodType(Class<?> returnType, Class<?>[] parameterTypes) {
|
||||
this.returnType = returnType;
|
||||
this.parameterTypes = parameterTypes;
|
||||
}
|
||||
|
||||
public static TMethodType methodType(Class<?> returnType) {
|
||||
return new TMethodType(returnType, NONE);
|
||||
}
|
||||
|
||||
public static TMethodType methodType(Class<?> returnType, Class<?> parameterType) {
|
||||
return new TMethodType(returnType, new Class<?>[] {parameterType});
|
||||
}
|
||||
|
||||
public static TMethodType methodType(Class<?> returnType, Class<?>[] parameterTypes) {
|
||||
return new TMethodType(returnType, parameterTypes.clone());
|
||||
}
|
||||
|
||||
public static TMethodType methodType(Class<?> returnType, Class<?> first, Class<?>... rest) {
|
||||
Class<?>[] types = new Class<?>[rest.length + 1];
|
||||
types[0] = first;
|
||||
System.arraycopy(rest, 0, types, 1, rest.length);
|
||||
return new TMethodType(returnType, types);
|
||||
}
|
||||
|
||||
public static TMethodType methodType(Class<?> returnType, List<Class<?>> parameterTypes) {
|
||||
return new TMethodType(returnType, parameterTypes.toArray(NONE));
|
||||
}
|
||||
|
||||
public static TMethodType methodType(Class<?> returnType, TMethodType parameters) {
|
||||
return new TMethodType(returnType, parameters.parameterTypes);
|
||||
}
|
||||
|
||||
public Class<?> returnType() {
|
||||
return returnType;
|
||||
}
|
||||
|
||||
public int parameterCount() {
|
||||
return parameterTypes.length;
|
||||
}
|
||||
|
||||
public Class<?> parameterType(int index) {
|
||||
return parameterTypes[index];
|
||||
}
|
||||
|
||||
public Class<?>[] parameterArray() {
|
||||
return parameterTypes.clone();
|
||||
}
|
||||
|
||||
public List<Class<?>> parameterList() {
|
||||
return List.of(parameterTypes);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
/** {@code java.lang.management.GarbageCollectorMXBean}; the browser build reports none. */
|
||||
public interface TGarbageCollectorMXBean {
|
||||
long getCollectionCount();
|
||||
|
||||
long getCollectionTime();
|
||||
|
||||
String getName();
|
||||
|
||||
boolean isValid();
|
||||
|
||||
String[] getMemoryPoolNames();
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* {@code java.lang.management.ManagementFactory}, which TeaVM lacks. The game reads memory, uptime
|
||||
* and thread numbers for its debug screen and crash reports; a page reports what the browser build
|
||||
* knows (TeaVM's memory figures) and zeros or nothing for the rest.
|
||||
*/
|
||||
public final class TManagementFactory {
|
||||
|
||||
private static final long START = System.currentTimeMillis();
|
||||
|
||||
private TManagementFactory() {}
|
||||
|
||||
public static TMemoryMXBean getMemoryMXBean() {
|
||||
return Memory.INSTANCE;
|
||||
}
|
||||
|
||||
public static TRuntimeMXBean getRuntimeMXBean() {
|
||||
return RuntimeBean.INSTANCE;
|
||||
}
|
||||
|
||||
public static TThreadMXBean getThreadMXBean() {
|
||||
return Threads.INSTANCE;
|
||||
}
|
||||
|
||||
public static List<TGarbageCollectorMXBean> getGarbageCollectorMXBeans() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public static javax.management.MBeanServer getPlatformMBeanServer() {
|
||||
throw new UnsupportedOperationException("The browser build has no MBean server");
|
||||
}
|
||||
|
||||
private static final class Memory implements TMemoryMXBean {
|
||||
static final Memory INSTANCE = new Memory();
|
||||
|
||||
@Override
|
||||
public TMemoryUsage getHeapMemoryUsage() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
long total = runtime.totalMemory();
|
||||
return new TMemoryUsage(-1, total - runtime.freeMemory(), total, total);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TMemoryUsage getNonHeapMemoryUsage() {
|
||||
return new TMemoryUsage(-1, 0, 0, -1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getObjectPendingFinalizationCount() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void gc() {
|
||||
System.gc();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVerbose() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVerbose(boolean value) {}
|
||||
}
|
||||
|
||||
private static final class RuntimeBean implements TRuntimeMXBean {
|
||||
static final RuntimeBean INSTANCE = new RuntimeBean();
|
||||
|
||||
@Override
|
||||
public long getPid() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "browser";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVmName() {
|
||||
return "TeaVM";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVmVendor() {
|
||||
return "TeaVM";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVmVersion() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSpecName() {
|
||||
return "Java Virtual Machine Specification";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSpecVendor() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSpecVersion() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getInputArguments() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getUptime() {
|
||||
return System.currentTimeMillis() - START;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getStartTime() {
|
||||
return START;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getSystemProperties() {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Threads implements TThreadMXBean {
|
||||
static final Threads INSTANCE = new Threads();
|
||||
|
||||
@Override
|
||||
public int getThreadCount() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers) {
|
||||
return new TThreadInfo[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isObjectMonitorUsageSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSynchronizerUsageSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isThreadCpuTimeSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCurrentThreadCpuTime() {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
/** {@code java.lang.management.MemoryMXBean}, which TeaVM lacks (see {@link TManagementFactory}). */
|
||||
public interface TMemoryMXBean {
|
||||
TMemoryUsage getHeapMemoryUsage();
|
||||
|
||||
TMemoryUsage getNonHeapMemoryUsage();
|
||||
|
||||
int getObjectPendingFinalizationCount();
|
||||
|
||||
void gc();
|
||||
|
||||
boolean isVerbose();
|
||||
|
||||
void setVerbose(boolean value);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
/** {@code java.lang.management.MemoryUsage}, which TeaVM lacks. Sizes in bytes; -1 is unknown. */
|
||||
public class TMemoryUsage {
|
||||
|
||||
private final long init;
|
||||
private final long used;
|
||||
private final long committed;
|
||||
private final long max;
|
||||
|
||||
public TMemoryUsage(long init, long used, long committed, long max) {
|
||||
this.init = init;
|
||||
this.used = used;
|
||||
this.committed = committed;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public long getInit() {
|
||||
return init;
|
||||
}
|
||||
|
||||
public long getUsed() {
|
||||
return used;
|
||||
}
|
||||
|
||||
public long getCommitted() {
|
||||
return committed;
|
||||
}
|
||||
|
||||
public long getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "init = " + init + "(" + (init >> 10) + "K) used = " + used + "(" + (used >> 10) + "K) committed = "
|
||||
+ committed + "(" + (committed >> 10) + "K) max = " + max + "(" + (max >> 10) + "K)";
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** {@code java.lang.management.RuntimeMXBean}, which TeaVM lacks (see {@link TManagementFactory}). */
|
||||
public interface TRuntimeMXBean {
|
||||
long getPid();
|
||||
|
||||
String getName();
|
||||
|
||||
String getVmName();
|
||||
|
||||
String getVmVendor();
|
||||
|
||||
String getVmVersion();
|
||||
|
||||
String getSpecName();
|
||||
|
||||
String getSpecVendor();
|
||||
|
||||
String getSpecVersion();
|
||||
|
||||
List<String> getInputArguments();
|
||||
|
||||
long getUptime();
|
||||
|
||||
long getStartTime();
|
||||
|
||||
Map<String, String> getSystemProperties();
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
/**
|
||||
* {@code java.lang.management.ThreadInfo}, which TeaVM lacks. The browser build can't dump its
|
||||
* threads, so none is ever created; the type exists for the game's watchdog and crash reports.
|
||||
*/
|
||||
public class TThreadInfo {
|
||||
|
||||
private TThreadInfo() {}
|
||||
|
||||
public long getThreadId() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public String getThreadName() {
|
||||
return "";
|
||||
}
|
||||
|
||||
public StackTraceElement[] getStackTrace() {
|
||||
return new StackTraceElement[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package incari.classlib.substitutes.java.lang.management;
|
||||
|
||||
/** {@code java.lang.management.ThreadMXBean}, which TeaVM lacks (see {@link TManagementFactory}). */
|
||||
public interface TThreadMXBean {
|
||||
int getThreadCount();
|
||||
|
||||
TThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers);
|
||||
|
||||
boolean isObjectMonitorUsageSupported();
|
||||
|
||||
boolean isSynchronizerUsageSupported();
|
||||
|
||||
boolean isThreadCpuTimeSupported();
|
||||
|
||||
long getCurrentThreadCpuTime();
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user