preserves-nim/src/preserves.nim

792 lines
24 KiB
Nim
Raw Normal View History

2021-08-24 15:29:29 +00:00
# SPDX-FileCopyrightText: 2021 ☭ Emery Hemingway
2021-08-31 15:00:00 +00:00
# SPDX-License-Identifier: Unlicense
2021-06-02 13:51:36 +00:00
import bigints
import std/[base64, endians, hashes, options, sets, sequtils, streams, tables, typetraits]
from std/json import escapeJson, escapeJsonUnquoted
from std/macros import hasCustomPragma, getCustomPragmaVal
2021-06-02 13:51:36 +00:00
type
2021-06-08 10:14:56 +00:00
PreserveKind* = enum
2021-09-01 09:37:49 +00:00
pkBoolean, pkFloat, pkDouble, pkSignedInteger, pkBigInteger, pkString, pkByteString, pkSymbol,
pkRecord, pkSequence, pkSet, pkDictionary
2021-06-02 13:51:36 +00:00
2021-09-01 09:37:49 +00:00
const
atomKinds* = {pkBoolean, pkFloat, pkDouble, pkSignedInteger, pkBigInteger, pkString, pkByteString, pkSymbol}
compoundKinds* = {pkRecord, pkSequence, pkSet, pkDictionary}
type
DictEntry = tuple[key: Preserve, val: Preserve]
2021-08-28 10:48:50 +00:00
Preserve* {.acyclic.} = object
2021-06-02 13:51:36 +00:00
case kind*: PreserveKind
of pkBoolean:
bool*: bool
of pkFloat:
float*: float32
of pkDouble:
double*: float64
of pkSignedInteger:
int*: BiggestInt
of pkBigInteger:
bigint*: BigInt
of pkString:
string*: string
of pkByteString:
bytes*: seq[byte]
of pkSymbol:
symbol*: string
of pkRecord:
record*: seq[Preserve] # label is last
2021-06-02 13:51:36 +00:00
of pkSequence:
sequence*: seq[Preserve]
2021-06-02 13:51:36 +00:00
of pkSet:
set*: seq[Preserve]
# TODO: HashSet
2021-06-02 13:51:36 +00:00
of pkDictionary:
dict*: seq[DictEntry]
# TODO: Tables
embedded*: bool
2021-06-24 15:31:30 +00:00
proc `==`*(x, y: Preserve): bool =
## Check `x` and `y` for equivalence.
if x.kind == y.kind and x.embedded == y.embedded:
case x.kind
of pkBoolean:
result = x.bool == y.bool
of pkFloat:
result = x.float == y.float
of pkDouble:
result = x.double == y.double
of pkSignedInteger:
result = x.int == y.int
of pkBigInteger:
result = x.bigint == y.bigint
of pkString:
result = x.string == y.string
of pkByteString:
result = x.bytes == y.bytes
of pkSymbol:
result = x.symbol == y.symbol
of pkRecord:
result = x.record == y.record
of pkSequence:
for i, val in x.sequence:
if y.sequence[i] != val: return false
result = true
of pkSet:
result = x.set == y.set
of pkDictionary:
result = x.dict == y.dict
2021-06-02 13:51:36 +00:00
proc `<`(x, y: string | seq[byte]): bool =
for i in 0 .. min(x.high, y.high):
2021-08-28 10:48:50 +00:00
if x[i] < y[i]: return true
if x[i] != y[i]: return false
2021-06-02 13:51:36 +00:00
x.len < y.len
proc `<`*(x, y: Preserve): bool =
2021-09-01 09:37:49 +00:00
## Preserves have a total order over Values. Check if `x` is ordered before `y`.
if x.embedded != y.embedded:
result = y.embedded
elif x.kind != y.kind:
if x.kind == pkSignedInteger and y.kind == pkBigInteger:
result = x.int.initBigInt < y.bigint
elif x.kind == pkBigInteger and y.kind == pkSignedInteger:
result = x.bigint < y.int.initBigInt
else:
result = x.kind < y.kind
2021-06-02 13:51:36 +00:00
else:
case x.kind
of pkBoolean:
result = (not x.bool) and y.bool
2021-08-28 10:48:50 +00:00
of pkFloat:
result = x.float < y.float
of pkDouble:
result = x.double < y.double
2021-06-02 13:51:36 +00:00
of pkSignedInteger:
result = x.int < y.int
of pkBigInteger:
result = x.bigint < y.bigint
of pkString:
result = x.string < y.string
of pkByteString:
result = x.bytes < y.bytes
of pkSymbol:
result = x.symbol < y.symbol
2021-08-28 10:48:50 +00:00
of pkRecord:
if x.record[x.record.high] < y.record[y.record.high]: return true
for i in 0..<min(x.record.high, y.record.high):
if x.record[i] < y.record[i]: return true
if x.record[i] == y.record[i]: return false
2021-08-28 10:48:50 +00:00
result = x.record.len < y.record.len
of pkSequence:
for i in 0..min(x.sequence.high, y.sequence.high):
if x.sequence[i] < y.sequence[i]: return true
if x.sequence[i] != y.sequence[i]: return false
result = x.sequence.len < y.sequence.len
of pkSet:
for i in 0..min(x.set.high, y.set.high):
if x.set[i] < y.set[i]: return true
if x.set[i] != y.set[i]: return false
result = x.set.len < y.set.len
of pkDictionary:
for i in 0..min(x.dict.high, y.dict.high):
if x.dict[i].key < y.dict[i].key: return true
if x.dict[i].key == y.dict[i].key:
if x.dict[i].val < y.dict[i].val: return true
if x.dict[i].val != y.dict[i].val: return false
result = x.dict.len < y.dict.len
proc hash*(pr: Preserve): Hash =
## Produce a `Hash` of `pr` for use with a `HashSet` or `Table`.
var h = hash(pr.kind.int) !& hash(pr.embedded)
case pr.kind
2021-06-02 13:51:36 +00:00
of pkBoolean:
h = h !& hash(pr.bool)
2021-06-02 13:51:36 +00:00
of pkFloat:
h = h !& hash(pr.float)
2021-06-02 13:51:36 +00:00
of pkDouble:
h = h !& hash(pr.double)
2021-06-02 13:51:36 +00:00
of pkSignedInteger:
h = h !& hash(pr.int)
2021-06-02 13:51:36 +00:00
of pkBigInteger:
h = h !& hash(pr.bigint.flags)
h = h !& hash(pr.bigint)
2021-06-02 13:51:36 +00:00
of pkString:
h = h !& hash(pr.string)
2021-06-02 13:51:36 +00:00
of pkByteString:
h = h !& hash(pr.bytes)
2021-06-02 13:51:36 +00:00
of pkSymbol:
h = h !& hash(pr.symbol)
2021-06-02 13:51:36 +00:00
of pkRecord:
for val in pr.record:
2021-08-28 10:48:50 +00:00
h = h !& hash(val)
2021-06-02 13:51:36 +00:00
of pkSequence:
for val in pr.sequence:
2021-08-28 10:48:50 +00:00
h = h !& hash(val)
2021-06-02 13:51:36 +00:00
of pkSet:
for val in pr.set.items:
2021-08-28 10:48:50 +00:00
h = h !& hash(val)
2021-06-02 13:51:36 +00:00
of pkDictionary:
for (key, val) in pr.dict.items:
2021-08-28 10:48:50 +00:00
h = h !& hash(key) !& hash(val)
!$h
proc `[]`*(pr: Preserve; i: int): Preserve =
## Select an indexed value from `pr`.
2021-09-01 09:37:49 +00:00
## Only valid for records and sequences.
case pr.kind
of pkRecord: pr.record[i]
of pkSequence: pr.sequence[i]
2021-08-28 10:48:50 +00:00
else:
raise newException(ValueError, "`[]` is not valid for " & $pr.kind)
2021-07-16 17:11:19 +00:00
proc incl*(pr: var Preserve; key: Preserve) =
## Include `key` in the Preserves set `pr`.
for i in 0..pr.set.high:
if key < pr.set[i]:
insert(pr.set, [key], i)
2021-08-28 10:48:50 +00:00
return
pr.set.add(key)
2021-08-28 10:48:50 +00:00
proc excl*(pr: var Preserve; key: Preserve) =
## Exclude `key` from the Preserves set `pr`.
for i in 0..pr.set.high:
if pr.set[i] == key:
delete(pr.set, i, i)
2021-08-28 10:48:50 +00:00
break
proc `[]`*(pr: var Preserve; key: Preserve): Preserve =
## Select a value by `key` from the Preserves dictionary `pr`.
for (k, v) in pr.dict.items:
2021-08-28 10:48:50 +00:00
if k == key: return v
raise newException(KeyError, "value not in Preserves dictionary")
proc `[]=`*(pr: var Preserve; key, val: Preserve) =
## Insert `val` by `key` in the Preserves dictionary `pr`.
for i in 0..pr.dict.high:
if key < pr.dict[i].key:
insert(pr.dict, [(key, val, )], i)
2021-08-28 10:48:50 +00:00
return
elif key == pr.dict[i].key:
pr.dict[i].val = val
2021-08-28 10:48:50 +00:00
return
pr.dict.add((key, val, ))
2021-08-28 10:48:50 +00:00
proc symbol*(s: string; E = void): Preserve {.inline.} =
2021-09-01 09:37:49 +00:00
## Create a Preserves symbol value.
Preserve(kind: pkSymbol, symbol: s)
2021-09-01 09:37:49 +00:00
proc initRecord*(label: Preserve; args: varargs[Preserve]): Preserve =
2021-09-01 09:37:49 +00:00
## Create a Preserves record value.
2021-08-28 10:48:50 +00:00
result = Preserve(kind: pkRecord,
record: newSeqOfCap[Preserve](1+args.len))
for arg in args:
result.record.add(arg)
result.record.add(label)
2021-09-01 09:37:49 +00:00
proc initRecord*(label: string; args: varargs[Preserve, toPreserve]): Preserve =
## Convert ``label`` to a symbol and create a new record.
runnableExamples:
assert($initRecord("foo", 1, 2.0) == "<foo 1 2.0f>")
initRecord(symbol(label), args)
proc initSet*(): Preserve = Preserve(kind: pkSet)
2021-09-01 09:37:49 +00:00
## Create a Preserves set value.
proc initDictionary*(): Preserve = Preserve(kind: pkDictionary)
2021-09-01 09:37:49 +00:00
## Create a Preserves dictionary value.
proc len*(pr: Preserve): int =
## Return the shallow count of values in ``pr``, that is the number of
2021-09-01 09:37:49 +00:00
## fields in a record, items in a sequence, items in a set, or key-value pairs
## in a dictionary.
case pr.kind
of pkRecord: pr.record.len.pred
of pkSequence: pr.sequence.len
of pkSet: pr.set.len
of pkDictionary: pr.dict.len
2021-08-28 10:48:50 +00:00
else: 0
iterator items*(pr: Preserve): Preserve =
## Shallow iterator over `pr`, yield the fields in a record,
2021-09-01 09:37:49 +00:00
## the items of a sequence, the items of a set, or the pairs
## of a dictionary.
case pr.kind
of pkRecord:
for i in 0..pr.record.high.pred:
yield pr.record[i]
of pkSequence:
for e in pr.sequence.items: yield e
of pkSet:
for e in pr.set.items: yield e
of pkDictionary:
for (k, v) in pr.dict.items:
yield k # key can be an arbitrary Preserve
yield v
else: discard
2021-09-23 11:32:04 +00:00
func isBoolean*(pr: Preserve): bool {.inline.} = pr.kind == pkBoolean
## Check if ``pr`` is a Preserve boolean.
func isFalse*(pr: Preserve): bool =
## Check if ``pr`` is equivalent to the zero-initialized ``Preserve``.
pr.kind == pkBoolean and pr.bool == false
2021-08-28 10:48:50 +00:00
2021-09-23 11:32:04 +00:00
func isFloat*(pr: Preserve): bool {.inline.} = pr.kind == pkFloat
## Check if ``pr`` is a Preserve float.
func isDouble*(pr: Preserve): bool {.inline.} = pr.kind == pkDouble
## Check if ``pr`` is a Preserve double.
func isInteger*(pr: Preserve): bool {.inline.} = pr.kind in {pkSignedInteger, pkBigInteger}
## Check if ``pr`` is a Preserve double.
func isString*(pr: Preserve): bool {.inline.} = pr.kind == pkString
## Check if ``pr`` is a Preserve text string.
func isByteString*(pr: Preserve): bool {.inline.} = pr.kind == pkByteString
## Check if ``pr`` is a Preserves byte string.
func isSymbol*(pr: Preserve): bool {.inline.} = pr.kind == pkSymbol
## Check if `pr` is a Preserves symbol.
2021-09-23 11:32:04 +00:00
func isSymbol*(pr: Preserve; sym: string): bool {.inline.} =
## Check if ``pr`` is a Preserves symbol of ``sym``.
(pr.kind == pkSymbol) and (pr.symbol == sym)
2021-08-28 10:48:50 +00:00
2021-09-23 11:32:04 +00:00
func isRecord*(pr: Preserve): bool {.inline.} = (pr.kind == pkRecord) and (pr.record.len > 0)
## Check if ``pr`` is a Preserves record.
proc isSequence*(pr: Preserve): bool {.inline.} = pr.kind == pkSequence
## Check if ``pr`` is a Preserves sequence.
proc isSet*(pr: Preserve): bool {.inline.} = pr.kind == pkSet
## Check if ``pr`` is a Preserves set.
proc isDictionary*(pr: Preserve): bool {.inline.} = pr.kind == pkDictionary
## Check if ``pr`` is a Preserves dictionary.
2021-06-24 15:31:30 +00:00
2021-09-23 11:32:04 +00:00
func isEmbedded*(pr: Preserve): bool {.inline.} = pr.embedded
## Check if ``pr`` is an embedded value.
proc label*(pr: Preserve): Preserve {.inline.} =
2021-09-01 09:37:49 +00:00
## Return the label of record value.
pr.record[pr.record.high]
proc arity*(pr: Preserve): int {.inline.} =
## Return the number of fields in record `pr`.
pred(pr.record.len)
proc fields*(pr: Preserve): seq[Preserve] {.inline.} =
## Return the fields of a record value.
pr.record[0..pr.record.high.pred]
iterator fields*(pr: Preserve): Preserve =
## Iterate the fields of a record value.
for i in 0..<pr.record.high: yield pr.record[i]
2021-06-02 13:51:36 +00:00
proc writeVarint(s: Stream; n: int) =
var n = n
while true:
let c = int8(n and 0x7f)
n = n shr 7
if n == 0:
s.write((char)c.char)
break
else:
s.write((char)c or 0x80)
proc readVarint(s: Stream): int =
var shift: int
while shift < (9*8):
let c = s.readChar.int
result = result or ((c and 0x7f) shl shift)
if (c and 0x80) == 0:
break
shift.inc 7
proc write*(str: Stream; pr: Preserve) =
2021-09-01 09:37:49 +00:00
## Write the binary-encoding of a Preserves value to a stream.
if pr.embedded: str.write(0x86'u8)
case pr.kind:
2021-06-02 13:51:36 +00:00
of pkBoolean:
case pr.bool
2021-06-02 13:51:36 +00:00
of false: str.write(0x80'u8)
of true: str.write(0x81'u8)
of pkFloat:
str.write(0x82'u8)
when system.cpuEndian == bigEndian:
str.write(pr.float)
2021-06-02 13:51:36 +00:00
else:
var be: float32
swapEndian32(be.addr, pr.float.unsafeAddr)
2021-06-02 13:51:36 +00:00
str.write(be)
of pkDouble:
str.write(0x83'u8)
when system.cpuEndian == bigEndian:
str.write(pr.double)
2021-06-02 13:51:36 +00:00
else:
var be: float64
swapEndian64(be.addr, pr.double.unsafeAddr)
2021-06-02 13:51:36 +00:00
str.write(be)
of pkSignedInteger:
if (-3 <= pr.int) and (pr.int <= 12):
str.write(0x90'i8 or int8(if pr.int < 0: pr.int + 16 else: pr.int))
2021-06-02 13:51:36 +00:00
else:
var bitCount = 1'u8
if pr.int < 0:
while ((not pr.int) shr bitCount) != 0:
2021-06-02 13:51:36 +00:00
inc(bitCount)
else:
while (pr.int shr bitCount) != 0:
2021-06-02 13:51:36 +00:00
inc(bitCount)
var byteCount = (bitCount + 8) div 8
str.write(0xa0'u8 or (byteCount - 1))
proc write(n: uint8; i: BiggestInt) =
2021-06-02 13:51:36 +00:00
if n > 0:
write(n.pred, i shr 8)
str.write(i.uint8)
write(byteCount, pr.int)
2021-06-02 13:51:36 +00:00
of pkBigInteger:
doAssert(Negative notin pr.bigint.flags, "negative big integers not implemented")
var bytes = newSeqOfCap[uint8](pr.bigint.limbs.len * 4)
2021-06-02 13:51:36 +00:00
var begun = false
for i in countdown(pr.bigint.limbs.high, 0):
let limb = pr.bigint.limbs[i]
2021-06-02 13:51:36 +00:00
for j in countdown(24, 0, 8):
let b = uint8(limb shr j)
begun = begun or (b != 0)
if begun:
bytes.add(b)
if bytes.len <= 16:
str.write(0xa0'u8 or bytes.high.uint8)
else:
str.write(0xb0'u8)
str.writeVarint(bytes.len)
str.write(cast[string](bytes))
of pkString:
str.write(0xb1'u8)
str.writeVarint(pr.string.len)
str.write(pr.string)
2021-06-02 13:51:36 +00:00
of pkByteString:
str.write(0xb2'u8)
str.writeVarint(pr.bytes.len)
str.write(cast[string](pr.bytes))
2021-06-02 13:51:36 +00:00
of pkSymbol:
str.write(0xb3'u8)
str.writeVarint(pr.symbol.len)
str.write(pr.symbol)
2021-06-02 13:51:36 +00:00
of pkRecord:
assert(pr.record.len > 0)
2021-06-02 13:51:36 +00:00
str.write(0xb4'u8)
str.write(pr.record[pr.record.high])
for i in 0..<pr.record.high:
str.write(pr.record[i])
2021-06-02 13:51:36 +00:00
str.write(0x84'u8)
of pkSequence:
str.write(0xb5'u8)
for e in pr.sequence:
2021-06-02 13:51:36 +00:00
str.write(e)
str.write(0x84'u8)
of pkSet:
str.write(0xb6'u8)
for val in pr.set.items:
str.write(val)
2021-06-02 13:51:36 +00:00
str.write(0x84'u8)
of pkDictionary:
str.write(0xb7'u8)
for (key, value) in pr.dict.items:
2021-06-02 13:51:36 +00:00
str.write(key)
str.write(value)
str.write(0x84'u8)
proc encode*(pr: Preserve): seq[byte] =
2021-09-01 09:37:49 +00:00
## Return the binary-encoding of a Preserves value.
2021-07-16 17:11:19 +00:00
let s = newStringStream()
s.write pr
2021-07-16 17:11:19 +00:00
s.setPosition 0
result = cast[seq[byte]](s.readAll)
2021-07-16 17:11:19 +00:00
proc decodePreserves*(s: Stream): Preserve =
2021-09-01 09:37:49 +00:00
## Decode a Preserves value from a binary-encoded stream.
2021-06-02 13:51:36 +00:00
proc assertStream(check: bool) =
if not check:
raise newException(ValueError, "invalid Preserves stream")
const endMarker = 0x84
let tag = s.readUint8()
case tag
of 0x80: result = Preserve(kind: pkBoolean, bool: false)
of 0x81: result = Preserve(kind: pkBoolean, bool: true)
2021-06-02 13:51:36 +00:00
of 0x82:
when system.cpuEndian == bigEndian:
result = Preserve(kind: pkFloat, float: s.readFloat32())
2021-06-02 13:51:36 +00:00
else:
result = Preserve(kind: pkFloat)
2021-06-02 13:51:36 +00:00
var be = s.readFloat32()
swapEndian32(result.float.addr, be.addr)
of 0x83:
when system.cpuEndian == bigEndian:
result = Preserve(kind: pkDouble, double: s.readFloat64())
2021-06-02 13:51:36 +00:00
else:
result = Preserve(kind: pkDouble)
2021-06-02 13:51:36 +00:00
var be = s.readFloat64()
swapEndian64(result.double.addr, be.addr)
2021-08-28 10:48:50 +00:00
of 0x86:
result = decodePreserves(s)
result.embedded = true
2021-06-02 13:51:36 +00:00
of 0xb1:
result = Preserve(kind: pkString)
2021-06-02 13:51:36 +00:00
let len = s.readVarint()
result.string = s.readStr(len)
of 0xb2:
result = Preserve(kind: pkByteString)
2021-06-02 13:51:36 +00:00
let len = s.readVarint()
result.bytes = cast[seq[byte]](s.readStr(len))
of 0xb3:
let len = s.readVarint()
result = Preserve(kind: pkSymbol, symbol: s.readStr(len))
2021-06-02 13:51:36 +00:00
of 0xb4:
result = Preserve(kind: pkRecord)
var label = decodePreserves(s)
2021-06-02 13:51:36 +00:00
while s.peekUint8() != endMarker:
result.record.add decodePreserves(s)
2021-08-28 10:48:50 +00:00
result.record.add(move label)
2021-06-02 13:51:36 +00:00
discard s.readUint8()
of 0xb5:
result = Preserve(kind: pkSequence)
2021-06-02 13:51:36 +00:00
while s.peekUint8() != endMarker:
result.sequence.add decodePreserves(s)
2021-06-02 13:51:36 +00:00
discard s.readUint8()
of 0xb6:
result = Preserve(kind: pkSet)
2021-06-02 13:51:36 +00:00
while s.peekUint8() != endMarker:
incl(result, decodePreserves(s))
2021-06-02 13:51:36 +00:00
discard s.readUint8()
of 0xb7:
result = Preserve(kind: pkDictionary)
2021-06-02 13:51:36 +00:00
while s.peekUint8() != endMarker:
result[decodePreserves(s)] = decodePreserves(s)
2021-06-02 13:51:36 +00:00
discard s.readUint8()
of 0xb0:
let len = s.readVarint()
result = Preserve(kind: pkBigInteger, bigint: initBigint 0)
for _ in 1..len:
2021-06-02 13:51:36 +00:00
result.bigint = (result.bigint shl 8) + s.readUint8().int32
2021-08-28 10:48:50 +00:00
of endMarker:
assertStream(false)
2021-06-02 13:51:36 +00:00
else:
case 0xf0 and tag
of 0x90:
var n = tag.BiggestInt
result = Preserve(kind: pkSignedInteger,
2021-06-02 13:51:36 +00:00
int: n - (if n > 0x9c: 0xa0 else: 0x90))
of 0xa0:
let len = (tag.int and 0x0f) + 1
if len <= 8:
result = Preserve(kind: pkSignedInteger, int: s.readUint8().BiggestInt)
2021-06-02 13:51:36 +00:00
if (result.int and 0x80) != 0: result.int.dec(0x100)
for i in 1..<len:
result.int = (result.int shl 8) or s.readUint8().BiggestInt
else:
result = Preserve(kind: pkBigInteger)
2021-06-02 13:51:36 +00:00
for i in 0..<len:
result.bigint = (result.bigint shl 8) + s.readUint8().int32
else:
assertStream(false)
proc decodePreserves*(s: string): Preserve =
2021-09-01 09:37:49 +00:00
## Decode a string of binary-encoded Preserves.
s.newStringStream.decodePreserves
2021-07-16 17:11:19 +00:00
proc decodePreserves*(s: seq[byte]): Preserve =
2021-09-01 09:37:49 +00:00
## Decode a byte-string of binary-encoded Preserves.
cast[string](s).decodePreserves
2021-07-15 12:24:30 +00:00
template record*(label: string) {.pragma.}
2021-09-01 09:37:49 +00:00
## Serialize this object or tuple as a record. See ``toPreserve``.
2021-07-01 10:47:30 +00:00
template unpreservable*() {.pragma.}
2021-09-01 09:37:49 +00:00
## Pragma to forbid a type from being converted by ``toPreserve``.
2021-07-01 10:47:30 +00:00
proc toPreserve*[T](x: T): Preserve =
2021-09-01 09:37:49 +00:00
## Serializes ``x`` to Preserves. Can be customized by defining
## ``toPreserveHook(x: T)`` in the calling scope.
when (T is Preserve): result = x
elif compiles(toPreserveHook(x)):
result = toPreserveHook(x)
elif T is Bigint:
result = Preserve(kind: pkBigInteger, bigint: x)
elif T is seq[byte]:
result = Preserve(kind: pkByteString, bytes: x)
elif T is array | seq:
result = Preserve(kind: pkSequence, sequence: newSeqOfCap[Preserve](x.len))
for v in x.items: result.sequence.add(toPreserve(v))
elif T is bool:
result = Preserve(kind: pkBoolean, bool: x)
elif T is distinct:
result = toPreserve(x.distinctBase)
elif T is float:
result = Preserve(kind: pkFloat, float: x)
elif T is float64:
result = Preserve(kind: pkDouble, double: x)
2021-06-24 15:31:30 +00:00
elif T is object | tuple:
when T.hasCustomPragma(unpreservable): {.fatal: "unpreservable type".}
2021-07-01 10:47:30 +00:00
elif T.hasCustomPragma(record):
result = Preserve(kind: pkRecord)
for _, f in x.fieldPairs: result.record.add(toPreserve(f))
result.record.add(symbol(T.getCustomPragmaVal(record)))
else:
result = Preserve(kind: pkDictionary)
2021-08-28 10:48:50 +00:00
for k, v in x.fieldPairs:
result[symbol(k)] = toPreserve(v)
elif T is Ordinal:
result = Preserve(kind: pkSignedInteger, int: x.ord.BiggestInt)
elif T is ptr | ref:
if system.`==`(x, nil): result = symbol("null")
else: result = toPreserve(x[])
elif T is string:
result = Preserve(kind: pkString, string: x)
elif T is SomeInteger:
result = Preserve(kind: pkSignedInteger, int: x.BiggestInt)
else:
raiseAssert("unpreservable type" & $T)
2021-06-02 13:51:36 +00:00
2021-06-24 15:31:30 +00:00
proc toPreserveHook*[T](set: HashSet[T]): Preserve =
2021-09-01 09:37:49 +00:00
## Hook for preserving ``HashSet``.
2021-06-24 15:31:30 +00:00
Preserve(kind: pkSet, set: set.map(toPreserve))
2021-09-01 09:37:49 +00:00
proc toPreserveHook*[A, B](table: Table[A, B]|TableRef[A, B]): Preserve =
## Hook for preserving ``Table``.
result = initDictionary()
for k, v in table.pairs: result[k.toPreserve] = v.toPreserve
2021-08-11 11:00:32 +00:00
proc fromPreserve*[T](v: var T; pr: Preserve): bool =
2021-09-01 09:37:49 +00:00
## Inplace version of `preserveTo`. Returns ``true`` on
## a complete match, otherwise returns ``false``.
# TODO: {.raises: [].}
runnableExamples:
2021-09-01 09:37:49 +00:00
import preserves, preserves/parse
type Foo {.record: "foo".} = object
2021-09-01 09:37:49 +00:00
x, y: int
var foo: Foo
2021-09-01 09:37:49 +00:00
assert(fromPreserve(foo, parsePreserves("""<foo 1 2>""")))
assert(foo.x == 1)
assert(foo.y == 2)
type Value = Preserve
2021-08-28 10:48:50 +00:00
when T is Value:
v = pr
result = true
elif compiles(fromPreserveHook(v, pr)):
result = fromPreserveHook(v, pr)
2021-06-24 15:31:30 +00:00
elif T is Bigint:
case pr.kind
of pkSignedInteger:
v = initBigint(pr.int)
result = true
of pkBigInteger:
v = pr.bigint
result = true
else: disard
2021-06-24 15:31:30 +00:00
elif T is bool:
if pr.kind == pkBoolean:
v = pr.bool
result = true
2021-06-24 15:31:30 +00:00
elif T is SomeInteger:
if pr.kind == pkSignedInteger:
v = T(pr.int)
result = true
2021-06-24 15:31:30 +00:00
elif T is float:
if pr.kind == pkFloat:
v = pr.float
result = true
2021-06-24 15:31:30 +00:00
elif T is seq:
if T is seq[byte] and pr.kind == pkByteString:
v = pr.bytes
result = true
elif pr.kind == pkSequence:
v.setLen(pr.len)
result = true
for i, e in pr.sequence:
result = result and fromPreserve(v[i], e)
2021-06-24 15:31:30 +00:00
elif T is float64:
case pr.kind
of pkFloat:
v = pr.float
result = true
of pkDouble:
v = pr.double
result = true
elif T is object | tuple:
case pr.kind
of pkRecord:
when T.hasCustomPragma(record):
if pr.record[pr.record.high].isSymbol T.getCustomPragmaVal(record):
result = true
var i = 0
for fname, field in v.fieldPairs:
if not result or (i == pr.record.high): break
result = result and fromPreserve(field, pr.record[i])
inc(i)
result = result and (i == pr.record.high) # arity equivalence check=
of pkDictionary:
result = true
2021-08-28 10:48:50 +00:00
var fieldCount = 0
for key, val in v.fieldPairs:
2021-08-28 10:48:50 +00:00
inc fieldCount
for (pk, pv) in pr.dict.items:
var sym = symbol(key)
2021-08-28 10:48:50 +00:00
if sym == pk:
result = result and fromPreserve(val, pv)
break
result = result and pr.dict.len == fieldCount
else: discard
elif T is Ordinal | SomeInteger:
if pr.kind == pkSignedInteger:
v = (T)pr.int
result = true
2021-08-11 11:00:32 +00:00
elif T is ref:
if pr != symbol("null"):
new v
result = fromPreserve(v[], pr)
2021-06-24 15:31:30 +00:00
elif T is string:
if pr.kind == pkString:
v = pr.string
result = true
elif T is distinct:
result = fromPreserve(result.distinctBase, pr)
2021-06-24 15:31:30 +00:00
else:
raiseAssert("no conversion of type Preserve to " & $T)
2021-09-01 09:37:49 +00:00
if not result: reset v
2021-06-24 15:31:30 +00:00
proc preserveTo*(pr: Preserve; T: typedesc): Option[T] =
2021-06-24 15:31:30 +00:00
## Reverse of `toPreserve`.
2021-09-01 09:37:49 +00:00
##
# TODO: {.raises: [].}
runnableExamples:
import std/options, preserves, preserves/parse
type Foo {.record: "foo".} = object
2021-09-01 09:37:49 +00:00
x, y: int
assert(parsePreserves("""<foo "abc">""").preserveTo(Foo).isNone)
2021-09-01 09:37:49 +00:00
assert(parsePreserves("""<bar 1 2>""").preserveTo(Foo).isNone)
assert(parsePreserves("""<foo 1 2>""").preserveTo(Foo).isSome)
var v: T
if fromPreserve(v, pr):
result = some(move v)
proc fromPreserveHook*[A,B,E](t: var Table[A,B]|TableRef[A,B]; pr: Preserve): bool =
if pr.isDictionary:
for k, v in pr.pairs:
t[preserveTo(k, A)] = preserveTo(v, B)
result = true
2021-08-11 11:00:32 +00:00
proc concat(result: var string; pr: Preserve) =
if pr.embedded: result.add("#!")
case pr.kind:
2021-08-28 10:48:50 +00:00
of pkBoolean:
case pr.bool
2021-08-28 10:48:50 +00:00
of false: result.add "#f"
of true: result.add "#t"
of pkFloat:
result.add($pr.float & "f")
2021-08-28 10:48:50 +00:00
of pkDouble:
result.add $pr.double
2021-08-28 10:48:50 +00:00
of pkSignedInteger:
result.add $pr.int
2021-08-28 10:48:50 +00:00
of pkBigInteger:
result.add $pr.bigint
2021-08-28 10:48:50 +00:00
of pkString:
result.add escapeJson(pr.string)
2021-08-28 10:48:50 +00:00
of pkByteString:
for b in pr.bytes:
2021-08-28 10:48:50 +00:00
if b.char notin {'\20'..'\21', '#'..'[', ']'..'~'}:
result.add("#[") #]#
result.add(base64.encode(pr.bytes))
2021-08-28 10:48:50 +00:00
result.add(']')
return
result.add("#\"")
result.add(cast[string](pr.bytes))
2021-08-28 10:48:50 +00:00
result.add('"')
of pkSymbol:
result.add(escapeJsonUnquoted(pr.symbol))
2021-08-28 10:48:50 +00:00
of pkRecord:
assert(pr.record.len > 0)
2021-08-28 10:48:50 +00:00
result.add('<')
result.concat(pr.record[pr.record.high])
for i in 0..<pr.record.high:
2021-08-28 10:48:50 +00:00
result.add(' ')
result.concat(pr.record[i])
2021-08-28 10:48:50 +00:00
result.add('>')
of pkSequence:
result.add('[')
for i, val in pr.sequence:
2021-08-28 10:48:50 +00:00
if i > 0:
result.add(' ')
result.concat(val)
result.add(']')
of pkSet:
result.add("#{")
for val in pr.set.items:
2021-08-28 10:48:50 +00:00
result.concat(val)
result.add(' ')
if pr.set.len > 1:
2021-08-28 10:48:50 +00:00
result.setLen(result.high)
result.add('}')
of pkDictionary:
result.add('{')
var i = 0
for (key, value) in pr.dict.items:
2021-08-28 10:48:50 +00:00
if i > 0:
result.add(' ')
result.concat(key)
result.add(": ")
result.concat(value)
inc i
result.add('}')
2021-08-11 11:00:32 +00:00
proc `$`*(pr: Preserve): string = concat(result, pr)
## Generate the textual representation of ``pr``.