buf.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2018 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package pool
  15. import (
  16. "sync"
  17. )
  18. var (
  19. bufPool16k sync.Pool
  20. bufPool5k sync.Pool
  21. bufPool2k sync.Pool
  22. bufPool1k sync.Pool
  23. bufPool sync.Pool
  24. )
  25. func GetBuf(size int) []byte {
  26. var x interface{}
  27. if size >= 16*1024 {
  28. x = bufPool16k.Get()
  29. } else if size >= 5*1024 {
  30. x = bufPool5k.Get()
  31. } else if size >= 2*1024 {
  32. x = bufPool2k.Get()
  33. } else if size >= 1*1024 {
  34. x = bufPool1k.Get()
  35. } else {
  36. x = bufPool.Get()
  37. }
  38. if x == nil {
  39. return make([]byte, size)
  40. }
  41. buf := x.([]byte)
  42. if cap(buf) < size {
  43. return make([]byte, size)
  44. }
  45. return buf[:size]
  46. }
  47. func PutBuf(buf []byte) {
  48. size := cap(buf)
  49. if size >= 16*1024 {
  50. bufPool16k.Put(buf)
  51. } else 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. }