Util .java

net.minecraft.util.Util (class): members: DEFAULT_SAFE_FILE_OPERATION_RETRIES, ALLOWED_UNTRUSTED_LINK_PROTOCOLS, FILENAME_DATE_TIME_FORMATTER, make, toMap.

net.minecraft.utilclass1,212 linescommon39.2 KB

API Surface (120)

long read()
<K, V> Collector<Entry<? extends K, ? extends V>, ?, Map<K, V>> toMap()
<T> Collector<T, ?, List<T>> toMutableList()
<T extends Comparable<T>> String getPropertyName(final Property<T> key, final Object value)
String makeDescriptionId(final String prefix, final @Nullable Identifier location)
TimeSource.NanoTimeSource timeSource()
void setTimeSource(final TimeSource.NanoTimeSource timeSource)
void shutdownTimeSource()
long getMillis()
long getNanos()
long getEpochMillis()
long toMillis(final double seconds)
String getFilenameFormattedDateTime()
void onStart()
void onTermination(final @Nullable Throwable exception)
int maxAllowedExecutorThreads()
TracingExecutor backgroundExecutor()
TracingExecutor ioPool()
TracingExecutor nonCriticalIoPool()
void shutdownExecutors()
void throwAsRuntime(final Throwable throwable)
void runNamed(final Runnable runnable, final String name)
<T> String getRegisteredName(final Registry<T> registry, final T entry)
<T> Predicate<T> allOf()
<T> Predicate<T> allOf(final Predicate<? super T> condition)
<T> Predicate<T> allOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2)
<T> Predicate<T> allOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3)
<T> Predicate<T> allOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3, final Predicate<? super T> condition4)
<T> Predicate<T> allOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3, final Predicate<? super T> condition4, final Predicate<? super T> condition5)
<T> Predicate<T> allOf(final Predicate<? super T>... conditions)
<T> Predicate<T> allOf(final List<? extends Predicate<? super T>> conditions)
<T> Predicate<T> anyOf()
<T> Predicate<T> anyOf(final Predicate<? super T> condition1)
<T> Predicate<T> anyOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2)
<T> Predicate<T> anyOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3)
<T> Predicate<T> anyOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3, final Predicate<? super T> condition4)
<T> Predicate<T> anyOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3, final Predicate<? super T> condition4, final Predicate<? super T> condition5)
<T> Predicate<T> anyOf(final Predicate<? super T>... conditions)
<T> Predicate<T> anyOf(final List<? extends Predicate<? super T>> conditions)
<T> boolean isSymmetrical(final int width, final int height, final List<T> ingredients)
int growByHalf(final int currentSize, final int minimalNewSize)
DateTimeFormatter localizedDateFormatter(final FormatStyle formatStyle)
ThreadInfo[] dumpThreadInfo()
Util.OS getPlatform()
boolean isAarch64()
boolean isAppleSiliconMac(final String renderer)
URI parseAndValidateUntrustedUri(final String uri)
<T> T findNextInIterable(final Iterable<T> collection, final @Nullable T current)
<T> T findPreviousInIterable(final Iterable<T> collection, final @Nullable T current)
<T> T make(final Supplier<T> factory)
<T> T make(final T t, final Consumer<? super T> consumer)
<K extends Enum<K>, V> Map<K, V> makeEnumMap(final Class<K> keyType, final Function<K, V> function)
<K, V1, V2> Map<K, V2> mapValues(final Map<K, V1> map, final Function<? super V1, V2> valueMapper)
<K, V1, V2> Map<K, V2> mapValuesLazy(final Map<K, V1> map, final com.google.common.base.Function<V1, V2> valueMapper)
<T extends Enum<T>> Set<T> allOfEnumExcept(final T value)
<V> CompletableFuture<List<V>> sequence(final List<? extends CompletableFuture<V>> futures)
<V> CompletableFuture<List<V>> sequenceFailFast(final List<? extends CompletableFuture<? extends V>> futures)
<V> CompletableFuture<List<V>> sequenceFailFastAndCancel(final List<? extends CompletableFuture<? extends V>> futures)
<T> Optional<T> ifElse(final Optional<T> input, final Consumer<T> onTrue, final Runnable onFalse)
<T> Supplier<T> name(final Supplier<T> task, final Supplier<String> nameGetter)
T get()
String toString()
Runnable name(final Runnable task, final Supplier<String> nameGetter)
void run()
String toString()
void logAndPauseIfInIde(final String message)
void logAndPauseIfInIde(final String message, final Throwable throwable)
<T extends Throwable> T pauseInIde(final T t)
void setPause(final Consumer<String> pauseFunction)
String describeError(final Throwable err)
<T> T getRandom(final T[] array, final RandomSource random)
int getRandom(final int[] array, final RandomSource random)
<T> T getRandom(final List<T> list, final RandomSource random)
<T> Optional<T> getRandomSafe(final List<T> list, final RandomSource random)
boolean getAsBoolean()
String toString()
boolean getAsBoolean()
String toString()
boolean getAsBoolean()
String toString()
boolean getAsBoolean()
String toString()
boolean safeMoveFile(final Path fromPath, final Path toPath, final CopyOption... options)
void safeReplaceFile(final Path targetPath, final Path newPath, final Path backupPath)
boolean safeReplaceOrMoveFile(final Path targetPath, final Path newPath, final Path backupPath, final boolean noRollback)
int offsetByCodepoints(final String input, int pos, final int offset)
Consumer<String> prefix(final String prefix, final Consumer<String> consumer)
DataResult<int[]> fixedSize(final IntStream stream, final int size)
DataResult<long[]> fixedSize(final LongStream stream, final int size)
<T> DataResult<List<T>> fixedSize(final List<T> list, final int size)
void startTimerHackThread()
void run()
void copyBetweenDirs(final Path sourceDir, final Path targetDir, final Path sourcePath)
String sanitizeName(final String value, final CharPredicate isAllowedChar)
<K, V> SingleKeyCache<K, V> singleKeyCache(final Function<K, V> computeValueFunction)
<T, R> Function<T, R> memoize(final Function<T, R> function)
R apply(final T arg)
String toString()
<T, U, R> BiFunction<T, U, R> memoize(final BiFunction<T, U, R> function)
R apply(final T a, final U b)
String toString()
<T> List<T> toShuffledList(final Stream<T> stream, final RandomSource random)
IntArrayList toShuffledList(final IntStream stream, final RandomSource random)
<T> List<T> shuffledCopy(final T[] array, final RandomSource random)
<T> List<T> shuffledCopy(final ObjectArrayList<T> list, final RandomSource random)
<T> void shuffle(final List<T> list, final RandomSource random)
<T> CompletableFuture<T> blockUntilDone(final Function<Executor, CompletableFuture<T>> task)
<T> T blockUntilDone(final Function<Executor, T> task, final Predicate<T> completionCheck)
<T> ToIntFunction<T> createIndexLookup(final List<T> values)
<T> ToIntFunction<T> createIndexIdentityLookup(final List<T> values)
<A, B> Typed<B> writeAndReadTypedOrThrow(final Typed<A> typed, final Type<B> newType, final UnaryOperator<Dynamic<?>> function)
<T> Typed<T> readTypedOrThrow(final Type<T> type, final Dynamic<?> dynamic)
<T> Typed<T> readTypedOrThrow(final Type<T> type, final Dynamic<?> dynamic, final boolean acceptPartial)
<T> List<T> copyAndAdd(final List<T> list, final T element)
<T> List<T> copyAndAdd(final List<T> list, final T... elements)
<T> List<T> copyAndAdd(final T element, final List<T> list)
<T> List<T> join(final Collection<T> first, final Collection<T> second)
<T> List<T> join(final Collection<T>... collections)
<K, V> Map<K, V> copyAndPut(final Map<K, V> map, final K key, final V value)
String telemetryName()

