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
|
//! Reading and writing state by field path, from the reflected layout alone.
//! Shared by the console, the memory overlay, scripts and the probe.
const std = @import("std");
const abi = @import("abi");
const Layout = @import("memory.zig").Layout;
const Leaf = Layout.Leaf;
/// Writes what `path` names: one value for a number, bool or enum leaf,
/// or every leaf under it for an array, a vector or a struct, in memory
/// order (for a Zig struct not always the declared one): `{ 250, 3 }`
/// when they are its elements, otherwise `{ .count = 12, .hz = 60 }` or
/// `{ [0].x = 1, [1].x = 2 }`.
/// Shows the first `max_values`, then how many more there are.
pub fn formatPath(layout: Layout, memory: []const u8, path: []const u8, w: *std.Io.Writer) (std.Io.Writer.Error || error{UnknownField})!void {
if (layout.find(path)) |leaf| if (!leaf.whole()) return format(leaf, memory, w);
// Names under `path`, found leaf by leaf; sorted by offset afterwards.
const Found = struct { offset: usize, leaf: Leaf };
var found: [max_values]Found = undefined;
var count: usize = 0;
var total: usize = 0;
var plain = true;
var name_buf: [256]u8 = undefined;
for (layout.fields) |leaf| {
if (leaf.whole()) continue;
var it = leaf.elements();
while (it.next()) |offset| {
var nw: std.Io.Writer = .fixed(&name_buf);
leaf.name(offset, &nw) catch continue;
const name = nw.buffered();
if (!under(name, path)) continue;
total += 1;
if (!isIndex(name[path.len..])) plain = false;
if (count < max_values) {
found[count] = .{ .offset = offset, .leaf = leaf };
count += 1;
} else {
// Keep the lowest offsets.
var highest: usize = 0;
for (found[1..], 1..) |f, i| if (f.offset > found[highest].offset) {
highest = i;
};
if (offset < found[highest].offset) found[highest] = .{ .offset = offset, .leaf = leaf };
}
}
}
if (total == 0) return error.UnknownField;
std.mem.sortUnstable(Found, found[0..count], {}, struct {
fn less(_: void, a: Found, b: Found) bool {
return a.offset < b.offset;
}
}.less);
try w.writeAll("{ ");
for (found[0..count], 0..) |f, i| {
if (i > 0) try w.writeAll(", ");
if (!plain) {
var nw: std.Io.Writer = .fixed(&name_buf);
f.leaf.name(f.offset, &nw) catch {};
try w.print("{s} = ", .{nw.buffered()[path.len..]});
}
try format(f.leaf.at(f.offset), memory, w);
}
if (total > count) try w.print(", ... {d} more", .{total - count});
try w.writeAll(" }");
}
pub const max_values = 64;
/// `name` is `path` itself or a field or element inside it.
fn under(name: []const u8, path: []const u8) bool {
if (!std.mem.startsWith(u8, name, path)) return false;
if (name.len == path.len) return true;
return name[path.len] == '.' or name[path.len] == '[';
}
/// `[3]`: one index and nothing more.
fn isIndex(suffix: []const u8) bool {
if (suffix.len < 3 or suffix[0] != '[' or suffix[suffix.len - 1] != ']') return false;
for (suffix[1 .. suffix.len - 1]) |ch| if (!std.ascii.isDigit(ch)) return false;
return true;
}
pub fn format(leaf: Leaf, memory: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void {
const bytes = leaf.bytes(memory);
switch (leaf.kind) {
.int => try w.print("{d}", .{readInt(i64, bytes)}),
.uint => try w.print("{d}", .{readInt(u64, bytes)}),
.bool => try w.writeAll(if (bytes[0] != 0) "true" else "false"),
.float => switch (leaf.size) {
4 => try w.print("{d}", .{@as(f32, @bitCast(bytes[0..4].*))}),
8 => try w.print("{d}", .{@as(f64, @bitCast(bytes[0..8].*))}),
else => try w.writeAll("?"),
},
.@"enum" => {
const value = readInt(i64, bytes);
if (tagName(leaf.tags, value)) |name| try w.print(".{s}", .{name}) else try w.print("{d}", .{value});
},
else => try w.print("<{d} bytes>", .{leaf.size}),
}
}
/// Parses `text` as the field's kind (enums by name or number) and stores it.
pub fn set(leaf: Leaf, memory: []u8, text: []const u8) !void {
const bytes = memory[leaf.offset..][0..leaf.size];
switch (leaf.kind) {
.int, .uint, .@"enum" => {
const name = std.mem.trimStart(u8, text, ".");
const value: i64 = if (leaf.kind == .@"enum" and tagValue(leaf.tags, name) != null)
tagValue(leaf.tags, name).?
else
std.fmt.parseInt(i64, text, 0) catch return error.InvalidValue;
writeInt(bytes, value);
},
.bool => bytes[0] = if (std.mem.eql(u8, text, "true") or std.mem.eql(u8, text, "1")) 1 else if (std.mem.eql(u8, text, "false") or std.mem.eql(u8, text, "0")) 0 else return error.InvalidValue,
.float => {
const value = std.fmt.parseFloat(f64, text) catch return error.InvalidValue;
switch (leaf.size) {
4 => bytes[0..4].* = @bitCast(@as(f32, @floatCast(value))),
8 => bytes[0..8].* = @bitCast(value),
else => return error.UnsupportedField,
}
},
else => return error.UnsupportedField,
}
}
/// True when the field's formatted value equals `text` (enum names compare
/// with or without the leading dot).
pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool {
var buf: [128]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
format(leaf, memory, &w) catch return false;
const shown = w.buffered();
if (std.mem.eql(u8, shown, text)) return true;
if (leaf.kind == .@"enum") {
if (std.mem.eql(u8, std.mem.trimStart(u8, shown, "."), std.mem.trimStart(u8, text, "."))) return true;
const value = std.fmt.parseInt(i64, text, 0) catch return false;
return value == readInt(i64, leaf.bytes(memory));
}
return false;
}
/// A number, bool or enum leaf's value as a float; null for other kinds.
pub fn number(leaf: Leaf, memory: []const u8) ?f64 {
const bytes = leaf.bytes(memory);
return switch (leaf.kind) {
.int, .@"enum" => @floatFromInt(readInt(i64, bytes)),
.uint => @floatFromInt(readInt(u64, bytes)),
.bool => if (bytes[0] != 0) 1 else 0,
.float => switch (leaf.size) {
4 => @as(f32, @bitCast(bytes[0..4].*)),
8 => @as(f64, @bitCast(bytes[0..8].*)),
else => null,
},
else => null,
};
}
pub fn readInt(comptime T: type, bytes: []const u8) T {
const n: usize = @min(bytes.len, 8);
const value = std.mem.readVarInt(u64, bytes[0..n], .little);
if (T == u64) return value;
// Sign-extend from the field's own width.
const shift: u6 = @intCast(64 - n * 8);
return @as(i64, @bitCast(value << shift)) >> shift;
}
pub fn writeInt(bytes: []u8, value: i64) void {
const raw: u64 = @bitCast(value);
for (bytes, 0..) |*b, i| b.* = if (i < 8) @truncate(raw >> @intCast(i * 8)) else 0;
}
pub fn tagName(tags: []const u8, value: i64) ?[]const u8 {
var it = std.mem.tokenizeScalar(u8, tags, ',');
while (it.next()) |pair| {
const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
if ((std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch continue) == value) return pair[0..eq];
}
return null;
}
pub fn tagValue(tags: []const u8, name: []const u8) ?i64 {
var it = std.mem.tokenizeScalar(u8, tags, ',');
while (it.next()) |pair| {
const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
if (std.mem.eql(u8, pair[0..eq], name)) return std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch null;
}
return null;
}
test "fields format, parse and compare by kind" {
const S = extern struct { mood: enum(u32) { calm, angry = 5 } = .calm, x: i16 = -3, speed: f32 = 1.5, on: bool = false };
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .state));
var s: S = .{};
const bytes = std.mem.asBytes(&s);
try std.testing.expect(matches(layout.find("x").?, bytes, "-3"));
try set(layout.find("mood").?, bytes, "angry");
try std.testing.expectEqual(.angry, s.mood);
try std.testing.expect(matches(layout.find("mood").?, bytes, ".angry"));
try std.testing.expect(matches(layout.find("mood").?, bytes, "5"));
try set(layout.find("speed").?, bytes, "0.25");
try std.testing.expectEqual(@as(f32, 0.25), s.speed);
try set(layout.find("on").?, bytes, "true");
try std.testing.expect(s.on);
try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana"));
}
test "indexed paths reach array elements and vector lanes" {
const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, boids: struct { buffer: [4]struct { pos: [2]f32 = .{ 0, 0 }, mood: enum(u8) { calm = 1, wild = 2 } = .calm } = @splat(.{}), len: u32 = 0 } = .{} };
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .state));
var s: S = .{};
const bytes = std.mem.asBytes(&s);
try std.testing.expect(matches(layout.find("pos[0]").?, bytes, "250"));
try std.testing.expectEqual(@as(?f64, 3), number(layout.find("pos[1]").?, bytes));
try set(layout.find("boids.buffer[3].pos[1]").?, bytes, "20.5");
try std.testing.expectEqual(@as(f32, 20.5), s.boids.buffer[3].pos[1]);
try set(layout.find("boids.buffer[2].mood").?, bytes, "wild");
try std.testing.expectEqual(.wild, s.boids.buffer[2].mood);
try std.testing.expect(layout.find("boids.buffer[4].mood") == null);
try std.testing.expect(layout.find("pos[2]") == null);
}
test "paths to vectors, arrays and structs print every value under them" {
const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, clock: struct { hz: f32 = 60, count: u64 = 12 } = .{}, list: struct { buffer: [3]struct { x: i32 = 1, on: bool = true } = @splat(.{}), len: u32 = 2 } = .{}, big: [100]u8 = @splat(7) };
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state));
var s: S = .{};
s.list.buffer[1].x = -4;
const bytes = std.mem.asBytes(&s);
var buf: [1024]u8 = undefined;
const cases = [_][2][]const u8{
.{ "pos", "{ 250, 3 }" },
.{ "pos[1]", "3" },
.{ "clock", "{ .count = 12, .hz = 60 }" }, // memory order
.{ "list.buffer[1]", "{ .x = -4, .on = true }" },
.{ "list.buffer", "{ [0].x = 1, [0].on = true, [1].x = -4, [1].on = true, [2].x = 1, [2].on = true }" },
};
for (cases) |case| {
var w: std.Io.Writer = .fixed(&buf);
try formatPath(layout, bytes, case[0], &w);
try std.testing.expectEqualStrings(case[1], w.buffered());
}
var w: std.Io.Writer = .fixed(&buf);
try formatPath(layout, bytes, "big", &w);
try std.testing.expect(std.mem.endsWith(u8, w.buffered(), "7, 7, ... 36 more }"));
try std.testing.expectError(error.UnknownField, formatPath(layout, bytes, "po", &w));
}
|