v2ray-core/common/buf/buffer_test.go

99 lines
1.8 KiB
Go
Raw Normal View History

2016-12-09 10:35:27 +00:00
package buf_test
2015-10-10 20:15:10 +00:00
import (
2018-11-02 14:01:33 +00:00
"bytes"
"crypto/rand"
2015-10-10 20:15:10 +00:00
"testing"
2018-10-24 11:16:08 +00:00
"v2ray.com/core/common"
2016-12-09 10:35:27 +00:00
. "v2ray.com/core/common/buf"
2018-11-02 14:01:33 +00:00
"v2ray.com/core/common/compare"
2017-10-24 14:15:35 +00:00
. "v2ray.com/ext/assert"
2015-10-10 20:15:10 +00:00
)
func TestBufferClear(t *testing.T) {
2017-10-24 14:15:35 +00:00
assert := With(t)
2015-10-10 20:15:10 +00:00
2016-12-09 11:08:25 +00:00
buffer := New()
2015-10-10 20:15:10 +00:00
defer buffer.Release()
payload := "Bytes"
2018-04-19 20:56:55 +00:00
buffer.Write([]byte(payload))
2018-04-02 18:00:50 +00:00
assert(buffer.Len(), Equals, int32(len(payload)))
2015-10-10 20:15:10 +00:00
buffer.Clear()
2018-04-02 18:00:50 +00:00
assert(buffer.Len(), Equals, int32(0))
2015-10-10 20:15:10 +00:00
}
2016-12-06 10:03:42 +00:00
func TestBufferIsEmpty(t *testing.T) {
2017-10-24 14:15:35 +00:00
assert := With(t)
2015-10-10 20:15:10 +00:00
2016-12-09 11:08:25 +00:00
buffer := New()
2015-10-10 20:15:10 +00:00
defer buffer.Release()
2017-10-24 14:15:35 +00:00
assert(buffer.IsEmpty(), IsTrue)
2015-10-10 20:15:10 +00:00
}
2016-01-31 20:24:40 +00:00
2016-04-29 21:47:42 +00:00
func TestBufferString(t *testing.T) {
2017-10-24 14:15:35 +00:00
assert := With(t)
2016-04-29 21:47:42 +00:00
2016-12-09 11:08:25 +00:00
buffer := New()
2016-04-29 21:47:42 +00:00
defer buffer.Release()
2018-11-02 20:34:04 +00:00
common.Must2(buffer.WriteString("Test String"))
2017-10-24 14:15:35 +00:00
assert(buffer.String(), Equals, "Test String")
2016-04-29 21:47:42 +00:00
}
2016-11-21 21:08:34 +00:00
2018-10-24 11:16:08 +00:00
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)
}
}
}
2018-11-02 14:01:33 +00:00
func TestBufferReadFullFrom(t *testing.T) {
payload := make([]byte, 1024)
common.Must2(rand.Read(payload))
reader := bytes.NewReader(payload)
b := New()
n, err := b.ReadFullFrom(reader, 1024)
common.Must(err)
if n != 1024 {
t.Error("expect reading 1024 bytes, but actually ", n)
}
if err := compare.BytesEqualWithDetail(payload, b.Bytes()); err != nil {
t.Error(err)
}
}
2017-04-21 12:32:29 +00:00
func BenchmarkNewBuffer(b *testing.B) {
2016-11-21 21:08:34 +00:00
for i := 0; i < b.N; i++ {
2016-12-09 11:08:25 +00:00
buffer := New()
2016-11-21 21:08:34 +00:00
buffer.Release()
}
}