diff options
author | bptato <nincsnevem662@gmail.com> | 2024-02-08 16:01:56 +0100 |
---|---|---|
committer | bptato <nincsnevem662@gmail.com> | 2024-02-08 16:03:33 +0100 |
commit | f8382a3db564fed31c3d6e1cc0731fe6a345acfe (patch) | |
tree | af603eac5ce55f9929417fde9357bf0d590c60da /src | |
parent | 118272314311e75800d066fce885e59b9f8dd5af (diff) | |
download | chawan-f8382a3db564fed31c3d6e1cc0731fe6a345acfe.tar.gz |
js: fix fromJSEnum
std enum parsing uses Nim ident matching rules, which is incorrect here.
Diffstat (limited to 'src')
-rw-r--r-- | src/js/error.nim | 3 | ||||
-rw-r--r-- | src/js/fromjs.nim | 20 |
2 files changed, 17 insertions, 6 deletions
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] = |