Skip to content

Commit

Permalink
Add Clear() method to gbytes.Buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
onsi committed Mar 7, 2021
1 parent d9ee1e2 commit c3c0920
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions gbytes/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,22 @@ func (b *Buffer) Read(d []byte) (int, error) {
return n, nil
}

/*
Clear clears out the buffer's contents
*/
func (b *Buffer) Clear() error {
b.lock.Lock()
defer b.lock.Unlock()

if b.closed {
return errors.New("attempt to clear closed buffer")
}

b.contents = []byte{}
b.readCursor = 0
return nil
}

/*
Close signifies that the buffer will no longer be written to
*/
Expand Down
20 changes: 20 additions & 0 deletions gbytes/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,26 @@ var _ = Describe("Buffer", func() {
})
})

Describe("clearing the buffer", func() {
It("should clear out the contents of the buffer", func() {
buffer.Write([]byte("abc"))
Expect(buffer).To(Say("ab"))
Expect(buffer.Clear()).To(Succeed())
Expect(buffer).NotTo(Say("c"))
Expect(buffer.Contents()).To(BeEmpty())
buffer.Write([]byte("123"))
Expect(buffer).To(Say("123"))
Expect(buffer.Contents()).To(Equal([]byte("123")))
})

It("should error when the buffer is closed", func() {
buffer.Write([]byte("abc"))
buffer.Close()
err := buffer.Clear()
Expect(err).To(HaveOccurred())
})
})

Describe("closing the buffer", func() {
It("should error when further write attempts are made", func() {
_, err := buffer.Write([]byte("abc"))
Expand Down

0 comments on commit c3c0920

Please sign in to comment.