Fields & Constants (27)

LOGGER
DEFAULT_MAX_THREADS
DEFAULT_SAFE_FILE_OPERATION_RETRIES
MAX_THREADS_SYSTEM_PROPERTY
BACKGROUND_EXECUTOR
IO_POOL
DOWNLOAD_POOL
FILENAME_DATE_TIME_FORMATTER
LINEAR_LOOKUP_THRESHOLD
ALLOWED_UNTRUSTED_LINK_PROTOCOLS
NANOS_PER_MILLI
MILLIS_PER_SECOND
INDIRECT_TIME_SOURCE
TICKER
NIL_UUID
ZIP_FILE_SYSTEM_PROVIDER
CONTROL_CHARACTER_ESCAPER
V1
U
timeSource
thePauser
K
condition3
condition1
condition2
condition4
futures

String literals (51)

"max.bg.threads"
"Main"
"IO-Worker-"
"Download-"
"yyyy-MM-dd_HH.mm.ss"
"http"
"https"
"No jar file system provider found"
".unregistered_sadface"
"Worker-"
"Exception on worker thread"
"ThreadInfo"
"[unregistered]"
"os.name"
"solaris"
"sunos"
"linux"
"unix"
"os.arch"
"aarch64"
"Apple"
"Missing protocol in URI: "
"Unsupported protocol in URI: "
"Did you remember to set a breakpoint here?"

Full Source

