# SPDX-FileCopyrightText: ☭ Emery Hemingway # SPDX-License-Identifier: Unlicense import std/[assertions, endians, streams] import bigints import ./values proc writeVarint(s: Stream; n: Natural) = var n = n while n > 0x7f: s.write(uint8 n or 0x80) n = n shr 7 s.write(uint8 n and 0x7f) proc write*(str: Stream; pr: Value) = ## Write the binary-encoding of a Preserves value to a stream. if pr.embedded: str.write(0x86'u8) case pr.kind: of pkBoolean: case pr.bool of false: str.write(0x80'u8) of true: str.write(0x81'u8) of pkFloat: str.write("\x87\x08") when system.cpuEndian == bigEndian: str.write(pr.double) else: var be: float64 swapEndian64(be.addr, pr.float.unsafeAddr) str.write(be) of pkRegister: if pr.register == 0: str.write("\xb0\x00") else: const bufLen = sizeof(int) var buf: array[bufLen, byte] when bufLen == 4: bigEndian32(addr buf[0], addr pr.register) elif bufLen == 8: bigEndian64(addr buf[0], addr pr.register) else: {.error: "int size " & $bufLen & " not supported here".} if buf[0] != 0x00 and buf[0] != 0xff: str.write(cast[string](buf)) # dumbass hex conversion else: var start = 0 while start < buf.high and buf[0] == buf[succ start]: inc start if start < buf.high and (buf[succ start] and 0x80) == (buf[0] and 0x80): inc start str.write('\xb0') str.write(uint8(bufLen - start)) str.write(cast[string](buf[start.. 0) str.write(0xb4'u8) str.write(pr.record[pr.record.high]) for i in 0..