Fix varint encoding and decoding
This commit is contained in:
parent
5e2cd329f6
commit
52faec6e43
|
@ -1,6 +1,6 @@
|
|||
# Package
|
||||
|
||||
version = "20230817"
|
||||
version = "20230823"
|
||||
author = "Emery Hemingway"
|
||||
description = "data model and serialization format"
|
||||
license = "Unlicense"
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# SPDX-FileCopyrightText: 2021 ☭ Emery Hemingway
|
||||
# SPDX-FileCopyrightText: ☭ Emery Hemingway
|
||||
# SPDX-License-Identifier: Unlicense
|
||||
|
||||
import std/[base64, endians, hashes, options, sets, sequtils, streams, strutils, tables, typetraits]
|
||||
|
@ -526,25 +526,23 @@ proc unembed*[E](pr: Preserve[E]): E =
|
|||
raise newException(ValueError, "not an embedded value")
|
||||
pr.embed
|
||||
|
||||
proc writeVarint(s: Stream; n: int) =
|
||||
proc writeVarint(s: Stream; n: Natural) =
|
||||
var n = n
|
||||
while true:
|
||||
let c = int8(n and 0x7f)
|
||||
while n > 0x7f:
|
||||
s.write(uint8 n or 0x80)
|
||||
n = n shr 7
|
||||
if n == 0:
|
||||
s.write((char)c.char)
|
||||
break
|
||||
else:
|
||||
s.write((char)c or 0x80)
|
||||
s.write(uint8 n and 0x7f)
|
||||
|
||||
proc readVarint(s: Stream): int =
|
||||
var shift = 0
|
||||
while shift < (9*8):
|
||||
let c = s.readInt8
|
||||
proc readVarint(s: Stream): uint =
|
||||
var
|
||||
shift = 0
|
||||
c = uint s.readUint8
|
||||
if c == 0x80: raise newException(ValueError, "invalid Preserves data")
|
||||
while (c and 0x80) == 0x80:
|
||||
result = result or ((c and 0x7f) shl shift)
|
||||
if (c and 0x80) == 0:
|
||||
break
|
||||
inc(shift, 7)
|
||||
c = uint s.readUint8
|
||||
result = result or (c shl shift)
|
||||
|
||||
proc write*[E](str: Stream; pr: Preserve[E]) =
|
||||
## Write the binary-encoding of a Preserves value to a stream.
|
||||
|
@ -792,7 +790,7 @@ proc decode*(dec: var BufferedDecoder; E = void): (bool, Preserve[E]) =
|
|||
dec.stream.data.setLen(0)
|
||||
dec.appendPosition = 0
|
||||
dec.decodePosition = 0
|
||||
except IOError, ValueError:
|
||||
except IOError:
|
||||
discard
|
||||
|
||||
template preservesRecord*(label: string) {.pragma.}
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
include_rules
|
||||
: foreach test_*.nim |> !nim_run |>
|
||||
: foreach t*.nim |> !nim_run |>
|
||||
|
|
Loading…
Reference in New Issue