Util.java1212 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.util;
2
3
import com.google.common.base.Ticker;
4
import com.google.common.collect.ImmutableList;
5
import com.google.common.collect.ImmutableMap;
6
import com.google.common.collect.Iterators;
7
import com.google.common.collect.Lists;
8
import com.google.common.collect.Maps;
9
import com.google.common.collect.ImmutableList.Builder;
10
import com.google.common.escape.Escaper;
11
import com.google.common.escape.Escapers;
12
import com.google.common.util.concurrent.MoreExecutors;
13
import com.mojang.datafixers.DataFixUtils;
14
import com.mojang.datafixers.Typed;
15
import com.mojang.datafixers.DSL.TypeReference;
16
import com.mojang.datafixers.types.Type;
17
import com.mojang.datafixers.util.Pair;
18
import com.mojang.jtracy.TracyClient;
19
import com.mojang.jtracy.Zone;
20
import com.mojang.logging.LogUtils;
21
import com.mojang.serialization.DataResult;
22
import com.mojang.serialization.Dynamic;
23
import it.unimi.dsi.fastutil.ints.IntArrayList;
24
import it.unimi.dsi.fastutil.objects.Object2IntMap;
25
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
26
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
27
import it.unimi.dsi.fastutil.objects.ObjectLists;
28
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
29
import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
30
import it.unimi.dsi.fastutil.objects.ReferenceImmutableList;
31
import it.unimi.dsi.fastutil.objects.ReferenceList;
32
import java.io.IOException;
33
import java.lang.management.ManagementFactory;
34
import java.lang.management.ThreadInfo;
35
import java.lang.management.ThreadMXBean;
36
import java.net.URI;
37
import java.net.URISyntaxException;
38
import java.nio.file.CopyOption;
39
import java.nio.file.Files;
40
import java.nio.file.Path;
41
import java.nio.file.spi.FileSystemProvider;
42
import java.time.Duration;
43
import java.time.Instant;
44
import java.time.ZonedDateTime;
45
import java.time.format.DateTimeFormatter;
46
import java.time.format.FormatStyle;
47
import java.util.Arrays;
48
import java.util.Collection;
49
import java.util.EnumMap;
50
import java.util.EnumSet;
51
import java.util.HexFormat;
52
import java.util.Iterator;
53
import java.util.List;
54
import java.util.Locale;
55
import java.util.Map;
56
import java.util.Optional;
57
import java.util.Set;
58
import java.util.UUID;
59
import java.util.Map.Entry;
60
import java.util.concurrent.BlockingQueue;
61
import java.util.concurrent.CompletableFuture;
62
import java.util.concurrent.CompletionException;
63
import java.util.concurrent.ConcurrentHashMap;
64
import java.util.concurrent.Executor;
65
import java.util.concurrent.ExecutorService;
66
import java.util.concurrent.Executors;
67
import java.util.concurrent.ForkJoinPool;
68
import java.util.concurrent.ForkJoinWorkerThread;
69
import java.util.concurrent.LinkedBlockingQueue;
70
import java.util.concurrent.TimeUnit;
71
import java.util.concurrent.atomic.AtomicInteger;
72
import java.util.function.BiFunction;
73
import java.util.function.BooleanSupplier;
74
import java.util.function.Consumer;
75
import java.util.function.Function;
76
import java.util.function.Predicate;
77
import java.util.function.Supplier;
78
import java.util.function.ToIntFunction;
79
import java.util.function.UnaryOperator;
80
import java.util.stream.Collector;
81
import java.util.stream.Collectors;
82
import java.util.stream.IntStream;
83
import java.util.stream.LongStream;
84
import java.util.stream.Stream;
85
import net.minecraft.CharPredicate;
86
import net.minecraft.CrashReport;
87
import net.minecraft.CrashReportCategory;
88
import net.minecraft.DefaultUncaughtExceptionHandler;
89
import net.minecraft.ReportedException;
90
import net.minecraft.SharedConstants;
91
import net.minecraft.SuppressForbidden;
92
import net.minecraft.TracingExecutor;
93
import net.minecraft.core.Registry;
94
import net.minecraft.resources.Identifier;
95
import net.minecraft.util.datafix.DataFixers;
96
import net.minecraft.util.thread.BlockableEventLoop;
97
import net.minecraft.world.level.block.state.properties.Property;
98
import org.jspecify.annotations.Nullable;
99
import org.slf4j.Logger;
100
101
public class Util {
102
	private static final Logger LOGGER = LogUtils.getLogger();
103
	private static final int DEFAULT_MAX_THREADS = 255;
104
	private static final int DEFAULT_SAFE_FILE_OPERATION_RETRIES = 10;
105
	private static final String MAX_THREADS_SYSTEM_PROPERTY = "max.bg.threads";
106
	private static final TracingExecutor BACKGROUND_EXECUTOR = makeExecutor("Main");
107
	private static final TracingExecutor IO_POOL = makeIoExecutor("IO-Worker-", false);
108
	private static final TracingExecutor DOWNLOAD_POOL = makeIoExecutor("Download-", true);
109
	private static final DateTimeFormatter FILENAME_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss", Locale.ROOT);
110
	public static final int LINEAR_LOOKUP_THRESHOLD = 8;
111
	private static final Set<String> ALLOWED_UNTRUSTED_LINK_PROTOCOLS = Set.of("http", "https");
112
	public static final long NANOS_PER_MILLI = 1000000L;
113
	public static final long MILLIS_PER_SECOND = 1000L;
114
	private static TimeSource.NanoTimeSource timeSource = System::nanoTime;
115
	private static final TimeSource.NanoTimeSource INDIRECT_TIME_SOURCE = () -> timeSource.getAsLong();
116
	public static final Ticker TICKER = new Ticker() {
117
		@Override
118
		public long read() {
119
			return Util.timeSource.getAsLong();
120
		}
121
	};
122
	public static final UUID NIL_UUID = new UUID(0L, 0L);
123
	public static final FileSystemProvider ZIP_FILE_SYSTEM_PROVIDER = FileSystemProvider.installedProviders()
124
		.stream()
125
		.filter(p -> p.getScheme().equalsIgnoreCase("jar"))
126
		.findFirst()
127
		.orElseThrow(() -> new IllegalStateException("No jar file system provider found"));
128
	public static final Escaper CONTROL_CHARACTER_ESCAPER = make(Escapers.builder(), escaper -> {
129
		HexFormat hexFormat = HexFormat.of().withUpperCase();
130
131
		for (char c = 0; c <= 255; c++) {
132
			if (Character.isISOControl(c)) {
133
				String replacement = switch (c) {
134
					case '\u0007' -> "\\a";
135
					case '\b' -> "\\b";
136
					case '\t' -> "\\t";
137
					case '\n' -> "\\n";
138
					case '\u000b' -> "\\v";
139
					case '\f' -> "\\f";
140
					case '\r' -> "\\r";
141
					default -> "\\x" + hexFormat.toHexDigits(c, 2);
142
				};
143
				escaper.addEscape(c, replacement);
144
			}
145
		}
146
147
		escaper.addEscape('\\', "\\\\");
148
	}).build();
149
	private static Consumer<String> thePauser = msg -> {};
150
151
	public static <K, V> Collector<Entry<? extends K, ? extends V>, ?, Map<K, V>> toMap() {
152
		return Collectors.toMap(Entry::getKey, Entry::getValue);
153
	}
154
155
	public static <T> Collector<T, ?, List<T>> toMutableList() {
156
		return Collectors.toCollection(Lists::newArrayList);
157
	}
158
159
	public static <T extends Comparable<T>> String getPropertyName(final Property<T> key, final Object value) {
160
		return key.getName((T)value);
161
	}
162
163
	public static String makeDescriptionId(final String prefix, final @Nullable Identifier location) {
164
		return location == null ? prefix + ".unregistered_sadface" : prefix + "." + location.getNamespace() + "." + location.getPath().replace('/', '.');
165
	}
166
167
	public static TimeSource.NanoTimeSource timeSource() {
168
		return INDIRECT_TIME_SOURCE;
169
	}
170
171
	public static void setTimeSource(final TimeSource.NanoTimeSource timeSource) {
172
		Util.timeSource = timeSource;
173
	}
174
175
	public static void shutdownTimeSource() {
176
		long currentTime = timeSource.getAsLong();
177
		timeSource = TimeSource.constant(currentTime);
178
	}
179
180
	public static long getMillis() {
181
		return getNanos() / 1000000L;
182
	}
183
184
	public static long getNanos() {
185
		return timeSource.getAsLong();
186
	}
187
188
	public static long getEpochMillis() {
189
		return Instant.now().toEpochMilli();
190
	}
191
192
	public static long toMillis(final double seconds) {
193
		return Mth.floor(seconds * 1000.0);
194
	}
195
196
	public static String getFilenameFormattedDateTime() {
197
		return FILENAME_DATE_TIME_FORMATTER.format(ZonedDateTime.now());
198
	}
199
200
	private static TracingExecutor makeExecutor(final String name) {
201
		int threads = maxAllowedExecutorThreads();
202
		ExecutorService executor;
203
		if (threads <= 0) {
204
			executor = MoreExecutors.newDirectExecutorService();
205
		} else {
206
			AtomicInteger workerCount = new AtomicInteger(1);
207
			executor = new ForkJoinPool(threads, pool -> {
208
				final String threadName = "Worker-" + name + "-" + workerCount.getAndIncrement();
209
				ForkJoinWorkerThread thread = new ForkJoinWorkerThread(pool) {
210
					@Override
211
					protected void onStart() {
212
						TracyClient.setThreadName(threadName, name.hashCode());
213
						super.onStart();
214
					}
215
216
					@Override
217
					protected void onTermination(final @Nullable Throwable exception) {
218
						if (exception != null) {
219
							Util.LOGGER.warn("{} died", this.getName(), exception);
220
						} else {
221
							Util.LOGGER.debug("{} shutdown", this.getName());
222
						}
223
224
						super.onTermination(exception);
225
					}
226
				};
227
				thread.setName(threadName);
228
				return thread;
229
			}, Util::onThreadException, true);
230
		}
231
232
		return new TracingExecutor(executor);
233
	}
234
235
	public static int maxAllowedExecutorThreads() {
236
		return Mth.clamp(Runtime.getRuntime().availableProcessors() - 1, 1, getMaxThreads());
237
	}
238
239
	private static int getMaxThreads() {
240
		String maxThreadsString = System.getProperty("max.bg.threads");
241
		if (maxThreadsString != null) {
242
			try {
243
				int maxThreads = Integer.parseInt(maxThreadsString);
244
				if (maxThreads >= 1 && maxThreads <= 255) {
245
					return maxThreads;
246
				}
247
248
				LOGGER.error("Wrong {} property value '{}'. Should be an integer value between 1 and {}.", "max.bg.threads", maxThreadsString, 255);
249
			} catch (NumberFormatException e) {
250
				LOGGER.error("Could not parse {} property value '{}'. Should be an integer value between 1 and {}.", "max.bg.threads", maxThreadsString, 255);
251
			}
252
		}
253
254
		return 255;
255
	}
256
257
	public static TracingExecutor backgroundExecutor() {
258
		return BACKGROUND_EXECUTOR;
259
	}
260
261
	public static TracingExecutor ioPool() {
262
		return IO_POOL;
263
	}
264
265
	public static TracingExecutor nonCriticalIoPool() {
266
		return DOWNLOAD_POOL;
267
	}
268
269
	public static void shutdownExecutors() {
270
		BACKGROUND_EXECUTOR.shutdownAndAwait(3L, TimeUnit.SECONDS);
271
		IO_POOL.shutdownAndAwait(3L, TimeUnit.SECONDS);
272
	}
273
274
	private static TracingExecutor makeIoExecutor(final String prefix, final boolean daemon) {
275
		AtomicInteger workerCount = new AtomicInteger(1);
276
		return new TracingExecutor(Executors.newCachedThreadPool(runnable -> {
277
			String name = prefix + workerCount.getAndIncrement();
278
			Thread thread = new Thread(runnable, name);
279
			TracyClient.setThreadName(name, prefix.hashCode());
280
			thread.setDaemon(daemon);
281
			thread.setUncaughtExceptionHandler(Util::onThreadException);
282
			return thread;
283
		}));
284
	}
285
286
	public static void throwAsRuntime(final Throwable throwable) {
287
		throw throwable instanceof RuntimeException runtimeException ? runtimeException : new RuntimeException(throwable);
288
	}
289
290
	private static void onThreadException(final Thread thread, Throwable throwable) {
291
		pauseInIde(throwable);
292
		if (throwable instanceof CompletionException) {
293
			throwable = throwable.getCause();
294
		}
295
296
		LOGGER.error("Caught exception in thread {}", thread, throwable);
297
		CrashReport report;
298
		if (throwable instanceof ReportedException reportedException) {
299
			report = reportedException.getReport();
300
		} else {
301
			report = CrashReport.forThrowable(throwable, "Exception on worker thread");
302
		}
303
304
		CrashReportCategory threadInfo = report.addCategory("ThreadInfo");
305
		threadInfo.setDetail("Name", thread.getName());
306
		BlockableEventLoop.relayDelayCrash(report);
307
	}
308
309
	public static @Nullable Type<?> fetchChoiceType(final TypeReference reference, final String name) {
310
		return !SharedConstants.CHECK_DATA_FIXER_SCHEMA ? null : doFetchChoiceType(reference, name);
311
	}
312
313
	private static @Nullable Type<?> doFetchChoiceType(final TypeReference reference, final String name) {
314
		Type<?> dataType = null;
315
316
		try {
317
			dataType = DataFixers.getDataFixer()
318
				.getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().dataVersion().version()))
319
				.getChoiceType(reference, name);
320
		} catch (IllegalArgumentException e) {
321
			LOGGER.error("No data fixer registered for {}", name);
322
			if (SharedConstants.IS_RUNNING_IN_IDE) {
323
				throw e;
324
			}
325
		}
