Browse Source

more test cases

Darien Raymond 7 years ago
parent
commit
2621305413
2 changed files with 35 additions and 3 deletions
  1. 3 3
      common/buf/buffer.go
  2. 32 0
      common/buf/buffer_test.go

+ 3 - 3
common/buf/buffer.go

@@ -65,11 +65,11 @@ func (b *Buffer) Bytes() []byte {
 // Reset resets the content of the Buffer with a supplier.
 func (b *Buffer) Reset(writer Supplier) error {
 	nBytes, err := writer(b.v)
+	if nBytes > len(b.v) {
+		return newError("too many bytes written: ", nBytes, " > ", len(b.v))
+	}
 	b.start = 0
 	b.end = int32(nBytes)
-	if b.end > int32(len(b.v)) {
-		b.end = int32(len(b.v))
-	}
 	return err
 }
 

+ 32 - 0
common/buf/buffer_test.go

@@ -3,6 +3,9 @@ package buf_test
 import (
 	"testing"
 
+	"v2ray.com/core/common"
+	"v2ray.com/core/common/compare"
+
 	. "v2ray.com/core/common/buf"
 	"v2ray.com/core/common/serial"
 	. "v2ray.com/ext/assert"
@@ -41,6 +44,35 @@ func TestBufferString(t *testing.T) {
 	assert(buffer.String(), Equals, "Test String")
 }
 
+func TestBufferSlice(t *testing.T) {
+	{
+		b := New()
+		common.Must2(b.Write([]byte("abcd")))
+		bytes := b.BytesFrom(-2)
+		if err := compare.BytesEqualWithDetail(bytes, []byte{'c', 'd'}); err != nil {
+			t.Error(err)
+		}
+	}
+
+	{
+		b := New()
+		common.Must2(b.Write([]byte("abcd")))
+		bytes := b.BytesTo(-2)
+		if err := compare.BytesEqualWithDetail(bytes, []byte{'a', 'b'}); err != nil {
+			t.Error(err)
+		}
+	}
+
+	{
+		b := New()
+		common.Must2(b.Write([]byte("abcd")))
+		bytes := b.BytesRange(-3, -1)
+		if err := compare.BytesEqualWithDetail(bytes, []byte{'b', 'c'}); err != nil {
+			t.Error(err)
+		}
+	}
+}
+
 func BenchmarkNewBuffer(b *testing.B) {
 	for i := 0; i < b.N; i++ {
 		buffer := New()