pool.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package pool
  2. import (
  3. "bytes"
  4. "sync"
  5. )
  6. const PoolSize = 64 * 1024
  7. const PoolSizeSmall = 100
  8. const PoolSizeUdp = 1472
  9. const PoolSizeCopy = 32 << 10
  10. var BufPool = sync.Pool{
  11. New: func() interface{} {
  12. return make([]byte, PoolSize)
  13. },
  14. }
  15. var BufPoolUdp = sync.Pool{
  16. New: func() interface{} {
  17. return make([]byte, PoolSizeUdp)
  18. },
  19. }
  20. var BufPoolMax = sync.Pool{
  21. New: func() interface{} {
  22. return make([]byte, PoolSize)
  23. },
  24. }
  25. var BufPoolSmall = sync.Pool{
  26. New: func() interface{} {
  27. return make([]byte, PoolSizeSmall)
  28. },
  29. }
  30. var BufPoolCopy = sync.Pool{
  31. New: func() interface{} {
  32. return make([]byte, PoolSizeCopy)
  33. },
  34. }
  35. func PutBufPoolUdp(buf []byte) {
  36. if cap(buf) == PoolSizeUdp {
  37. BufPoolUdp.Put(buf[:PoolSizeUdp])
  38. }
  39. }
  40. func PutBufPoolCopy(buf []byte) {
  41. if cap(buf) == PoolSizeCopy {
  42. BufPoolCopy.Put(buf[:PoolSizeCopy])
  43. }
  44. }
  45. func GetBufPoolCopy() []byte {
  46. return (BufPoolCopy.Get().([]byte))[:PoolSizeCopy]
  47. }
  48. func PutBufPoolMax(buf []byte) {
  49. if cap(buf) == PoolSize {
  50. BufPoolMax.Put(buf[:PoolSize])
  51. }
  52. }
  53. type CopyBufferPool struct {
  54. pool sync.Pool
  55. }
  56. func (Self *CopyBufferPool) New() {
  57. Self.pool = sync.Pool{
  58. New: func() interface{} {
  59. return make([]byte, PoolSizeCopy, PoolSizeCopy)
  60. },
  61. }
  62. }
  63. func (Self *CopyBufferPool) Get() []byte {
  64. buf := Self.pool.Get().([]byte)
  65. return buf[:cap(buf)] // grow to capacity
  66. }
  67. func (Self *CopyBufferPool) Put(x []byte) {
  68. x = x[:0]
  69. Self.pool.Put(x)
  70. }
  71. type BufferPool struct {
  72. pool sync.Pool
  73. }
  74. func (Self *BufferPool) New() {
  75. Self.pool = sync.Pool{
  76. New: func() interface{} {
  77. return new(bytes.Buffer)
  78. },
  79. }
  80. }
  81. func (Self *BufferPool) Get() *bytes.Buffer {
  82. return Self.pool.Get().(*bytes.Buffer)
  83. }
  84. func (Self *BufferPool) Put(x *bytes.Buffer) {
  85. x.Reset()
  86. Self.pool.Put(x)
  87. }
  88. var once = sync.Once{}
  89. var BuffPool = BufferPool{}
  90. var CopyBuff = CopyBufferPool{}
  91. func newPool() {
  92. BuffPool.New()
  93. CopyBuff.New()
  94. }
  95. func init() {
  96. once.Do(newPool)
  97. }