adt

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: May 4, 2023 License: Apache-2.0 Imports: 9 Imported by: 18

Documentation

Overview

Package adt provides "atomic data types" as strongly-typed generic helpers for simple atomic operations (including sync.Map, sync.Pool, and a typed value).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareAndSwap

func CompareAndSwap[T comparable](a AtomicValue[T], old, new T) bool

CompareAndSwap exposes the CompareAndSwap option for atomics that store values of comparable types. Only supports the Atomic and Synchronized types, as well as any type that implement a CompareAndSwap method for old/new values of T. Panics for all other types.

func IsAtomicZero

func IsAtomicZero[T comparable](in AtomicValue[T]) bool

IsAtomicZero checks an atomic value for a comparable type to see if it's zero. The fun.IsZero() function can't correctly check both that the Atomic is zero and that it holds a zero value, and because atomics need not be comparable this can't be a method on Atomic.

func Mnemonize added in v0.9.0

func Mnemonize[T any](in func() T) func() T

Mnemonize, like adt.Once, provides a way to lazily resolve and cache a value. Mnemonize takes an input function that returns a type and returns a function of the same signature. When the function is called the first time it caches the value and.

While the function produced by Mnemonize is safe to use concurrently, there is no provision for protecting mutable types returned by the function and concurrent modification of mutable returned values is a race.

func NewIterator added in v0.8.5

func NewIterator[T any](mtx *sync.Mutex, iter fun.Iterator[T]) fun.Iterator[T]

NewIterator constructs an iterator that wraps the input iterator but that protects every single operations against the iterator with the mutext. Be careful, however, because single logical operations (e.g. advance with Next() and access with Value()) are not isolated with regards to eachother so multiple goroutines can have logical races if both are iterating concurrently. As a special case the fun.IterateOne function allows for safe, concurrent iteration of these iterators.

func SafeSet

func SafeSet[T comparable](atom AtomicValue[T], value T)

SafeSet sets the atomic to the given value only if the value is not the Zero value for that type.

Types

type Atomic

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

Atomic is a very simple atomic Get/Set operation, providing a generic type-safe implementation wrapping sync/atomic.Value.

func NewAtomic

func NewAtomic[T any](initial T) *Atomic[T]

NewAtomic creates a new Atomic Get/Set value with the initial value already set.

func (*Atomic[T]) Get

func (a *Atomic[T]) Get() T

Get resolves the atomic value, returning the zero value of the type T if the value is unset.

func (*Atomic[T]) Set

func (a *Atomic[T]) Set(in T)

Set atomically sets the value of the Atomic.

func (*Atomic[T]) Swap

func (a *Atomic[T]) Swap(new T) (old T)

Swap does an in place exchange of the contents of a value exchanging the new value for the old. Unlike sync.Atomic.Swap() if new is nil, adt.Atomic.Swap() does NOT panic, and instead constructs the zero value of type T.

type AtomicValue added in v0.9.0

type AtomicValue[T any] interface {
	Get() T
	Set(T)
	Swap(T) T
}

AtomicValue describes the public interface of the Atomic type. Use this definition to compose atomic types into other interfaces.

type Map

type Map[K comparable, V any] struct {
	// Default handles construction and pools objects in
	// the map for the Ensure and Get operations which must
	// construct zero-value items. No configuration or
	// construction is necessary; however, callers can modify the
	// default value constructed as needed.
	Default Pool[V]
	// contains filtered or unexported fields
}

Map provides a wrapper around the standard library's sync.Map type with key/value types enforced by generics. Additional helpers (Append, Extend, Populate) support adding multiple items to the map, while Iterator and StoreFrom provide compatibility with iterators.

func (*Map[K, V]) Contains

func (mp *Map[K, V]) Contains(key K) bool

Contain returns true if the key exists in the map or false otherwise.

func (*Map[K, V]) Delete

func (mp *Map[K, V]) Delete(key K)

