Make mapEmbeds more general

This commit is contained in:
Emery Hemingway 2024-01-07 17:38:31 +02:00
parent 7b17f935ea
commit 79ea25d1be
1 changed files with 8 additions and 15 deletions

View File

@ -883,12 +883,12 @@ proc apply*(result: var Value; op: proc(_: var Value) {.gcsafe.}) {.gcsafe.} =
recurse(e.val) recurse(e.val)
cannonicalize(result) cannonicalize(result)
proc mapEmbeds*[T](pr: sink Value; op: proc (x: T): Value {.gcsafe.}): Value {.gcsafe.} = proc mapEmbeds*(pr: sink Value; op: proc (x: Value): Value {.gcsafe.}): Value {.gcsafe.} =
## Process all embeds in a `Value` that are of type `T`. ## Process all embeds in a `Value`.
case pr.kind case pr.kind
of pkBoolean, pkFloat, pkDouble, pkRegister, pkBigInt, of pkBoolean, pkFloat, pkDouble, pkRegister, pkBigInt,
pkString, pkByteString, pkSymbol: pkString, pkByteString, pkSymbol, pkEmbedded:
result = cast[Value](pr) result = pr
of pkRecord: of pkRecord:
result = Value(kind: pr.kind) result = Value(kind: pr.kind)
result.record = map(pr.record) do (x: Value) -> Value: result.record = map(pr.record) do (x: Value) -> Value:
@ -905,18 +905,11 @@ proc mapEmbeds*[T](pr: sink Value; op: proc (x: T): Value {.gcsafe.}): Value {.g
result = Value(kind: pr.kind) result = Value(kind: pr.kind)
result.dict = map(pr.dict) do (e: DictEntry) -> DictEntry: result.dict = map(pr.dict) do (e: DictEntry) -> DictEntry:
(mapEmbeds(e.key, op), mapEmbeds(e.val, op)) (mapEmbeds(e.key, op), mapEmbeds(e.val, op))
of pkEmbedded: if pr.embedded or pr.kind == pkEmbedded:
when T is Value: result = pr result = op(result)
else: result.embedded = true
if pr.embeddedRef of T:
result = op(T pr.embeddedRef)
result.embedded = true
else: result = pr
when T is Value:
if result.embedded:
result = op(pr)
cannonicalize(result) cannonicalize(result)
# TODO: is this necessary? # TODO: is this necessary?
proc getOrDefault*[T, V](pr: Value; key: string; default: V): V = proc getOrDefault*[T, V](pr: Value; key: string; default: V): V =
## Retrieves the value of `pr[key]` if `pr` is a dictionary containing `key` ## Retrieves the value of `pr[key]` if `pr` is a dictionary containing `key`