From f8382a3db564fed31c3d6e1cc0731fe6a345acfe Mon Sep 17 00:00:00 2001 From: bptato Date: Thu, 8 Feb 2024 16:01:56 +0100 Subject: js: fix fromJSEnum std enum parsing uses Nim ident matching rules, which is incorrect here. --- src/js/error.nim | 3 +++ src/js/fromjs.nim | 20 ++++++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) (limited to 'src/js') diff --git a/src/js/error.nim b/src/js/error.nim index 3b05c1ec..860f4f80 100644 --- a/src/js/error.nim +++ b/src/js/error.nim @@ -78,3 +78,6 @@ proc newAggregateError*(message: string): JSError = e: JS_AGGREGATE_ERROR0, message: message ) + +template errTypeError*(message: string): untyped = + err(newTypeError(message)) diff --git a/src/js/fromjs.nim b/src/js/fromjs.nim index 9de975f2..823a045e 100644 --- a/src/js/fromjs.nim +++ b/src/js/fromjs.nim @@ -1,6 +1,5 @@ import std/macros import std/options -import std/strutils import std/tables import std/unicode @@ -378,11 +377,20 @@ proc fromJSEnum[T: enum](ctx: JSContext, val: JSValue): JSResult[T] = if JS_IsException(val): return err() let s = ?toString(ctx, val) - try: - return ok(parseEnum[T](s)) - except ValueError: - return err(newTypeError("`" & s & - "' is not a valid value for enumeration " & $T)) + # cmp when len is small enough, otherwise hashmap + when {T.low..T.high}.len <= 4: + for e in T.low .. T.high: + if $e == s: + return ok(e) + else: + const tab = (func(): Table[string, T] = + result = initTable[string, T]() + for e in T.low .. T.high: + result[$e] = e + )() + if s in tab: + return ok(tab[s]) + return errTypeError("`" & s & "' is not a valid value for enumeration " & $T) proc fromJSPObj0(ctx: JSContext, val: JSValue, t: string): JSResult[pointer] = -- cgit 1.4.1-2-gfad0