github.com/trim21/go-phpserialize@v0.0.22-0.20240301204449-2fca0319b3f0/internal/encoder/context.go (about)

     1  package encoder
     2  
     3  import (
     4  	"sync"
     5  	"unsafe"
     6  
     7  	"github.com/trim21/go-phpserialize/internal/runtime"
     8  )
     9  
    10  var ctxPool = sync.Pool{
    11  	New: func() any {
    12  		return &Ctx{
    13  			Buf:         make([]byte, 0, 1024),
    14  			KeepRefs:    make([]unsafe.Pointer, 0, 8),
    15  			smallBuffer: make([]byte, 0, 20),
    16  		}
    17  	},
    18  }
    19  
    20  type Ctx struct {
    21  	smallBuffer []byte // a small buffer to encode float and time.Time as string
    22  	KeepRefs    []unsafe.Pointer
    23  	Buf         []byte
    24  }
    25  
    26  func newCtx() *Ctx {
    27  	ctx := ctxPool.Get().(*Ctx)
    28  	ctx.KeepRefs = ctx.KeepRefs[:0]
    29  	ctx.smallBuffer = ctx.smallBuffer[:0]
    30  
    31  	return ctx
    32  }
    33  
    34  func freeCtx(ctx *Ctx) {
    35  	ctx.KeepRefs = ctx.KeepRefs[:0]
    36  
    37  	ctxPool.Put(ctx)
    38  }
    39  
    40  // A mapIter is an iterator for ranging over a map.
    41  // See ValueUnsafeAddress.MapRange.
    42  type mapIter struct {
    43  	Iter runtime.HashIter
    44  }
    45  
    46  var mapCtxPool = sync.Pool{
    47  	New: func() any {
    48  		return &mapIter{}
    49  	},
    50  }
    51  
    52  func newMapCtx() *mapIter {
    53  	ctx := mapCtxPool.Get().(*mapIter)
    54  	return ctx
    55  }
    56  
    57  func freeMapCtx(ctx *mapIter) {
    58  	ctx.Iter = runtime.HashIter{}
    59  	mapCtxPool.Put(ctx)
    60  }