ring_test.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "fmt"
  5. "reflect"
  6. "testing"
  7. )
  8. var _ = fmt.Print
  9. func TestRingBuffer(t *testing.T) {
  10. r := NewRingBuffer[int](8)
  11. test_contents := func(expected ...int) {
  12. actual := make([]int, len(expected))
  13. num_read := r.ReadTillEmpty(actual)
  14. if num_read != uint64(len(actual)) {
  15. t.Fatalf("Did not read expected num of items: %d != %d", num_read, len(expected))
  16. }
  17. if !reflect.DeepEqual(expected, actual) {
  18. t.Fatalf("Did not read expected items:\n%#v != %#v", actual, expected)
  19. }
  20. if r.Len() != 0 {
  21. t.Fatalf("Reading contents did not empty the buffer")
  22. }
  23. }
  24. r.WriteTillFull(1, 2, 3, 4)
  25. test_contents(1, 2, 3, 4)
  26. r.WriteTillFull(1, 2, 3, 4)
  27. test_contents(1, 2, 3, 4)
  28. r.Clear()
  29. r.WriteTillFull(1, 2, 3, 4)
  30. r.ReadTillEmpty([]int{0, 1})
  31. test_contents(3, 4)
  32. r.WriteTillFull(1, 2, 3, 4, 5)
  33. test_contents(1, 2, 3, 4, 5)
  34. r.Clear()
  35. r.WriteTillFull(1, 2, 3, 4)
  36. r.WriteAllAndDiscardOld(5, 6, 7, 8, 9)
  37. test_contents(2, 3, 4, 5, 6, 7, 8, 9)
  38. }