pool_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package bytebufferpool
  2. import (
  3. "math/rand"
  4. "testing"
  5. "time"
  6. )
  7. func TestIndex(t *testing.T) {
  8. testIndex(t, 0, 0)
  9. testIndex(t, 1, 0)
  10. testIndex(t, minSize-1, 0)
  11. testIndex(t, minSize, 0)
  12. testIndex(t, minSize+1, 1)
  13. testIndex(t, 2*minSize-1, 1)
  14. testIndex(t, 2*minSize, 1)
  15. testIndex(t, 2*minSize+1, 2)
  16. testIndex(t, maxSize-1, steps-1)
  17. testIndex(t, maxSize, steps-1)
  18. testIndex(t, maxSize+1, steps-1)
  19. }
  20. func testIndex(t *testing.T, n, expectedIdx int) {
  21. idx := index(n)
  22. if idx != expectedIdx {
  23. t.Fatalf("unexpected idx for n=%d: %d. Expecting %d", n, idx, expectedIdx)
  24. }
  25. }
  26. func TestPoolCalibrate(t *testing.T) {
  27. for i := 0; i < steps*calibrateCallsThreshold; i++ {
  28. n := 1004
  29. if i%15 == 0 {
  30. n = rand.Intn(15234)
  31. }
  32. testGetPut(t, n)
  33. }
  34. }
  35. func TestPoolVariousSizesSerial(t *testing.T) {
  36. testPoolVariousSizes(t)
  37. }
  38. func TestPoolVariousSizesConcurrent(t *testing.T) {
  39. concurrency := 5
  40. ch := make(chan struct{})
  41. for i := 0; i < concurrency; i++ {
  42. go func() {
  43. testPoolVariousSizes(t)
  44. ch <- struct{}{}
  45. }()
  46. }
  47. for i := 0; i < concurrency; i++ {
  48. select {
  49. case <-ch:
  50. case <-time.After(3 * time.Second):
  51. t.Fatalf("timeout")
  52. }
  53. }
  54. }
  55. func testPoolVariousSizes(t *testing.T) {
  56. for i := 0; i < steps+1; i++ {
  57. n := (1 << uint32(i))
  58. testGetPut(t, n)
  59. testGetPut(t, n+1)
  60. testGetPut(t, n-1)
  61. for j := 0; j < 10; j++ {
  62. testGetPut(t, j+n)
  63. }
  64. }
  65. }
  66. func testGetPut(t *testing.T, n int) {
  67. bb := Get()
  68. if len(bb.B) > 0 {
  69. t.Fatalf("non-empty byte buffer returned from acquire")
  70. }
  71. bb.B = allocNBytes(bb.B, n)
  72. Put(bb)
  73. }
  74. func allocNBytes(dst []byte, n int) []byte {
  75. diff := n - cap(dst)
  76. if diff <= 0 {
  77. return dst[:n]
  78. }
  79. return append(dst, make([]byte, diff)...)
  80. }