pool.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package common
  2. import (
  3. "sync"
  4. )
  5. const PoolSize = 64 * 1024
  6. const PoolSizeSmall = 100
  7. const PoolSizeUdp = 1472 + 200
  8. const PoolSizeCopy = 32 << 10
  9. var BufPool = sync.Pool{
  10. New: func() interface{} {
  11. return make([]byte, PoolSize)
  12. },
  13. }
  14. var BufPoolUdp = sync.Pool{
  15. New: func() interface{} {
  16. return make([]byte, PoolSizeUdp)
  17. },
  18. }
  19. var BufPoolMax = sync.Pool{
  20. New: func() interface{} {
  21. return make([]byte, PoolSize)
  22. },
  23. }
  24. var BufPoolSmall = sync.Pool{
  25. New: func() interface{} {
  26. return make([]byte, PoolSizeSmall)
  27. },
  28. }
  29. var BufPoolCopy = sync.Pool{
  30. New: func() interface{} {
  31. return make([]byte, PoolSizeCopy)
  32. },
  33. }
  34. func PutBufPoolUdp(buf []byte) {
  35. if cap(buf) == PoolSizeUdp {
  36. BufPoolUdp.Put(buf[:PoolSizeUdp])
  37. }
  38. }
  39. func PutBufPoolCopy(buf []byte) {
  40. if cap(buf) == PoolSizeCopy {
  41. BufPoolCopy.Put(buf[:PoolSizeCopy])
  42. }
  43. }
  44. func GetBufPoolCopy() []byte {
  45. return (BufPoolCopy.Get().([]byte))[:PoolSizeCopy]
  46. }
  47. func PutBufPoolMax(buf []byte) {
  48. if cap(buf) == PoolSize {
  49. BufPoolMax.Put(buf[:PoolSize])
  50. }
  51. }
  52. type copyBufferPool struct {
  53. pool sync.Pool
  54. }
  55. func (Self *copyBufferPool) New() {
  56. Self.pool = sync.Pool{
  57. New: func() interface{} {
  58. return make([]byte, PoolSizeCopy, PoolSizeCopy)
  59. },
  60. }
  61. }
  62. func (Self *copyBufferPool) Get() []byte {
  63. buf := Self.pool.Get().([]byte)
  64. return buf[:PoolSizeCopy] // just like make a new slice, but data may not be 0
  65. }
  66. func (Self *copyBufferPool) Put(x []byte) {
  67. if len(x) == PoolSizeCopy {
  68. Self.pool.Put(x)
  69. } else {
  70. x = nil // buf is not full, not allowed, New method returns a full buf
  71. }
  72. }
  73. var once = sync.Once{}
  74. var CopyBuff = copyBufferPool{}
  75. func newPool() {
  76. CopyBuff.New()
  77. }
  78. func init() {
  79. once.Do(newPool)
  80. }