Documentation ¶
Overview ¶
Package safepool provides a wrapper for sync.Pool which ensures type and state safety.
Because the type constraint on the pool, you can always rely to retrieve the expected type specified to the pool. Also, all objects put into the pool need to implement ResetState which sets the state of the objects to a clean "zero" state on putting it back into the pool.
Example ¶
package main import ( "fmt" "github.com/zekrotja/safepool" ) type User struct { Name string } func (t *User) ResetState() { t.Name = "" } func main() { sp := safepool.New(func() *User { return &User{} }) u1 := sp.Get() defer sp.Put(u1) u2 := sp.Get() defer sp.Put(u2) u1.Name = "Zero Two" u2.Name = "Ichigo" fmt.Printf("u1: %+v\n", u1) fmt.Printf("u2: %+v\n", u2) }
Output: u1: &{Name:Zero Two} u2: &{Name:Ichigo}
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ResetState ¶
type ResetState interface {
ResetState()
}
ResetState describes an object which state can be reset to its "zero" state to be put back into the object pool ready for reuse.
type ResetWrapper ¶ added in v1.1.0
type ResetWrapper[T any] struct { Inner T // contains filtered or unexported fields }
ResetWrapper
Example ¶
package main import ( "fmt" "github.com/zekrotja/safepool" ) type ExternalUser struct { Name string } func main() { sp := safepool.New(func() *safepool.ResetWrapper[*ExternalUser] { return safepool.Wrap(&ExternalUser{}, func(v *ExternalUser) { v.Name = "" }) }) user := sp.Get() defer sp.Put(user) user.Inner.Name = "Zero Two" fmt.Printf("user.Inner: %+v\n", user.Inner) }
Output: user.Inner: &{Name:Zero Two}
func Wrap ¶ added in v1.1.0
func Wrap[T any](v T, reset func(v T)) *ResetWrapper[T]
func (ResetWrapper[T]) ResetState ¶ added in v1.1.0
func (t ResetWrapper[T]) ResetState()
type SafePool ¶
type SafePool[T ResetState] struct { // contains filtered or unexported fields }
SafePool wraps sync.Pool in a type and state safe manner. You can always expect to retrieve the object type set to the pool on retrival due to the type constraint on the pool.
All objects need to implement ResetState, which is called when an object instance is put back into the pool to ensure a clean "zero" state on retrival.
func New ¶
func New[T ResetState](new func() T) SafePool[T]
New creates a new SafePool with the given new function to create new objects on demand.