mem

package
v2.9.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2024 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package mem implements the memory utility such as memory pool.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields
}

Pool represents memory pool of T.

It is suitable for managing temporary objects that can be individually saved and retrieved (mem.Pool.Put and mem.Pool.Get). Unlike variables or pointer variables, mem.Pool is safe for use by multiple goroutines and no new memory will be allocated.

It is a wrapper of sync.Pool to support generics and easy to use. For the actual usage, see the example in the package documentation.

Example
package main

import (
	"fmt"

	"github.com/ikawaha/kagome/v2/tokenizer/lattice/mem"
)

func main() {
	type Foo struct {
		Bar string
	}

	// newFoo is a constructor of Foo type.
	newFoo := func() *Foo {
		return &Foo{
			Bar: "let the foo begin",
		}
	}

	// Create a new memory pool of Foo type.
	// If the memory pool is empty, it creates a new instance of Foo using newFoo.
	bufPool := mem.NewPool[Foo](newFoo)

	// Retrieve a Foo instance from the memory pool and print the current value
	// of the Bar field.
	a := bufPool.Get()
	fmt.Println(a.Bar)

	// Set the Bar field then put it back to the memory pool.
	a.Bar = "buz"
	bufPool.Put(a)

	// Same as above but set a different value to the Bar field.
	//
	// This will overwrite the previous value. But note that this will not allocate
	// new memory and is safe for use by multiple goroutines simultaneously.
	// See the benchmark in the same test file.
	b := bufPool.Get()
	b.Bar = "qux"
	bufPool.Put(b)

	// Retrieve a Foo instance from the memory pool and print the current value
	// of the Bar field.
	c := bufPool.Get()
	fmt.Println(c.Bar)
}
Output:

let the foo begin
qux

func NewPool

func NewPool[T any](newF func() *T) Pool[T]

NewPool returns a memory pool of T. newF is a constructor of T, and it is called when the memory pool is empty.

func (Pool[T]) Get

func (p Pool[T]) Get() *T

Get gets instance of T from the memory pool.

func (Pool[T]) Put

func (p Pool[T]) Put(x *T)

Put puts the instance to the memory pool.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL