diff options
author | 2023-05-08 22:34:01 -0700 | |
---|---|---|
committer | 2023-05-08 22:34:01 -0700 | |
commit | 73b0d8a51cc86ba47d37f0dadf0f871fc402668c (patch) | |
tree | 20f90a208075bbcd28dde442fa526f7737cb7ba0 | |
parent | b874d0b387d27efc5f0a78c5391889ecea24db2e (diff) | |
download | bun-73b0d8a51cc86ba47d37f0dadf0f871fc402668c.tar.gz bun-73b0d8a51cc86ba47d37f0dadf0f871fc402668c.tar.zst bun-73b0d8a51cc86ba47d37f0dadf0f871fc402668c.zip |
Make the enum serializer more flexible
-rw-r--r-- | src/bun.js/bindings/bindings.zig | 8 | ||||
-rw-r--r-- | src/meta.zig | 15 |
2 files changed, 19 insertions, 4 deletions
diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index 71409da4f..f64c13a22 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -3960,12 +3960,12 @@ pub const JSValue = enum(JSValueReprInt) { return null; } - pub fn toEnumWithMapField( + pub fn toEnumFromMap( this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8, comptime Enum: type, - comptime map_name: []const u8, + comptime StringMap: anytype, ) !Enum { if (!this.isString()) { globalThis.throwInvalidArguments(property_name ++ " must be a string", .{}); @@ -3973,11 +3973,11 @@ pub const JSValue = enum(JSValueReprInt) { } const target_str = this.getZigString(globalThis); - return @field(Enum, map_name).getWithEql(target_str, ZigString.eqlComptime) orelse { + return StringMap.getWithEql(target_str, ZigString.eqlComptime) orelse { const one_of = struct { pub const list = brk: { var str: []const u8 = "'"; - const field_names = std.meta.fieldNames(Enum); + const field_names = bun.meta.enumFieldNames(Enum); for (field_names, 0..) |entry, i| { str = str ++ entry ++ "'"; if (i < field_names.len - 2) { diff --git a/src/meta.zig b/src/meta.zig index 5bf99bbaa..954e77f29 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -24,3 +24,18 @@ pub fn typeBaseName(comptime fullname: []const u8) []const u8 { const name = if (idx == null) fullname else fullname[(idx.? + 1)..]; return comptime std.fmt.comptimePrint("{s}", .{name}); } + +pub fn enumFieldNames(comptime Type: type) []const []const u8 { + var names: [std.meta.fields(Type).len][]const u8 = std.meta.fieldNames(Type).*; + var i: usize = 0; + for (names) |name| { + // zig seems to include "_" or an empty string in the list of enum field names + // it makes sense, but humans don't want that + if (@import("root").bun.strings.eqlAnyComptime(name, &.{ "_none", "", "_" })) { + continue; + } + names[i] = name; + i += 1; + } + return names[0..i]; +} |