2025-05-22 16:39:37 +05:30
|
|
|
|
# This file is a modified version of Emery Hemingway’s CBOR library for Nim,
|
|
|
|
|
|
# originally available at https://github.com/ehmry/cbor-nim and released under The Unlicense.
|
2025-05-21 03:22:35 +05:30
|
|
|
|
|
|
|
|
|
|
import ./types
|
|
|
|
|
|
import ./errors
|
|
|
|
|
|
from macros import newDotExpr, newIdentNode, strVal
|
|
|
|
|
|
|
2025-05-31 17:38:35 +05:30
|
|
|
|
template expectCborKind*(
|
|
|
|
|
|
expectedType: type, expectedKinds: set[CborNodeKind], cbor: CborNode
|
|
|
|
|
|
) =
|
2025-05-21 03:22:35 +05:30
|
|
|
|
if cbor.kind notin expectedKinds:
|
|
|
|
|
|
return failure(newUnexpectedKindError(expectedType, expectedKinds, cbor))
|
|
|
|
|
|
|
2025-05-31 17:38:35 +05:30
|
|
|
|
template expectCborKind*(
|
|
|
|
|
|
expectedType: type, expectedKind: CborNodeKind, cbor: CborNode
|
|
|
|
|
|
) =
|
2025-05-28 11:49:50 +05:30
|
|
|
|
expectCborKind(expectedType, {expectedKind}, cbor)
|
2025-05-21 03:22:35 +05:30
|
|
|
|
|
2025-05-31 17:38:35 +05:30
|
|
|
|
template expectCborKind*(
|
|
|
|
|
|
expectedType: type, expectedKinds: set[CborEventKind], cbor: CborNode
|
|
|
|
|
|
) =
|
2025-05-21 03:22:35 +05:30
|
|
|
|
if cbor.kind notin expectedKinds:
|
|
|
|
|
|
return failure(newUnexpectedKindError(expectedType, expectedKinds, cbor))
|
|
|
|
|
|
|
2025-05-31 17:38:35 +05:30
|
|
|
|
template expectCborKind*(
|
|
|
|
|
|
expectedType: type, expectedKind: CborEventKind, cbor: CborNode
|
|
|
|
|
|
) =
|
2025-05-28 11:49:50 +05:30
|
|
|
|
expectCborKind(expectedType, {expectedKind}, cbor)
|
2025-05-21 03:22:35 +05:30
|
|
|
|
|
|
|
|
|
|
macro dot*(obj: object, fld: string): untyped =
|
|
|
|
|
|
## Turn ``obj.dot("fld")`` into ``obj.fld``.
|
|
|
|
|
|
newDotExpr(obj, newIdentNode(fld.strVal))
|
|
|
|
|
|
|
|
|
|
|
|
func floatSingle*(half: uint16): float32 =
|
|
|
|
|
|
## Convert a 16-bit float to 32-bits.
|
2025-05-31 17:38:35 +05:30
|
|
|
|
func ldexp(
|
|
|
|
|
|
x: float64, exponent: int
|
|
|
|
|
|
): float64 {.importc: "ldexp", header: "<math.h>".}
|
2025-05-21 03:22:35 +05:30
|
|
|
|
let
|
|
|
|
|
|
exp = (half shr 10) and 0x1f
|
|
|
|
|
|
mant = float64(half and 0x3ff)
|
2025-05-31 17:38:35 +05:30
|
|
|
|
val =
|
|
|
|
|
|
if exp == 0:
|
2025-05-21 03:22:35 +05:30
|
|
|
|
ldexp(mant, -24)
|
|
|
|
|
|
elif exp != 31:
|
|
|
|
|
|
ldexp(mant + 1024, exp.int - 25)
|
|
|
|
|
|
else:
|
|
|
|
|
|
if mant == 0: Inf else: NaN
|
2025-05-31 17:38:35 +05:30
|
|
|
|
if (half and 0x8000) == 0:
|
|
|
|
|
|
val
|
|
|
|
|
|
else:
|
|
|
|
|
|
-val
|