From f743e05e207046073999ee7234a157359d6a4f57 Mon Sep 17 00:00:00 2001 From: Christian Segundo Date: Mon, 24 Jul 2023 10:28:58 +0200 Subject: wip --- src/response.zig | 93 +++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 62 insertions(+), 31 deletions(-) (limited to 'src/response.zig') diff --git a/src/response.zig b/src/response.zig index 8964de4..a370133 100644 --- a/src/response.zig +++ b/src/response.zig @@ -4,44 +4,75 @@ const Types = @import("types.zig"); pub const Response = @This(); +pub const default_parse_options = std.json.ParseOptions{ + .ignore_unknown_fields = true, + .duplicate_field_behavior = .@"error", +}; + +allocator: std.mem.Allocator, +data: Data, + +pub const Data = union(enum) { + TorrentGet: TorrentGet, + TorrentAdd: TorrentAdd, +}; + +pub fn parseBody( + allocator: std.mem.Allocator, + method: Request.Method, + body: []const u8, + parseOptions: ?std.json.ParseOptions, +) !Response { + @setEvalBranchQuota(10000); + switch (method) { + .@"torrent-get" => { + const decoded = try std.json.parseFromSlice( + TorrentGet, + allocator, + body, + parseOptions orelse default_parse_options, + ); + return Response{ + .data = Data{ .TorrentGet = decoded }, + .allocator = allocator, + }; + }, + .@"torrent-add" => { + const decoded = try std.json.parseFromSlice( + TorrentAdd, + allocator, + body, + parseOptions orelse default_parse_options, + ); + return Response{ + .data = Data{ .TorrentAdd = decoded }, + .allocator = allocator, + }; + }, + else => unreachable, + } +} + +pub fn deinit(self: *Response) void { + std.json.parseFree(@TypeOf(self.data), self.allocator, self.*.data); +} + pub const TorrentGet = struct { pub const Arguments = struct { torrents: ?[]Types.Torrent = null, }; - result: []const u8, - arguments: Arguments, + arguments: @This().Arguments, }; -pub const Object = struct { - pub const Arguments = union(Request.Method) { - torrent_start, - torrent_start_now, - torrent_stop, - torrent_verify, - torrent_reannounce, - torrent_set, - torrent_get: TorrentGet.Arguments, - torrent_add, - torrent_remove, - torrent_set_location, - torrent_rename_path, - session_get, - session_set, +pub const TorrentAdd = struct { + pub const Arguments = struct { + @"torrent-added": ?struct { + hashString: []const u8, + id: u64, + name: []const u8, + } = null, }; - result: []const u8, - arguments: Arguments, - - pub fn init(arguments: Arguments, result: []const u8) Object { - switch (arguments) { - .torrent_get => { - return Object{ - .result = result, - .arguments = arguments, - }; - }, - else => unreachable, - } - } + arguments: @This().Arguments, }; -- cgit v1.2.3