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)
cannonicalize(result)
proc mapEmbeds*[T](pr: sink Value; op: proc (x: T): Value {.gcsafe.}): Value {.gcsafe.} =
## Process all embeds in a `Value` that are of type `T`.
proc mapEmbeds*(pr: sink Value; op: proc (x: Value): Value {.gcsafe.}): Value {.gcsafe.} =
## Process all embeds in a `Value`.
case pr.kind
of pkBoolean, pkFloat, pkDouble, pkRegister, pkBigInt,
pkString, pkByteString, pkSymbol:
result = cast[Value](pr)
pkString, pkByteString, pkSymbol, pkEmbedded:
result = pr
of pkRecord:
result = Value(kind: pr.kind)
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.dict = map(pr.dict) do (e: DictEntry) -> DictEntry:
(mapEmbeds(e.key, op), mapEmbeds(e.val, op))
of pkEmbedded:
when T is Value: result = pr
else:
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)
if pr.embedded or pr.kind == pkEmbedded:
result = op(result)
result.embedded = true
cannonicalize(result)
# TODO: is this necessary?
# TODO: is this necessary?
proc getOrDefault*[T, V](pr: Value; key: string; default: V): V =
## Retrieves the value of `pr[key]` if `pr` is a dictionary containing `key`