326
327
		return dataType;
328
	}
329
330
	public static void runNamed(final Runnable runnable, final String name) {
331
		if (SharedConstants.IS_RUNNING_IN_IDE) {
332
			Thread thread = Thread.currentThread();
333
			String oldName = thread.getName();
334
			thread.setName(name);
335
336
			try (Zone ignored = TracyClient.beginZone(name, SharedConstants.IS_RUNNING_IN_IDE)) {
337
				runnable.run();
338
			} finally {
339
				thread.setName(oldName);
340
			}
341
		} else {
342
			try (Zone ignored = TracyClient.beginZone(name, SharedConstants.IS_RUNNING_IN_IDE)) {
343
				runnable.run();
344
			}
345
		}
346
	}
347
348
	public static <T> String getRegisteredName(final Registry<T> registry, final T entry) {
349
		Identifier key = registry.getKey(entry);
350
		return key == null ? "[unregistered]" : key.toString();
351
	}
352
353
	public static <T> Predicate<T> allOf() {
354
		return context -> true;
355
	}
356
357
	public static <T> Predicate<T> allOf(final Predicate<? super T> condition) {
358
		return (Predicate<T>)condition;
359
	}
360
361
	public static <T> Predicate<T> allOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2) {
362
		return context -> condition1.test(context) && condition2.test(context);
363
	}
364
365
	public static <T> Predicate<T> allOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3) {
366
		return context -> condition1.test(context) && condition2.test(context) && condition3.test(context);
367
	}
368
369
	public static <T> Predicate<T> allOf(
370
		final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3, final Predicate<? super T> condition4
371
	) {
372
		return context -> condition1.test(context) && condition2.test(context) && condition3.test(context) && condition4.test(context);
373
	}
374
375
	public static <T> Predicate<T> allOf(
376
		final Predicate<? super T> condition1,
377
		final Predicate<? super T> condition2,
378
		final Predicate<? super T> condition3,
379
		final Predicate<? super T> condition4,
380
		final Predicate<? super T> condition5
381
	) {
382
		return context -> condition1.test(context) && condition2.test(context) && condition3.test(context) && condition4.test(context) && condition5.test(context);
383
	}
384
385
	@SafeVarargs
386
	public static <T> Predicate<T> allOf(final Predicate<? super T>... conditions) {
387
		return context -> {
388
			for (Predicate<? super T> entry : conditions) {
389
				if (!entry.test(context)) {
390
					return false;
391
				}
392
			}
393
394
			return true;
395
		};
396
	}
397
398
	public static <T> Predicate<T> allOf(final List<? extends Predicate<? super T>> conditions) {
399
		return switch (conditions.size()) {
400
			case 0 -> allOf();
401
			case 1 -> allOf((Predicate<? super T>)conditions.get(0));
402
			case 2 -> allOf((Predicate<? super T>)conditions.get(0), (Predicate<? super T>)conditions.get(1));
403
			case 3 -> allOf((Predicate<? super T>)conditions.get(0), (Predicate<? super T>)conditions.get(1), (Predicate<? super T>)conditions.get(2));
404
			case 4 -> allOf(
405
				(Predicate<? super T>)conditions.get(0),
406
				(Predicate<? super T>)conditions.get(1),
407
				(Predicate<? super T>)conditions.get(2),
408
				(Predicate<? super T>)conditions.get(3)
409
			);
410
			case 5 -> allOf(
411
				(Predicate<? super T>)conditions.get(0),
412
				(Predicate<? super T>)conditions.get(1),
413
				(Predicate<? super T>)conditions.get(2),
414
				(Predicate<? super T>)conditions.get(3),
415
				(Predicate<? super T>)conditions.get(4)
416
			);
417
			default -> {
418
				Predicate<? super T>[] conditionsCopy = conditions.toArray(Predicate[]::new);
419
				yield allOf(conditionsCopy);
420
			}
421
		};
422
	}
423
424
	public static <T> Predicate<T> anyOf() {
425
		return context -> false;
426
	}
427
428
	public static <T> Predicate<T> anyOf(final Predicate<? super T> condition1) {
429
		return (Predicate<T>)condition1;
430
	}
431
432
	public static <T> Predicate<T> anyOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2) {
433
		return context -> condition1.test(context) || condition2.test(context);
434
	}
435
436
	public static <T> Predicate<T> anyOf(final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3) {
437
		return context -> condition1.test(context) || condition2.test(context) || condition3.test(context);
438
	}
439
440
	public static <T> Predicate<T> anyOf(
441
		final Predicate<? super T> condition1, final Predicate<? super T> condition2, final Predicate<? super T> condition3, final Predicate<? super T> condition4
442
	) {
443
		return context -> condition1.test(context) || condition2.test(context) || condition3.test(context) || condition4.test(context);
444
	}
445
446
	public static <T> Predicate<T> anyOf(
447
		final Predicate<? super T> condition1,
448
		final Predicate<? super T> condition2,
449
		final Predicate<? super T> condition3,
450
		final Predicate<? super T> condition4,
451
		final Predicate<? super T> condition5
452
	) {
453
		return context -> condition1.test(context) || condition2.test(context) || condition3.test(context) || condition4.test(context) || condition5.test(context);
454
	}
455
456
	@SafeVarargs
457
	public static <T> Predicate<T> anyOf(final Predicate<? super T>... conditions) {
458
		return context -> {
459
			for (Predicate<? super T> entry : conditions) {
460
				if (entry.test(context)) {
461
					return true;
462
				}
463
			}
464
465
			return false;
466
		};
467
	}
