buffer_seeker_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package bufioutil
  2. import (
  3. "bytes"
  4. "io"
  5. "strings"
  6. "testing"
  7. )
  8. func TestBufferedSeeker(t *testing.T) {
  9. const alphabet = "abcdefghijklmnopqrstuvwxyz"
  10. bs := NewBufferedSeeker(strings.NewReader(alphabet), 0) // minReadBufferSize = 16
  11. checkRead := func(buf []byte, expected string) {
  12. t.Helper()
  13. _, err := bs.Read(buf)
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. if !bytes.Equal(buf, []byte(expected)) {
  18. t.Fatalf("expected %s, got %s", expected, buf)
  19. }
  20. }
  21. // Read the first 5 bytes
  22. buf := make([]byte, 5)
  23. checkRead(buf, "abcde")
  24. // Seek back to the beginning
  25. _, err := bs.Seek(0, io.SeekStart)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. // read 'a'
  30. checkRead(buf[:1], "a")
  31. if bs.br.Buffered() == 0 {
  32. t.Fatalf("totally unexpected sanity check failed")
  33. }
  34. // Seek past 'b'
  35. _, err = bs.Seek(1, io.SeekCurrent)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. checkRead(buf, "cdefg")
  40. // Seek back to the beginning
  41. _, err = bs.Seek(0, io.SeekStart)
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. checkRead(buf, "abcde")
  46. // Seek to the end
  47. _, err = bs.Seek(-5, io.SeekEnd)
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. checkRead(buf, "vwxyz")
  52. }