File tree Expand file tree Collapse file tree 2 files changed +28
-19
lines changed
Expand file tree Collapse file tree 2 files changed +28
-19
lines changed Original file line number Diff line number Diff line change 5858 when defined (debug):
5959 state: VarintState
6060
61+ VarintBuffer * = object
62+ bytes* : array [10 , byte ]
63+ totalBytesWritten* : int
64+
65+ func append * (buf: var VarintBuffer , b: byte ) =
66+ buf.bytes[buf.totalBytesWritten] = b
67+ inc buf.totalBytesWritten
68+
69+ template writtenBytes * (buf: VarintBuffer ): auto =
70+ buf.bytes.toOpenArray (0 , buf.totalBytesWritten - 1 )
71+
6172func maxBits (T: type VarintParser ): uint8 {.compileTime .} =
6273 when T.flavour == ProtoBuf :
6374 uint8 (sizeof (T.IntType ) * 8 )
@@ -199,3 +210,12 @@ func vsizeof*(x: SomeInteger): int {.inline.} =
199210 if x == 0 : 1
200211 else : (log2trunc (x) + 1 + 7 - 1 ) div 7
201212
213+ template varintBytes * (x: SomeInteger ,
214+ flavour: static VarintFlavour = ProtoBuf ): untyped =
215+ var buf: VarintBuffer
216+ buf.appendVarint (x, flavour)
217+ # TODO : toOpenArray doesn't work here for some reason, so we must
218+ # use the less optimal approach of allocating a sequence copy.
219+ # buf.bytes.toOpenArray(0, buf.totalBytesWritten - 1)
220+ buf.bytes[0 .. buf.totalBytesWritten - 1 ]
221+
Original file line number Diff line number Diff line change @@ -25,42 +25,31 @@ const edgeValues = {
2525 0x FFFF_FFFF_FFFF_FFFF 'u64 : " ffffffffffffffffff01"
2626}
2727
28- type
29- PseudoStream = object
30- bytes: array [12 , byte ]
31- bytesWritten: int
32-
33- func append (s: var PseudoStream , b: byte ) =
34- s.bytes[s.bytesWritten] = b
35- inc s.bytesWritten
36-
37- template writtenData (s: PseudoStream ): auto =
38- s.bytes.toOpenArray (0 , s.bytesWritten - 1 )
39-
4028suite " varints" :
4129 template roundtipTest (val) =
42- var s {.inject .}: PseudoStream
30+ var s {.inject .}: VarintBuffer
4331 s.appendVarint val
4432
4533 var roundtripVal: uint64
4634 let bytesRead = readVarint (s.bytes, roundtripVal)
4735
4836 check:
4937 val == roundtripVal
50- bytesRead == s.bytesWritten
38+ bytesRead == s.totalBytesWritten
5139 bytesRead == vsizeof (val)
5240
5341 test " [ProtoBuf] Success edge cases test" :
5442 for pair in edgeValues:
5543 let (val, hex) = pair
5644 roundtipTest val
5745 check:
58- s.bytesWritten == hex.len div 2
59- toHex (s.writtenData) == hex
46+ s.totalBytesWritten == hex.len div 2
47+ toHex (s.writtenBytes) == hex
48+ toHex (val.varintBytes) == hex
6049
6150 test " [ProtoBuf] random values" :
62- for i in 0 .. 10000 :
63- let val = rand (0 'u64 .. 0x FFFF_FFFF_FFFF_FFFE 'u64 )
64- roundtipTest val
51+ for i in 0 .. 10000 :
52+ let val = rand (0 'u64 .. 0x FFFF_FFFF_FFFF_FFFE 'u64 )
53+ roundtipTest val
6554
6655 # TODO Migrate the rest of the LibP2P test cases
You can’t perform that action at this time.
0 commit comments