authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2024-05-19 18:55:18 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2024-05-19 18:55:18 -07:00
logb2abe69ab629432c456cbf737de7f52ce8c1f8b0
tree91d49f12be63c9e6ffbf49b8a74641af26d6283a
parent18292e8659fef2f691ad29fa8b7fd30bb958f6c4

delete the old implementation and upgrade to zig 0.12


9 files changed, 13 insertions(+), 251 deletions(-)

.gitignore+1
......@@ -1,3 +1,4 @@
11/.zigmod
22/deps.zig
33/zig-*
4zigmod.lock
build.zig+9-9
......@@ -1,23 +1,23 @@
11const std = @import("std");
22const deps = @import("./deps.zig");
33
4pub fn build(b: *std.build.Builder) void {
4pub fn build(b: *std.Build) void {
55 const target = b.standardTargetOptions(.{});
6 const mode = b.option(std.builtin.Mode, "mode", "") orelse .Debug;
67
7 const mode = b.standardReleaseOptions();
8
9 const exe = b.addExecutable("zig-json", "src/main.zig");
10 exe.setTarget(target);
11 exe.setBuildMode(mode);
8 const exe = b.addTest(.{
9 .root_source_file = b.path("test.zig"),
10 .target = target,
11 .optimize = mode,
12 });
1213 deps.addAllTo(exe);
13 exe.install();
1414
15 const run_cmd = exe.run();
15 const run_cmd = b.addRunArtifact(exe);
1616 run_cmd.step.dependOn(b.getInstallStep());
1717 if (b.args) |args| {
1818 run_cmd.addArgs(args);
1919 }
2020
21 const run_step = b.step("run", "Run the app");
21 const run_step = b.step("test", "Run the tests");
2222 run_step.dependOn(&run_cmd.step);
2323}
json.zig created+1
......@@ -0,0 +1 @@
1const std = @import("std");
licenses.txt-5
......@@ -1,8 +1,3 @@
11MIT:
22= https://spdx.org/licenses/MIT
33- This
4- git https://github.com/MasterQ32/zig-uri
5- git https://github.com/nektro/iguanaTLS
6- git https://github.com/nektro/zig-extras
7- git https://github.com/truemedian/hzzp
8- git https://github.com/truemedian/zfetch
src/lib.zig deleted-190
......@@ -1,190 +0,0 @@
1const std = @import("std");
2const extras = @import("extras");
3
4pub const Value = union(enum) {
5 Object: []Member,
6 Array: []Value,
7 String: []const u8,
8 Int: i64,
9 Float: f64,
10 Bool: bool,
11 Null: void,
12
13 fn get_obj(self: Value, key: []const u8) ?Value {
14 if (self == .Object) {
15 for (self.Object) |member| {
16 if (std.mem.eql(u8, member.key, key)) {
17 return member.value;
18 }
19 }
20 }
21 return null;
22 }
23
24 pub fn get(self: Value, query: anytype) ?Value {
25 const TO = @TypeOf(query);
26 if (comptime std.meta.trait.isZigString(TO)) {
27 return self.get_obj(@as([]const u8, query));
28 }
29 const TI = @typeInfo(TO);
30 if (TI == .Int or TI == .ComptimeInt) {
31 if (self == .Array) {
32 return self.Array[query];
33 }
34 }
35 return self.fetch_inner(query, 0);
36 }
37
38 pub fn getT(self: Value, query: anytype, comptime ty: std.meta.FieldEnum(Value)) ?extras.FieldType(Value, ty) {
39 if (self.get(query)) |val| {
40 if (val == .Null) return null;
41 return @field(val, @tagName(ty));
42 }
43 return null;
44 }
45
46 fn fetch_inner(self: Value, query: anytype, comptime n: usize) ?Value {
47 if (query.len == n) {
48 return self;
49 }
50 const i = query[n];
51 const TO = @TypeOf(i);
52 const TI = @typeInfo(TO);
53 if (comptime std.meta.trait.isZigString(TO)) {
54 if (self.get_obj(i)) |v| {
55 return v.fetch_inner(query, n + 1);
56 }
57 }
58 if (TI == .Int or TI == .ComptimeInt) {
59 if (self == .Array) {
60 return self.Array[i].fetch_inner(query, n + 1);
61 }
62 }
63 return null;
64 }
65
66 pub fn format(self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void {
67 _ = fmt;
68 _ = options;
69
70 switch (self) {
71 .Object => {
72 try writer.writeAll("{");
73 for (self.Object, 0..) |member, i| {
74 if (i > 0) {
75 try writer.writeAll(", ");
76 }
77 try writer.print("{}", .{member});
78 }
79 try writer.writeAll("}");
80 },
81 .Array => {
82 try writer.writeAll("[");
83 for (self.Array, 0..) |val, i| {
84 if (i > 0) {
85 try writer.writeAll(", ");
86 }
87 try writer.print("{}", .{val});
88 }
89 try writer.writeAll("]");
90 },
91 .String => {
92 try writer.print("\"{s}\"", .{self.String});
93 },
94 .Int => {
95 try writer.print("{d}", .{self.Int});
96 },
97 .Float => {
98 try writer.print("{}", .{self.Float});
99 },
100 .Bool => {
101 try writer.print("{}", .{self.Bool});
102 },
103 .Null => {
104 try writer.writeAll("null");
105 },
106 }
107 }
108};
109
110pub const Member = struct {
111 key: []const u8,
112 value: Value,
113
114 pub fn format(self: Member, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void {
115 _ = fmt;
116 _ = options;
117
118 try writer.print("\"{s}\": {}", .{ self.key, self.value });
119 }
120};
121
122const Parser = struct {
123 p: std.json.Scanner,
124
125 pub fn next(self: *Parser) !?std.json.Token {
126 const tok = try self.p.next();
127 if (tok == .end_of_document) return null;
128 return tok;
129 }
130
131 pub const Error =
132 std.fs.File.OpenError ||
133 std.json.StreamingParser.Error ||
134 std.mem.Allocator.Error ||
135 error{Overflow} ||
136 error{InvalidCharacter} ||
137 error{ JsonExpectedObjKey, JsonExpectedValueStartGotEnd };
138};
139
140pub fn parse(alloc: std.mem.Allocator, input: []const u8) Parser.Error!Value {
141 var p = Parser{
142 .p = std.json.Scanner.initCompleteInput(alloc, input),
143 };
144 return try parse_value(&p, null);
145}
146
147fn parse_value(p: *Parser, start: ?std.json.Token) Parser.Error!Value {
148 const tok = start orelse try p.next();
149 return switch (tok.?) {
150 .ObjectBegin => Value{ .Object = try parse_object(p) },
151 .ObjectEnd => error.JsonExpectedValueStartGotEnd,
152 .ArrayBegin => Value{ .Array = try parse_array(p) },
153 .ArrayEnd => error.JsonExpectedValueStartGotEnd,
154 .String => |t| Value{ .String = t.slice(p.input, p.index - 1) },
155 .Number => |t| if (t.is_integer) Value{ .Int = try std.fmt.parseInt(i64, t.slice(p.input, p.index - 1), 10) } else Value{ .Float = try std.fmt.parseFloat(f64, t.slice(p.input, p.index - 1)) },
156 .True => Value{ .Bool = true },
157 .False => Value{ .Bool = false },
158 .Null => Value{ .Null = {} },
159 };
160}
161
162fn parse_object(p: *Parser) Parser.Error![]Member {
163 var array = std.ArrayList(Member).init(p.alloc);
164 errdefer array.deinit();
165 while (true) {
166 const tok = try p.next();
167 if (tok.? == .ObjectEnd) {
168 return array.toOwnedSlice();
169 }
170 if (tok.? != .String) {
171 return error.JsonExpectedObjKey;
172 }
173 try array.append(Member{
174 .key = tok.?.String.slice(p.input, p.index - 1),
175 .value = try parse_value(p, null),
176 });
177 }
178}
179
180fn parse_array(p: *Parser) Parser.Error![]Value {
181 var array = std.ArrayList(Value).init(p.alloc);
182 errdefer array.deinit();
183 while (true) {
184 const tok = try p.next();
185 if (tok.? == .ArrayEnd) {
186 return array.toOwnedSlice();
187 }
188 try array.append(try parse_value(p, tok.?));
189 }
190}
src/main.zig deleted-33
......@@ -1,33 +0,0 @@
1const std = @import("std");
2
3const json = @import("json");
4const zfetch = @import("zfetch");
5
6pub fn main() !void {
7 var gpa = std.heap.GeneralPurposeAllocator(.{}){};
8 const alloc = gpa.allocator();
9
10 const url = "https://old.reddit.com/r/Zig/.json";
11
12 const req = try zfetch.Request.init(alloc, url, null);
13 defer req.deinit();
14
15 try req.do(.GET, null, null);
16 const r = req.reader();
17
18 const body_content = try r.readAllAlloc(alloc, std.math.maxInt(usize));
19 const val = try json.parse(alloc, body_content);
20
21 std.log.info("hot posts from r/Zig", .{});
22 std.log.info("", .{});
23
24 var count: usize = 1;
25 for (val.get(.{ "data", "children" }).?.Array) |ch| {
26 const post = ch.get("data").?;
27 const title = post.get("title").?.String;
28 const author = post.get("author").?.String;
29 std.log.info("{}: {s} -- u/{s} ", .{ count, title, author });
30 count += 1;
31 }
32 _ = std.math.lossyCast(i32, 2.4);
33}
test.zig created+1
......@@ -0,0 +1 @@
1const std = @import("std");
zig.mod+1-6
......@@ -1,10 +1,5 @@
11id: ocmr9rtohgccd6gm6tp8b1yzylyzkqwvo1q4btrsvj0cse9y
22name: json
3main: src/lib.zig
3main: json.zig
44license: MIT
55description: "A JSON library for inspecting arbitrary values"
6dependencies:
7 - src: git https://github.com/nektro/zig-extras
8
9root_dependencies:
10 - src: git https://github.com/truemedian/zfetch
zigmod.lock deleted-8
......@@ -1,8 +0,0 @@
12
2git https://github.com/nektro/zig-extras commit-fa1138e1a0a2f666b2cd26818e280b6171e417ac
3git https://github.com/nektro/zig-range commit-4b2f12808aa09be4b27a163efc424dd4e0415992
4git https://github.com/truemedian/zfetch commit-271cab5da4d12c8f08e67aa0cd5268da100e52f1
5git https://github.com/truemedian/hzzp commit-bf5aaf224e94561e035a631c3c40fbf02faa27d2
6git https://github.com/marler8997/iguanaTLS commit-2b37c575b3df76a4ee040b5a72a4fc277ed4057b
7git https://github.com/MasterQ32/zig-network commit-b9c52822f3bb3ce25164a2f1f6eedee4d1c0a279
8git https://github.com/MasterQ32/zig-uri commit-01155026c8362bb75dcab10bafc31abff0c8bac4