bytes.go 770 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package pool
  2. import "sync"
  3. var (
  4. bufPool5k sync.Pool
  5. bufPool2k sync.Pool
  6. bufPool1k sync.Pool
  7. bufPool sync.Pool
  8. )
  9. func GetBytes(size int) []byte {
  10. if size <= 0 {
  11. return nil
  12. }
  13. var x interface{}
  14. if size >= 5*1024 {
  15. x = bufPool5k.Get()
  16. } else if size >= 2*1024 {
  17. x = bufPool2k.Get()
  18. } else if size >= 1*1024 {
  19. x = bufPool1k.Get()
  20. } else {
  21. x = bufPool.Get()
  22. }
  23. if x == nil {
  24. return make([]byte, size)
  25. }
  26. buf := x.([]byte)
  27. if cap(buf) < size {
  28. return make([]byte, size)
  29. }
  30. return buf[:size]
  31. }
  32. func PutBytes(buf []byte) {
  33. size := cap(buf)
  34. if size <= 0 {
  35. return
  36. }
  37. if size >= 5*1024 {
  38. bufPool5k.Put(buf)
  39. } else if size >= 2*1024 {
  40. bufPool2k.Put(buf)
  41. } else if size >= 1*1024 {
  42. bufPool1k.Put(buf)
  43. } else {
  44. bufPool.Put(buf)
  45. }
  46. }