Delete removes a key--and its corresponding value--from the map, if it exists.

func (*Map[K, V]) Ensure

func (mp *Map[K, V]) Ensure(key K)

Ensure adds a key to the map if it does not already exist, using the default value. The default value, is taken from the pool, which has a configurable constructor if you want a different default value.

func (*Map[K, V]) EnsureDefault

func (mp *Map[K, V]) EnsureDefault(key K, constr func() V) V

EnsureDefault is similar to EnsureStore and Ensure, but provides the default value as a function that produces a value rather than the value directly. The returned value is *always* the value of the key, which is either the value from the map or the value produced by the function.

The constructor function is *always* called, even when the key exists in the map. Unlike Get and Ensure which have similar semantics and roles, the value produced by function does not participate in the default object pool.

func (*Map[K, V]) EnsureSet added in v0.8.5

func (mp *Map[K, V]) EnsureSet(i fun.Pair[K, V]) bool

EnsureSet has the same semantics as EnsureStore, but takes a fun.Pair object.

func (*Map[K, V]) EnsureStore added in v0.8.5

func (mp *Map[K, V]) EnsureStore(k K, v V) bool

Ensure store takes a value and returns true if the value was stored in the map.

func (*Map[K, V]) Get

func (mp *Map[K, V]) Get(key K) V

Get retrieves the value from the map at the given value. If the key is not present in the map a default value is created and added to the map.

func (*Map[K, V]) Iterator

func (mp *Map[K, V]) Iterator() fun.Iterator[fun.Pair[K, V]]

Iterator returns an iterator that produces a sequence of pair objects.

This operation relies on a the underlying Range iterator, and advances lazily through the Range operation as callers advance the iterator. Be aware that this produces an iterator that does not reflect any particular atomic of the underlying map.

func (*Map[K, V]) Keys added in v0.8.5

func (mp *Map[K, V]) Keys() fun.Iterator[K]

Keys returns an iterator that renders all of the keys in the map.

This operation relies on a the underlying Range iterator, and advances lazily through the Range operation as callers advance the iterator. Be aware that this produces an iterator that does not reflect any particular atomic of the underlying map.

func (*Map[K, V]) Len

func (mp *Map[K, V]) Len() int

Len counts and reports on the number of items in the map. This is provided by iterating and counting the values in the map, and has O(n) performance.

Len uses a range function and therefore does not reflect a specific snapshot of the map at any time if keys are being deleted while Len is running. Len will never report a number that is larger than the total number of items in the map while Len is running, but the number of items in the map may be smaller at the beginning and/or the end than reported.

func (*Map[K, V]) Load

func (mp *Map[K, V]) Load(key K) (V, bool)

Load retrieves the value from the map. The semantics are the same as for maps in go: if the value does not exist it always returns the zero value for the type, while the second value indicates if the key was present in the map.

func (*Map[K, V]) MarshalJSON

