forked from ashishgandhi/buffer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer_test.go
More file actions
601 lines (526 loc) · 15.1 KB
/
Copy pathbuffer_test.go
File metadata and controls
601 lines (526 loc) · 15.1 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package buffer
import (
"bytes"
"crypto/rand"
"io"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
var bufFile = filepath.Join(os.TempDir(), "buffer-test")
func init() {
os.Remove(bufFile)
}
func TestFrame(t *testing.T) {
data := []byte("much data. such big. wow.")
f, err := newFrame(0, data)
if err != nil {
t.Fatalf("Failed to create frame: %v", err)
}
fdata := f.data()
if !bytes.Equal(fdata, data) {
t.Errorf("f.data() = %x, want %x", fdata, data)
}
fsize := f.size()
want := len(data) + size + sequence
if int(fsize) != want {
t.Errorf("f.size() = %d, want %d", fsize, want)
}
data = make([]byte, maxBytes+1)
if _, err = newFrame(0, data); err != errFrameTooBig {
t.Errorf("newFrame err = %v; want %v", err, errFrameTooBig)
}
f = make([]byte, total-1)
if data = f.data(); len(data) != 0 {
// Frame that is smaller than its
// header size cannot have data.
t.Errorf("f.data() = %x; want nil", data)
}
if seq := f.seq(); seq != 0 {
// Frame that is smaller than its
// header size cannot have data
// and should not ret seq number.
t.Errorf("f.seq() = %d; want nil", seq)
}
}
func TestMaxByteValue(t *testing.T) {
var want uint32 = 4294967284
if maxBytes != want {
t.Errorf("maxBytes = %d, want %d", maxBytes, want)
}
}
func TestLargeFrame(t *testing.T) {
mb := maxBytes
maxBytes = 10
defer func() { maxBytes = mb }()
t.SkipNow() // takes a lot of memory
data := make([]byte, maxBytes)
if _, err := newFrame(0, data); err != nil {
t.Errorf("Failed to create max size frame: %v", err)
}
data = make([]byte, maxBytes+1)
if _, err := newFrame(0, data); err != errFrameTooBig {
t.Errorf("Expected to fail to create frame because of size: %v", err)
}
}
func TestNewAndLoadBuffer(t *testing.T) {
n := 100
b, err := New(n, bufFile)
if err != nil {
t.Fatalf("Failed to create Buffer: %v", err)
}
if !bytes.Equal(b.data[n:], make([]byte, metadata)) {
t.Errorf("Expect 0s in metadata, got = %x", b.data[n:])
}
mustInsert(t, b.Insert([]byte("This is data")))
bufData := make([]byte, len(b.data))
copy(bufData, b.data)
b.Unmap()
if _, err = Load("🚫"); err == nil {
t.Errorf("Successfully loaded buffer from non-existent file")
}
b, err = Load(bufFile)
if err != nil {
os.Remove(bufFile)
t.Fatalf("Failed to load buf from file: %v", err)
}
defer b.Close()
if !bytes.Equal(b.data, bufData) {
t.Errorf("Load returned buf with data %x; want %x", b.data, bufData)
}
_, err = New(n, bufFile)
if err != ErrFileExists {
t.Errorf("Should fail to create new buffer if file already exists")
}
}
func TestBufferInsert(t *testing.T) {
n := 3 + total
b, err := New(n, bufFile)
if err != nil {
t.Fatalf("Failed to create Buffer: %v", err)
}
defer b.Close()
metaoff := len(b.data) - metadata
data := []byte("123")
if err := b.Insert(data); err != nil {
t.Errorf("First insert failed: %v", err)
}
if !bytes.Equal(data, b.data[total:metaoff]) {
t.Error("First write data encoded incorrectly")
}
if err := b.Insert([]byte("ab")); err != nil {
t.Errorf("Second insert failed: %v", err)
}
if !bytes.Equal([]byte("ab3"), b.data[total:metaoff]) {
t.Error("Second write data encoded incorrectly")
}
data = []byte("x")
if err := b.Insert(data); err != nil {
t.Errorf("Third insert failed: %v", err)
}
if !bytes.Equal(data, b.data[total-1:total]) {
// The first byte of the frame header should have
// been written where "3" was before wrapping.
t.Error("Third write data encoded incorrectly")
}
}
func TestEmptyBufferRead(t *testing.T) {
b, err := New(10, bufFile)
if err != nil {
t.Fatalf("Failed to create buffer: %v", err)
}
defer b.Close()
var data []byte
if _, _, err := b.ReadFirst(data); err != ErrNotArrived {
t.Errorf("b.ReadFirst err = %v; want %v", err, ErrNotArrived)
}
}
func TestBufferRead(t *testing.T) {
input := [][]byte{
[]byte("data goes in"),
[]byte("data comes back out"),
[]byte("salad a month"),
[]byte("is a good thing"),
}
var n int
for _, d := range input {
n += len(d) + total
}
n -= 1 // slightly smaller than all data
b, err := New(n, bufFile)
if err != nil {
t.Fatalf("Failed to create Buffer: %v", err)
}
defer b.Close()
l := len(input)
insertedBytes := 0
for i := 0; i < l-1; i++ {
data := input[i]
insertedBytes += len(data)
mustInsert(t, b.Insert(data))
}
if length := b.Len(); length != uint64(insertedBytes) {
t.Errorf("b.Len() = %d; want %d", length, insertedBytes)
}
in := input[0]
data := make([]byte, len(in))
_, c, err := b.ReadFirst(data)
second := c
if err != nil {
t.Errorf("b.ReadFirst err = %v; want nil", err)
}
if seq := c.Seq(); seq != 1 {
t.Errorf("b.ReadFirst seq = %d; want 0", seq)
}
if !bytes.Equal(data, in) {
t.Errorf("b.ReadFirst data = %x; want %x", data, in)
}
wantoff := total + len(in)
if c.offset != uint64(wantoff) {
t.Errorf("b.ReadFirst offset = %d; want %d", c.offset, wantoff)
}
// Haven't written input[3] yet.
want := uint64(len(input[1])+len(input[2])) + 2*total
if remaining := b.Remaining(second); remaining != want {
t.Errorf("b.Reamining(c) = %d; want %d", remaining, want)
}
in = input[1]
cutoff := len(in) - 4
data = make([]byte, cutoff)
_, c, err = b.Read(data, c)
third := c
if err != ErrPartialData {
t.Errorf("b.Read err = %v, expect %v", err, ErrPartialData)
}
if !bytes.Equal(data, in[:cutoff]) {
t.Errorf("b.Read data = %x; want %x", data, in[:cutoff])
}
mustInsert(t, b.Insert(input[l-1]))
data = make([]byte, len(in))
_, c, err = b.ReadFirst(data)
if err != nil {
t.Errorf("b.ReadFirst err = %v; want nil", err)
}
if seq := c.Seq(); seq != 2 {
t.Errorf("b.ReadFirst seq = %d; want 2", seq)
}
if c.offset != third.offset {
t.Errorf("b.Read offset = %d; want %d", c.offset, third.offset)
}
if !bytes.Equal(data, in) {
t.Errorf("b.Read data = %x; want %x", data, in)
}
_, c, err = b.Read(data, second)
if err != nil {
t.Errorf("b.Read err = %v; want nil", err)
}
if c.offset != third.offset {
t.Errorf("b.Read offset = %d; want %d", c.offset, third.offset)
}
want = uint64(len(input[1])+len(input[2])+len(input[3])) + 3*total
if remaining := b.Remaining(second); remaining != want {
t.Errorf("b.Reamining(c) = %d; want %d", remaining, want)
}
in = make([]byte, n-total)
copy(in, []byte("Record where frame size equals capacity"))
mustInsert(t, b.Insert(in))
if length := b.Len(); length != uint64(len(in)) {
t.Errorf("b.Len() = %d; want %d", length, len(in))
}
want = uint64(len(in)) + total
if remaining := b.Remaining(second); remaining != want {
t.Errorf("b.Reamining(c) = %d; want %d", remaining, want)
}
_, _, err = b.Read(data, second)
if err != ErrPartialData {
t.Errorf("b.Read err = %v; want %v", err, ErrPartialData)
}
data = make([]byte, len(in))
_, c, err = b.Read(data, second)
if err != nil {
t.Errorf("b.Read err = %v; want nil", err)
}
if seq := c.Seq(); seq != 5 {
t.Errorf("b.Read seq = %d; want 5", seq)
}
if !bytes.Equal(data, in) {
t.Errorf("b.Read data = %x; want %x", data, in)
}
if remaining := b.Remaining(c); remaining != 0 {
t.Errorf("b.Reamining(c) = %d; want 0", remaining)
}
_, _, err = b.Read(data, c)
if err != ErrNotArrived {
t.Errorf("b.Read err = %v; want %v", err, ErrNotArrived)
}
if err := b.Insert(make([]byte, n+1)); err != errDataTooBig {
t.Errorf("b.Insert err = %v; want %v", err, errDataTooBig)
}
in = []byte("Adding data when the buffer can contain only one record")
mustInsert(t, b.Insert(in))
if length := b.Len(); length != uint64(len(in)) {
t.Errorf("b.Len() = %d; want %d", length, len(in))
}
data = make([]byte, len(in))
_, c, err = b.Read(data, c)
if err != nil {
t.Errorf("b.Read err = %v; want nil", err)
}
if seq := c.Seq(); seq != 6 {
t.Errorf("b.Read seq = %d; want 6", seq)
}
if !bytes.Equal(data, in) {
t.Errorf("b.Read data = %x; want %x", data, in)
}
}
func TestWrappingData(t *testing.T) {
// This test tests a special scenario (henceforth situation) where:
//
// end = wrapped start + length of record
// b.capacity - start < end % b.capacity
//
// because there was a bug where partial record would not be copied
// into the output slice.
var (
d1 = []byte("dragons")
d2 = []byte("winter is coming")
d3 = []byte("snakes are found in south of the kingdom")
data = make([]byte, 1<<10)
)
if l := len(d1); l != 7 {
t.Fatalf("len(d1) = %d; want 7 to re-created situation", l)
}
if l := len(d2); l != 16 {
t.Fatalf("len(d2) = %d; want 16 to re-created situation", l)
}
if l := len(d3); l != 40 {
t.Fatalf("len(d3) = %d; want 40 to re-created situation", l)
}
n := total + len(d3) + 1
b, err := New(n, bufFile)
if err != nil {
t.Fatalf("Failed to create buffer: %v", err)
}
defer b.Close()
mustInsert(t, b.Insert(d1))
mustInsert(t, b.Insert(d2))
n, c, err := b.ReadFirst(data)
if err != nil {
t.Errorf("ReadFirst err = %v; want nil", err)
}
if n != len(d1) {
t.Errorf("ReadFirst n = %d; want %d", n, len(d1))
}
got := data[:n]
if !bytes.Equal(got, d1) {
t.Errorf("ReadFirst got %x; want %x", got, d1)
}
n, c, err = b.Read(data, c)
if err != nil {
t.Errorf("Read err = %v; want nil", err)
}
if n != len(d2) {
t.Errorf("Read n = %d; want %d", n, len(d2))
}
got = data[:n]
if !bytes.Equal(got, d2) {
t.Errorf("Read got %x; want %x", got, d2)
}
_, _, err = b.Read(data, c)
if err != ErrNotArrived {
t.Errorf("Read err = %v; want %v", err, ErrNotArrived)
}
mustInsert(t, b.Insert(d3))
n, c, err = b.Read(data, c)
if err != nil {
t.Errorf("Read err = %v; want nil", err)
}
if n != len(d3) {
t.Errorf("Read n = %d; want %d", n, len(d3))
}
got = data[:n]
if !bytes.Equal(got, d3) {
t.Errorf("Read got %x; want %x", got, d3)
}
}
func TestOffByOneWrapping(t *testing.T) {
var (
s = 10
n = 2 * (s + total)
d = make([]byte, s)
)
for i := 0; i < len(d); i++ {
d[i] = 42
}
b, err := New(n, bufFile)
if err != nil {
t.Fatalf("Failed to create buffer: %v", err)
}
defer b.Close()
mustInsert(t, b.Insert(d))
mustInsert(t, b.Insert(d))
mustInsert(t, b.Insert(d))
mustInsert(t, b.Insert(d))
if l := b.Len(); l != 20 {
// Using length as a proxy to test wrapping
// is done right when the record ejected
// after previous write ends just at the
// last byte.
t.Errorf("b.Len() = %d; want 20", l)
}
}
func TestAdviseOne(t *testing.T) {
n := os.Getpagesize()
b, err := New(n+total, bufFile)
if err != nil {
t.Fatalf("Failed to create buffer: %v", err)
}
defer b.Close()
data := make([]byte, n)
mustInsert(t, b.Insert(data))
_, c, err := b.ReadFirst(data)
if err != nil {
t.Fatalf("b.ReadFirst err = %v; want nil", err)
}
if err = b.DontNeed(c); err != nil {
t.Errorf("b.DontNeed = %v, want nil", err)
}
}
func TestAdviseTwo(t *testing.T) {
p := os.Getpagesize()
b, err := New(2*p, bufFile)
if err != nil {
t.Fatalf("Failed to create buffer: %v", err)
}
defer b.Close()
mustInsert(t, b.Insert(make([]byte, p-total)))
data := make([]byte, 2*p-total)
mustInsert(t, b.Insert(data))
_, c, err := b.ReadFirst(data)
if err != nil {
t.Fatalf("b.ReadFirst err = %v; want nil", err)
}
if err = b.DontNeed(c); err != nil {
t.Errorf("b.DontNeed = %v, want nil", err)
}
}
func mustInsert(t *testing.T, err error) {
if err != nil {
t.Fatalf("Insert failed: %v", err)
}
}
// This test covers a case when buffer starts circling and consumer tries
// to read the record which is already overlapped by another record.
// To reproduce that few conditions must be met:
// - read cursor should point to the body of the overlapping record, but not header
// - read cursor should point on first of 4 bytes which represent the length of the record
// in little Endian notation and must be >= 12
// - next 8 bytes must be uint number equals to cursor sequence number
// The data in the test was chosen to satisfy those conditions
func TestBrokenCursorBeforeFirstRecord(t *testing.T) {
var (
firstRecord = []byte{1, 2, 3}
secondRecord = []byte{1, 2, 3, 4, 5}
overlappingRecord = []byte{5, 6, 7, 12, 0, 0, 0, 1}
data = make([]byte, 1<<10)
)
// Initial buffer state: buffer size= 3 + 12 + 5 + 12 = 32 bytes
// |0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|
// ^rc, wc
// read and write cursors point at the beggining of the buffer (offset:0, seq:0)
n := len(firstRecord) + total + len(secondRecord) + total
b, err := New(n, bufFile)
if err != nil {
t.Fatalf("Failed to create buffer: %v", err)
}
defer b.Close()
// inserts the first record: 4 bytes header, 8 bytes sequence number, 3 bytes data
// |15|0|0|0|0|0|0|0|0|0|0|0|1|2|3|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|
// ^rc, wc
// read and write cursors point at the next record position (offset:15, seq:1)
b.Insert(firstRecord)
_, c, _ := b.ReadFirst(data)
// inserts the second record: 4 bytes header, 8 bytes sequence number, 5 bytes data
// |15|0|0|0|0|0|0|0|0|0|0|0|1|2|3|17|1|0|0|0|0|0|0|0|0|0|0|1|2|3|4|5|
// ^wc ^rc
// read cursor remains the same (offset:15, seq:1)
// write cursor points at the begging of the circular buffer,
// because buffer is full (offset:0, seq:2)
b.Insert(secondRecord)
// inserts the overlapping record: 4 bytes header, 8 bytes sequence number, 8 bytes data
// |20|0|0|0|0|0|0|0|0|0|0|2|5|6|7|12|0|0|0|1|0|0|0|0|0|0|0|1|2|3|4|5|
// ^rc ^wc
// read cursor remains the same (offset:15, seq:1) and now it's broken,
// because it points not on the header, but on the data of the sequence 2
// write cursor points at (offset:21, seq:3)
b.Insert(overlappingRecord)
// reads |12|0|0|0|1|0|0|0|0|0|0|0| record which is broken, because
// overlapped by previous record
_, c, _ = b.Read(data, c)
if c.seq == 0 {
t.Fatalf("b.Read err = %v; want read first record", err)
}
readData := data[:len(overlappingRecord)]
if !bytes.Equal(readData, overlappingRecord) {
t.Errorf("Read got %x; want %x", readData, overlappingRecord)
}
}
func BenchmarkRead(b *testing.B) {
var input [][]byte
isize := 1024
for i := 0; i < 50; i++ {
data := make([]byte, isize)
io.ReadFull(rand.Reader, data)
input = append(input, data)
}
f, err := ioutil.TempFile("", "buffer-bench-")
if err != nil {
b.Fatalf("Cannot create temp file: %v", err)
}
name := f.Name()
if err := os.Remove(name); err != nil {
b.Fatalf("Cannot remove temp file: %v", err)
}
buf, err := New(10<<20, f.Name())
if err != nil {
b.Fatalf("Failed to created buf: %v", err)
}
defer buf.Close()
b.ResetTimer()
closec := make(chan struct{})
go insertAll(buf, input, closec)
data := make([]byte, isize)
_, c, err := buf.ReadFirst(data)
if err != nil && err != ErrPartialData && err != ErrNotArrived {
b.Fatalf("buf.ReadFirst err = %v", err)
}
for i := 0; i < b.N; i++ {
_, c, err = buf.Read(data, c)
if err != nil && err != ErrPartialData && err != ErrNotArrived {
b.Fatalf("buf.Read err = %v", err)
}
}
close(closec)
}
func insertAll(b *Buffer, input [][]byte, closec <-chan struct{}) {
inc := make(chan []byte)
for i := 0; i < 12; i++ {
go inserter(b, inc)
}
l := len(input)
for i := 0; ; i++ {
select {
case <-closec:
close(inc)
return
default:
inc <- input[i%l]
}
}
}
func inserter(b *Buffer, inc <-chan []byte) {
for data := range inc {
b.Insert(data)
}
}