1
0

buf.go 1.4 KB

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