Skip to content

Commit ecdb898

Browse files
authored
Merge pull request #2678 from CortexFoundation/dev
rlp: add Size method to EncoderBuffer
2 parents 94c4371 + 615ee68 commit ecdb898

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

rlp/encbuffer.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,16 @@ func (w *EncoderBuffer) AppendToBytes(dst []byte) []byte {
350350
return out
351351
}
352352

353+
// Size returns the total size of the content that was encoded up to this point.
354+
// Note this does not count the size of any lists which are still 'open' (i.e. for
355+
// which ListEnd has not been called yet).
356+
func (w EncoderBuffer) Size() int {
357+
if w.buf == nil {
358+
return 0
359+
}
360+
return w.buf.size()
361+
}
362+
353363
// Write appends b directly to the encoder output.
354364
func (w EncoderBuffer) Write(b []byte) (int, error) {
355365
return w.buf.Write(b)

rlp/encode_test.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,40 @@ func TestEncodeToReaderReturnToPool(t *testing.T) {
503503
wg.Wait()
504504
}
505505

506-
var sink any
506+
func TestEncoderBufferSize(t *testing.T) {
507+
var output bytes.Buffer
508+
eb := NewEncoderBuffer(&output)
509+
510+
assertSize := func(state string, expectedSize int) {
511+
t.Helper()
512+
if s := eb.Size(); s != expectedSize {
513+
t.Fatalf("wrong size %s: %d", state, s)
514+
}
515+
}
516+
517+
assertSize("empty buffer", 0)
518+
outerList := eb.List()
519+
assertSize("after outer List()", 0)
520+
eb.WriteString("abc")
521+
assertSize("after string write", 4)
522+
innerList := eb.List()
523+
assertSize("after inner List()", 4)
524+
eb.WriteUint64(1)
525+
eb.WriteUint64(2)
526+
assertSize("after inner list writes", 6)
527+
eb.ListEnd(innerList)
528+
assertSize("after end of inner list", 7)
529+
eb.ListEnd(outerList)
530+
assertSize("after end of outer list", 8)
531+
eb.Flush()
532+
assertSize("after Flush()", 0)
533+
534+
if output.Len() != 8 {
535+
t.Fatalf("wrong final output size %d", output.Len())
536+
}
537+
}
538+
539+
var sink interface{}
507540

508541
func BenchmarkIntsize(b *testing.B) {
509542
for i := 0; i < b.N; i++ {

0 commit comments

Comments
 (0)