From b92f8368c1c98cac62852d33f5f77df47a7c3306 Mon Sep 17 00:00:00 2001 From: Dmitriy Ryajov Date: Sun, 12 Apr 2020 23:00:17 -0600 Subject: [PATCH] implement streaming length prefixed parser --- libp2p/stream/lenprefixed.nim | 1 - libp2p/stream/ringbuffer.nim | 27 +++++++++++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/libp2p/stream/lenprefixed.nim b/libp2p/stream/lenprefixed.nim index 11d402874..fe777a4fa 100644 --- a/libp2p/stream/lenprefixed.nim +++ b/libp2p/stream/lenprefixed.nim @@ -72,7 +72,6 @@ proc read(lp: LenPrefixed, lp.mode = Mode.Reading else: result = lp.readBuff.read(lp.size) - echo result lp.size -= result.len if lp.size == 0: lp.mode = Mode.Decoding diff --git a/libp2p/stream/ringbuffer.nim b/libp2p/stream/ringbuffer.nim index 13c4d9309..0d54bf26d 100644 --- a/libp2p/stream/ringbuffer.nim +++ b/libp2p/stream/ringbuffer.nim @@ -110,7 +110,7 @@ proc read*[T](b: var RingBuffer[T], size: int = -1): seq[T] = ## assert(buff.read() == @[...]) ## var isize = size - if size < 0: + if size < 0 or size > b.len: isize = b.len result = newSeq[T](isize) @@ -131,7 +131,9 @@ proc clear*[T](b: var RingBuffer[T]) = b.buff.setLen(0) when isMainModule: - block Basic: + + block: + ## Basic tests var buff = RingBuffer[char].init(10) var data = newSeq[char](10) @@ -194,7 +196,23 @@ when isMainModule: assert(buff.head == 4, "head should be 9") assert(buff.tail == 4, "tail should be 9") - block Errors: + block: + ## Complex reading scenarios + var buff = RingBuffer[char].init(10) + var data = newSeq[char](10) + + buff.append(@['a']) + assert(buff.len == 1, "len should be 1") + assert(buff.head == 0, "head should be 0") + assert(buff.tail == 1, "tail should be 1") + + assert(buff.read(5) == @['a']) + assert(buff.len == 0, "len should be 0") + assert(buff.head == 1, "head should be 9") + assert(buff.tail == 1, "tail should be 9") + + block: + ## Error checking var buff = RingBuffer[char].init(5) try: @@ -219,7 +237,8 @@ when isMainModule: except CatchableError as exc: assert(true) - block Cleanup: + block: + ## Cleanup var buff = RingBuffer[char].init(5) buff.reset()