diff --git a/src/dom.zig b/src/dom.zig index ec20f75..d142f19 100644 --- a/src/dom.zig +++ b/src/dom.zig @@ -1640,6 +1640,19 @@ const Object = struct { return child; } + + pub const KeyIterator = struct { + tape_it: TapeRefIterator, + + pub fn next(it: *KeyIterator) ?[]const u8 { + const s = it.tape_it.element().get_string() catch return null; + _ = it.tape_it.next(); + return s; + } + }; + pub fn key_iterator(o: Object) KeyIterator { + return .{ .tape_it = TapeRefIterator.init(o) }; + } }; // TODO rename these diff --git a/src/tests.zig b/src/tests.zig index 82956b8..dd879ba 100644 --- a/src/tests.zig +++ b/src/tests.zig @@ -453,6 +453,35 @@ test "get_string_int64/uint64" { } } +test "dom object key iterator" { + const input = + \\{"a": {"c": null, "d": 3}, "b": 2} + ; + var parser = try dom.Parser.initFixedBuffer(allr, input, .{}); + defer parser.deinit(); + try parser.parse(); + const ele = parser.element(); + const o = try ele.get_object(); + { + var keyit = o.key_iterator(); + for ([_][]const u8{ "a", "b" }) |exkey| { + const key = keyit.next() orelse return error.TestUnexpectedResult; + try testing.expectEqualStrings(key, exkey); + } + try testing.expect(keyit.next() == null); + } + { + const ele2 = o.at_key("a") orelse return error.TestUnexpectedResult; + const o2 = try ele2.get_object(); + var keyit = o2.key_iterator(); + for ([_][]const u8{ "c", "d" }) |exkey| { + const key = keyit.next() orelse return error.TestUnexpectedResult; + try testing.expectEqualStrings(key, exkey); + } + try testing.expect(keyit.next() == null); + } +} + // const ondemand = simdjzon.ondemand; test "ondemand get with struct" { const S = struct { a: struct { b: []const u8 } };