buffer_pool.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package buf
  2. import (
  3. "os"
  4. "strconv"
  5. "sync"
  6. )
  7. // Pool provides functionality to generate and recycle buffers on demand.
  8. type Pool interface {
  9. // Allocate either returns a unused buffer from the pool, or generates a new one from system.
  10. Allocate() *Buffer
  11. // Free recycles the given buffer.
  12. Free(*Buffer)
  13. }
  14. // SyncPool is a buffer pool based on sync.Pool
  15. type SyncPool struct {
  16. allocator *sync.Pool
  17. }
  18. // NewSyncPool creates a SyncPool with given buffer size.
  19. func NewSyncPool(bufferSize uint32) *SyncPool {
  20. pool := &SyncPool{
  21. allocator: &sync.Pool{
  22. New: func() interface{} { return make([]byte, bufferSize) },
  23. },
  24. }
  25. return pool
  26. }
  27. // Allocate implements Pool.Allocate().
  28. func (p *SyncPool) Allocate() *Buffer {
  29. return CreateBuffer(p.allocator.Get().([]byte), p)
  30. }
  31. // Free implements Pool.Free().
  32. func (p *SyncPool) Free(buffer *Buffer) {
  33. rawBuffer := buffer.v
  34. if rawBuffer == nil {
  35. return
  36. }
  37. p.allocator.Put(rawBuffer)
  38. }
  39. type BufferPool struct {
  40. chain chan []byte
  41. allocator *sync.Pool
  42. }
  43. func NewBufferPool(bufferSize, poolSize uint32) *BufferPool {
  44. pool := &BufferPool{
  45. chain: make(chan []byte, poolSize),
  46. allocator: &sync.Pool{
  47. New: func() interface{} { return make([]byte, bufferSize) },
  48. },
  49. }
  50. for i := uint32(0); i < poolSize; i++ {
  51. pool.chain <- make([]byte, bufferSize)
  52. }
  53. return pool
  54. }
  55. func (p *BufferPool) Allocate() *Buffer {
  56. var b []byte
  57. select {
  58. case b = <-p.chain:
  59. default:
  60. b = p.allocator.Get().([]byte)
  61. }
  62. return CreateBuffer(b, p)
  63. }
  64. func (p *BufferPool) Free(buffer *Buffer) {
  65. rawBuffer := buffer.v
  66. if rawBuffer == nil {
  67. return
  68. }
  69. select {
  70. case p.chain <- rawBuffer:
  71. default:
  72. p.allocator.Put(rawBuffer)
  73. }
  74. }
  75. const (
  76. BufferSize = 8 * 1024
  77. SmallBufferSize = 2 * 1024
  78. PoolSizeEnvKey = "v2ray.buffer.size"
  79. )
  80. var (
  81. mediumPool Pool
  82. smallPool = NewSyncPool(2048)
  83. )
  84. func init() {
  85. var size uint32 = 20
  86. sizeStr := os.Getenv(PoolSizeEnvKey)
  87. if len(sizeStr) > 0 {
  88. customSize, err := strconv.ParseUint(sizeStr, 10, 32)
  89. if err == nil {
  90. size = uint32(customSize)
  91. }
  92. }
  93. if size > 0 {
  94. totalByteSize := size * 1024 * 1024
  95. mediumPool = NewBufferPool(BufferSize, totalByteSize/BufferSize)
  96. } else {
  97. mediumPool = NewSyncPool(BufferSize)
  98. }
  99. }