ExtraCodecs .java

net.minecraft.util.ExtraCodecs (class): members: relativeNormalizedSubPathCodec, MAX_PROPERTY_SIGNATURE_LENGTH, optionalAlwaysPresentFieldOf, NBT, JSON.

net.minecraft.utilclass753 linescommon32.4 KB

API Surface (65)

<T> Codec<T> converter(final DynamicOps<T> ops)
<P, I> Codec<I> intervalCodec(final Codec<P> pointCodec, final String lowerBoundName, final String upperBoundName, final BiFunction<P, P, DataResult<I>> makeInterval, final Function<I, P> getMin, final Function<I, P> getMax)
<A> ResultFunction<A> orElsePartial(final A value)
<T> DataResult<Pair<A, T>> apply(final DynamicOps<T> ops, final T input, final DataResult<Pair<A, T>> a)
<T> DataResult<T> coApply(final DynamicOps<T> ops, final A input, final DataResult<T> t)
String toString()
<E> Codec<E> idResolverCodec(final ToIntFunction<E> toInt, final IntFunction<@Nullable E> fromInt, final int unknownId)
<I, E> Codec<E> idResolverCodec(final Codec<I> value, final Function<I, @Nullable E> fromId, final Function<E, @Nullable I> toId)
<E> Codec<E> orCompressed(final Codec<E> normal, final Codec<E> compressed)
<T> DataResult<T> encode(final E input, final DynamicOps<T> ops, final T prefix)
<T> DataResult<Pair<E, T>> decode(final DynamicOps<T> ops, final T input)
String toString()
<E> MapCodec<E> orCompressed(final MapCodec<E> normal, final MapCodec<E> compressed)
<T> RecordBuilder<T> encode(final E input, final DynamicOps<T> ops, final RecordBuilder<T> prefix)
<T> DataResult<E> decode(final DynamicOps<T> ops, final MapLike<T> input)
<T> Stream<T> keys(final DynamicOps<T> ops)
String toString()
<E> Codec<E> overrideLifecycle(final Codec<E> codec, final Function<E, Lifecycle> decodeLifecycle, final Function<E, Lifecycle> encodeLifecycle)
<T> DataResult<Pair<E, T>> apply(final DynamicOps<T> ops, final T input, final DataResult<Pair<E, T>> a)
<T> DataResult<T> coApply(final DynamicOps<T> ops, final E input, final DataResult<T> t)
String toString()
<E> Codec<E> overrideLifecycle(final Codec<E> codec, final Function<E, Lifecycle> lifecycleGetter)
<K, V> ExtraCodecs.StrictUnboundedMapCodec<K, V> strictUnboundedMap(final Codec<K> keyCodec, final Codec<V> elementCodec)
<E> Codec<List<E>> compactListCodec(final Codec<E> elementCodec)
<E> Codec<List<E>> compactListCodec(final Codec<E> elementCodec, final Codec<List<E>> listCodec)
Codec<Integer> intRange(final int minInclusive, final int maxInclusive)
Codec<Long> longRange(final int minInclusive, final int maxInclusive)
Codec<Float> floatRange(final float minInclusive, final float maxInclusive)
<T> Codec<List<T>> nonEmptyList(final Codec<List<T>> listCodec)
<T> Codec<HolderSet<T>> nonEmptyHolderSet(final Codec<HolderSet<T>> listCodec)
<M extends Map<?, ?>> Codec<M> nonEmptyMap(final Codec<M> mapCodec)
<E> MapCodec<E> retrieveContext(final Function<DynamicOps<?>, DataResult<E>> getter)
<T> RecordBuilder<T> encode(final E input, final DynamicOps<T> ops, final RecordBuilder<T> prefix)
<T> DataResult<E> decode(final DynamicOps<T> ops, final MapLike<T> input)
String toString()
<T> Stream<T> keys(final DynamicOps<T> ops)
<E, L extends Collection<E>, T> Function<L, DataResult<L>> ensureHomogenous(final Function<E, T> typeGetter)
<A> Codec<A> catchDecoderException(final Codec<A> codec)
<T> DataResult<Pair<A, T>> decode(final DynamicOps<T> ops, final T input)
Codec<TemporalAccessor> temporalCodec(final DateTimeFormatter formatter)
MapCodec<OptionalLong> asOptionalLong(final MapCodec<Optional<Long>> fieldCodec)
<K, V> Codec<Map<K, V>> sizeLimitedMap(final Codec<Map<K, V>> codec, final int maxSizeInclusive)
<T> Codec<Object2BooleanMap<T>> object2BooleanMap(final Codec<T> keyCodec)
<K, V> MapCodec<V> dispatchOptionalValue(final String typeKey, final String valueKey, final Codec<K> typeCodec, final Function<? super V, ? extends K> typeGetter, final Function<? super K, ? extends Codec<? extends V>> valueCodec)
<T> Stream<T> keys(final DynamicOps<T> ops)
<T> DataResult<V> decode(final DynamicOps<T> ops, final MapLike<T> input)
<T> RecordBuilder<T> encode(final V input, final DynamicOps<T> ops, final RecordBuilder<T> builder)
<A> Codec<Optional<A>> optionalEmptyMap(final Codec<A> codec)
<T> DataResult<Pair<Optional<A>, T>> decode(final DynamicOps<T> ops, final T input)
<T> DataResult<T> encode(final Optional<A> input, final DynamicOps<T> ops, final T prefix)
<E extends Enum<E>> Codec<E> legacyEnum(final Function<String, E> valueOf)
Codec<Path> pathCodec(final Function<String, Path> pathFactory)
Codec<Path> relativeNormalizedSubPathCodec(final Function<String, Path> pathFactory)
Codec<Path> guardedPathCodec(final Path baseFolder)
<A> MapCodec<A> optionalAlwaysPresentFieldOf(final Codec<A> elementCodec, final String name, final A defaultValue, final boolean lenient)
<A> MapCodec<A> optionalAlwaysPresentFieldOf(final Codec<A> elementCodec, final String name, final A defaultValue)
Codec<V> codec(final Codec<I> idCodec)
ExtraCodecs.LateBoundIdMapper<I, V> put(final I id, final V value)
Set<V> values()
<T> DataResult<Map<K, V>> decode(final DynamicOps<T> ops, final MapLike<T> input)
<T> DataResult<Pair<Map<K, V>, T>> decode(final DynamicOps<T> ops, final T input)
<T> DataResult<T> encode(final Map<K, V> input, final DynamicOps<T> ops, final T prefix)
String toString()
record TagOrElementLocation(Identifier id, boolean tag)
String toString()