func (mp *Map[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON produces a JSON form of the map, using a Range function to iterate through the values in the map. Range functions do not reflect a specific snapshot of the map if the map is being modified while being marshaled: keys will only appear at most once but order or which version of a value is not defined.

func (*Map[K, V]) Range

func (mp *Map[K, V]) Range(fn func(K, V) bool)

Range provides a method for iterating over the values in the map, with a similar API as the standard library's sync.Map. The function is called once on every key in the map. When the range function returns false the iteration stops.

Range functions do not reflect a specific snapshot of the map if the map is being modified while being marshaled: keys will only appear at most once but order or which version of a value is not defined.

func (*Map[K, V]) Set

func (mp *Map[K, V]) Set(it fun.Pair[K, V])

Set adds a key and value to the map from a Pair.

func (*Map[K, V]) Store

func (mp *Map[K, V]) Store(k K, v V)

Store adds a key and value to the map, replacing any existing values as needed.

func (*Map[K, V]) Swap

func (mp *Map[K, V]) Swap(k K, v V) (V, bool)

func (*Map[K, V]) UnmarshalJSON

func (mp *Map[K, V]) UnmarshalJSON(in []byte) error

UnmarshalJSON takes a json sequence and adds the values to the map. This does not remove or reset the values in the map, and

func (*Map[K, V]) Values added in v0.8.5

func (mp *Map[K, V]) Values() fun.Iterator[V]

Values returns an iterator that renders all of the values in the map.

This operation relies on a the underlying Range iterator, and advances lazily through the Range operation as callers advance the iterator. Be aware that this produces an iterator that does not reflect any particular atomic of the underlying map.

type Once added in v0.9.0

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

Once provides a mnemonic form of sync.Once, caching and returning a value after the Do() function is called.

func (*Once[T]) Do added in v0.9.0

func (o *Once[T]) Do(constr func() T) T

Do runs the function provided and returns its value. All subsequent calls to Do return the value of the first function passed to do. If multiple callers use Do at the same time, like sync.Once.Do none will return until return until the first operation completes.

Functions passed to Do should return values that are safe for concurrent access: while the Do operation is synchronized, the return value from Do is responsible for its own synchronization.

type Pool

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

Pool is an ergonomic wrapper around sync.Pool that provides some additional functionality: generic type interface, a default clean up hook to modify (optionally) the object before returning it to the pool.

Additionally, the Make() method attaches an object finalizer to the object produced by the pool that returns the object to the pool rather than garbage collect it. This is likely to be less efficient than return the objects to the pool using defer functions, but may be more ergonomic in some situations.

Pool can be used with default construction; however, you should set the Constructor before calling Get() or Make() on the pool.

func (*Pool[T]) Get

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

Get returns an object from the pool or constructs a default object according to the constructor.

func (*Pool[T]) Make

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

Make gets an object out of the sync.Pool, and attaches a finalizer that returns the item to the pool when the object would be garbage collected.

Finalizer hooks are not automatically cleared by the Put() operation, so objects retrieved with Make should not be passed manually to Put().

func (*Pool[T]) Put

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

Put returns an object in the pool, calling the cleanuphook if set. Put *always* clears the object's finalizer before calling the cleanuphook or returning it to the pool.

func (*Pool[T]) SetCleanupHook

func (p *Pool[T]) SetCleanupHook(in func(T) T)

SetCleanupHook sets a function to be called on every object renetering the pool. By default, the cleanup function is a noop.

func (*Pool[T]) SetConstructor

func (p *Pool[T]) SetConstructor(in func() T)

SetConstructor overrides the default constructor (which makes an object with a Zero value by default) for Get/Make operations.

type Synchronized added in v0.8.7

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

Synchronized wraps an arbitrary type with a lock, and provides a functional interface for interacting with that type. In general Synchronize is ideal for container and interface types which are not safe for concurrent use, when either `adt.Map`, `adt.Atomic` are not appropriate.

func NewSynchronized added in v0.8.7

func NewSynchronized[T any](in T) *Synchronized[T]

NewSynchronized constructs a new synchronized object that wraps the input type.

func (*Synchronized[T]) Get added in v0.8.9

func (s *Synchronized[T]) Get() T

Get returns the underlying protected object. Use with caution.

func (*Synchronized[T]) Set added in v0.8.7

func (s *Synchronized[T]) Set(in T)

Set overrides the current value of the protected object. Use with caution.

func (*Synchronized[T]) String added in v0.8.9

func (s *Synchronized[T]) String() string

String implements fmt.Stringer using this type.

func (*Synchronized[T]) Swap added in v0.8.9

func (s *Synchronized[T]) Swap(new T) (old T)

Swap sets the locked value to the new value and returns the old.

func (*Synchronized[T]) With added in v0.8.7

func (s *Synchronized[T]) With(in func(obj T))

With runs the input function within the lock, to mutate the object.

Jump to

Keyboard shortcuts

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