buffer_pool.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package quic
  2. import (
  3. "sync"
  4. "github.com/Psiphon-Labs/quic-go/internal/protocol"
  5. )
  6. type packetBuffer struct {
  7. Data []byte
  8. // refCount counts how many packets Data is used in.
  9. // It doesn't support concurrent use.
  10. // It is > 1 when used for coalesced packet.
  11. refCount int
  12. }
  13. // Split increases the refCount.
  14. // It must be called when a packet buffer is used for more than one packet,
  15. // e.g. when splitting coalesced packets.
  16. func (b *packetBuffer) Split() {
  17. b.refCount++
  18. }
  19. // Decrement decrements the reference counter.
  20. // It doesn't put the buffer back into the pool.
  21. func (b *packetBuffer) Decrement() {
  22. b.refCount--
  23. if b.refCount < 0 {
  24. panic("negative packetBuffer refCount")
  25. }
  26. }
  27. // MaybeRelease puts the packet buffer back into the pool,
  28. // if the reference counter already reached 0.
  29. func (b *packetBuffer) MaybeRelease() {
  30. // only put the packetBuffer back if it's not used any more
  31. if b.refCount == 0 {
  32. b.putBack()
  33. }
  34. }
  35. // Release puts back the packet buffer into the pool.
  36. // It should be called when processing is definitely finished.
  37. func (b *packetBuffer) Release() {
  38. b.Decrement()
  39. if b.refCount != 0 {
  40. panic("packetBuffer refCount not zero")
  41. }
  42. b.putBack()
  43. }
  44. // Len returns the length of Data
  45. func (b *packetBuffer) Len() protocol.ByteCount {
  46. return protocol.ByteCount(len(b.Data))
  47. }
  48. func (b *packetBuffer) putBack() {
  49. if cap(b.Data) != int(protocol.MaxPacketBufferSize) {
  50. panic("putPacketBuffer called with packet of wrong size!")
  51. }
  52. bufferPool.Put(b)
  53. }
  54. var bufferPool sync.Pool
  55. func getPacketBuffer() *packetBuffer {
  56. buf := bufferPool.Get().(*packetBuffer)
  57. buf.refCount = 1
  58. buf.Data = buf.Data[:0]
  59. return buf
  60. }
  61. func init() {
  62. bufferPool.New = func() interface{} {
  63. return &packetBuffer{
  64. Data: make([]byte, 0, protocol.MaxPacketBufferSize),
  65. }
  66. }
  67. }