Repository navigation
Expand file tree
/
Copy pathstorage.zig
More file actions
640 lines (580 loc) · 28.9 KB
/
Copy pathstorage.zig
File metadata and controls
640 lines (580 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Mods' storage ([#498](https://github.com/OpenReliant/openreliant/issues/498)): named sections
//! of plain data, kept for each mod outside Luau, so that the game's scripts and the player's see
//! the same (`Storage`), and scripts reach them through `openreliant.storage` (`package`).
//!
//! - A game section (`storage.game_section`) is kept with the saved game, and starts empty with
//! each new game. Global and object scripts change it, since it's part of what happens; other
//! scripts read it.
//! - A global section (`storage.global_section`) is kept across every game, in the game folder's
//! `storage` folder, a file for each mod (`file_extension`). Any script changes it: it suits
//! settings, and what a mod keeps from game to game.
//!
//! A section is a table of fields, each named by a string and holding plain data. Reading a field
//! gives a copy, so changing a table read from a section changes nothing until it's stored again.
//!
//! A mod's scripts may keep up to `max_storage` in each place, counted as the memory the sections
//! take (`stored.Value.footprint`), so that they keep to a limit as the scripts' own memory does,
//! and so that a file of global sections always reads back.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const log = std.log.scoped(.scripts);
const openreliant = @import("openreliant");
const Mod = openreliant.engine.game.bigfile.mods.Mod;
const luau = @import("luau.zig");
const State = luau.State;
const stored = @import("stored.zig");
const Value = stored.Value;
const runtime_module = @import("runtime.zig");
const api = @import("api.zig");
const Call = api.Call;
const options = @import("options.zig");
/// Where a section is kept.
pub const Scope = enum {
/// With the saved game.
game,
/// In the game folder, across every game.
global,
};
/// The folder in the game folder that keeps the global sections, and its files' extension.
pub const folder_name = "storage";
pub const file_extension = ".data";
/// What a global sections' file starts with, and the version of its form.
const magic = "ORST";
const version: u16 = 1;
/// The longest file a mod's global sections may take.
const max_file = std.fmt.parseIntSizeSuffix("16MiB", 10) catch unreachable;
/// What a global sections' file holds before its sections: its magic, its version and its count of
/// sections.
const file_header = magic.len + @sizeOf(u16) + @sizeOf(u32);
/// Room the engine keeps in each mod's file for what it stores for the mod itself, such as its
/// options (`options.zig`) and its game modes' progress, past what the mod's scripts may store.
const engine_room = std.fmt.parseIntSizeSuffix("1MiB", 10) catch unreachable;
/// The most a mod's scripts may keep in each place, in sections and their fields, as the memory
/// they take. A section's binary form takes no more than its memory, so a file of global sections
/// always fits in `max_file`.
pub const max_storage: usize = max_file - file_header - engine_room;
/// Why a section can't be changed or made: memory runs out, or the mod's scripts would keep more than
/// `max_storage` in its place.
pub const Error = Allocator.Error || error{StorageFull};
/// Whether a change counts against the mod's `max_storage`: a script's does, while what the
/// engine keeps for the mod, and what a file holds as it's read back, don't.
const Limit = enum {
quota,
none,
/// What a change within `limit` can fail with: only a change that counts against the quota
/// can find the storage full.
fn Failure(comptime limit: Limit) type {
return switch (limit) {
.quota => Error,
.none => Allocator.Error,
};
}
};
/// A section: its mod, its name and where it's kept, and its fields.
const Section = struct {
mod: []const u8,
name: []const u8,
scope: Scope,
fields: std.ArrayList(Field) = .empty,
/// The memory it takes, with its fields (`footprint`, `Field.footprint`).
used: usize,
const Field = struct {
key: []const u8,
value: Value,
/// The memory a field of `key` holding `value` takes: the field, its key's bytes, and what
/// the value holds. Its binary form takes no more.
fn footprint(key: []const u8, value: Value) usize {
return @sizeOf(Field) - @sizeOf(Value) + key.len + value.footprint();
}
};
/// The memory a section of `mod` named `name` takes without its fields. Its binary form
/// (`encodeSection`) takes no more.
fn footprint(mod: []const u8, name: []const u8) usize {
return @sizeOf(Section) + mod.len + name.len;
}
/// Whether it's kept with the saved game: a game section that holds fields.
fn keptWithGame(section: *const Section) bool {
return section.scope == .game and section.fields.items.len > 0;
}
fn deinit(section: *Section, gpa: Allocator) void {
for (section.fields.items) |field| {
gpa.free(field.key);
field.value.deinit(gpa);
}
section.fields.deinit(gpa);
gpa.free(section.mod);
gpa.free(section.name);
}
fn find(section: *const Section, key: []const u8) ?usize {
for (section.fields.items, 0..) |field, at| {
if (std.mem.eql(u8, field.key, key)) return at;
}
return null;
}
};
/// Every mod's sections.
pub const Storage = struct {
gpa: Allocator,
/// The game folder, where the global sections are kept; null where they're kept nowhere, as in
/// a test.
folder: ?Folder = null,
sections: std.ArrayList(*Section) = .empty,
/// The mods whose global sections changed since they were written.
changed: std.array_hash_map.String(void) = .empty,
pub const Folder = struct { io: Io, dir: Io.Dir };
pub fn deinit(storage: *Storage) void {
for (storage.sections.items) |section| {
section.deinit(storage.gpa);
storage.gpa.destroy(section);
}
storage.sections.deinit(storage.gpa);
for (storage.changed.keys()) |mod| storage.gpa.free(mod);
storage.changed.deinit(storage.gpa);
}
fn find(storage: *const Storage, mod: []const u8, name: []const u8, scope: Scope) ?*Section {
for (storage.sections.items) |section| {
if (section.scope == scope and std.mem.eql(u8, section.mod, mod) and std.mem.eql(u8, section.name, name)) return section;
}
return null;
}
/// The section `name` of `mod` kept in `scope`, made empty if there's none yet, within the
/// mod's `max_storage` where `limit` says.
fn obtain(storage: *Storage, mod: []const u8, name: []const u8, scope: Scope, comptime limit: Limit) limit.Failure()!*Section {
if (storage.find(mod, name, scope)) |section| return section;
const used = Section.footprint(mod, name);
if (limit == .quota) {
if (storage.usage(mod, scope) + used > max_storage) return error.StorageFull;
}
try storage.sections.ensureUnusedCapacity(storage.gpa, 1);
const section = try storage.gpa.create(Section);
errdefer storage.gpa.destroy(section);
const mod_copy = try storage.gpa.dupe(u8, mod);
errdefer storage.gpa.free(mod_copy);
section.* = .{ .mod = mod_copy, .name = try storage.gpa.dupe(u8, name), .scope = scope, .used = used };
storage.sections.appendAssumeCapacity(section);
return section;
}
/// The memory the sections of `mod` kept in `scope` take, with their fields.
fn usage(storage: *const Storage, mod: []const u8, scope: Scope) usize {
var total: usize = 0;
for (storage.sections.items) |section| {
if (section.scope == scope and std.mem.eql(u8, section.mod, mod)) total += section.used;
}
return total;
}
/// Sets the field `key` of `section` to `value`, which it takes over unless it fails; nil takes
/// the field out. Where `limit` says, a change that would take the mod's sections in their place
/// past `max_storage` is refused, unless it makes them smaller.
fn set(storage: *Storage, section: *Section, key: []const u8, value: Value, comptime limit: Limit) limit.Failure()!void {
const at = section.find(key);
const old = if (at) |found| Section.Field.footprint(key, section.fields.items[found].value) else 0;
const new = if (value == .nil) 0 else Section.Field.footprint(key, value);
if (limit == .quota) {
if (new > old and storage.usage(section.mod, section.scope) - old + new > max_storage) return error.StorageFull;
}
if (section.scope == .global) try storage.markChanged(section.mod);
if (at) |found| {
const field = §ion.fields.items[found];
field.value.deinit(storage.gpa);
if (value == .nil) {
storage.gpa.free(field.key);
_ = section.fields.orderedRemove(found);
} else field.value = value;
} else if (value != .nil) {
try section.fields.ensureUnusedCapacity(storage.gpa, 1);
section.fields.appendAssumeCapacity(.{ .key = try storage.gpa.dupe(u8, key), .value = value });
}
section.used = section.used - old + new;
}
/// Sets the field `key` of the section `name` of `mod` kept in `scope` to `value`, which it takes
/// over unless it fails; nil takes the field out. What the engine keeps for a mod, such as its
/// options, doesn't count against the mod's `max_storage`.
pub fn put(storage: *Storage, mod: []const u8, name: []const u8, scope: Scope, key: []const u8, value: Value) Allocator.Error!void {
try storage.set(try storage.obtain(mod, name, scope, .none), key, value, .none);
}
fn markChanged(storage: *Storage, mod: []const u8) Allocator.Error!void {
if (storage.changed.contains(mod)) return;
const copy = try storage.gpa.dupe(u8, mod);
errdefer storage.gpa.free(copy);
try storage.changed.put(storage.gpa, copy, {});
}
/// The field `key` of the section `name` of `mod` kept in `scope`; null for none.
pub fn read(storage: *const Storage, mod: []const u8, name: []const u8, scope: Scope, key: []const u8) ?Value {
const held = storage.find(mod, name, scope) orelse return null;
const at = held.find(key) orelse return null;
return held.fields.items[at].value;
}
/// Empties every game section, as a new game starts. The sections themselves stay, since
/// scripts hold them.
pub fn clearGame(storage: *Storage) void {
for (storage.sections.items) |section| {
if (section.scope != .game) continue;
for (section.fields.items) |held| {
storage.gpa.free(held.key);
held.value.deinit(storage.gpa);
}
section.fields.clearRetainingCapacity();
section.used = Section.footprint(section.mod, section.name);
}
}
/// Writes the game sections in the binary form (`stored.encode`), but those of the mods in
/// `left_out`.
pub fn encodeGame(storage: *const Storage, w: *Io.Writer, left_out: *const std.array_hash_map.String(void)) Io.Writer.Error!void {
var count: u32 = 0;
for (storage.sections.items) |section| count += @intFromBool(section.keptWithGame() and !left_out.contains(section.mod));
try w.writeInt(u32, count, .little);
for (storage.sections.items) |section| {
if (section.keptWithGame() and !left_out.contains(section.mod)) try encodeGameSection(w, section);
}
}
/// Adds to each mod's share in `shares` the bytes its game sections take in `encodeGame`.
pub fn measureGame(storage: *const Storage, gpa: Allocator, shares: *std.array_hash_map.String(usize)) Allocator.Error!void {
for (storage.sections.items) |section| {
if (!section.keptWithGame()) continue;
const share = try shares.getOrPutValue(gpa, section.mod, 0);
share.value_ptr.* += stored.encodedSize(encodeGameSection, .{section});
}
}
/// Writes a game section as `encodeGame` does: its mod's name, then the section.
fn encodeGameSection(w: *Io.Writer, section: *const Section) Io.Writer.Error!void {
try stored.encode(w, .{ .string = section.mod });
try encodeSection(w, section);
}
/// Reads game sections written by `encodeGame`, in place of the game sections there are.
pub fn decodeGame(storage: *Storage, r: *Io.Reader) stored.DecodeError!void {
storage.clearGame();
const count = r.takeInt(u32, .little) catch return error.Damaged;
for (0..count) |_| {
const mod = try stored.decode(r, storage.gpa);
defer mod.deinit(storage.gpa);
const mod_name = switch (mod) {
.string => |bytes| bytes,
else => return error.Damaged,
};
try storage.decodeSection(r, mod_name, .game);
}
}
fn encodeSection(w: *Io.Writer, section: *const Section) Io.Writer.Error!void {
try stored.encode(w, .{ .string = section.name });
try w.writeInt(u32, @intCast(section.fields.items.len), .little);
for (section.fields.items) |field| {
try stored.encode(w, .{ .string = field.key });
try stored.encode(w, field.value);
}
}
fn decodeSection(storage: *Storage, r: *Io.Reader, mod: []const u8, scope: Scope) stored.DecodeError!void {
const name = try stored.decode(r, storage.gpa);
defer name.deinit(storage.gpa);
const section_name = switch (name) {
.string => |bytes| bytes,
else => return error.Damaged,
};
const section = try storage.obtain(mod, section_name, scope, .none);
const count = r.takeInt(u32, .little) catch return error.Damaged;
for (0..count) |_| {
const key = try stored.decode(r, storage.gpa);
defer key.deinit(storage.gpa);
const field_key = switch (key) {
.string => |bytes| bytes,
else => return error.Damaged,
};
const value = try stored.decode(r, storage.gpa);
storage.set(section, field_key, value, .none) catch |err| {
value.deinit(storage.gpa);
return err;
};
}
}
/// Reads the global sections of the mods `opened` from the game folder, as OpenReliant starts.
/// A file that can't be read is logged and left out.
pub fn readGlobal(storage: *Storage, opened: []const Mod) Allocator.Error!void {
const folder = storage.folder orelse return;
for (opened) |*each| {
const mod = each.name;
var name_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path = std.mem.print(&name_buffer, folder_name ++ "/{s}" ++ file_extension, .{mod}) catch continue;
const bytes = folder.dir.readFileAlloc(folder.io, path, storage.gpa, .limited(max_file)) catch |err| switch (err) {
error.FileNotFound => continue,
error.OutOfMemory => |e| return e,
else => {
log.warn("{s}: its storage can't be read: {s}", .{ mod, @errorName(err) });
continue;
},
};
defer storage.gpa.free(bytes);
var r: Io.Reader = .fixed(bytes);
storage.decodeGlobal(&r, mod) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.Damaged => log.warn("{s}: its storage is damaged, and left out", .{mod}),
};
}
for (storage.changed.keys()) |mod| storage.gpa.free(mod);
storage.changed.clearRetainingCapacity();
}
fn decodeGlobal(storage: *Storage, r: *Io.Reader, mod: []const u8) stored.DecodeError!void {
const start = r.take(magic.len) catch return error.Damaged;
if (!std.mem.eql(u8, start, magic)) return error.Damaged;
if ((r.takeInt(u16, .little) catch return error.Damaged) != version) return error.Damaged;
const count = r.takeInt(u32, .little) catch return error.Damaged;
for (0..count) |_| try storage.decodeSection(r, mod, .global);
}
/// Writes the global sections of each mod whose sections changed to the game folder, each file
/// safely (`files.writeAtomic`). The main loop calls it every two seconds, and once more as
/// OpenReliant quits. A file that can't be written is logged.
pub fn flush(storage: *Storage) void {
const folder = storage.folder orelse return;
if (storage.changed.count() == 0) return;
folder.dir.createDirPath(folder.io, folder_name) catch |err| {
log.warn("the mods' storage can't be kept: {s}", .{@errorName(err)});
return;
};
for (storage.changed.keys()) |mod| {
storage.writeGlobal(folder, mod) catch |err| log.warn("{s}: its storage can't be kept: {s}", .{ mod, @errorName(err) });
storage.gpa.free(mod);
}
storage.changed.clearRetainingCapacity();
}
fn writeGlobal(storage: *Storage, folder: Folder, mod: []const u8) !void {
var bytes: Io.Writer.Allocating = .init(storage.gpa);
defer bytes.deinit();
const w = &bytes.writer;
try w.writeAll(magic);
try w.writeInt(u16, version, .little);
var count: u32 = 0;
for (storage.sections.items) |section| count += @intFromBool(section.scope == .global and std.mem.eql(u8, section.mod, mod));
try w.writeInt(u32, count, .little);
for (storage.sections.items) |section| {
if (section.scope == .global and std.mem.eql(u8, section.mod, mod)) try encodeSection(w, section);
}
// A file that reading would refuse is left unwritten, which keeps the file there was.
if (bytes.written().len > max_file) return error.FileTooBig;
var name_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path = try std.mem.print(&name_buffer, folder_name ++ "/{s}" ++ file_extension, .{mod});
try openreliant.engine.files.writeAtomic(folder.io, folder.dir, path, bytes.written());
}
/// Registers the metatable of a section's handle.
pub fn register(state: *State) void {
state.registerUserdata(Handle.tag, "section", &.{
.{ "__index", luau.wrap(get) },
.{ "__newindex", luau.wrap(setField) },
.{ "__iter", luau.wrap(iterate) },
});
}
};
/// A section as scripts hold it.
const Handle = struct {
section: *Section,
const tag = @backingInt(runtime_module.Tag.section);
fn of(state: *State, at: i32) *Section {
return (state.toUserdata(Handle, at, tag) orelse state.raise("expected a storage section, got {s}", .{state.typeName(at)})).section;
}
};
/// `section[key]`: a copy of the field `key`, or nil.
fn get(state: *State) i32 {
const section = Handle.of(state, 1);
const key = state.toString(2) orelse state.raise("a storage section's fields are named by strings, not {s}", .{state.typeName(2)});
const at = section.find(key) orelse {
state.pushNil();
return 1;
};
stored.push(state, section.fields.items[at].value);
return 1;
}
/// `section[key] = value`: keeps a copy of `value`, which must be plain data; nil takes the field
/// out. A game section can only be changed by global and object scripts.
fn setField(state: *State) i32 {
const section = Handle.of(state, 1);
const key = state.toString(2) orelse state.raise("a storage section's fields are named by strings, not {s}", .{state.typeName(2)});
const call: Call = .of(state, "storage");
if (section.scope == .game) switch (call.context.family) {
.global, .object => {},
.load, .player, .menu => state.raise("{t} scripts can only read a game section", .{call.context.family}),
};
const storage = storageOf(call);
const gpa = storage.gpa;
const value = stored.capture(state, gpa, 3, "storage");
storage.set(section, key, value, .quota) catch |err| {
value.deinit(gpa);
raiseError(call, err, section.scope);
};
return 0;
}
/// Raises `err`, which a change of one of the calling mod's sections kept in `scope` ran into.
fn raiseError(call: Call, err: Error, scope: Scope) noreturn {
switch (err) {
error.OutOfMemory => call.raise("out of memory", .{}),
error.StorageFull => call.raise("storage: the mod's {t} sections would take more than {d} bytes", .{ scope, max_storage }),
}
}
/// `__iter`: each field's name and a copy of its value, from a copy of the section made as the
/// loop starts, so that the loop can change the section, such as to empty it.
fn iterate(state: *State) i32 {
const section = Handle.of(state, 1);
if (!state.checkStack(4)) state.raise("storage: out of memory", .{});
_ = state.getGlobal("next");
state.newTable(0, @intCast(@min(section.fields.items.len, std.math.maxInt(u16))));
const copy = state.top();
for (section.fields.items) |field| {
state.pushString(field.key);
stored.push(state, field.value);
state.rawSet(copy);
}
state.pushNil();
return 3;
}
fn storageOf(call: Call) *Storage {
return call.runtime().options.shared.storage orelse call.raise("storage isn't kept here", .{});
}
/// The handle of the calling mod's section `name` in `scope`.
fn sectionOf(call: Call, name: []const u8, scope: Scope) Handle {
const storage = storageOf(call);
return .{ .section = storage.obtain(call.context.modOf().name, name, scope, .quota) catch |err| raiseError(call, err, scope) };
}
/// What `openreliant.storage` holds.
pub const package = struct {
pub const game_section = api.Native("The section `name` of the calling mod's storage that's kept with the saved game, and starts empty with each new game. Global and object scripts change it; other scripts read it.", "name: string", "Section", gameSection);
pub const global_section = api.Native("The section `name` of the calling mod's storage that's kept in the game folder, across every game. Any script changes it.", "name: string", "Section", globalSection);
};
fn gameSection(call: Call) i32 {
return pushSection(call, .game);
}
fn globalSection(call: Call) i32 {
const reserved = call.state.toString(1) orelse "";
if (std.mem.eql(u8, reserved, options.section_name)) call.raise("the section '{s}' keeps the mod's options; read them with openreliant.options", .{reserved});
return pushSection(call, .global);
}
fn pushSection(call: Call, scope: Scope) i32 {
const state = call.state;
const name = state.toString(1) orelse call.raise("expected a section's name, got {s}", .{state.typeName(1)});
const handle = sectionOf(call, name, scope);
state.newUserdata(Handle, Handle.tag).* = handle;
return 1;
}
test "scripts read, change and go through sections" {
const gpa = std.testing.allocator;
const io = std.testing.io;
const load = @import("load.zig");
const mods = openreliant.engine.game.bigfile.mods;
var tmp = std.testing.tmpDir(.{ .iterate = true });
defer tmp.cleanup();
try load.testing.makeMods(io, tmp.dir, &.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nLoad=best.luau\n" },
.{
"best.luau",
\\local storage = require("openreliant.storage")
\\local best = storage.global_section("best")
\\best.a = 1
\\best.b = { 2, 3 }
\\best.c = "x"
\\local list = best.b
\\list[1] = 5
\\assert(best.b[1] == 2)
\\local count = 0
\\for name, value in best do
\\ count += 1
\\ best[name] = nil
\\end
\\assert(count == 3 and best.a == nil and best.b == nil and best.c == nil)
\\assert(not pcall(function() storage.game_section("tally").x = 1 end))
\\assert(not pcall(function() best.f = print end))
\\best.done = vector.create(1, 2, 3)
},
},
}});
var opened: mods.Mods = try .open(gpa, io, tmp.dir, null);
defer opened.close(gpa);
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
var held = try load.testing.records3(arena.allocator());
var storage: Storage = .{ .gpa = gpa };
defer storage.deinit();
try load.run(gpa, io, opened.list, &held, "0.7.0", .{ .storage = &storage });
try std.testing.expectEqual(@Vector(3, f32){ 1, 2, 3 }, storage.read("a", "best", .global, "done").?.vector);
try std.testing.expectEqual(1, storage.find("a", "best", .global).?.fields.items.len);
}
test "sections keep their fields, and go to a file and back" {
const gpa = std.testing.allocator;
var storage: Storage = .{ .gpa = gpa };
defer storage.deinit();
const game = try storage.obtain("a", "tally", .game, .quota);
try storage.set(game, "kills", .{ .number = 3 }, .quota);
try storage.set(game, "best", .{ .number = 5 }, .quota);
try storage.set(game, "best", .nil, .quota);
const global = try storage.obtain("a", "settings", .global, .quota);
try storage.set(global, "reach", .{ .number = 50000 }, .quota);
try std.testing.expect(storage.changed.contains("a"));
var bytes: Io.Writer.Allocating = .init(gpa);
defer bytes.deinit();
try storage.encodeGame(&bytes.writer, &.empty);
storage.clearGame();
try std.testing.expectEqual(null, storage.read("a", "tally", .game, "kills"));
var r: Io.Reader = .fixed(bytes.written());
try storage.decodeGame(&r);
const back = storage.find("a", "tally", .game).?;
try std.testing.expectEqual(1, back.fields.items.len);
try std.testing.expectEqual(3, back.fields.items[0].value.number);
// The global section stays as it was.
try std.testing.expectEqual(50000, storage.find("a", "settings", .global).?.fields.items[0].value.number);
}
test "the game sections of mods left out aren't written, and each mod's share is what's written" {
const gpa = std.testing.allocator;
var storage: Storage = .{ .gpa = gpa };
defer storage.deinit();
for ([_][]const u8{ "a", "b" }) |mod| {
const section = try storage.obtain(mod, "tally", .game, .quota);
try storage.set(section, "kills", .{ .number = 3 }, .quota);
}
// An empty section isn't written, so its mod has no share.
_ = try storage.obtain("c", "empty", .game, .quota);
var shares: std.array_hash_map.String(usize) = .empty;
defer shares.deinit(gpa);
try storage.measureGame(gpa, &shares);
try std.testing.expectEqual(2, shares.count());
var left_out: std.array_hash_map.String(void) = .empty;
defer left_out.deinit(gpa);
try left_out.put(gpa, "a", {});
var bytes: Io.Writer.Allocating = .init(gpa);
defer bytes.deinit();
try storage.encodeGame(&bytes.writer, &left_out);
// The count of sections, then b's alone.
try std.testing.expectEqual(@sizeOf(u32) + shares.get("b").?, bytes.written().len);
storage.clearGame();
var r: Io.Reader = .fixed(bytes.written());
try storage.decodeGame(&r);
try std.testing.expectEqual(null, storage.read("a", "tally", .game, "kills"));
try std.testing.expectEqual(3, storage.read("b", "tally", .game, "kills").?.number);
}
test "a mod's scripts keep to their storage, and a file that wouldn't read back isn't written" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
var storage: Storage = .{ .gpa = gpa, .folder = .{ .io = io, .dir = tmp.dir } };
defer storage.deinit();
const section = try storage.obtain("a", "big", .global, .quota);
// A field up to what's left fits, and a field past it doesn't.
const room = max_storage - storage.usage("a", .global) - Section.Field.footprint("x", .{ .string = "" });
try storage.set(section, "x", .{ .string = try gpa.alloc(u8, room) }, .quota);
try std.testing.expectEqual(max_storage, storage.usage("a", .global));
const more = try gpa.alloc(u8, 1);
defer gpa.free(more);
try std.testing.expectError(error.StorageFull, storage.set(section, "y", .{ .string = more }, .quota));
try std.testing.expectError(error.StorageFull, storage.obtain("a", "another", .global, .quota));
// Another mod, and the mod's game sections, have their own room.
_ = try storage.obtain("b", "big", .global, .quota);
_ = try storage.obtain("a", "tally", .game, .quota);
// A smaller value goes in all the same, and so does what the engine keeps for the mod.
try storage.set(section, "x", .{ .number = 1 }, .quota);
try storage.put("a", "options", .global, "flee", .{ .number = 0.9 });
try std.testing.expect(storage.usage("a", .global) < max_storage);
storage.flush();
try std.testing.expect(storage.read("a", "big", .global, "x") != null);
// A file past what reading takes is left as it was.
try storage.put("a", "options", .global, "huge", .{ .string = try gpa.alloc(u8, max_file) });
storage.flush();
const length = (try tmp.dir.statFile(io, folder_name ++ "/a" ++ file_extension, .{})).size;
try std.testing.expect(length < max_file);
}