File: ring_test.go

package info (click to toggle)
golang-github-cilium-ebpf 0.11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,776 kB
  • sloc: ansic: 1,046; makefile: 103; sh: 100
file content (67 lines) | stat: -rw-r--r-- 1,303 bytes parent folder | download | duplicates (3)
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
package ringbuf

import (
	"bytes"
	"io"
	"testing"
)

func TestRingBufferReader(t *testing.T) {
	buf := make([]byte, 2)

	ring := makeRing(2, 0)
	n, err := ring.Read(buf)
	if err != io.EOF {
		t.Error("Expected io.EOF, got", err)
	}
	if n != 2 {
		t.Errorf("Expected to read 2 bytes, got %d", n)
	}
	if !bytes.Equal(buf, []byte{0, 1}) {
		t.Error("Expected [0, 1], got", buf)
	}
	n, err = ring.Read(buf)
	if err != io.EOF {
		t.Error("Expected io.EOF, got", err)
	}
	if n != 0 {
		t.Error("Expected to read 0 bytes, got", n)
	}

	buf = make([]byte, 4)

	ring = makeRing(4, 4)
	n, err = io.ReadFull(ring, buf)
	if err != nil {
		t.Error("Expected nil, got", err)
	}
	if n != 4 {
		t.Errorf("Expected to read 4 bytes, got %d", n)
	}
	if !bytes.Equal(buf, []byte{0, 1, 2, 3}) {
		t.Error("Expected [0, 1, 2, 3], got", buf)
	}
	n, err = ring.Read(buf)
	if err != io.EOF {
		t.Error("Expected io.EOF, got", err)
	}
	if n != 0 {
		t.Error("Expected to read 0 bytes, got", n)
	}
}

func makeRing(size, offset int) *ringReader {
	if size != 0 && (size&(size-1)) != 0 {
		panic("size must be power of two")
	}

	ring := make([]byte, 2*size)
	for i := range ring {
		ring[i] = byte(i)
	}

	consumer := uint64(offset)
	producer := uint64(len(ring)/2 + offset)

	return newRingReader(&consumer, &producer, ring)
}