iobufpool.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Package iobufpool implements a global segregated-fit pool of buffers for IO.
  2. //
  3. // It uses *[]byte instead of []byte to avoid the sync.Pool allocation with Put. Unfortunately, using a pointer to avoid
  4. // an allocation is purposely not documented. https://github.com/golang/go/issues/16323
  5. package iobufpool
  6. import (
  7. "math/bits"
  8. "sync"
  9. )
  10. const minPoolExpOf2 = 8
  11. var pools [18]*sync.Pool
  12. func init() {
  13. for i := range pools {
  14. bufLen := 1 << (minPoolExpOf2 + i)
  15. pools[i] = &sync.Pool{
  16. New: func() any {
  17. buf := make([]byte, bufLen)
  18. return &buf
  19. },
  20. }
  21. }
  22. }
  23. // Get gets a []byte of len size with cap <= size*2.
  24. func Get(size int) *[]byte {
  25. i := getPoolIdx(size)
  26. if i >= len(pools) {
  27. buf := make([]byte, size)
  28. return &buf
  29. }
  30. ptrBuf := (pools[i].Get().(*[]byte))
  31. *ptrBuf = (*ptrBuf)[:size]
  32. return ptrBuf
  33. }
  34. func getPoolIdx(size int) int {
  35. if size < 2 {
  36. return 0
  37. }
  38. idx := bits.Len(uint(size-1)) - minPoolExpOf2
  39. if idx < 0 {
  40. return 0
  41. }
  42. return idx
  43. }
  44. // Put returns buf to the pool.
  45. func Put(buf *[]byte) {
  46. i := putPoolIdx(cap(*buf))
  47. if i < 0 {
  48. return
  49. }
  50. pools[i].Put(buf)
  51. }
  52. func putPoolIdx(size int) int {
  53. // Only exact power-of-2 sizes match pool buckets
  54. if size&(size-1) != 0 {
  55. return -1
  56. }
  57. // Calculate log2(size) using trailing zeros count
  58. exp := bits.TrailingZeros(uint(size))
  59. idx := exp - minPoolExpOf2
  60. if idx < 0 || idx >= len(pools) {
  61. return -1
  62. }
  63. return idx
  64. }