468
469
	public static <T> Predicate<T> anyOf(final List<? extends Predicate<? super T>> conditions) {
470
		return switch (conditions.size()) {
471
			case 0 -> anyOf();
472
			case 1 -> anyOf((Predicate<? super T>)conditions.get(0));
473
			case 2 -> anyOf((Predicate<? super T>)conditions.get(0), (Predicate<? super T>)conditions.get(1));
474
			case 3 -> anyOf((Predicate<? super T>)conditions.get(0), (Predicate<? super T>)conditions.get(1), (Predicate<? super T>)conditions.get(2));
475
			case 4 -> anyOf(
476
				(Predicate<? super T>)conditions.get(0),
477
				(Predicate<? super T>)conditions.get(1),
478
				(Predicate<? super T>)conditions.get(2),
479
				(Predicate<? super T>)conditions.get(3)
480
			);
481
			case 5 -> anyOf(
482
				(Predicate<? super T>)conditions.get(0),
483
				(Predicate<? super T>)conditions.get(1),
484
				(Predicate<? super T>)conditions.get(2),
485
				(Predicate<? super T>)conditions.get(3),
486
				(Predicate<? super T>)conditions.get(4)
487
			);
488
			default -> {
489
				Predicate<? super T>[] conditionsCopy = conditions.toArray(Predicate[]::new);
490
				yield anyOf(conditionsCopy);
491
			}
492
		};
493
	}
494
495
	public static <T> boolean isSymmetrical(final int width, final int height, final List<T> ingredients) {
496
		if (width == 1) {
497
			return true;
498
		}
499
500
		int centerX = width / 2;
501
502
		for (int y = 0; y < height; y++) {
503
			for (int leftX = 0; leftX < centerX; leftX++) {
504
				int rightX = width - 1 - leftX;
505
				T left = ingredients.get(leftX + y * width);
506
				T right = ingredients.get(rightX + y * width);
507
				if (!left.equals(right)) {
508
					return false;
509
				}
510
			}
511
		}
512
513
		return true;
514
	}
515
516
	public static int growByHalf(final int currentSize, final int minimalNewSize) {
517
		return (int)Math.max(Math.min((long)currentSize + (currentSize >> 1), 2147483639L), minimalNewSize);
518
	}
519
520
	@SuppressForbidden(reason = "Intentional use of default locale for user-visible date")
521
	public static DateTimeFormatter localizedDateFormatter(final FormatStyle formatStyle) {
522
		return DateTimeFormatter.ofLocalizedDateTime(formatStyle);
523
	}
524
525
	public static ThreadInfo[] dumpThreadInfo() {
526
		ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
527
		return threadMXBean.dumpAllThreads(threadMXBean.isObjectMonitorUsageSupported(), threadMXBean.isSynchronizerUsageSupported());
528
	}
529
530
	public static Util.OS getPlatform() {
531
		String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
532
		if (osName.contains("win")) {
533
			return Util.OS.WINDOWS;
534
		} else if (osName.contains("mac")) {
535
			return Util.OS.OSX;
536
		} else if (osName.contains("solaris")) {
537
			return Util.OS.SOLARIS;
538
		} else if (osName.contains("sunos")) {
539
			return Util.OS.SOLARIS;
540
		} else if (osName.contains("linux")) {
541
			return Util.OS.LINUX;
542
		} else {
543
			return osName.contains("unix") ? Util.OS.LINUX : Util.OS.UNKNOWN;
544
		}
545
	}
546
547
	public static boolean isAarch64() {
548
		String arch = System.getProperty("os.arch").toLowerCase(Locale.ROOT);
549
		return arch.equals("aarch64");
550
	}
551
552
	public static boolean isAppleSiliconMac(final String renderer) {
553
		return renderer.startsWith("Apple");
554
	}
555
556
	public static URI parseAndValidateUntrustedUri(final String uri) throws URISyntaxException {
557
		URI parsedUri = new URI(uri);
558
		String scheme = parsedUri.getScheme();
559
		if (scheme == null) {
560
			throw new URISyntaxException(uri, "Missing protocol in URI: " + uri);
561
		} else {
562
			String protocol = scheme.toLowerCase(Locale.ROOT);
563
			if (!ALLOWED_UNTRUSTED_LINK_PROTOCOLS.contains(protocol)) {
564
				throw new URISyntaxException(uri, "Unsupported protocol in URI: " + uri);
565
			} else {
566
				return parsedUri;
567
			}
568
		}
569
	}
570
571
	public static <T> T findNextInIterable(final Iterable<T> collection, final @Nullable T current) {
572
		Iterator<T> iterator = collection.iterator();
573
		T first = iterator.next();
574
		if (current != null) {
575
			T property = first;
576
577
			while (property != current) {
578
				if (iterator.hasNext()) {
579
					property = iterator.next();
580
				}
581
			}
582
583
			if (iterator.hasNext()) {
584
				return iterator.next();
585
			}
586
		}
587
588
		return first;
589
	}
590
591
	public static <T> T findPreviousInIterable(final Iterable<T> collection, final @Nullable T current) {
592
		Iterator<T> iterator = collection.iterator();
593
		T last = null;
594
595
		while (iterator.hasNext()) {
596
			T next = iterator.next();
597
			if (next == current) {
598
				if (last == null) {
599
					last = iterator.hasNext() ? Iterators.getLast(iterator) : current;
600
				}
601
				break;
602
			}
603
604
			last = next;
605
		}
606
607
		return last;
608
	}
609
610
	public static <T> T make(final Supplier<T> factory) {
611
		return factory.get();
612
	}
613
614
	public static <T> T make(final T t, final Consumer<? super T> consumer) {
615
		consumer.accept(t);
616
		return t;
617
	}
618
619
	public static <K extends Enum<K>, V> Map<K, V> makeEnumMap(final Class<K> keyType, final Function<K, V> function) {
620
		EnumMap<K, V> map = new EnumMap<>(keyType);
621
622
		for (K key : (Enum[])keyType.getEnumConstants()) {
623
			map.put(key, function.apply(key));
624
		}
625
626
		return map;
627
	}
628
629
	public static <K, V1, V2> Map<K, V2> mapValues(final Map<K, V1> map, final Function<? super V1, V2> valueMapper) {
630
		return map.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> valueMapper.apply(e.getValue())));
631
	}
632
633
	public static <K, V1, V2> Map<K, V2> mapValuesLazy(final Map<K, V1> map, final com.google.common.base.Function<V1, V2> valueMapper) {
634
		return Maps.transformValues(map, valueMapper);
635
	}
636
637
	public static <T extends Enum<T>> Set<T> allOfEnumExcept(final T value) {
638
		return EnumSet.complementOf(EnumSet.of(value));
639
	}
640
641
	public static <V> CompletableFuture<List<V>> sequence(final List<? extends CompletableFuture<V>> futures) {
642
		if (futures.isEmpty()) {
643
			return CompletableFuture.completedFuture(List.of());
644
		}
645
646
		if (futures.size() == 1) {
647
			return futures.getFirst().thenApply(ObjectLists::singleton);
648
		}
649
650
		CompletableFuture<Void> all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
651
		return all.thenApply(ignored -> futures.stream().map(CompletableFuture::join).toList());
652
	}
