diff options
Diffstat (limited to 'src/host/fields.zig')
| -rw-r--r-- | src/host/fields.zig | 116 |
1 files changed, 116 insertions, 0 deletions
diff --git a/src/host/fields.zig b/src/host/fields.zig new file mode 100644 index 0000000..215f176 --- /dev/null +++ b/src/host/fields.zig @@ -0,0 +1,116 @@ +//! 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 Leaf = @import("memory.zig").Layout.Leaf; + +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; +} + +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, .forbidden)); + 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")); +} |
