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
|
//! Owned, bounded source cache. No animation-global cache can outlive these bytes.
const std = @import("std");
const canim = @import("canim");
const zt = @import("ztrace");
const Sources = @This();
const File = struct { id: u64, path: []const u8, bytes: []const u8, text: ?canim.source.Text };
files: std.ArrayList(File) = .empty,
paths: ?zt.Symbols = null,
pub fn close(s: *Sources, gpa: std.mem.Allocator) void {
s.clear(gpa);
if (s.paths) |*paths| paths.deinit();
s.* = .{};
}
pub fn map(s: *Sources, gpa: std.mem.Allocator, io: std.Io, from: []const u8, to: []const u8) !void {
if (s.paths == null) s.paths = .{ .gpa = gpa, .io = io };
try s.paths.?.mapSource(from, to);
s.clear(gpa);
}
fn clear(s: *Sources, gpa: std.mem.Allocator) void {
for (s.files.items) |file| {
if (file.text) |t| t.deinit();
gpa.free(file.path);
gpa.free(file.bytes);
}
s.files.deinit(gpa);
s.files = .empty;
}
pub fn get(s: *Sources, gpa: std.mem.Allocator, io: std.Io, m: zt.store.Moment, id: u64) ?*const File {
for (s.files.items) |*file| if (file.id == id) return file;
if (s.files.items.len == 32) return null;
var buffer: [4096]u8 = undefined;
const name = (m.string(id, &buffer) catch null) orelse return null;
const path = (if (s.paths) |*paths| paths.sourcePath(.{ .key = 0, .dir = "", .name = name, .line = 0, .column = 0 }) else gpa.dupe(u8, name)) catch return null;
const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(8 * 1024 * 1024)) catch &.{};
const text = if (bytes.len > 0) canim.source.prepare(bytes, path) catch null else null;
s.files.append(gpa, .{ .id = id, .path = path, .bytes = bytes, .text = text }) catch {
if (text) |t| t.deinit();
gpa.free(path);
gpa.free(bytes);
return null;
};
return &s.files.items[s.files.items.len - 1];
}
|