]> Cypherpunks repositories - gostls13.git/commitdiff
bytes: export Cap method for buffer
authorCristian Staretu <unclejacksons@gmail.com>
Wed, 1 Apr 2015 15:59:51 +0000 (18:59 +0300)
committerRob Pike <r@golang.org>
Fri, 3 Apr 2015 23:50:02 +0000 (23:50 +0000)
Obtaining the actual size of the underlying storage of the buffer can
be very useful in various scenarios. Long running programs which write
and read large amounts of data to buffers might have to recycle
buffers in order to avoid holding onto potentially huge buffers.

For example, a piece of code which buffers a lot of data in a buffer
might need to release the big buffer and start again with a smaller
buffer after it finished processing the huge amount of data.

In cases where pools of bytes.Buffer are used, being able to check the
size of the allocated data can be very useful.

Instead of forking bytes.Buffer or writing new code, we can export the
Cap() method.

Change-Id: I79d4f0a3cff53b9419d82c8122964761e9e38566
Reviewed-on: https://go-review.googlesource.com/8342
Reviewed-by: Rob Pike <r@golang.org>
src/bytes/buffer.go
src/bytes/buffer_test.go
src/bytes/export_test.go

index 46ca1d5ad3f6377ed0b3b587792ed216946526df..7f9139bca8472c8ea011819b145519317b8ab92e 100644 (file)
@@ -56,6 +56,10 @@ func (b *Buffer) String() string {
 // b.Len() == len(b.Bytes()).
 func (b *Buffer) Len() int { return len(b.buf) - b.off }
 
+// Cap returns the capacity of the buffer's underlying byte slice, that is, the
+// total space allocated for the the buffer's data.
+func (b *Buffer) Cap() int { return cap(b.buf) }
+
 // Truncate discards all but the first n unread bytes from the buffer.
 // It panics if n is negative or greater than the length of the buffer.
 func (b *Buffer) Truncate(n int) {
index 75145b05e92df6619214c142c67644af89988eef..7de17ae47e28ff00f00dd295637a9917779e9e32 100644 (file)
@@ -231,6 +231,23 @@ func TestMixedReadsAndWrites(t *testing.T) {
        empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()))
 }
 
+func TestCapWithPreallocatedSlice(t *testing.T) {
+       buf := NewBuffer(make([]byte, 10))
+       n := buf.Cap()
+       if n != 10 {
+               t.Errorf("expected 10, got %d", n)
+       }
+}
+
+func TestCapWithSliceAndWrittenData(t *testing.T) {
+       buf := NewBuffer(make([]byte, 0, 10))
+       buf.Write([]byte("test"))
+       n := buf.Cap()
+       if n != 10 {
+               t.Errorf("expected 10, got %d", n)
+       }
+}
+
 func TestNil(t *testing.T) {
        var b *Buffer
        if b.String() != "<nil>" {
index 3b915d5ead80ae1aa7a4e32cb744709f7bd02401..f61523e60bbb3fd209594912ebcaa76cde9acd20 100644 (file)
@@ -7,7 +7,3 @@ package bytes
 // Export func for testing
 var IndexBytePortable = indexBytePortable
 var EqualPortable = equalPortable
-
-func (b *Buffer) Cap() int {
-       return cap(b.buf)
-}