pool.go 1016 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package yamux
  2. import (
  3. "bytes"
  4. "sync"
  5. )
  6. var (
  7. bufferPool sync.Pool
  8. bufPool5k sync.Pool
  9. bufPool2k sync.Pool
  10. bufPool1k sync.Pool
  11. bufPool sync.Pool
  12. )
  13. func getBuffer() *bytes.Buffer {
  14. if v := bufferPool.Get(); v != nil {
  15. return v.(*bytes.Buffer)
  16. }
  17. return bytes.NewBuffer([]byte{})
  18. }
  19. func putBuffer(b *bytes.Buffer) {
  20. b.Reset()
  21. bufferPool.Put(b)
  22. }
  23. func getBytes(size int) []byte {
  24. if size <= 0 {
  25. return nil
  26. }
  27. var x interface{}
  28. if size >= 5*1024 {
  29. x = bufPool5k.Get()
  30. } else if size >= 2*1024 {
  31. x = bufPool2k.Get()
  32. } else if size >= 1*1024 {
  33. x = bufPool1k.Get()
  34. } else {
  35. x = bufPool.Get()
  36. }
  37. if x == nil {
  38. return make([]byte, size)
  39. }
  40. buf := x.([]byte)
  41. if cap(buf) < size {
  42. return make([]byte, size)
  43. }
  44. return buf[:size]
  45. }
  46. func putBytes(buf []byte) {
  47. size := cap(buf)
  48. if size <= 0 {
  49. return
  50. }
  51. if size >= 5*1024 {
  52. bufPool5k.Put(buf)
  53. } else if size >= 2*1024 {
  54. bufPool2k.Put(buf)
  55. } else if size >= 1*1024 {
  56. bufPool1k.Put(buf)
  57. } else {
  58. bufPool.Put(buf)
  59. }
  60. }