| 1 | package net.minecraft.client.multiplayer.chat;
|
| 2 |
|
| 3 | import com.mojang.serialization.Codec;
|
| 4 | import com.mojang.serialization.DataResult;
|
| 5 | import java.util.ArrayList;
|
| 6 | import java.util.List;
|
| 7 | import net.fabricmc.api.EnvType;
|
| 8 | import net.fabricmc.api.Environment;
|
| 9 | import org.jspecify.annotations.Nullable;
|
| 10 |
|
| 11 | @Environment(EnvType.CLIENT)
|
| 12 | public class ChatLog {
|
| 13 | private final LoggedChatEvent[] buffer;
|
| 14 | private int nextId;
|
| 15 |
|
| 16 | public static Codec<ChatLog> codec(final int capacity) {
|
| 17 | return Codec.list(LoggedChatEvent.CODEC)
|
| 18 | .comapFlatMap(
|
| 19 | loggedChatEvents -> {
|
| 20 | int parsedSize = loggedChatEvents.size();
|
| 21 | return parsedSize > capacity
|
| 22 | ? DataResult.error(() -> "Expected: a buffer of size less than or equal to " + capacity + " but: " + parsedSize + " is greater than " + capacity)
|
| 23 | : DataResult.success(new ChatLog(capacity, (List<LoggedChatEvent>)loggedChatEvents));
|
| 24 | },
|
| 25 | ChatLog::loggedChatEvents
|
| 26 | );
|
| 27 | }
|
| 28 |
|
| 29 | public ChatLog(final int capacity) {
|
| 30 | this.buffer = new LoggedChatEvent[capacity];
|
| 31 | }
|
| 32 |
|
| 33 | private ChatLog(final int capacity, final List<LoggedChatEvent> buffer) {
|
| 34 | this.buffer = buffer.toArray(LoggedChatEvent[]::new);
|
| 35 | this.nextId = buffer.size();
|
| 36 | }
|
| 37 |
|
| 38 | private List<LoggedChatEvent> loggedChatEvents() {
|
| 39 | List<LoggedChatEvent> loggedChatEvents = new ArrayList<>(this.size());
|
| 40 |
|
| 41 | for (int i = this.start(); i <= this.end(); i++) {
|
| 42 | loggedChatEvents.add(this.lookup(i));
|
| 43 | }
|
| 44 |
|
| 45 | return loggedChatEvents;
|
| 46 | }
|
| 47 |
|
| 48 | public void push(final LoggedChatEvent event) {
|
| 49 | this.buffer[this.index(this.nextId++)] = event;
|
| 50 | }
|
| 51 |
|
| 52 | public @Nullable LoggedChatEvent lookup(final int id) {
|
| 53 | return id >= this.start() && id <= this.end() ? this.buffer[this.index(id)] : null;
|
| 54 | }
|
| 55 |
|
| 56 | private int index(final int id) {
|
| 57 | return id % this.buffer.length;
|
| 58 | }
|
| 59 |
|
| 60 | public int start() {
|
| 61 | return Math.max(this.nextId - this.buffer.length, 0);
|
| 62 | }
|
| 63 |
|
| 64 | public int end() {
|
| 65 | return this.nextId - 1;
|
| 66 | }
|
| 67 |
|
| 68 | private int size() {
|
| 69 | return this.end() - this.start() + 1;
|
| 70 | }
|
| 71 | }
|
| 72 |
|