v2ray-core/common/buf/multi_buffer_test.go

110 lines
2.0 KiB
Go
Raw Normal View History

2017-04-15 19:07:23 +00:00
package buf_test
import (
2018-03-28 12:33:34 +00:00
"crypto/rand"
2018-04-13 11:54:36 +00:00
"io"
2017-04-15 19:07:23 +00:00
"testing"
2018-11-18 21:12:31 +00:00
"github.com/google/go-cmp/cmp"
2018-03-28 12:33:34 +00:00
"v2ray.com/core/common"
2017-04-15 19:07:23 +00:00
. "v2ray.com/core/common/buf"
2017-10-24 14:15:35 +00:00
. "v2ray.com/ext/assert"
2017-04-15 19:07:23 +00:00
)
func TestMultiBufferRead(t *testing.T) {
2017-10-24 14:15:35 +00:00
assert := With(t)
2017-04-15 19:07:23 +00:00
b1 := New()
2018-11-14 21:55:20 +00:00
b1.WriteString("ab")
2017-04-15 19:07:23 +00:00
b2 := New()
2018-11-14 21:55:20 +00:00
b2.WriteString("cd")
2018-11-16 10:08:12 +00:00
mb := MultiBuffer{b1, b2}
2017-04-15 19:07:23 +00:00
bs := make([]byte, 32)
_, nBytes := SplitBytes(mb, bs)
2017-10-24 14:15:35 +00:00
assert(nBytes, Equals, 4)
assert(bs[:nBytes], Equals, []byte("abcd"))
2017-04-15 19:07:23 +00:00
}
func TestMultiBufferAppend(t *testing.T) {
2017-10-24 14:15:35 +00:00
assert := With(t)
var mb MultiBuffer
b := New()
2018-11-14 21:55:20 +00:00
b.WriteString("ab")
2018-11-17 08:12:20 +00:00
mb = append(mb, b)
2018-04-02 18:00:50 +00:00
assert(mb.Len(), Equals, int32(2))
}
2018-03-28 12:33:34 +00:00
func TestMultiBufferSliceBySizeLarge(t *testing.T) {
2018-08-16 10:05:33 +00:00
lb := make([]byte, 8*1024)
common.Must2(io.ReadFull(rand.Reader, lb))
2018-03-28 12:33:34 +00:00
2018-11-18 18:36:36 +00:00
mb := MergeBytes(nil, lb)
2018-03-28 12:33:34 +00:00
2018-11-18 19:16:14 +00:00
mb, mb2 := SplitSize(mb, 1024)
2018-11-18 21:12:31 +00:00
if mb2.Len() != 1024 {
t.Error("expect length 1024, but got ", mb2.Len())
}
if mb.Len() != 7*1024 {
t.Error("expect length 7*1024, but got ", mb.Len())
}
mb, mb3 := SplitSize(mb, 7*1024)
if mb3.Len() != 7*1024 {
t.Error("expect length 7*1024, but got", mb.Len())
}
if !mb.IsEmpty() {
t.Error("expect empty buffer, but got ", mb.Len())
}
}
func TestMultiBufferSplitFirst(t *testing.T) {
b1 := New()
b1.WriteString("b1")
b2 := New()
b2.WriteString("b2")
b3 := New()
b3.WriteString("b3")
var mb MultiBuffer
mb = append(mb, b1, b2, b3)
mb, c1 := SplitFirst(mb)
if diff := cmp.Diff(b1.String(), c1.String()); diff != "" {
t.Error(diff)
}
mb, c2 := SplitFirst(mb)
if diff := cmp.Diff(b2.String(), c2.String()); diff != "" {
t.Error(diff)
}
mb, c3 := SplitFirst(mb)
if diff := cmp.Diff(b3.String(), c3.String()); diff != "" {
t.Error(diff)
}
if !mb.IsEmpty() {
t.Error("expect empty buffer, but got ", mb.String())
}
2018-03-28 12:33:34 +00:00
}
2018-11-18 23:33:00 +00:00
func BenchmarkSplitBytes(b *testing.B) {
var mb MultiBuffer
raw := make([]byte, Size)
b.ResetTimer()
for i := 0; i < b.N; i++ {
buffer := StackNew()
buffer.Extend(Size)
mb = append(mb, &buffer)
mb, _ = SplitBytes(mb, raw)
}
}