-
Notifications
You must be signed in to change notification settings - Fork 63
/
ringbuffer_test.go
121 lines (97 loc) · 2.03 KB
/
ringbuffer_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package chanx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRingBuffer(t *testing.T) {
rb := NewRingBuffer[int](10)
v, err := rb.Read()
assert.Equal(t, v, 0)
assert.Error(t, err, ErrIsEmpty)
write := 0
read := 0
// write one and read it
rb.Write(0)
v, err = rb.Read()
assert.NoError(t, err)
assert.Equal(t, 0, v)
assert.Equal(t, 1, rb.r)
assert.Equal(t, 1, rb.w)
assert.True(t, rb.IsEmpty())
// then write 10
for i := 0; i < 9; i++ {
rb.Write(i)
write += i
}
assert.Equal(t, 10, rb.Capacity())
assert.Equal(t, 9, rb.Len())
// write one more, the buffer is full so it grows
rb.Write(10)
write += 10
assert.Equal(t, 20, rb.Capacity())
assert.Equal(t, 10, rb.Len())
for i := 0; i < 90; i++ {
rb.Write(i)
write += i
}
assert.Equal(t, 160, rb.Capacity())
assert.Equal(t, 100, rb.Len())
for {
v, err := rb.Read()
if err == ErrIsEmpty {
break
}
read += v
}
assert.Equal(t, write, read)
rb.Reset()
assert.Equal(t, 10, rb.Capacity())
assert.Equal(t, 0, rb.Len())
assert.True(t, rb.IsEmpty())
}
func TestRingBuffer_One(t *testing.T) {
rb := NewRingBuffer[int](1)
v, err := rb.Read()
assert.Equal(t, v, 0)
assert.Error(t, err, ErrIsEmpty)
write := 0
read := 0
// write one and read it
rb.Write(0)
v, err = rb.Read()
assert.NoError(t, err)
assert.Equal(t, 0, v)
assert.Equal(t, 1, rb.r)
assert.Equal(t, 1, rb.w)
assert.True(t, rb.IsEmpty())
// then write 10
for i := 0; i < 9; i++ {
rb.Write(i)
write += i
}
assert.Equal(t, 16, rb.Capacity())
assert.Equal(t, 9, rb.Len())
// write one more, the buffer is full so it grows
rb.Write(10)
write += 10
assert.Equal(t, 16, rb.Capacity())
assert.Equal(t, 10, rb.Len())
for i := 0; i < 90; i++ {
rb.Write(i)
write += i
}
assert.Equal(t, 128, rb.Capacity())
assert.Equal(t, 100, rb.Len())
for {
v, err := rb.Read()
if err == ErrIsEmpty {
break
}
read += v
}
assert.Equal(t, write, read)
rb.Reset()
assert.Equal(t, 2, rb.Capacity())
assert.Equal(t, 0, rb.Len())
assert.True(t, rb.IsEmpty())
}