pool.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2016 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 "sync"
  16. var (
  17. bufPool5k sync.Pool
  18. bufPool2k sync.Pool
  19. bufPool1k sync.Pool
  20. bufPool sync.Pool
  21. )
  22. func GetBuf(size int) []byte {
  23. var x interface{}
  24. if size >= 5*1024 {
  25. x = bufPool5k.Get()
  26. } else if size >= 2*1024 {
  27. x = bufPool2k.Get()
  28. } else if size >= 1*1024 {
  29. x = bufPool1k.Get()
  30. } else {
  31. x = bufPool.Get()
  32. }
  33. if x == nil {
  34. return make([]byte, size)
  35. }
  36. buf := x.([]byte)
  37. if cap(buf) < size {
  38. return make([]byte, size)
  39. }
  40. return buf[:size]
  41. }
  42. func PutBuf(buf []byte) {
  43. size := cap(buf)
  44. if size >= 5*1024 {
  45. bufPool5k.Put(buf)
  46. } else if size >= 2*1024 {
  47. bufPool2k.Put(buf)
  48. } else if size >= 1*1024 {
  49. bufPool1k.Put(buf)
  50. } else {
  51. bufPool.Put(buf)
  52. }
  53. }