buffer_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package buf_test
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "testing"
  6. "v2ray.com/core/common"
  7. . "v2ray.com/core/common/buf"
  8. "v2ray.com/core/common/compare"
  9. "v2ray.com/core/common/serial"
  10. . "v2ray.com/ext/assert"
  11. )
  12. func TestBufferClear(t *testing.T) {
  13. assert := With(t)
  14. buffer := New()
  15. defer buffer.Release()
  16. payload := "Bytes"
  17. buffer.Write([]byte(payload))
  18. assert(buffer.Len(), Equals, int32(len(payload)))
  19. buffer.Clear()
  20. assert(buffer.Len(), Equals, int32(0))
  21. }
  22. func TestBufferIsEmpty(t *testing.T) {
  23. assert := With(t)
  24. buffer := New()
  25. defer buffer.Release()
  26. assert(buffer.IsEmpty(), IsTrue)
  27. }
  28. func TestBufferString(t *testing.T) {
  29. assert := With(t)
  30. buffer := New()
  31. defer buffer.Release()
  32. assert(buffer.AppendSupplier(serial.WriteString("Test String")), IsNil)
  33. assert(buffer.String(), Equals, "Test String")
  34. }
  35. func TestBufferSlice(t *testing.T) {
  36. {
  37. b := New()
  38. common.Must2(b.Write([]byte("abcd")))
  39. bytes := b.BytesFrom(-2)
  40. if err := compare.BytesEqualWithDetail(bytes, []byte{'c', 'd'}); err != nil {
  41. t.Error(err)
  42. }
  43. }
  44. {
  45. b := New()
  46. common.Must2(b.Write([]byte("abcd")))
  47. bytes := b.BytesTo(-2)
  48. if err := compare.BytesEqualWithDetail(bytes, []byte{'a', 'b'}); err != nil {
  49. t.Error(err)
  50. }
  51. }
  52. {
  53. b := New()
  54. common.Must2(b.Write([]byte("abcd")))
  55. bytes := b.BytesRange(-3, -1)
  56. if err := compare.BytesEqualWithDetail(bytes, []byte{'b', 'c'}); err != nil {
  57. t.Error(err)
  58. }
  59. }
  60. }
  61. func TestBufferReadFullFrom(t *testing.T) {
  62. payload := make([]byte, 1024)
  63. common.Must2(rand.Read(payload))
  64. reader := bytes.NewReader(payload)
  65. b := New()
  66. n, err := b.ReadFullFrom(reader, 1024)
  67. common.Must(err)
  68. if n != 1024 {
  69. t.Error("expect reading 1024 bytes, but actually ", n)
  70. }
  71. if err := compare.BytesEqualWithDetail(payload, b.Bytes()); err != nil {
  72. t.Error(err)
  73. }
  74. }
  75. func BenchmarkNewBuffer(b *testing.B) {
  76. for i := 0; i < b.N; i++ {
  77. buffer := New()
  78. buffer.Release()
  79. }
  80. }