SavedDataStorage .java

net.minecraft.world.level.storage.SavedDataStorage (class): members: pendingWriteFuture, readTagFromDisk, scheduleSave, saveAndJoin, dataFolder, cache.

net.minecraft.world.level.storageclass228 linescommon7.5 KB

Implements

API Surface (6)

<T extends SavedData> T computeIfAbsent(final SavedDataType<T> type)
<T extends SavedData> void set(final SavedDataType<T> type, final T data)
CompoundTag readTagFromDisk(final Path dataFile, final DataFixTypes type, final int newVersion)
CompletableFuture<?> scheduleSave()
void saveAndJoin()
void close()

Fields & Constants (7)

LOGGER
cache
fixerUpper
registries
dataFolder
pendingWriteFuture
closed

String literals (1)

".dat"

Full Source

SavedDataStorage.java228 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.storage;
2
3
import com.google.common.collect.Iterables;
4
import com.mojang.datafixers.DataFixer;
5
import com.mojang.logging.LogUtils;
6
import com.mojang.serialization.Codec;
7
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
8
import java.io.DataInputStream;
9
import java.io.IOException;
10
import java.io.InputStream;
11
import java.io.PushbackInputStream;
12
import java.nio.file.Files;
13
import java.nio.file.Path;
14
import java.util.ArrayList;
15
import java.util.HashMap;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Optional;
19
import java.util.Map.Entry;
20
import java.util.concurrent.CompletableFuture;
21
import net.minecraft.SharedConstants;
22
import net.minecraft.core.HolderLookup;
23
import net.minecraft.nbt.CompoundTag;
24
import net.minecraft.nbt.NbtAccounter;
25
import net.minecraft.nbt.NbtIo;
26
import net.minecraft.nbt.NbtOps;
27
import net.minecraft.nbt.NbtUtils;
28
import net.minecraft.nbt.Tag;
29
import net.minecraft.resources.Identifier;
30
import net.minecraft.resources.RegistryOps;
31
import net.minecraft.util.FastBufferedInputStream;
32
import net.minecraft.util.FileUtil;
33
import net.minecraft.util.Mth;
34
import net.minecraft.util.Util;
35
import net.minecraft.util.datafix.DataFixTypes;
36
import net.minecraft.world.level.saveddata.SavedData;
37
import net.minecraft.world.level.saveddata.SavedDataType;
38
import org.jspecify.annotations.Nullable;
39
import org.slf4j.Logger;
40
41
public class SavedDataStorage implements AutoCloseable {
42
	private static final Logger LOGGER = LogUtils.getLogger();
43
	private final Map<SavedDataType<?>, Optional<SavedData>> cache = new HashMap<>();
44
	private final DataFixer fixerUpper;
45
	private final HolderLookup.Provider registries;
46
	private final Path dataFolder;
47
	private CompletableFuture<?> pendingWriteFuture = CompletableFuture.completedFuture(null);
48
	private boolean closed;
49
50
	public SavedDataStorage(final Path dataFolder, final DataFixer fixerUpper, final HolderLookup.Provider registries) {
51
		this.fixerUpper = fixerUpper;
52
		this.dataFolder = dataFolder;
53
		this.registries = registries;
54
	}
55
56
	private Path getDataFile(final Identifier id) {
57
		Path path = id.withSuffix(".dat").resolveAgainst(this.dataFolder);
58
		if (!path.toAbsolutePath().startsWith(this.dataFolder.toAbsolutePath())) {
59
			throw new IllegalArgumentException("SavedDataStorage attempted file access outside of data directory: {}" + path);
60
		} else {
61
			return path;
62
		}
63
	}
64
65
	public <T extends SavedData> T computeIfAbsent(final SavedDataType<T> type) {
66
		T data = this.get(type);
67
		if (data != null) {
68
			return data;
69
		}
70
71
		T newData = (T)type.constructor().get();
72
		this.set(type, newData);
73
		return newData;
74
	}
75
76
	public <T extends SavedData> @Nullable T get(final SavedDataType<T> type) {
77
		Optional<SavedData> data = this.cache.get(type);
78
		if (data == null) {
79
			data = Optional.ofNullable(this.readSavedData(type));
80
			this.cache.put(type, data);
81
		}
82
83
		return (T)data.orElse(null);
84
	}
85
86
	private <T extends SavedData> @Nullable T readSavedData(final SavedDataType<T> type) {
87
		try {
88
			Path file = this.getDataFile(type.id());
89
			if (Files.exists(file)) {
90
				CompoundTag tag = this.readTagFromDisk(file, type.dataFixType(), SharedConstants.getCurrentVersion().dataVersion().version());
91
				RegistryOps<Tag> ops = this.registries.createSerializationContext(NbtOps.INSTANCE);
92
				return type.codec().parse(ops, tag.get("data")).resultOrPartial(error -> LOGGER.error("Failed to parse saved data for '{}': {}", type, error)).orElse(null);
93
			}
94
		} catch (Exception e) {
95
			LOGGER.error("Error loading saved data: {}", type, e);
96
		}
97
98
		return null;
99
	}
100
101
	public <T extends SavedData> void set(final SavedDataType<T> type, final T data) {
102
		this.cache.put(type, Optional.of(data));
103
		data.setDirty();
104
	}
105
106
	public CompoundTag readTagFromDisk(final Path dataFile, final DataFixTypes type, final int newVersion) throws IOException {
107
		try (
108
			InputStream in = Files.newInputStream(dataFile);
109
			PushbackInputStream inputStream = new PushbackInputStream(new FastBufferedInputStream(in), 2);
110
		) {
111
			CompoundTag tag;
112
			if (this.isGzip(inputStream)) {
113
				tag = NbtIo.readCompressed(inputStream, NbtAccounter.unlimitedHeap());
114
			} else {
115
				try (DataInputStream dis = new DataInputStream(inputStream)) {
116
					tag = NbtIo.read(dis);
117
				}
118
			}
119
120
			int version = NbtUtils.getDataVersion(tag, 1343);
121
			return type.update(this.fixerUpper, tag, version, newVersion);
122
		}
123
	}
124
125
	private boolean isGzip(final PushbackInputStream inputStream) throws IOException {
126
		byte[] header = new byte[2];
127
		boolean gzip = false;
128
		int read = inputStream.read(header, 0, 2);
129
		if (read == 2) {
130
			int fullHeader = (header[1] & 255) << 8 | header[0] & 255;
131
			if (fullHeader == 35615) {
132
				gzip = true;
133
			}
134
		}
135
136
		if (read != 0) {
137
			inputStream.unread(header, 0, read);
138
		}
139
140
		return gzip;
141
	}
142
143
	public CompletableFuture<?> scheduleSave() {
144
		if (this.closed) {
145
			throw new IllegalStateException("Trying to schedule save when SavedDataStorage is already closed");
146
		}
147
148
		Map<SavedDataType<?>, CompoundTag> tagsToSave = this.collectDirtyTagsToSave();
149
		if (tagsToSave.isEmpty()) {
150
			return CompletableFuture.completedFuture(null);
151
		}
152
153
		int threads = Util.maxAllowedExecutorThreads();
154
		int taskCount = tagsToSave.size();
155
		if (taskCount > threads) {
156
			this.pendingWriteFuture = this.pendingWriteFuture.thenCompose(ignored -> {
157
				List<CompletableFuture<?>> tasks = new ArrayList<>(threads);
158
				int bucketSize = Mth.positiveCeilDiv(taskCount, threads);
159
160
				for (List<Entry<SavedDataType<?>, CompoundTag>> entries : Iterables.partition(tagsToSave.entrySet(), bucketSize)) {
161
					tasks.add(CompletableFuture.runAsync(() -> {
162
						for (Entry<SavedDataType<?>, CompoundTag> entry : entries) {
163
							this.tryWrite(entry.getKey(), entry.getValue());
164
						}
165
					}, Util.ioPool()));
166
				}
167
168
				return CompletableFuture.allOf(tasks.toArray(CompletableFuture[]::new));
169
			});
170
		} else {
171
			this.pendingWriteFuture = this.pendingWriteFuture
172
				.thenCompose(
173
					ignored -> CompletableFuture.allOf(
174
						tagsToSave.entrySet()
175
							.stream()
176
							.map(entry -> CompletableFuture.runAsync(() -> this.tryWrite(entry.getKey(), entry.getValue()), Util.ioPool()))
177
							.toArray(CompletableFuture[]::new)
178
					)
179
				);
180
		}
181
182
		return this.pendingWriteFuture;
183
	}
184
185
	private Map<SavedDataType<?>, CompoundTag> collectDirtyTagsToSave() {
186
		Map<SavedDataType<?>, CompoundTag> tagsToSave = new Object2ObjectArrayMap<>();
187
		RegistryOps<Tag> ops = this.registries.createSerializationContext(NbtOps.INSTANCE);
188
		this.cache.forEach((type, optional) -> optional.filter(SavedData::isDirty).ifPresent(data -> {
189
			tagsToSave.put(type, this.encodeUnchecked(type, data, ops));
190
			data.setDirty(false);
191
		}));
192
		return tagsToSave;
193
	}
194
195
	private <T extends SavedData> CompoundTag encodeUnchecked(final SavedDataType<T> type, final SavedData data, final RegistryOps<Tag> ops) {
196
		Codec<T> codec = type.codec();
197
		CompoundTag tag = new CompoundTag();
198
		tag.put("data", codec.encodeStart(ops, (T)data).getOrThrow());
199
		NbtUtils.addCurrentDataVersion(tag);
200
		return tag;
201
	}
202
203
	private void tryWrite(final SavedDataType<?> type, final CompoundTag tag) {
204
		Path path = this.getDataFile(type.id());
205
206
		try {
207
			FileUtil.createDirectoriesSafe(path.getParent());
208
			NbtIo.writeCompressed(tag, path);
209
		} catch (IOException e) {
210
			LOGGER.error("Could not save data to {}", path.getFileName(), e);
211
		}
212
	}
213
214
	public void saveAndJoin() {
215
		this.scheduleSave().join();
216
	}
217
218
	@Override
219
	public void close() {
220
		if (this.closed) {
221
			throw new IllegalStateException("Trying to close SavedDataStorage when it is already closed");
222
		}
223
224
		this.saveAndJoin();
225
		this.closed = true;
226
	}
227
}
228

Decompiled Minecraft 26.3 source of SavedDataStorage (net/minecraft/world/level/storage/SavedDataStorage.java) with Mojang official mappings, stored verbatim on the site.