You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ring_test.go 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package io2
  2. import (
  3. "bytes"
  4. "io"
  5. "testing"
  6. . "github.com/smartystreets/goconvey/convey"
  7. "gitlink.org.cn/cloudream/common/utils/sync2"
  8. )
  9. type syncReader struct {
  10. data [][]byte
  11. curDataIndex int
  12. nextData int
  13. counter *sync2.CounterCond
  14. }
  15. func (r *syncReader) Read(p []byte) (n int, err error) {
  16. if r.nextData >= len(r.data) {
  17. return 0, io.EOF
  18. }
  19. if r.data[r.nextData] == nil {
  20. r.counter.Wait()
  21. r.nextData++
  22. }
  23. n = copy(p, r.data[r.nextData][r.curDataIndex:])
  24. r.curDataIndex += n
  25. if r.curDataIndex == len(r.data[r.nextData]) {
  26. r.curDataIndex = 0
  27. r.nextData++
  28. }
  29. return n, nil
  30. }
  31. func (r *syncReader) Close() error {
  32. return nil
  33. }
  34. func Test_RingBuffer(t *testing.T) {
  35. Convey("写满读满", t, func() {
  36. b := Ring(io.NopCloser(bytes.NewBuffer([]byte{1, 2, 3})), 4)
  37. ret := make([]byte, 3)
  38. n, err := b.Read(ret)
  39. So(err, ShouldEqual, nil)
  40. So(n, ShouldEqual, 3)
  41. So(ret, ShouldResemble, []byte{1, 2, 3})
  42. })
  43. Convey("1+3+1", t, func() {
  44. sy := sync2.NewCounterCond(0)
  45. b := Ring(&syncReader{
  46. data: [][]byte{
  47. {1},
  48. nil,
  49. {2, 3, 4, 5},
  50. },
  51. counter: sy,
  52. }, 4)
  53. ret := make([]byte, 3)
  54. n, err := b.Read(ret)
  55. So(err, ShouldEqual, nil)
  56. So(n, ShouldEqual, 1)
  57. So(ret[:n], ShouldResemble, []byte{1})
  58. sy.Release()
  59. n, err = b.Read(ret)
  60. So(err, ShouldEqual, nil)
  61. So(n, ShouldEqual, 3)
  62. So(ret[:n], ShouldResemble, []byte{2, 3, 4})
  63. n, err = b.Read(ret)
  64. So(err, ShouldEqual, nil)
  65. So(n, ShouldEqual, 1)
  66. So(ret[:n], ShouldResemble, []byte{5})
  67. })
  68. Convey("3+1+2", t, func() {
  69. sy := sync2.NewCounterCond(0)
  70. b := Ring(&syncReader{
  71. data: [][]byte{
  72. {1, 2, 3, 4, 5, 6},
  73. },
  74. counter: sy,
  75. }, 4)
  76. ret := make([]byte, 3)
  77. n, err := b.Read(ret)
  78. So(err, ShouldEqual, nil)
  79. So(n, ShouldEqual, 3)
  80. So(ret[:n], ShouldResemble, []byte{1, 2, 3})
  81. n, err = b.Read(ret)
  82. So(err, ShouldEqual, nil)
  83. So(n, ShouldEqual, 1)
  84. So(ret[:n], ShouldResemble, []byte{4})
  85. n, err = b.Read(ret)
  86. So(err, ShouldEqual, nil)
  87. So(n, ShouldEqual, 2)
  88. So(ret[:n], ShouldResemble, []byte{5, 6})
  89. })
  90. }