653
654
	public static <V> CompletableFuture<List<V>> sequenceFailFast(final List<? extends CompletableFuture<? extends V>> futures) {
655
		CompletableFuture<List<V>> failureFuture = new CompletableFuture<>();
656
		return fallibleSequence(futures, failureFuture::completeExceptionally).applyToEither(failureFuture, Function.identity());
657
	}
658
659
	public static <V> CompletableFuture<List<V>> sequenceFailFastAndCancel(final List<? extends CompletableFuture<? extends V>> futures) {
660
		CompletableFuture<List<V>> failureFuture = new CompletableFuture<>();
661
		return fallibleSequence(futures, exception -> {
662
			if (failureFuture.completeExceptionally(exception)) {
663
				for (CompletableFuture<? extends V> future : futures) {
664
					future.cancel(true);
665
				}
666
			}
667
		}).applyToEither(failureFuture, Function.identity());
668
	}
669
670
	private static <V> CompletableFuture<List<V>> fallibleSequence(
671
		final List<? extends CompletableFuture<? extends V>> futures, final Consumer<Throwable> failureHandler
672
	) {
673
		ObjectArrayList<V> results = new ObjectArrayList<>();
674
		results.size(futures.size());
675
		CompletableFuture<?>[] decoratedFutures = new CompletableFuture[futures.size()];
676
677
		for (int i = 0; i < futures.size(); i++) {
678
			int index = i;
679
			decoratedFutures[i] = futures.get(i).whenComplete((result, exception) -> {
680
				if (exception != null) {
681
					failureHandler.accept(exception);
682
				} else {
683
					results.set(index, (V)result);
684
				}
685
			});
686
		}
687
688
		return CompletableFuture.allOf(decoratedFutures).thenApply(nothing -> results);
689
	}
690
691
	public static <T> Optional<T> ifElse(final Optional<T> input, final Consumer<T> onTrue, final Runnable onFalse) {
692
		if (input.isPresent()) {
693
			onTrue.accept(input.get());
694
		} else {
695
			onFalse.run();
696
		}
697
698
		return input;
699
	}
700
701
	public static <T> Supplier<T> name(final Supplier<T> task, final Supplier<String> nameGetter) {
702
		if (SharedConstants.DEBUG_NAMED_RUNNABLES) {
703
			final String name = nameGetter.get();
704
			return new Supplier<T>() {
705
				@Override
706
				public T get() {
707
					return task.get();
708
				}
709
710
				@Override
711
				public String toString() {
712
					return name;
713
				}
714
			};
715
		} else {
716
			return task;
717
		}
718
	}
719
720
	public static Runnable name(final Runnable task, final Supplier<String> nameGetter) {
721
		if (SharedConstants.DEBUG_NAMED_RUNNABLES) {
722
			final String name = nameGetter.get();
723
			return new Runnable() {
724
				@Override
725
				public void run() {
726
					task.run();
727
				}
728
729
				@Override
730
				public String toString() {
731
					return name;
732
				}
733
			};
734
		} else {
735
			return task;
736
		}
737
	}
738
739
	public static void logAndPauseIfInIde(final String message) {
740
		LOGGER.error("{}", message);
741
		if (SharedConstants.IS_RUNNING_IN_IDE) {
742
			doPause(message);
743
		}
744
	}
745
746
	public static void logAndPauseIfInIde(final String message, final Throwable throwable) {
747
		LOGGER.error("{}", message, throwable);
748
		if (SharedConstants.IS_RUNNING_IN_IDE) {
749
			doPause(message);
750
		}
751
	}
752
753
	public static <T extends Throwable> T pauseInIde(final T t) {
754
		if (SharedConstants.IS_RUNNING_IN_IDE) {
755
			LOGGER.error("Trying to throw a fatal exception, pausing in IDE", t);
756
			doPause(t.getMessage());
757
		}
758
759
		return t;
760
	}
761
762
	public static void setPause(final Consumer<String> pauseFunction) {
763
		thePauser = pauseFunction;
764
	}
765
766
	private static void doPause(final String message) {
767
		Instant preLog = Instant.now();
768
		LOGGER.warn("Did you remember to set a breakpoint here?");
769
		boolean dontBotherWithPause = Duration.between(preLog, Instant.now()).toMillis() > 500L;
770
		if (!dontBotherWithPause) {
771
			thePauser.accept(message);
772
		}
773
	}
774
775
	public static String describeError(final Throwable err) {
776
		if (err.getCause() != null) {
777
			return describeError(err.getCause());
778
		} else {
779
			return err.getMessage() != null ? err.getMessage() : err.toString();
780
		}
781
	}
782
783
	public static <T> T getRandom(final T[] array, final RandomSource random) {
784
		return array[random.nextInt(array.length)];
785
	}
786
787
	public static int getRandom(final int[] array, final RandomSource random) {
788
		return array[random.nextInt(array.length)];
789
	}
790
791
	public static <T> T getRandom(final List<T> list, final RandomSource random) {
792
		return list.get(random.nextInt(list.size()));
793
	}
794
795
	public static <T> Optional<T> getRandomSafe(final List<T> list, final RandomSource random) {
796
		return list.isEmpty() ? Optional.empty() : Optional.of(getRandom(list, random));
797
	}
798
799
	private static BooleanSupplier createRenamer(final Path from, final Path to, final CopyOption... options) {
800
		return new BooleanSupplier() {
801
			@Override
802
			public boolean getAsBoolean() {
803
				try {
804
					Files.move(from, to, options);
805
					return true;
806
				} catch (IOException e) {
807
					Util.LOGGER.error("Failed to rename", e);
808
					return false;
809
				}
810
			}
811
812
			@Override
813
			public String toString() {
814
				return "rename " + from + " to " + to;
815
			}
816
		};
817
	}
818
819
	private static BooleanSupplier createDeleter(final Path target) {
820
		return new BooleanSupplier() {
821
			@Override
822
			public boolean getAsBoolean() {
823
				try {
824
					Files.deleteIfExists(target);
825
					return true;
826
				} catch (IOException e) {
827
					Util.LOGGER.warn("Failed to delete", e);
828
					return false;
829
				}
830
			}
831
832
			@Override
833
			public String toString() {
834
				return "delete old " + target;
835
			}
836
		};
837
	}
838
839
	private static BooleanSupplier createFileDeletedCheck(final Path target) {
840
		return new BooleanSupplier() {
841
			@Override
842
			public boolean getAsBoolean() {
843
				return !Files.exists(target);
844
			}
845
846
			@Override
847
			public String toString() {
848
				return "verify that " + target + " is deleted";
849
			}
850
		};
851
	}
852
853
	private static BooleanSupplier createFileCreatedCheck(final Path target) {
854
		return new BooleanSupplier() {
855
			@Override
856
			public boolean getAsBoolean() {
857
				return Files.isRegularFile(target);
858
			}
859
860
			@Override
861
			public String toString() {
862
				return "verify that " + target + " is present";
863
			}
864
		};
865
	}
866
867
	private static boolean executeInSequence(final BooleanSupplier... operations) {
868
		for (BooleanSupplier operation : operations) {
869
			if (!operation.getAsBoolean()) {
870
				LOGGER.warn("Failed to execute {}", operation);
871
				return false;
872
			}
873
		}
874
875
		return true;
876
	}
877
878
	private static boolean runWithRetries(final int numberOfRetries, final String description, final BooleanSupplier... operations) {
879
		for (int retry = 0; retry < numberOfRetries; retry++) {
880
			if (executeInSequence(operations)) {
881
				return true;
882
			}
883
884
			LOGGER.error("Failed to {}, retrying {}/{}", description, retry, numberOfRetries);
885
		}
886
887
		LOGGER.error("Failed to {}, aborting, progress might be lost", description);
888
		return false;
889
	}
890
891
	public static boolean safeMoveFile(final Path fromPath, final Path toPath, final CopyOption... options) {
892
		return runWithRetries(10, "move from  " + fromPath + " to " + toPath, createRenamer(fromPath, toPath, options), createFileCreatedCheck(toPath));
893
	}
894
895
	public static void safeReplaceFile(final Path targetPath, final Path newPath, final Path backupPath) {
896
		safeReplaceOrMoveFile(targetPath, newPath, backupPath, false);
897
	}
898
899
	public static boolean safeReplaceOrMoveFile(final Path targetPath, final Path newPath, final Path backupPath, final boolean noRollback) {
900
		if (Files.exists(targetPath)
901
			&& !runWithRetries(10, "create backup " + backupPath, createDeleter(backupPath), createRenamer(targetPath, backupPath), createFileCreatedCheck(backupPath))) {
902
			return false;
903
		} else if (!runWithRetries(10, "remove old " + targetPath, createDeleter(targetPath), createFileDeletedCheck(targetPath))) {
904
			return false;
905
		} else if (!runWithRetries(10, "replace " + targetPath + " with " + newPath, createRenamer(newPath, targetPath), createFileCreatedCheck(targetPath))
906
			&& !noRollback) {
907
			runWithRetries(10, "restore " + targetPath + " from " + backupPath, createRenamer(backupPath, targetPath), createFileCreatedCheck(targetPath));
908
			return false;
909
		} else {
910
			return true;
911
		}
912
	}
913
914
	public static int offsetByCodepoints(final String input, int pos, final int offset) {
915
		int length = input.length();
916
		if (offset >= 0) {
917
			for (int i = 0; pos < length && i < offset; i++) {
918
				if (Character.isHighSurrogate(input.charAt(pos++)) && pos < length && Character.isLowSurrogate(input.charAt(pos))) {
919
					pos++;
920
				}
921
			}
922
		} else {
923
			for (int i = offset; pos > 0 && i < 0; i++) {
924
				pos--;
925
				if (Character.isLowSurrogate(input.charAt(pos)) && pos > 0 && Character.isHighSurrogate(input.charAt(pos - 1))) {
926
					pos--;
927
				}
928
			}
929
		}
930
931
		return pos;
932
	}
933
934
	public static Consumer<String> prefix(final String prefix, final Consumer<String> consumer) {
935
		return s -> consumer.accept(prefix + s);
936
	}
937
938
	public static DataResult<int[]> fixedSize(final IntStream stream, final int size) {
939
		int[] ints = stream.limit(size + 1).toArray();
940
		if (ints.length != size) {
941
			Supplier<String> message = () -> "Input is not a list of " + size + " ints";
942
			return ints.length >= size ? DataResult.error(message, Arrays.copyOf(ints, size)) : DataResult.error(message);
943
		} else {
944
			return DataResult.success(ints);
945
		}
946
	}
947
948
	public static DataResult<long[]> fixedSize(final LongStream stream, final int size) {
949
		long[] longs = stream.limit(size + 1).toArray();
950
		if (longs.length != size) {
951
			Supplier<String> message = () -> "Input is not a list of " + size + " longs";
952
			return longs.length >= size ? DataResult.error(message, Arrays.copyOf(longs, size)) : DataResult.error(message);
953
		} else {
954
			return DataResult.success(longs);
955
		}
956
	}
957
958
	public static <T> DataResult<List<T>> fixedSize(final List<T> list, final int size) {
959
		if (list.size() != size) {
960
			Supplier<String> message = () -> "Input is not a list of " + size + " elements";
961
			return list.size() >= size ? DataResult.error(message, list.subList(0, size)) : DataResult.error(message);
962
		} else {
963
			return DataResult.success(list);
964
		}
965
	}
966
967
	public static void startTimerHackThread() {
968
		Thread timerThread = new Thread("Timer hack thread") {
969
			@Override
970
			public void run() {
971
				while (true) {
972
					try {
973
						Thread.sleep(2147483647L);
974
					} catch (InterruptedException e) {
975
						Util.LOGGER.warn("Timer hack thread interrupted, that really should not happen");
976
						return;
977
					}
978
				}
979
			}
980
		};
981
		timerThread.setDaemon(true);
982
		timerThread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
983
		timerThread.start();
984
	}
985
986
	public static void copyBetweenDirs(final Path sourceDir, final Path targetDir, final Path sourcePath) throws IOException {
987
		Path relative = sourceDir.relativize(sourcePath);
988
		Path target = targetDir.resolve(relative);
989
		Files.copy(sourcePath, target);
990
	}
991
992
	public static String sanitizeName(final String value, final CharPredicate isAllowedChar) {
993
		return value.toLowerCase(Locale.ROOT).chars().mapToObj(c -> isAllowedChar.test((char)c) ? Character.toString((char)c) : "_").collect(Collectors.joining());
994
	}
995
996
	public static <K, V> SingleKeyCache<K, V> singleKeyCache(final Function<K, V> computeValueFunction) {
997
		return new SingleKeyCache<>(computeValueFunction);
998
	}
999
1000
	public static <T, R> Function<T, R> memoize(final Function<T, R> function) {
1001
		return new Function<T, R>() {
1002
			private final Map<T, R> cache = new ConcurrentHashMap<>();
1003
1004
			@Override
1005
			public R apply(final T arg) {
1006
				return this.cache.computeIfAbsent(arg, function);
1007
			}
1008
1009
			@Override
1010
			public String toString() {
1011
				return "memoize/1[function=" + function + ", size=" + this.cache.size() + "]";
1012
			}
1013
		};
1014
	}
1015
1016
	public static <T, U, R> BiFunction<T, U, R> memoize(final BiFunction<T, U, R> function) {
1017
		return new BiFunction<T, U, R>() {
1018
			private final Map<Pair<T, U>, R> cache = new ConcurrentHashMap<>();
1019
1020
			@Override
1021
			public R apply(final T a, final U b) {
1022
				return this.cache.computeIfAbsent(Pair.of(a, b), args -> function.apply(args.getFirst(), args.getSecond()));
1023
			}
1024
1025
			@Override
1026
			public String toString() {
1027
				return "memoize/2[function=" + function + ", size=" + this.cache.size() + "]";
1028
			}
1029
		};
1030
	}
1031
1032
	public static <T> List<T> toShuffledList(final Stream<T> stream, final RandomSource random) {
1033
		ObjectArrayList<T> result = stream.collect(ObjectArrayList.toList());
1034
		shuffle(result, random);
1035
		return result;
1036
	}
