Format query strings properly

This commit is contained in:
jaina heartles 2022-12-16 01:05:36 -08:00
parent b015bb8356
commit f47c1ee751

View file

@ -183,7 +183,7 @@ pub fn EncodeStruct(comptime Params: type) type {
return struct {
params: Params,
pub fn format(v: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
try formatQuery("", "", v.params, writer);
try formatQuery("", v.params, writer);
}
};
}
@ -221,16 +221,16 @@ fn formatScalar(comptime name: []const u8, val: anytype, writer: anytype) !void
try writer.writeByte('&');
}
fn formatQuery(comptime prefix: []const u8, comptime name: []const u8, params: anytype, writer: anytype) !void {
fn formatQuery(comptime prefix: []const u8, params: anytype, writer: anytype) !void {
const T = @TypeOf(params);
const eff_prefix = if (prefix.len == 0) "" else prefix ++ ".";
if (comptime isScalar(T)) return formatScalar(eff_prefix ++ name, params, writer);
if (comptime isScalar(T)) return formatScalar(prefix, params, writer);
switch (@typeInfo(T)) {
.Struct => {
const eff_prefix = if (prefix.len == 0) "" else prefix ++ ".";
inline for (std.meta.fields(T)) |field| {
const val = @field(params, field.name);
try formatQuery(eff_prefix ++ name, field.name, val, writer);
try formatQuery(eff_prefix ++ field.name, val, writer);
}
},
.Union => {
@ -239,12 +239,12 @@ fn formatQuery(comptime prefix: []const u8, comptime name: []const u8, params: a
const tag_name = field.name;
if (@as(std.meta.Tag(T), params) == tag) {
const val = @field(params, tag_name);
try formatQuery(prefix, tag_name, val, writer);
try formatQuery(prefix, val, writer);
}
}
},
.Optional => {
if (params) |p| try formatQuery(prefix, name, p, writer);
if (params) |p| try formatQuery(prefix, p, writer);
},
else => @compileError("Unsupported query type"),
}