Skip to content

Commit

Permalink
Add Truncate method to replace Reset. Add PutFunc method.
Browse files Browse the repository at this point in the history
  • Loading branch information
qianbin committed Dec 27, 2023
1 parent 141b785 commit 805c20d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
19 changes: 16 additions & 3 deletions buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package drlp
// Buffer is essentially a byte slice. It holds encoded elements.
type Buffer []byte

// Reset resets all content.
func (b *Buffer) Reset() {
*b = (*b)[:0]
// Truncate truncates the buffer to size.
func (b *Buffer) Truncate(size int) {
*b = (*b)[:size]
}

// PutUint puts the uint value.
Expand Down Expand Up @@ -36,6 +36,19 @@ func (b *Buffer) PutString(str []byte) {
}
}

// PutFunc puts the string value returned by func build.
// The build func should not modify existing content of buf,
// and should follow the behavior like append.
func (b *Buffer) PutFunc(build func(buf []byte) []byte) {
offset := len(*b)
// make room for string header
*b = append(*b, make([]byte, 9)...)
*b = build(*b)
str := (*b)[offset+9:]
b.Truncate(offset)
b.PutString(str)
}

// List starts a RLP list.
func (b *Buffer) List() List {
return List{b, len(*b)}
Expand Down
14 changes: 13 additions & 1 deletion buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,22 @@ func encode(v interface{}, b *Buffer) {
func TestBuffer(t *testing.T) {
var buf Buffer
for i, tt := range tests {
buf.Reset()
buf.Truncate(0)
encode(tt.val, &buf)
if got := strings.ToUpper(hex.EncodeToString(buf)); got != tt.want {
t.Errorf("#%v: got %v, want %v", i, got, tt.want)
}
}
}

func TestBuffer_PutFunc(t *testing.T) {
var buf Buffer
buf.PutFunc(func(buf []byte) []byte {
return append(buf, "Lorem ipsum dolor sit amet, consectetur adipisicing eli"...)
})
want := "B74C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E7365637465747572206164697069736963696E6720656C69"
if got := strings.ToUpper(hex.EncodeToString(buf)); got != want {
t.Errorf("got %v, want %v", got, want)
}

}

0 comments on commit 805c20d

Please sign in to comment.