feature_pool.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package jsoniter
  2. import (
  3. "io"
  4. )
  5. // IteratorPool a thread safe pool of iterators with same configuration
  6. type IteratorPool interface {
  7. BorrowIterator(data []byte) *Iterator
  8. ReturnIterator(iter *Iterator)
  9. }
  10. // StreamPool a thread safe pool of streams with same configuration
  11. type StreamPool interface {
  12. BorrowStream(writer io.Writer) *Stream
  13. ReturnStream(stream *Stream)
  14. }
  15. func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream {
  16. select {
  17. case stream := <-cfg.streamPool:
  18. stream.Reset(writer)
  19. return stream
  20. default:
  21. return NewStream(cfg, writer, 512)
  22. }
  23. }
  24. func (cfg *frozenConfig) ReturnStream(stream *Stream) {
  25. stream.Error = nil
  26. stream.Attachment = nil
  27. select {
  28. case cfg.streamPool <- stream:
  29. return
  30. default:
  31. return
  32. }
  33. }
  34. func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator {
  35. select {
  36. case iter := <-cfg.iteratorPool:
  37. iter.ResetBytes(data)
  38. return iter
  39. default:
  40. return ParseBytes(cfg, data)
  41. }
  42. }
  43. func (cfg *frozenConfig) ReturnIterator(iter *Iterator) {
  44. iter.Error = nil
  45. iter.Attachment = nil
  46. select {
  47. case cfg.iteratorPool <- iter:
  48. return
  49. default:
  50. return
  51. }
  52. }