Add ReadRemaining helper (#27)

* Add ReadRemaining helper

* Add readBytes helper

* Add size check
This commit is contained in:
iteyelmp 2026-07-06 15:44:10 +08:00 committed by GitHub
parent 10a17d62aa
commit d24560ad65
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -24,6 +24,9 @@ func (bb *ByteBuffer) GetOffset() int {
} }
func (bb *ByteBuffer) getBytes(size int) ([]byte, error) { func (bb *ByteBuffer) getBytes(size int) ([]byte, error) {
if size < 0 {
return nil, fmt.Errorf("deser: negative size %d is invalid", size)
}
if size > bb.size-bb.position { if size > bb.size-bb.position {
return nil, fmt.Errorf("deser: buffer is shorter than expected") return nil, fmt.Errorf("deser: buffer is shorter than expected")
} }
@ -120,3 +123,14 @@ func (bb *ByteBuffer) GetVarBytes(byteSizeOfSliceLen int) ([]byte, error) {
func (bb *ByteBuffer) Remaining() int { func (bb *ByteBuffer) Remaining() int {
return bb.size - bb.position return bb.size - bb.position
} }
// ReadRemaining returns all unread bytes in the buffer.
// Used by types that need to consume the rest of the buffer (e.g. opaque
// placeholder types for forward-compatible deserialization).
func (bb *ByteBuffer) ReadRemaining() ([]byte, error) {
return bb.getBytes(bb.Remaining())
}
func (bb *ByteBuffer) ReadBytes(n int) ([]byte, error) {
return bb.getBytes(n)
}