Fields & Constants (59)

JSON
JAVA
NBT
VECTOR2F
VECTOR3F
VECTOR3I
VECTOR4F
QUATERNIONF_COMPONENTS
AXISANGLE4F
QUATERNIONF
MATRIX4F
HEX_COLOR_PREFIX
RGB_COLOR_CODEC
ARGB_COLOR_CODEC
RGB_COLOR_VEC3_CODEC
ARGB_COLOR_VEC4_CODEC
STRING_RGB_COLOR
STRING_ARGB_COLOR
STRING_RGB_VEC3_COLOR
STRING_ARGB_VEC4_COLOR
UNSIGNED_BYTE
NON_NEGATIVE_INT
POSITIVE_INT
NON_NEGATIVE_LONG
POSITIVE_LONG
NON_NEGATIVE_FLOAT
POSITIVE_FLOAT
PATTERN
INSTANT_ISO8601
BASE64_STRING
ESCAPED_STRING
TAG_OR_ELEMENT_ID
toOptionalLong
fromOptionalLong
BIT_SET
MAX_PROPERTY_NAME_LENGTH
MAX_PROPERTY_VALUE_LENGTH
MAX_PROPERTY_SIGNATURE_LENGTH
MAX_PROPERTIES
PROPERTY
PROPERTY_MAP
PLAYER_NAME
AUTHLIB_GAME_PROFILE
STORED_GAME_PROFILE
NON_EMPTY_STRING
CODEPOINT
RESOURCE_PATH_CODEC
UNTRUSTED_URI
CHAT_STRING
pointCodec
lowerBoundName
upperBoundName
makeInterval
getMin
typeKey
valueKey
typeCodec
typeGetter
K

String literals (45)

"angle"
"axis"
"Unsigned byte was too large: "
"Value must be non-negative: "
"Value must be positive: "
"Invalid regex pattern '"
"Malformed base64 string"
"signature"
"Cannot have more than 16 properties, but was "
"Player name contained disallowed characters: '"
"Expected non-empty string"
"Expected one codepoint, got: "
"Disallowed chat character: '"
"Hex color must begin with #"
"Hex color is wrong size, expected "
" digits but got "
"Color value out of range: "
"Invalid color value: "
" -> using default)"
"OrElsePartial["
"Unknown element id: "
"Element with unknown id: "
" orCompressed "
"WithLifecycle["

Code Graph: Dependencies (9)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

