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
|
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const ArenaAllocator = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const ObjectMap = @import("dynamic.zig").ObjectMap;
const Array = @import("dynamic.zig").Array;
const Value = @import("dynamic.zig").Value;
const parseFromSlice = @import("static.zig").parseFromSlice;
const parseFromSliceLeaky = @import("static.zig").parseFromSliceLeaky;
const parseFromTokenSource = @import("static.zig").parseFromTokenSource;
const parseFromValueLeaky = @import("static.zig").parseFromValueLeaky;
const ParseOptions = @import("static.zig").ParseOptions;
const jsonReader = @import("scanner.zig").reader;
test "json.parser.dynamic" {
const s =
\\{
\\ "Image": {
\\ "Width": 800,
\\ "Height": 600,
\\ "Title": "View from 15th Floor",
\\ "Thumbnail": {
\\ "Url": "http://www.example.com/image/481989943",
\\ "Height": 125,
\\ "Width": 100
\\ },
\\ "Animated" : false,
\\ "IDs": [116, 943, 234, 38793],
\\ "ArrayOfObject": [{"n": "m"}],
\\ "double": 1.3412,
\\ "LargeInt": 18446744073709551615
\\ }
\\}
;
var parsed = try parseFromSlice(Value, testing.allocator, s, .{});
defer parsed.deinit();
var root = parsed.value;
var image = root.object.get("Image").?;
const width = image.object.get("Width").?;
try testing.expect(width.integer == 800);
const height = image.object.get("Height").?;
try testing.expect(height.integer == 600);
const title = image.object.get("Title").?;
try testing.expect(mem.eql(u8, title.string, "View from 15th Floor"));
const animated = image.object.get("Animated").?;
try testing.expect(animated.bool == false);
const array_of_object = image.object.get("ArrayOfObject").?;
try testing.expect(array_of_object.array.items.len == 1);
const obj0 = array_of_object.array.items[0].object.get("n").?;
try testing.expect(mem.eql(u8, obj0.string, "m"));
const double = image.object.get("double").?;
try testing.expect(double.float == 1.3412);
const large_int = image.object.get("LargeInt").?;
try testing.expect(mem.eql(u8, large_int.number_string, "18446744073709551615"));
}
const writeStream = @import("./write_stream.zig").writeStream;
test "write json then parse it" {
var out_buffer: [1000]u8 = undefined;
var fixed_buffer_stream = std.io.fixedBufferStream(&out_buffer);
const out_stream = fixed_buffer_stream.writer();
var jw = writeStream(out_stream, 4);
try jw.beginObject();
try jw.objectField("f");
try jw.emitBool(false);
try jw.objectField("t");
try jw.emitBool(true);
try jw.objectField("int");
try jw.emitNumber(1234);
try jw.objectField("array");
try jw.beginArray();
try jw.arrayElem();
try jw.emitNull();
try jw.arrayElem();
try jw.emitNumber(12.34);
try jw.endArray();
try jw.objectField("str");
try jw.emitString("hello");
try jw.endObject();
fixed_buffer_stream = std.io.fixedBufferStream(fixed_buffer_stream.getWritten());
var json_reader = jsonReader(testing.allocator, fixed_buffer_stream.reader());
defer json_reader.deinit();
var parsed = try parseFromTokenSource(Value, testing.allocator, &json_reader, .{});
defer parsed.deinit();
try testing.expect(parsed.value.object.get("f").?.bool == false);
try testing.expect(parsed.value.object.get("t").?.bool == true);
try testing.expect(parsed.value.object.get("int").?.integer == 1234);
try testing.expect(parsed.value.object.get("array").?.array.items[0].null == {});
try testing.expect(parsed.value.object.get("array").?.array.items[1].float == 12.34);
try testing.expect(mem.eql(u8, parsed.value.object.get("str").?.string, "hello"));
}
fn testParse(allocator: std.mem.Allocator, json_str: []const u8) !Value {
return parseFromSliceLeaky(Value, allocator, json_str, .{});
}
test "parsing empty string gives appropriate error" {
var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_allocator.deinit();
try testing.expectError(error.UnexpectedEndOfInput, testParse(arena_allocator.allocator(), ""));
}
test "Value.array allocator should still be usable after parsing" {
var parsed = try parseFromSlice(Value, std.testing.allocator, "[]", .{});
defer parsed.deinit();
// Allocation should succeed
var i: usize = 0;
while (i < 100) : (i += 1) {
try parsed.value.array.append(Value{ .integer = 100 });
}
try testing.expectEqual(parsed.value.array.items.len, 100);
}
test "integer after float has proper type" {
var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_allocator.deinit();
const parsed = try testParse(arena_allocator.allocator(),
\\{
\\ "float": 3.14,
\\ "ints": [1, 2, 3]
\\}
);
try std.testing.expect(parsed.object.get("ints").?.array.items[0] == .integer);
}
test "escaped characters" {
var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_allocator.deinit();
const input =
\\{
\\ "backslash": "\\",
\\ "forwardslash": "\/",
\\ "newline": "\n",
\\ "carriagereturn": "\r",
\\ "tab": "\t",
\\ "formfeed": "\f",
\\ "backspace": "\b",
\\ "doublequote": "\"",
\\ "unicode": "\u0105",
\\ "surrogatepair": "\ud83d\ude02"
\\}
;
const obj = (try testParse(arena_allocator.allocator(), input)).object;
try testing.expectEqualSlices(u8, obj.get("backslash").?.string, "\\");
try testing.expectEqualSlices(u8, obj.get("forwardslash").?.string, "/");
try testing.expectEqualSlices(u8, obj.get("newline").?.string, "\n");
try testing.expectEqualSlices(u8, obj.get("carriagereturn").?.string, "\r");
try testing.expectEqualSlices(u8, obj.get("tab").?.string, "\t");
try testing.expectEqualSlices(u8, obj.get("formfeed").?.string, "\x0C");
try testing.expectEqualSlices(u8, obj.get("backspace").?.string, "\x08");
try testing.expectEqualSlices(u8, obj.get("doublequote").?.string, "\"");
try testing.expectEqualSlices(u8, obj.get("unicode").?.string, "ą");
try testing.expectEqualSlices(u8, obj.get("surrogatepair").?.string, "😂");
}
test "Value.jsonStringify" {
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try @as(Value, .null).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "null");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .bool = true }).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "true");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .integer = 42 }).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "42");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .number_string = "43" }).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "43");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .float = 42 }).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "4.2e+01");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .string = "weeee" }).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "\"weeee\"");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
var vals = [_]Value{
.{ .integer = 1 },
.{ .integer = 2 },
.{ .number_string = "3" },
};
try (Value{
.array = Array.fromOwnedSlice(undefined, &vals),
}).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "[1,2,3]");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
var obj = ObjectMap.init(testing.allocator);
defer obj.deinit();
try obj.putNoClobber("a", .{ .string = "b" });
try (Value{ .object = obj }).jsonStringify(.{}, fbs.writer());
try testing.expectEqualSlices(u8, fbs.getWritten(), "{\"a\":\"b\"}");
}
}
test "polymorphic parsing" {
if (true) return error.SkipZigTest; // See https://github.com/ziglang/zig/issues/16108
const doc =
\\{ "type": "div",
\\ "color": "blue",
\\ "children": [
\\ { "type": "button",
\\ "caption": "OK" },
\\ { "type": "button",
\\ "caption": "Cancel" } ] }
;
const Node = union(enum) {
div: Div,
button: Button,
const Self = @This();
const Div = struct {
color: enum { red, blue },
children: []Self,
};
const Button = struct {
caption: []const u8,
};
pub fn jsonParseFromValue(allocator: Allocator, source: Value, options: ParseOptions) !@This() {
if (source != .object) return error.UnexpectedToken;
const type_value = source.object.get("type") orelse return error.UnexpectedToken; // Missing "type" field.
if (type_value != .string) return error.UnexpectedToken; // "type" expected to be string.
const type_str = type_value.string;
var child_options = options;
child_options.ignore_unknown_fields = true;
if (std.mem.eql(u8, type_str, "div")) return .{ .div = try parseFromValueLeaky(Div, allocator, source, child_options) };
if (std.mem.eql(u8, type_str, "button")) return .{ .button = try parseFromValueLeaky(Button, allocator, source, child_options) };
return error.UnexpectedToken; // unknown type.
}
};
var arena = ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const dynamic_tree = try parseFromSliceLeaky(Value, arena.allocator(), doc, .{});
const tree = try parseFromValueLeaky(Node, arena.allocator(), dynamic_tree, .{});
try testing.expect(tree.div.color == .blue);
try testing.expectEqualStrings("Cancel", tree.div.children[1].button.caption);
}
|