1037
1038
	public static IntArrayList toShuffledList(final IntStream stream, final RandomSource random) {
1039
		IntArrayList result = IntArrayList.wrap(stream.toArray());
1040
		int size = result.size();
1041
1042
		for (int i = size; i > 1; i--) {
1043
			int swapTo = random.nextInt(i);
1044
			result.set(i - 1, result.set(swapTo, result.getInt(i - 1)));
1045
		}
1046
1047
		return result;
1048
	}
1049
1050
	public static <T> List<T> shuffledCopy(final T[] array, final RandomSource random) {
1051
		ObjectArrayList<T> copy = new ObjectArrayList<>(array);
1052
		shuffle(copy, random);
1053
		return copy;
1054
	}
1055
1056
	public static <T> List<T> shuffledCopy(final ObjectArrayList<T> list, final RandomSource random) {
1057
		ObjectArrayList<T> copy = new ObjectArrayList<>(list);
1058
		shuffle(copy, random);
1059
		return copy;
1060
	}
1061
1062
	public static <T> void shuffle(final List<T> list, final RandomSource random) {
1063
		int size = list.size();
1064
1065
		for (int i = size; i > 1; i--) {
1066
			int swapTo = random.nextInt(i);
1067
			list.set(i - 1, list.set(swapTo, list.get(i - 1)));
1068
		}
1069
	}
1070
1071
	public static <T> CompletableFuture<T> blockUntilDone(final Function<Executor, CompletableFuture<T>> task) {
1072
		return blockUntilDone(task, CompletableFuture::isDone);
1073
	}
1074
1075
	public static <T> T blockUntilDone(final Function<Executor, T> task, final Predicate<T> completionCheck) {
1076
		BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();
1077
		T result = task.apply(tasks::add);
1078
1079
		while (!completionCheck.test(result)) {
1080
			try {
1081
				Runnable runnable = tasks.poll(100L, TimeUnit.MILLISECONDS);
1082
				if (runnable != null) {
1083
					runnable.run();
1084
				}
1085
			} catch (InterruptedException e) {
1086
				LOGGER.warn("Interrupted wait");
1087
				break;
1088
			}
1089
		}
1090
1091
		int remainingSize = tasks.size();
1092
		if (remainingSize > 0) {
1093
			LOGGER.warn("Tasks left in queue: {}", remainingSize);
1094
		}
1095
1096
		return result;
1097
	}
1098
1099
	public static <T> ToIntFunction<T> createIndexLookup(final List<T> values) {
1100
		int size = values.size();
1101
		if (size < 8) {
1102
			return values::indexOf;
1103
		}
1104
1105
		Object2IntMap<T> lookup = new Object2IntOpenHashMap<>(size);
1106
		lookup.defaultReturnValue(-1);
1107
1108
		for (int i = 0; i < size; i++) {
1109
			lookup.put(values.get(i), i);
1110
		}
1111
1112
		return lookup;
1113
	}
1114
1115
	public static <T> ToIntFunction<T> createIndexIdentityLookup(final List<T> values) {
1116
		int size = values.size();
1117
		if (size < 8) {
1118
			ReferenceList<T> referenceLookup = new ReferenceImmutableList<>(values);
1119
			return referenceLookup::indexOf;
1120
		}
1121
1122
		Reference2IntMap<T> lookup = new Reference2IntOpenHashMap<>(size);
1123
		lookup.defaultReturnValue(-1);
1124
1125
		for (int i = 0; i < size; i++) {
1126
			lookup.put(values.get(i), i);
1127
		}
1128
1129
		return lookup;
1130
	}
1131
1132
	public static <A, B> Typed<B> writeAndReadTypedOrThrow(final Typed<A> typed, final Type<B> newType, final UnaryOperator<Dynamic<?>> function) {
1133
		Dynamic<?> dynamic = (Dynamic<?>)typed.write().getOrThrow();
1134
		return readTypedOrThrow(newType, function.apply(dynamic), true);
1135
	}
1136
1137
	public static <T> Typed<T> readTypedOrThrow(final Type<T> type, final Dynamic<?> dynamic) {
1138
		return readTypedOrThrow(type, dynamic, false);
1139
	}
1140
1141
	public static <T> Typed<T> readTypedOrThrow(final Type<T> type, final Dynamic<?> dynamic, final boolean acceptPartial) {
1142
		DataResult<Typed<T>> result = type.readTyped(dynamic).map(Pair::getFirst);
1143
1144
		try {
1145
			return acceptPartial ? result.getPartialOrThrow(IllegalStateException::new) : result.getOrThrow(IllegalStateException::new);
1146
		} catch (IllegalStateException e) {
1147
			CrashReport report = CrashReport.forThrowable(e, "Reading type");
1148
			CrashReportCategory category = report.addCategory("Info");
1149
			category.setDetail("Data", dynamic);
1150
			category.setDetail("Type", type);
1151
			throw new ReportedException(report);
1152
		}
1153
	}
1154
1155
	public static <T> List<T> copyAndAdd(final List<T> list, final T element) {
1156
		return ImmutableList.<T>builderWithExpectedSize(list.size() + 1).addAll(list).add(element).build();
1157
	}
1158
1159
	public static <T> List<T> copyAndAdd(final List<T> list, final T... elements) {
1160
		return ImmutableList.<T>builderWithExpectedSize(list.size() + elements.length).addAll(list).add(elements).build();
1161
	}
1162
1163
	public static <T> List<T> copyAndAdd(final T element, final List<T> list) {
1164
		return ImmutableList.<T>builderWithExpectedSize(list.size() + 1).add(element).addAll(list).build();
1165
	}
1166
1167
	public static <T> List<T> join(final Collection<T> first, final Collection<T> second) {
1168
		Builder<T> builder = ImmutableList.builderWithExpectedSize(first.size() + second.size());
1169
		builder.addAll(first);
1170
		builder.addAll(second);
1171
		return builder.build();
1172
	}
1173
1174
	public static <T> List<T> join(final Collection<T>... collections) {
1175
		int size = 0;
1176
1177
		for (Collection<T> collection : collections) {
1178
			size += collection.size();
1179
		}
1180
1181
		Builder<T> builder = ImmutableList.builderWithExpectedSize(size);
1182
1183
		for (Collection<T> collection : collections) {
1184
			builder.addAll(collection);
1185
		}
1186
1187
		return builder.build();
1188
	}
1189
1190
	public static <K, V> Map<K, V> copyAndPut(final Map<K, V> map, final K key, final V value) {
1191
		return ImmutableMap.<K, V>builderWithExpectedSize(map.size() + 1).putAll(map).put(key, value).buildKeepingLast();
1192
	}
1193
1194
	public enum OS {
1195
		LINUX("linux"),
1196
		SOLARIS("solaris"),
1197
		WINDOWS("windows"),
1198
		OSX("mac"),
1199
		UNKNOWN("unknown");
1200
1201
		private final String telemetryName;
1202
1203
		OS(final String telemetryName) {
1204
			this.telemetryName = telemetryName;
1205
		}
1206
1207
		public String telemetryName() {
1208
			return this.telemetryName;
1209
		}
1210
	}
1211
}
1212

Decompiled Minecraft 26.3 source of Util (net/minecraft/util/Util.java) with Mojang official mappings, stored verbatim on the site.