Weighted .java

net.minecraft.util.random.Weighted (record): members: value, weight, ByteBuf, streamCodec, map, LOGGER, codec. strings: "Weight should be >= 0", "weight".

net.minecraft.util.randomrecord49 linescommon1.8 KB

API Surface (4)

<E> Codec<Weighted<E>> codec(final Codec<E> elementCodec)
<E> Codec<Weighted<E>> codec(final MapCodec<E> elementCodec)
<B extends ByteBuf, T> StreamCodec<B, Weighted<T>> streamCodec(final StreamCodec<B, T> valueCodec)
<U> Weighted<U> map(final Function<T, U> function)

Fields & Constants (2)

LOGGER
ByteBuf

String literals (3)

"Weight should be >= 0"
"Found 0 weight, make sure this is intentional!"
"weight"

Code Graph: Dependencies (5)

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

Full Source

Weighted.java49 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.util.random;
2
3
import com.mojang.logging.LogUtils;
4
import com.mojang.serialization.Codec;
5
import com.mojang.serialization.MapCodec;
6
import com.mojang.serialization.codecs.RecordCodecBuilder;
7
import io.netty.buffer.ByteBuf;
8
import java.util.function.BiFunction;
9
import java.util.function.Function;
10
import net.minecraft.SharedConstants;
11
import net.minecraft.network.codec.ByteBufCodecs;
12
import net.minecraft.network.codec.StreamCodec;
13
import net.minecraft.util.ExtraCodecs;
14
import net.minecraft.util.Util;
15
import org.slf4j.Logger;
16
17
public record Weighted<T>(T value, int weight) {
18
	private static final Logger LOGGER = LogUtils.getLogger();
19
20
	public Weighted {
21
		if (weight < 0) {
22
			throw (IllegalArgumentException)Util.pauseInIde(new IllegalArgumentException("Weight should be >= 0"));
23
		}
24
25
		if (weight == 0 && SharedConstants.IS_RUNNING_IN_IDE) {
26
			LOGGER.warn("Found 0 weight, make sure this is intentional!");
27
		}
28
	}
29
30
	public static <E> Codec<Weighted<E>> codec(final Codec<E> elementCodec) {
31
		return codec(elementCodec.fieldOf("data"));
32
	}
33
34
	public static <E> Codec<Weighted<E>> codec(final MapCodec<E> elementCodec) {
35
		return RecordCodecBuilder.create(
36
			i -> i.group(elementCodec.forGetter((Function<Weighted<E>, E>)(Weighted::value)), ExtraCodecs.NON_NEGATIVE_INT.fieldOf("weight").forGetter(Weighted::weight))
37
				.apply(i, (BiFunction<E, Integer, Weighted<E>>)(Weighted::new))
38
		);
39
	}
40
41
	public static <B extends ByteBuf, T> StreamCodec<B, Weighted<T>> streamCodec(final StreamCodec<B, T> valueCodec) {
42
		return StreamCodec.composite(valueCodec, Weighted::value, ByteBufCodecs.VAR_INT, Weighted::weight, Weighted::new);
43
	}
44
45
	public <U> Weighted<U> map(final Function<T, U> function) {
46
		return new Weighted<>(function.apply(this.value()), this.weight);
47
	}
48
}
49

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