ExtraCodecs.java753 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.util;
2
3
import com.google.common.collect.BiMap;
4
import com.google.common.collect.HashBiMap;
5
import com.google.common.collect.ImmutableList;
6
import com.google.common.collect.ImmutableMap;
7
import com.google.common.collect.ImmutableMultimap;
8
import com.google.common.collect.ImmutableMultimap.Builder;
9
import com.google.common.primitives.UnsignedBytes;
10
import com.google.gson.JsonElement;
11
import com.mojang.authlib.GameProfile;
12
import com.mojang.authlib.properties.Property;
13
import com.mojang.authlib.properties.PropertyMap;
14
import com.mojang.datafixers.util.Either;
15
import com.mojang.datafixers.util.Pair;
16
import com.mojang.serialization.Codec;
17
import com.mojang.serialization.DataResult;
18
import com.mojang.serialization.Decoder;
19
import com.mojang.serialization.Dynamic;
20
import com.mojang.serialization.DynamicOps;
21
import com.mojang.serialization.JavaOps;
22
import com.mojang.serialization.JsonOps;
23
import com.mojang.serialization.Lifecycle;
24
import com.mojang.serialization.MapCodec;
25
import com.mojang.serialization.MapLike;
26
import com.mojang.serialization.RecordBuilder;
27
import com.mojang.serialization.Codec.ResultFunction;
28
import com.mojang.serialization.DataResult.Error;
29
import com.mojang.serialization.codecs.BaseMapCodec;
30
import com.mojang.serialization.codecs.RecordCodecBuilder;
31
import it.unimi.dsi.fastutil.floats.FloatArrayList;
32
import it.unimi.dsi.fastutil.floats.FloatList;
33
import it.unimi.dsi.fastutil.objects.Object2BooleanMap;
34
import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap;
35
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
36
import java.net.URI;
37
import java.net.URISyntaxException;
38
import java.nio.file.FileSystem;
39
import java.nio.file.Path;
40
import java.time.Instant;
41
import java.time.format.DateTimeFormatter;
42
import java.time.temporal.TemporalAccessor;
43
import java.util.Arrays;
44
import java.util.Base64;
45
import java.util.BitSet;
46
import java.util.Collection;
47
import java.util.Collections;
48
import java.util.HexFormat;
49
import java.util.Iterator;
50
import java.util.List;
51
import java.util.Locale;
52
import java.util.Map;
53
import java.util.Objects;
54
import java.util.Optional;
55
import java.util.OptionalLong;
56
import java.util.Set;
57
import java.util.UUID;
58
import java.util.function.BiFunction;
59
import java.util.function.Function;
60
import java.util.function.IntFunction;
61
import java.util.function.ToIntFunction;
62
import java.util.regex.Pattern;
63
import java.util.regex.PatternSyntaxException;
64
import java.util.stream.Stream;
65
import net.minecraft.core.HolderSet;
66
import net.minecraft.core.UUIDUtil;
67
import net.minecraft.nbt.NbtOps;
68
import net.minecraft.nbt.Tag;
69
import net.minecraft.resources.Identifier;
70
import org.apache.commons.io.FilenameUtils;
71
import org.apache.commons.lang3.StringEscapeUtils;
72
import org.apache.commons.lang3.mutable.MutableObject;
73
import org.joml.AxisAngle4f;
74
import org.joml.Matrix4f;
75
import org.joml.Matrix4fc;
76
import org.joml.Quaternionf;
77
import org.joml.Quaternionfc;
78
import org.joml.Vector2f;
79
import org.joml.Vector2fc;
80
import org.joml.Vector3f;
81
import org.joml.Vector3fc;
82
import org.joml.Vector3i;
83
import org.joml.Vector3ic;
84
import org.joml.Vector4f;
85
import org.joml.Vector4fc;
86
import org.jspecify.annotations.Nullable;
87
88
public class ExtraCodecs {
89
	public static final Codec<JsonElement> JSON = converter(JsonOps.INSTANCE);
90
	public static final Codec<Object> JAVA = converter(JavaOps.INSTANCE);
91
	public static final Codec<Tag> NBT = converter(NbtOps.INSTANCE);
92
	public static final Codec<Vector2fc> VECTOR2F = Codec.FLOAT
93
		.listOf()
94
		.comapFlatMap(input -> Util.fixedSize((List<Float>)input, 2).map(d -> new Vector2f(d.get(0), d.get(1))), vec -> List.of(vec.x(), vec.y()));
95
	public static final Codec<Vector3fc> VECTOR3F = Codec.FLOAT
96
		.listOf()
97
		.comapFlatMap(input -> Util.fixedSize((List<Float>)input, 3).map(d -> new Vector3f(d.get(0), d.get(1), d.get(2))), vec -> List.of(vec.x(), vec.y(), vec.z()));
98
	public static final Codec<Vector3ic> VECTOR3I = Codec.INT
99
		.listOf()
100
		.comapFlatMap(
101
			input -> Util.fixedSize((List<Integer>)input, 3).map(d -> new Vector3i(d.get(0), d.get(1), d.get(2))), vec -> List.of(vec.x(), vec.y(), vec.z())
102
		);
103
	public static final Codec<Vector4fc> VECTOR4F = Codec.FLOAT
104
		.listOf()
105
		.comapFlatMap(
106
			input -> Util.fixedSize((List<Float>)input, 4).map(d -> new Vector4f(d.get(0), d.get(1), d.get(2), d.get(3))),
107
			vec -> List.of(vec.x(), vec.y(), vec.z(), vec.w())
108
		);
109
	public static final Codec<Quaternionfc> QUATERNIONF_COMPONENTS = Codec.FLOAT
110
		.listOf()
111
		.comapFlatMap(
112
			input -> Util.fixedSize((List<Float>)input, 4).map(d -> new Quaternionf(d.get(0), d.get(1), d.get(2), d.get(3)).normalize()),
113
			q -> List.of(q.x(), q.y(), q.z(), q.w())
114
		);
115
	public static final Codec<AxisAngle4f> AXISANGLE4F = RecordCodecBuilder.create(
116
		i -> i.group(Codec.FLOAT.fieldOf("angle").forGetter(o -> o.angle), VECTOR3F.fieldOf("axis").forGetter(o -> new Vector3f(o.x, o.y, o.z)))
117
			.apply(i, AxisAngle4f::new)
118
	);
119
	public static final Codec<Quaternionfc> QUATERNIONF = Codec.withAlternative(QUATERNIONF_COMPONENTS, AXISANGLE4F.xmap(Quaternionf::new, AxisAngle4f::new));
120
	public static final Codec<Matrix4fc> MATRIX4F = Codec.FLOAT.listOf().comapFlatMap(input -> Util.fixedSize((List<Float>)input, 16).map(l -> {
121
		Matrix4f result = new Matrix4f();
122
123
		for (int i = 0; i < l.size(); i++) {
124
			result.setRowColumn(i >> 2, i & 3, l.get(i));
125
		}
126
127
		return result.determineProperties();
128
	}), m -> {
129
		FloatList output = new FloatArrayList(16);
130
131
		for (int i = 0; i < 16; i++) {
132
			output.add(m.getRowColumn(i >> 2, i & 3));
133
		}
134
135
		return output;
136
	});
137
	private static final String HEX_COLOR_PREFIX = "#";
138
	public static final Codec<Integer> RGB_COLOR_CODEC = Codec.withAlternative(Codec.INT, VECTOR3F, v -> ARGB.colorFromFloat(1.0F, v.x(), v.y(), v.z()));
139
	public static final Codec<Integer> ARGB_COLOR_CODEC = Codec.withAlternative(Codec.INT, VECTOR4F, v -> ARGB.colorFromFloat(v.w(), v.x(), v.y(), v.z()));
140
	public static final Codec<Vector3fc> RGB_COLOR_VEC3_CODEC = Codec.withAlternative(VECTOR3F, Codec.INT, ARGB::vector3fFromRGB24);
141
	public static final Codec<Vector4fc> ARGB_COLOR_VEC4_CODEC = Codec.withAlternative(VECTOR4F, Codec.INT, ARGB::vector4fFromARGB32);
142
	public static final Codec<Integer> STRING_RGB_COLOR = Codec.withAlternative(hexColor(6).xmap(ARGB::opaque, ARGB::transparent), RGB_COLOR_CODEC);
143
	public static final Codec<Integer> STRING_ARGB_COLOR = Codec.withAlternative(hexColor(8), ARGB_COLOR_CODEC);
144
	public static final Codec<Vector3fc> STRING_RGB_VEC3_COLOR = Codec.withAlternative(
145
		hexColor(6).xmap(ARGB::opaque, ARGB::transparent).xmap(ARGB::vector3fFromRGB24, ARGB::colorFromVector3f), RGB_COLOR_VEC3_CODEC
146
	);
147
	public static final Codec<Vector4fc> STRING_ARGB_VEC4_COLOR = Codec.withAlternative(
148
		hexColor(8).xmap(ARGB::vector4fFromARGB32, ARGB::colorFromVector4f), ARGB_COLOR_VEC4_CODEC
149
	);
150
	public static final Codec<Integer> UNSIGNED_BYTE = Codec.BYTE
151
		.flatComapMap(
152
			UnsignedBytes::toInt,
153
			integer -> integer > 255 ? DataResult.error(() -> "Unsigned byte was too large: " + integer + " > 255") : DataResult.success(integer.byteValue())
154
		);
155
	public static final Codec<Integer> NON_NEGATIVE_INT = intRangeWithMessage(0, Integer.MAX_VALUE, n -> "Value must be non-negative: " + n);
156
	public static final Codec<Integer> POSITIVE_INT = intRangeWithMessage(1, Integer.MAX_VALUE, n -> "Value must be positive: " + n);
157
	public static final Codec<Long> NON_NEGATIVE_LONG = longRangeWithMessage(0L, Long.MAX_VALUE, n -> "Value must be non-negative: " + n);
158
	public static final Codec<Long> POSITIVE_LONG = longRangeWithMessage(1L, Long.MAX_VALUE, n -> "Value must be positive: " + n);
159
	public static final Codec<Float> NON_NEGATIVE_FLOAT = floatRangeMinInclusiveWithMessage(0.0F, Float.MAX_VALUE, n -> "Value must be non-negative: " + n);
160
	public static final Codec<Float> POSITIVE_FLOAT = floatRangeMinExclusiveWithMessage(0.0F, Float.MAX_VALUE, n -> "Value must be positive: " + n);
161
	public static final Codec<Pattern> PATTERN = Codec.STRING.comapFlatMap(pattern -> {
162
		try {
163
			return DataResult.success(Pattern.compile(pattern));
164
		} catch (PatternSyntaxException e) {
165
			return DataResult.error(() -> "Invalid regex pattern '" + pattern + "': " + e.getMessage());
166
		}
167
	}, Pattern::pattern);
168
	public static final Codec<Instant> INSTANT_ISO8601 = temporalCodec(DateTimeFormatter.ISO_INSTANT).xmap(Instant::from, Function.identity());
169
	public static final Codec<byte[]> BASE64_STRING = Codec.STRING.comapFlatMap(string -> {
170
		try {
171
			return DataResult.success(Base64.getDecoder().decode(string));
172
		} catch (IllegalArgumentException e) {
173
			return DataResult.error(() -> "Malformed base64 string");
174
		}
175
	}, bytes -> Base64.getEncoder().encodeToString(bytes));
176
	public static final Codec<String> ESCAPED_STRING = Codec.STRING
177
		.comapFlatMap(str -> DataResult.success(StringEscapeUtils.unescapeJava(str)), StringEscapeUtils::escapeJava);
178
	public static final Codec<ExtraCodecs.TagOrElementLocation> TAG_OR_ELEMENT_ID = Codec.STRING
179
		.comapFlatMap(
180
			name -> name.startsWith("#")
181
				? Identifier.read(name.substring(1)).map(id -> new ExtraCodecs.TagOrElementLocation(id, true))
182
				: Identifier.read(name).map(id -> new ExtraCodecs.TagOrElementLocation(id, false)),
183
			ExtraCodecs.TagOrElementLocation::decoratedId
184
		);
185
	public static final Function<Optional<Long>, OptionalLong> toOptionalLong = o -> o.map(OptionalLong::of).orElseGet(OptionalLong::empty);
186
	public static final Function<OptionalLong, Optional<Long>> fromOptionalLong = l -> l.isPresent() ? Optional.of(l.getAsLong()) : Optional.empty();
187
	public static final Codec<BitSet> BIT_SET = Codec.LONG_STREAM
188
		.xmap(longStream -> BitSet.valueOf(longStream.toArray()), bitSet -> Arrays.stream(bitSet.toLongArray()));
189
	public static final int MAX_PROPERTY_NAME_LENGTH = 64;
190
	public static final int MAX_PROPERTY_VALUE_LENGTH = 32767;
191
	public static final int MAX_PROPERTY_SIGNATURE_LENGTH = 1024;
192
	public static final int MAX_PROPERTIES = 16;
193
	private static final Codec<Property> PROPERTY = RecordCodecBuilder.create(
194
		i -> i.group(
195
				Codec.sizeLimitedString(64).fieldOf("name").forGetter(Property::name),
196
				Codec.sizeLimitedString(32767).fieldOf("value").forGetter(Property::value),
197
				Codec.sizeLimitedString(1024).optionalFieldOf("signature").forGetter(property -> Optional.ofNullable(property.signature()))
198
			)
199
			.apply(i, (name, value, signature) -> new Property(name, value, signature.orElse(null)))
200
	);
201
	public static final Codec<PropertyMap> PROPERTY_MAP = Codec.either(
202
			Codec.unboundedMap(Codec.STRING, Codec.STRING.listOf())
203
				.validate(map -> map.size() > 16 ? DataResult.error(() -> "Cannot have more than 16 properties, but was " + map.size()) : DataResult.success(map)),
204
			PROPERTY.sizeLimitedListOf(16)
205
		)
206
		.xmap(mapListEither -> {
207
			Builder<String, Property> result = ImmutableMultimap.builder();
208
			mapListEither.ifLeft(s -> s.forEach((name, properties) -> {
209
				for (String property : properties) {
210
					result.put(name, new Property(name, property));
211
				}
212
			})).ifRight(properties -> {
213
				for (Property property : properties) {
214
					result.put(property.name(), property);
215
				}
216
			});
217
			return new PropertyMap(result.build());
218
		}, propertyMap -> Either.right(propertyMap.values().stream().toList()));
219
	public static final Codec<String> PLAYER_NAME = Codec.string(0, 16)
220
		.validate(
221
			name -> StringUtil.isValidPlayerName(name)
222
				? DataResult.success(name)
223
				: DataResult.error(() -> "Player name contained disallowed characters: '" + name + "'")
224
		);
225
	public static final Codec<GameProfile> AUTHLIB_GAME_PROFILE = gameProfileCodec(UUIDUtil.AUTHLIB_CODEC).codec();
226
	public static final MapCodec<GameProfile> STORED_GAME_PROFILE = gameProfileCodec(UUIDUtil.CODEC);
227
	public static final Codec<String> NON_EMPTY_STRING = Codec.STRING
228
		.validate(value -> value.isEmpty() ? DataResult.error(() -> "Expected non-empty string") : DataResult.success(value));
229
	public static final Codec<Integer> CODEPOINT = Codec.STRING.comapFlatMap(s -> {
230
		int[] codepoint = s.codePoints().toArray();
231
		return codepoint.length != 1 ? DataResult.error(() -> "Expected one codepoint, got: " + s) : DataResult.success(codepoint[0]);
232
	}, Character::toString);
233
	public static final Codec<String> RESOURCE_PATH_CODEC = Codec.STRING
234
		.validate(s -> !Identifier.isValidPath(s) ? DataResult.error(() -> "Invalid string to use as a resource path element: " + s) : DataResult.success(s));
235
	public static final Codec<URI> UNTRUSTED_URI = Codec.STRING.comapFlatMap(string -> {
236
		try {
237
			return DataResult.success(Util.parseAndValidateUntrustedUri(string));
238
		} catch (URISyntaxException e) {
239
			return DataResult.error(e::getMessage);
240
		}
241
	}, URI::toString);
242
	public static final Codec<String> CHAT_STRING = Codec.STRING.validate(string -> {
243
		for (int i = 0; i < string.length(); i++) {
244
			char c = string.charAt(i);
245
			if (!StringUtil.isAllowedChatCharacter(c)) {
246
				return DataResult.error(() -> "Disallowed chat character: '" + c + "'");
247
			}
248
		}
249
250
		return DataResult.success(string);
251
	});
252
253
	public static <T> Codec<T> converter(final DynamicOps<T> ops) {
254
		return Codec.PASSTHROUGH.xmap(t -> t.convert(ops).getValue(), t -> new Dynamic<>(ops, (T)t));
255
	}
256
257
	private static Codec<Integer> hexColor(final int expectedDigits) {
258
		long maxValue = (1L << expectedDigits * 4) - 1L;
259
		return Codec.STRING.comapFlatMap(string -> {
260
			if (!string.startsWith("#")) {
261
				return DataResult.error(() -> "Hex color must begin with #");
262
			}
263
264
			int digits = string.length() - "#".length();
265
			if (digits != expectedDigits) {
266
				return DataResult.error(() -> "Hex color is wrong size, expected " + expectedDigits + " digits but got " + digits);
267
			}
268
269
			try {
270
				long value = HexFormat.fromHexDigitsToLong(string, "#".length(), string.length());
271
				return value >= 0L && value <= maxValue ? DataResult.success((int)value) : DataResult.error(() -> "Color value out of range: " + string);
272
			} catch (NumberFormatException e) {
273
				return DataResult.error(() -> "Invalid color value: " + string);
274
			}
275
		}, value -> "#" + HexFormat.of().toHexDigits(value.intValue(), expectedDigits));
276
	}
277
278
	public static <P, I> Codec<I> intervalCodec(
279
		final Codec<P> pointCodec,
280
		final String lowerBoundName,
281
		final String upperBoundName,
282
		final BiFunction<P, P, DataResult<I>> makeInterval,
283
		final Function<I, P> getMin,
284
		final Function<I, P> getMax
285
	) {
286
		Codec<I> arrayCodec = Codec.list(pointCodec).comapFlatMap(list -> Util.fixedSize((List<P>)list, 2).flatMap(l -> {
287
			P min = l.get(0);
288
			P max = l.get(1);
289
			return makeInterval.apply(min, max);
290
		}), p -> ImmutableList.of(getMin.apply((I)p), getMax.apply((I)p)));
291
		Codec<I> objectCodec = RecordCodecBuilder.<Pair>create(
292
				i -> i.group(pointCodec.fieldOf(lowerBoundName).forGetter(Pair::getFirst), pointCodec.fieldOf(upperBoundName).forGetter(Pair::getSecond))
293
					.apply(i, Pair::of)
294
			)
295
			.comapFlatMap(p -> makeInterval.apply((P)p.getFirst(), (P)p.getSecond()), i -> Pair.of(getMin.apply((I)i), getMax.apply((I)i)));
296
		Codec<I> arrayOrObjectCodec = Codec.withAlternative(arrayCodec, objectCodec);
297
		return Codec.either(pointCodec, arrayOrObjectCodec).comapFlatMap(either -> either.map(min -> makeInterval.apply((P)min, (P)min), DataResult::success), p -> {
298
			P min = getMin.apply((I)p);
299
			P max = getMax.apply((I)p);
300
			return Objects.equals(min, max) ? Either.left(min) : Either.right((I)p);
301
		});
302
	}
303
304
	public static <A> ResultFunction<A> orElsePartial(final A value) {
305
		return new ResultFunction<A>() {
306
			@Override
307
			public <T> DataResult<Pair<A, T>> apply(final DynamicOps<T> ops, final T input, final DataResult<Pair<A, T>> a) {
308
				MutableObject<String> message = new MutableObject<>();
309
				Optional<Pair<A, T>> result = a.resultOrPartial(message::setValue);
310
				return result.isPresent() ? a : DataResult.error(() -> "(" + message.get() + " -> using default)", Pair.of(value, input));
311
			}
312
313
			@Override
314
			public <T> DataResult<T> coApply(final DynamicOps<T> ops, final A input, final DataResult<T> t) {
315
				return t;
316
			}
317
318
			@Override
319
			public String toString() {
320
				return "OrElsePartial[" + value + "]";
321
			}
322
		};
323
	}
324
325
	public static <E> Codec<E> idResolverCodec(final ToIntFunction<E> toInt, final IntFunction<@Nullable E> fromInt, final int unknownId) {
326
		return Codec.INT
327
			.flatXmap(id -> Optional.ofNullable(fromInt.apply(id)).map(DataResult::success).orElseGet(() -> DataResult.error(() -> "Unknown element id: " + id)), e -> {
328
				int id = toInt.applyAsInt((E)e);
329
				return id == unknownId ? DataResult.error(() -> "Element with unknown id: " + e) : DataResult.success(id);
330
			});
331
	}
332
333
	public static <I, E> Codec<E> idResolverCodec(final Codec<I> value, final Function<I, @Nullable E> fromId, final Function<E, @Nullable I> toId) {
334
		return value.flatXmap(id -> {
335
			E element = fromId.apply((I)id);
336
			return element == null ? DataResult.error(() -> "Unknown element id: " + id) : DataResult.success(element);
337
		}, e -> {
338
			I id = toId.apply((E)e);
339
			return id == null ? DataResult.error(() -> "Element with unknown id: " + e) : DataResult.success(id);
340
		});
341
	}
342
343
	public static <E> Codec<E> orCompressed(final Codec<E> normal, final Codec<E> compressed) {
344
		return new Codec<E>() {
345
			@Override
346
			public <T> DataResult<T> encode(final E input, final DynamicOps<T> ops, final T prefix) {
347
				return ops.compressMaps() ? compressed.encode(input, ops, prefix) : normal.encode(input, ops, prefix);
348
			}
349
350
			@Override
351
			public <T> DataResult<Pair<E, T>> decode(final DynamicOps<T> ops, final T input) {
352
				return ops.compressMaps() ? compressed.decode(ops, input) : normal.decode(ops, input);
353
			}
354
355
			@Override
356
			public String toString() {
357
				return normal + " orCompressed " + compressed;
358
			}
359
		};
360
	}
361
362
	public static <E> MapCodec<E> orCompressed(final MapCodec<E> normal, final MapCodec<E> compressed) {
363
		return new MapCodec<E>() {
364
			@Override
365
			public <T> RecordBuilder<T> encode(final E input, final DynamicOps<T> ops, final RecordBuilder<T> prefix) {
366
				return ops.compressMaps() ? compressed.encode(input, ops, prefix) : normal.encode(input, ops, prefix);
367
			}
368
369
			@Override
370
			public <T> DataResult<E> decode(final DynamicOps<T> ops, final MapLike<T> input) {
371
				return ops.compressMaps() ? compressed.decode(ops, input) : normal.decode(ops, input);
372
			}
373
374
			@Override
375
			public <T> Stream<T> keys(final DynamicOps<T> ops) {
376
				return compressed.keys(ops);
377
			}
378
379
			@Override
380
			public String toString() {
381
				return normal + " orCompressed " + compressed;
382
			}
383
		};
384
	}
385
386
	public static <E> Codec<E> overrideLifecycle(final Codec<E> codec, final Function<E, Lifecycle> decodeLifecycle, final Function<E, Lifecycle> encodeLifecycle) {
387
		return codec.mapResult(new ResultFunction<E>() {
388
			@Override
389
			public <T> DataResult<Pair<E, T>> apply(final DynamicOps<T> ops, final T input, final DataResult<Pair<E, T>> a) {
390
				return a.result().map(r -> a.setLifecycle(decodeLifecycle.apply(r.getFirst()))).orElse(a);
391
			}
392
393
			@Override
394
			public <T> DataResult<T> coApply(final DynamicOps<T> ops, final E input, final DataResult<T> t) {
395
				return t.setLifecycle(encodeLifecycle.apply(input));
396
			}
397
398
			@Override
399
			public String toString() {
400
				return "WithLifecycle[" + decodeLifecycle + " " + encodeLifecycle + "]";
401
			}
402
		});
403
	}
404
405
	public static <E> Codec<E> overrideLifecycle(final Codec<E> codec, final Function<E, Lifecycle> lifecycleGetter) {
406
		return overrideLifecycle(codec, lifecycleGetter, lifecycleGetter);
407
	}
408
409
	public static <K, V> ExtraCodecs.StrictUnboundedMapCodec<K, V> strictUnboundedMap(final Codec<K> keyCodec, final Codec<V> elementCodec) {
410
		return new ExtraCodecs.StrictUnboundedMapCodec<>(keyCodec, elementCodec);
411
	}
412
413
	public static <E> Codec<List<E>> compactListCodec(final Codec<E> elementCodec) {
414
		return compactListCodec(elementCodec, elementCodec.listOf());
415
	}
416
417
	public static <E> Codec<List<E>> compactListCodec(final Codec<E> elementCodec, final Codec<List<E>> listCodec) {
418
		return Codec.either(listCodec, elementCodec).xmap(e -> e.map(l -> l, List::of), v -> v.size() == 1 ? Either.right(v.getFirst()) : Either.left((List<E>)v));
419
	}
420
421
	private static Codec<Integer> intRangeWithMessage(final int minInclusive, final int maxInclusive, final Function<Integer, String> error) {
422
		return Codec.INT
423
			.validate(
424
				value -> value.compareTo(minInclusive) >= 0 && value.compareTo(maxInclusive) <= 0 ? DataResult.success(value) : DataResult.error(() -> error.apply(value))
425
			);
426
	}
427
428
	public static Codec<Integer> intRange(final int minInclusive, final int maxInclusive) {
429
		return intRangeWithMessage(minInclusive, maxInclusive, n -> "Value must be within range [" + minInclusive + ";" + maxInclusive + "]: " + n);
430
	}
431
432
	private static Codec<Long> longRangeWithMessage(final long minInclusive, final long maxInclusive, final Function<Long, String> error) {
433
		return Codec.LONG
434
			.validate(
435
				value -> value.compareTo(minInclusive) >= 0L && value.compareTo(maxInclusive) <= 0L
436
					? DataResult.success(value)
437
					: DataResult.error(() -> error.apply(value))
438
			);
439
	}
440
441
	public static Codec<Long> longRange(final int minInclusive, final int maxInclusive) {
442
		return longRangeWithMessage(minInclusive, maxInclusive, n -> "Value must be within range [" + minInclusive + ";" + maxInclusive + "]: " + n);
443
	}
444
445
	private static Codec<Float> floatRangeMinInclusiveWithMessage(final float minInclusive, final float maxInclusive, final Function<Float, String> error) {
446
		return Codec.FLOAT
447
			.validate(
448
				value -> value.compareTo(minInclusive) >= 0 && value.compareTo(maxInclusive) <= 0 ? DataResult.success(value) : DataResult.error(() -> error.apply(value))
449
			);
450
	}
451
452
	private static Codec<Float> floatRangeMinExclusiveWithMessage(final float minExclusive, final float maxInclusive, final Function<Float, String> error) {
453
		return Codec.FLOAT
454
			.validate(
455
				value -> value.compareTo(minExclusive) > 0 && value.compareTo(maxInclusive) <= 0 ? DataResult.success(value) : DataResult.error(() -> error.apply(value))
456
			);
457
	}
458
459
	public static Codec<Float> floatRange(final float minInclusive, final float maxInclusive) {
460
		return floatRangeMinInclusiveWithMessage(minInclusive, maxInclusive, n -> "Value must be within range [" + minInclusive + ";" + maxInclusive + "]: " + n);
461
	}
462
463
	public static <T> Codec<List<T>> nonEmptyList(final Codec<List<T>> listCodec) {
464
		return listCodec.validate(list -> list.isEmpty() ? DataResult.error(() -> "List must have contents") : DataResult.success(list));
465
	}
466
467
	public static <T> Codec<HolderSet<T>> nonEmptyHolderSet(final Codec<HolderSet<T>> listCodec) {
468
		return listCodec.validate(
469
			list -> list.unwrap().right().filter(List::isEmpty).isPresent() ? DataResult.error(() -> "List must have contents") : DataResult.success(list)
470
		);
471
	}
472
473
	public static <M extends Map<?, ?>> Codec<M> nonEmptyMap(final Codec<M> mapCodec) {
474
		return mapCodec.validate(map -> map.isEmpty() ? DataResult.error(() -> "Map must have contents") : DataResult.success(map));
475
	}
476
477
	public static <E> MapCodec<E> retrieveContext(final Function<DynamicOps<?>, DataResult<E>> getter) {
478
		class ContextRetrievalCodec extends MapCodec<E> {
479
			@Override
480
			public <T> RecordBuilder<T> encode(final E input, final DynamicOps<T> ops, final RecordBuilder<T> prefix) {
481
				return prefix;
482
			}
483
484
			@Override
485
			public <T> DataResult<E> decode(final DynamicOps<T> ops, final MapLike<T> input) {
486
				return getter.apply(ops);
487
			}
488
489
			@Override
490
			public String toString() {
491
				return "ContextRetrievalCodec[" + getter + "]";
492
			}
493
494
			@Override
495
			public <T> Stream<T> keys(final DynamicOps<T> ops) {
496
				return Stream.empty();
497
			}
498
		}
499
500
		return new ContextRetrievalCodec();
501
	}
502
503
	public static <E, L extends Collection<E>, T> Function<L, DataResult<L>> ensureHomogenous(final Function<E, T> typeGetter) {
504
		return container -> {
505
			Iterator<E> it = container.iterator();
506
			if (it.hasNext()) {
507
				T firstType = typeGetter.apply(it.next());
508
509
				while (it.hasNext()) {
510
					E next = it.next();
511
					T nextType = typeGetter.apply(next);
512
					if (nextType != firstType) {
513
						return DataResult.error(() -> "Mixed type list: element " + next + " had type " + nextType + ", but list is of type " + firstType);
514
					}
515
				}
516
			}
517
518
			return DataResult.success(container, Lifecycle.stable());
519
		};
520
	}
521
522
	public static <A> Codec<A> catchDecoderException(final Codec<A> codec) {
523
		return Codec.of(codec, new Decoder<A>() {
524
			@Override
525
			public <T> DataResult<Pair<A, T>> decode(final DynamicOps<T> ops, final T input) {
526
				try {
527
					return codec.decode(ops, input);
528
				} catch (Exception e) {
529
					return DataResult.error(() -> "Caught exception decoding " + input + ": " + e.getMessage());
530
				}
531
			}
532
		});
533
	}
534
535
	public static Codec<TemporalAccessor> temporalCodec(final DateTimeFormatter formatter) {
536
		return Codec.STRING.comapFlatMap(s -> {
537
			try {
538
				return DataResult.success(formatter.parse(s));
539
			} catch (Exception e) {
540
				return DataResult.error(e::getMessage);
541
			}
542
		}, formatter::format);
543
	}
544
545
	public static MapCodec<OptionalLong> asOptionalLong(final MapCodec<Optional<Long>> fieldCodec) {
546
		return fieldCodec.xmap(toOptionalLong, fromOptionalLong);
547
	}
548
549
	private static MapCodec<GameProfile> gameProfileCodec(final Codec<UUID> uuidCodec) {
550
		return RecordCodecBuilder.mapCodec(
551
			i -> i.group(
552
					uuidCodec.fieldOf("id").forGetter(GameProfile::id),
553
					PLAYER_NAME.fieldOf("name").forGetter(GameProfile::name),
554
					PROPERTY_MAP.optionalFieldOf("properties", PropertyMap.EMPTY).forGetter(GameProfile::properties)
555
				)
556
				.apply(i, GameProfile::new)
557
		);
558
	}
559
560
	public static <K, V> Codec<Map<K, V>> sizeLimitedMap(final Codec<Map<K, V>> codec, final int maxSizeInclusive) {
561
		return codec.validate(
562
			map -> map.size() > maxSizeInclusive
563
				? DataResult.error(() -> "Map is too long: " + map.size() + ", expected range [0-" + maxSizeInclusive + "]")
564
				: DataResult.success(map)
565
		);
566
	}
567
568
	public static <T> Codec<Object2BooleanMap<T>> object2BooleanMap(final Codec<T> keyCodec) {
569
		return Codec.unboundedMap(keyCodec, Codec.BOOL).xmap(Object2BooleanOpenHashMap::new, Object2ObjectOpenHashMap::new);
570
	}
571
572
	@Deprecated
573
	public static <K, V> MapCodec<V> dispatchOptionalValue(
574
		final String typeKey,
575
		final String valueKey,
576
		final Codec<K> typeCodec,
577
		final Function<? super V, ? extends K> typeGetter,
578
		final Function<? super K, ? extends Codec<? extends V>> valueCodec
579
	) {
580
		return new MapCodec<V>() {
581
			@Override
582
			public <T> Stream<T> keys(final DynamicOps<T> ops) {
583
				return Stream.of(ops.createString(typeKey), ops.createString(valueKey));
584
			}
585
586
			@Override
587
			public <T> DataResult<V> decode(final DynamicOps<T> ops, final MapLike<T> input) {
588
				T typeName = input.get(typeKey);
589
				return typeName == null ? DataResult.error(() -> "Missing \"" + typeKey + "\" in: " + input) : typeCodec.decode(ops, typeName).flatMap(type -> {
590
					T value = Objects.requireNonNullElseGet(input.get(valueKey), ops::emptyMap);
591
					return valueCodec.apply(type.getFirst()).decode(ops, value).map(Pair::getFirst);
592
				});
593
			}
594
595
			@Override
596
			public <T> RecordBuilder<T> encode(final V input, final DynamicOps<T> ops, final RecordBuilder<T> builder) {
597
				K type = (K)typeGetter.apply(input);
598
				builder.add(typeKey, typeCodec.encodeStart(ops, type));
599
				DataResult<T> parameters = this.encode(valueCodec.apply(type), input, ops);
600
				if (parameters.result().isEmpty() || !Objects.equals(parameters.result().get(), ops.emptyMap())) {
601
					builder.add(valueKey, parameters);
602
				}
603
604
				return builder;
605
			}
606
607
			private <T, V2 extends V> DataResult<T> encode(final Codec<V2> codec, final V input, final DynamicOps<T> ops) {
608
				return codec.encodeStart(ops, (V2)input);
609
			}
610
		};
611
	}
612
613
	public static <A> Codec<Optional<A>> optionalEmptyMap(final Codec<A> codec) {
614
		return new Codec<Optional<A>>() {
615
			@Override
616
			public <T> DataResult<Pair<Optional<A>, T>> decode(final DynamicOps<T> ops, final T input) {
617
				return isEmptyMap(ops, input) ? DataResult.success(Pair.of(Optional.empty(), input)) : codec.decode(ops, input).map(pair -> pair.mapFirst(Optional::of));
618
			}
619
620
			private static <T> boolean isEmptyMap(final DynamicOps<T> ops, final T input) {
621
				Optional<MapLike<T>> map = ops.getMap(input).result();
622
				return map.isPresent() && map.get().entries().findAny().isEmpty();
623
			}
624
625
			public <T> DataResult<T> encode(final Optional<A> input, final DynamicOps<T> ops, final T prefix) {
626
				return input.isEmpty() ? DataResult.success(ops.emptyMap()) : codec.encode(input.get(), ops, prefix);
627
			}
628
		};
629
	}
630
631
	@Deprecated
632
	public static <E extends Enum<E>> Codec<E> legacyEnum(final Function<String, E> valueOf) {
633
		return Codec.STRING.comapFlatMap(key -> {
634
			try {
635
				return DataResult.success(valueOf.apply(key));
636
			} catch (IllegalArgumentException ignored) {
637
				return DataResult.error(() -> "No value with id: " + key);
638
			}
639
		}, Enum::toString);
640
	}
641
642
	public static Codec<Path> pathCodec(final Function<String, Path> pathFactory) {
643
		return Codec.STRING.xmap(pathFactory, path -> FilenameUtils.separatorsToUnix(path.toString()));
644
	}
645
646
	public static Codec<Path> relativeNormalizedSubPathCodec(final Function<String, Path> pathFactory) {
647
		return pathCodec(pathFactory).xmap(Path::normalize, Path::normalize).validate(path -> {
648
			if (path.isAbsolute()) {
649
				return DataResult.error(() -> "Illegal absolute path: " + path);
650
			}
651
652
			for (Path pathElement : path) {
653
				if (pathElement.startsWith("..") || pathElement.startsWith(".")) {
654
					return DataResult.error(() -> "Illegal path traversal: " + path);
655
				}
656
			}
657
658
			return FileUtil.isEmptyPath(path) ? DataResult.error(() -> "Path is empty: " + path) : DataResult.success(path);
659
		});
660
	}
661
662
	public static Codec<Path> guardedPathCodec(final Path baseFolder) {
663
		FileSystem var1 = baseFolder.getFileSystem();
664
		return relativeNormalizedSubPathCodec(x$0 -> var1.getPath(x$0))
665
			.xmap(baseFolder::resolve, baseFolder::relativize)
666
			.validate(
667
				path -> !path.startsWith(baseFolder)
668
					? DataResult.error(() -> String.format(Locale.ROOT, "Path %s does not start with base folder %s", path, baseFolder))
669
					: DataResult.success(path)
670
			);
671
	}
672
673
	public static <A> MapCodec<A> optionalAlwaysPresentFieldOf(final Codec<A> elementCodec, final String name, final A defaultValue, final boolean lenient) {
674
		return Codec.optionalField(name, elementCodec, lenient).xmap(o -> o.orElse(defaultValue), Optional::of);
675
	}
676
677
	public static <A> MapCodec<A> optionalAlwaysPresentFieldOf(final Codec<A> elementCodec, final String name, final A defaultValue) {
678
		return optionalAlwaysPresentFieldOf(elementCodec, name, defaultValue, false);
679
	}
680
681
	public static class LateBoundIdMapper<I, V> {
682
		private final BiMap<I, V> idToValue = HashBiMap.create();
683
684
		public Codec<V> codec(final Codec<I> idCodec) {
685
			BiMap<V, I> valueToId = this.idToValue.inverse();
686
			return ExtraCodecs.idResolverCodec(idCodec, this.idToValue::get, valueToId::get);
687
		}
688
689
		public ExtraCodecs.LateBoundIdMapper<I, V> put(final I id, final V value) {
690
			Objects.requireNonNull(value, () -> "Value for " + id + " is null");
691
			this.idToValue.put(id, value);
692
			return this;
693
		}
694
695
		public Set<V> values() {
696
			return Collections.unmodifiableSet(this.idToValue.values());
697
		}
698
	}
699
700
	public record StrictUnboundedMapCodec<K, V>(Codec<K> keyCodec, Codec<V> elementCodec) implements BaseMapCodec<K, V>, Codec<Map<K, V>> {
701
		@Override
702
		public <T> DataResult<Map<K, V>> decode(final DynamicOps<T> ops, final MapLike<T> input) {
703
			com.google.common.collect.ImmutableMap.Builder<K, V> read = ImmutableMap.builder();
704
705
			for (Pair<T, T> pair : input.entries().toList()) {
706
				DataResult<K> k = this.keyCodec().parse(ops, pair.getFirst());
707
				DataResult<V> v = this.elementCodec().parse(ops, pair.getSecond());
708
				DataResult<Pair<K, V>> entry = k.apply2stable(Pair::of, v);
709
				Optional<Error<Pair<K, V>>> error = entry.error();
710
				if (error.isPresent()) {
711
					String errorMessage = error.get().message();
712
					return DataResult.error(() -> k.result().isPresent() ? "Map entry '" + k.result().get() + "' : " + errorMessage : errorMessage);
713
				}
714
715
				if (!entry.result().isPresent()) {
716
					return DataResult.error(() -> "Empty or invalid map contents are not allowed");
717
				}
718
719
				Pair<K, V> kvPair = entry.result().get();
720
				read.put(kvPair.getFirst(), kvPair.getSecond());
721
			}
722
723
			Map<K, V> elements = read.build();
724
			return DataResult.success(elements);
725
		}
726
727
		@Override
728
		public <T> DataResult<Pair<Map<K, V>, T>> decode(final DynamicOps<T> ops, final T input) {
729
			return ops.getMap(input).setLifecycle(Lifecycle.stable()).flatMap(map -> this.decode(ops, (MapLike<T>)map)).map(r -> Pair.of((Map<K, V>)r, input));
730
		}
731
732
		public <T> DataResult<T> encode(final Map<K, V> input, final DynamicOps<T> ops, final T prefix) {
733
			return this.encode(input, ops, ops.mapBuilder()).build(prefix);
734
		}
735
736
		@Override
737
		public String toString() {
738
			return "StrictUnboundedMapCodec[" + this.keyCodec + " -> " + this.elementCodec + "]";
739
		}
740
	}
741
742
	public record TagOrElementLocation(Identifier id, boolean tag) {
743
		@Override
744
		public String toString() {
745
			return this.decoratedId();
746
		}
747
748
		private String decoratedId() {
749
			return this.tag ? "#" + this.id : this.id.toString();
750
		}
751
	}
752
}
753

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