buffer.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2016 The Internal Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package buffer implements a pool of pointers to byte slices.
  5. //
  6. // Example usage pattern
  7. //
  8. // p := buffer.Get(size)
  9. // b := *p // Now you can use b in any way you need.
  10. // ...
  11. // // When b will not be used anymore
  12. // buffer.Put(p)
  13. // ...
  14. // // If b or p are not going out of scope soon, optionally
  15. // b = nil
  16. // p = nil
  17. //
  18. // Otherwise the pool cannot release the buffer on garbage collection.
  19. //
  20. // Do not do
  21. //
  22. // p := buffer.Get(size)
  23. // b := *p
  24. // ...
  25. // buffer.Put(&b)
  26. //
  27. // or
  28. //
  29. // b := *buffer.Get(size)
  30. // ...
  31. // buffer.Put(&b)
  32. package buffer
  33. import (
  34. "github.com/cznic/internal/slice"
  35. )
  36. // CGet returns a pointer to a byte slice of len size. The pointed to byte
  37. // slice is zeroed up to its cap. CGet panics for size < 0.
  38. //
  39. // CGet is safe for concurrent use by multiple goroutines.
  40. func CGet(size int) *[]byte { return slice.Bytes.CGet(size).(*[]byte) }
  41. // Get returns a pointer to a byte slice of len size. The pointed to byte slice
  42. // is not zeroed. Get panics for size < 0.
  43. //
  44. // Get is safe for concurrent use by multiple goroutines.
  45. func Get(size int) *[]byte { return slice.Bytes.Get(size).(*[]byte) }
  46. // Put puts a pointer to a byte slice into a pool for possible later reuse by
  47. // CGet or Get.
  48. //
  49. // Put is safe for concurrent use by multiple goroutines.
  50. func Put(p *[]byte) { slice.Bytes.Put(p) }