1
0
Fork 0
mirror of https://github.com/zigzap/zap.git synced 2025-10-20 15:14:08 +00:00

Endpoint better json handling

This commit is contained in:
Rene Schallner 2023-01-19 21:24:22 +01:00
parent 886f1ea299
commit 172ddd3e0f
2 changed files with 24 additions and 11 deletions

View file

@ -64,18 +64,31 @@ fn getUser(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void {
fn listUsers(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void { fn listUsers(e: *zap.SimpleEndpoint, r: zap.SimpleRequest) void {
_ = e; _ = e;
// 1MB json buffer
var jsonbuf: [1024 * 1024]u8 = undefined;
var l: std.ArrayList(User) = std.ArrayList(User).init(alloc); var l: std.ArrayList(User) = std.ArrayList(User).init(alloc);
if (users.list(&l)) {} else |_| { if (users.list(&l)) {} else |_| {
return; return;
} }
// attention: if you add too many users, this will not be enough var maybe_json: ?[]const u8 = null;
var jsonbuf: [1024 * 1024]u8 = undefined; var maybe_free: ?std.ArrayList(u8) = null;
if (zap.stringifyArrayListBuf(&jsonbuf, User, &l, .{})) |maybe_json| { // if (users.count > 0) {
if (maybe_json) |json| { if (users.count > 20000) {
_ = r.sendJson(json); // if > 20000 users, 1MB might not be enough for json
if (zap.stringifyArrayListAlloc(alloc, User, &l, .{}) catch null) |string| {
maybe_free = string;
maybe_json = string.items;
} }
} else |_| { } else {
return; maybe_json = zap.stringifyArrayListBuf(&jsonbuf, User, &l, .{}) catch null;
}
if (maybe_json) |json| {
_ = r.sendJson(json);
}
if (maybe_free) |free| {
free.deinit();
} }
} }

View file

@ -87,10 +87,10 @@ pub fn stringifyAlloc(
a: std.mem.Allocator, a: std.mem.Allocator,
value: anytype, value: anytype,
options: std.json.StringifyOptions, options: std.json.StringifyOptions,
) ?[]const u8 { ) ?std.ArrayList(u8) {
var string = std.ArrayList(u8).init(a); var string = std.ArrayList(u8).init(a);
if (std.json.stringify(value, options, string.writer())) { if (std.json.stringify(value, options, string.writer())) {
return string.items; return string;
} else |_| { // error } else |_| { // error
return null; return null;
} }
@ -102,7 +102,7 @@ pub fn stringifyArrayListAlloc(
comptime T: anytype, comptime T: anytype,
list: *std.ArrayList(T), list: *std.ArrayList(T),
options: std.json.StringifyOptions, options: std.json.StringifyOptions,
) !?[]const u8 { ) !?std.ArrayList(u8) {
var string = std.ArrayList(u8).init(a); var string = std.ArrayList(u8).init(a);
var writer = string.writer(); var writer = string.writer();
try writer.writeByte('['); try writer.writeByte('[');
@ -113,5 +113,5 @@ pub fn stringifyArrayListAlloc(
try std.json.stringify(user, options, string.writer()); try std.json.stringify(user, options, string.writer());
} }
try writer.writeByte(']'); try writer.writeByte(']');
return string.items; return string;
} }