mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-03-21 18:38:07 +00:00
rlp: add Size method to EncoderBuffer (#34052)
The new method returns the size of the written data, excluding any unfinished list structure.
This commit is contained in:
parent
fd859638bd
commit
35b91092c5
2 changed files with 43 additions and 0 deletions
|
|
@ -366,6 +366,16 @@ func (w *EncoderBuffer) AppendToBytes(dst []byte) []byte {
|
|||
return out
|
||||
}
|
||||
|
||||
// Size returns the total size of the content that was encoded up to this point.
|
||||
// Note this does not count the size of any lists which are still 'open' (i.e. for
|
||||
// which ListEnd has not been called yet).
|
||||
func (w EncoderBuffer) Size() int {
|
||||
if w.buf == nil {
|
||||
return 0
|
||||
}
|
||||
return w.buf.size()
|
||||
}
|
||||
|
||||
// Write appends b directly to the encoder output.
|
||||
func (w EncoderBuffer) Write(b []byte) (int, error) {
|
||||
return w.buf.Write(b)
|
||||
|
|
|
|||
|
|
@ -507,6 +507,39 @@ func TestEncodeToReaderReturnToPool(t *testing.T) {
|
|||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestEncoderBufferSize(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
eb := NewEncoderBuffer(&output)
|
||||
|
||||
assertSize := func(state string, expectedSize int) {
|
||||
t.Helper()
|
||||
if s := eb.Size(); s != expectedSize {
|
||||
t.Fatalf("wrong size %s: %d", state, s)
|
||||
}
|
||||
}
|
||||
|
||||
assertSize("empty buffer", 0)
|
||||
outerList := eb.List()
|
||||
assertSize("after outer List()", 0)
|
||||
eb.WriteString("abc")
|
||||
assertSize("after string write", 4)
|
||||
innerList := eb.List()
|
||||
assertSize("after inner List()", 4)
|
||||
eb.WriteUint64(1)
|
||||
eb.WriteUint64(2)
|
||||
assertSize("after inner list writes", 6)
|
||||
eb.ListEnd(innerList)
|
||||
assertSize("after end of inner list", 7)
|
||||
eb.ListEnd(outerList)
|
||||
assertSize("after end of outer list", 8)
|
||||
eb.Flush()
|
||||
assertSize("after Flush()", 0)
|
||||
|
||||
if output.Len() != 8 {
|
||||
t.Fatalf("wrong final output size %d", output.Len())
|
||||
}
|
||||
}
|
||||
|
||||
var sink interface{}
|
||||
|
||||
func BenchmarkIntsize(b *testing.B) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue