package xpool

import (
	"github.com/m3db/m3/src/x/checked"
	"github.com/m3db/m3/src/x/pool"
)

type checkedPool struct {
	pool pool.ObjectPool
	opts checked.BytesOptions
}

// NewCheckedBytesWrapperPool returns a new CheckedBytesWrapperPool with the
// defined size.
func NewCheckedBytesWrapperPool(popts pool.ObjectPoolOptions) CheckedBytesWrapperPool {
	p := pool.NewObjectPool(popts)
	opts := checked.NewBytesOptions().SetFinalizer(
		checked.BytesFinalizerFn(func(b checked.Bytes) {
			b.IncRef()
			b.Reset(nil)
			b.DecRef()
			p.Put(b)
		}))

	return &checkedPool{
		pool: p,
		opts: opts,
	}
}

func (p *checkedPool) Init() {
	p.pool.Init(func() interface{} {
		return checked.NewBytes(nil, p.opts)
	})
}

func (p *checkedPool) Get(b []byte) checked.Bytes {
	checkedBytes := p.pool.Get().(checked.Bytes)
	checkedBytes.IncRef()
	checkedBytes.Reset(b)
	checkedBytes.DecRef()
	return checkedBytes
}
