harden `ProtoBuffer.finish()` assert (#672)

This hardens the length check in `ProtoBuffer.finish` to account for
passed `options`.
This commit is contained in:
Etan Kissling 2021-12-13 19:31:05 +01:00 committed by GitHub
parent 8fe44e35c2
commit 0be9180977
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 1 deletions

View File

@ -265,8 +265,8 @@ proc write*(pb: var ProtoBuffer, field: int, value: ProtoBuffer) {.inline.} =
proc finish*(pb: var ProtoBuffer) = proc finish*(pb: var ProtoBuffer) =
## Prepare protobuf's buffer ``pb`` for writing to stream. ## Prepare protobuf's buffer ``pb`` for writing to stream.
doAssert(len(pb.buffer) > 0)
if WithVarintLength in pb.options: if WithVarintLength in pb.options:
doAssert(len(pb.buffer) >= 10)
let size = uint(len(pb.buffer) - 10) let size = uint(len(pb.buffer) - 10)
let pos = 10 - vsizeof(size) let pos = 10 - vsizeof(size)
var usedBytes = 0 var usedBytes = 0
@ -274,14 +274,17 @@ proc finish*(pb: var ProtoBuffer) =
doAssert(res.isOk()) doAssert(res.isOk())
pb.offset = pos pb.offset = pos
elif WithUint32BeLength in pb.options: elif WithUint32BeLength in pb.options:
doAssert(len(pb.buffer) >= 4)
let size = uint(len(pb.buffer) - 4) let size = uint(len(pb.buffer) - 4)
pb.buffer[0 ..< 4] = toBytesBE(uint32(size)) pb.buffer[0 ..< 4] = toBytesBE(uint32(size))
pb.offset = 4 pb.offset = 4
elif WithUint32LeLength in pb.options: elif WithUint32LeLength in pb.options:
doAssert(len(pb.buffer) >= 4)
let size = uint(len(pb.buffer) - 4) let size = uint(len(pb.buffer) - 4)
pb.buffer[0 ..< 4] = toBytesLE(uint32(size)) pb.buffer[0 ..< 4] = toBytesLE(uint32(size))
pb.offset = 4 pb.offset = 4
else: else:
doAssert(len(pb.buffer) > 0)
pb.offset = 0 pb.offset = 0
proc getHeader(data: var ProtoBuffer, proc getHeader(data: var ProtoBuffer,