stw

package
v0.14.5 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2026 License: Apache-2.0 Imports: 10 Imported by: 17

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs[T SignedInteger](in T) T

Abs returns the absolute value of the integer.

func AbsBounds

func AbsBounds[T SignedInteger](a, b T) (minVal T, maxVal T)

AbsBounds resolves the absolute values of two numbers and then return the lower (absolute) value followed by the higher absolute value.

func AbsMax

func AbsMax[T SignedInteger](a, b T) T

AbsMax resolves the absolute value of both arguments and returns the larger value.

func AbsMin

func AbsMin[T SignedInteger](a, b T) T

AbsMin resolves the absolute value of both arguments and returns the smaller value.

func Bounds

func Bounds[T Integers](a, b T) (minVal T, maxVal T)

Bounds returns the two arguments as a (min,max): values less than zero become zero.

func Default

func Default[T comparable](input T, defaultValue T) T

Default takes two values. if the first value is the zero value for the type T, then Default returns the second (default) value. Otherwise it returns the first input type.

func DefaultMap

func DefaultMap[K comparable, V any](input map[K]V, args ...int) map[K]V

DefaultMap takes a map value and returns it if it's non-nil. If the map is nil, it constructs and returns a new map, with the (optionally specified length.

func Deref

func Deref[T any](in *T) T

Deref de-references a pointer, panicing if the pointer is nil.

func DerefOk

func DerefOk[T any](in *T) (value T, ok bool)

DerefOk takes a pointer to an value and returns the concrete type for that pointer. If the pointer is nil, DerefOk returns the zero value for that type. The boolean value indicates if the zero value returned is because the reference.

func DerefZ

func DerefZ[T any](in *T) (value T)

DerefZ de-references a pointer value, and if the pointer is nil, returns the zero value for that type. This cannot panic, but does not distinguish between "nil pointer" and "pointer to the zero value for the type" input.

func Diff

func Diff[T Integers](a, b T) T

Diff returns the absolute value of the difference between two values.

func FloatMillis

func FloatMillis[T SignedInteger](in T) float64

FloatMillis reverses, though potentially (often) not without some loss of fidelity, the operation of Millis.

func IsZero

func IsZero[T comparable](in T) bool

IsZero returns true if the input value compares "true" to the zero value for the type of the argument. If the type implements an IsZero() method (e.g. time.Time), then IsZero returns that value, otherwise, IsZero constructs a zero valued object of type T and compares the input value to the zero value.

func Millis

func Millis[T SignedInteger](in float64) T

Millis converts a float into a an integer that represents one thousandth of the units of the original.

Millis will panic in the case of an overflow (wraparound).

func Ptr

func Ptr[T any](in T) *T

Ptr returns a pointer for the object. Useful for setting the value in structs where you cannot easily create a reference (e.g. the output of functions, and for constant literals.). If you pass a value that is a pointer (e.x. *string), then Ptr returns **string. If the input object is a nil pointer, then Ptr returns a non-nil pointer to a nil pointer.

func Range

func Range[T Integers](a, b T) (start T, end T)

Range orders two numbers and returns the pair as (lower, higher).

func RoundToLargestMultiple

func RoundToLargestMultiple[T SignedInteger](a, b T) T

RoundToLargestMultiple rounds up to a larger value: The argument with the smaller absolute value is always the "multiple" and the "larger" is always the value that is rounded.

The output value is always *larget* than the input value.

func RoundToMultipleAwayFromZero

func RoundToMultipleAwayFromZero[T SignedInteger](a, b T) T

RoundToMultipleAwayFromZero rounds a value to the nearest multiple of the other number. The argument with the smaller absolute value is always the "multiple" and value with larger absolute value is rounded.

The rounded always has a higher absolute value than the input value.

func RoundToMultipleTowardZero

func RoundToMultipleTowardZero[T SignedInteger](a, b T) T

RoundToMultipleTowardZero rounds a value to the nearest multiple of the other number. The argument with the smaller absolute value is always the "multiple" and value with larger absolute value is rounded.

The rounded always has a lower absolute value than the input value.

func RoundToSmallestMultiple

func RoundToSmallestMultiple[T SignedInteger](a, b T) T

RoundToSmallestMultiple rounds to smaller numbers: The argument with the smaller absolute value is always the "multiple" and the "larger" is always the value that is rounded.

The rounded value is always *smaller* than the input value.

Types

type ChanOp

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

ChanOp is a wrapper around a channel, to make it easier to write clear code that uses and handles basic operations with single channels. From a high level an operation might look like:

ch := make(chan string)
err := fun.Blocking().Send("hello world")

Methods on ChanOp and related structures are not pointer receivers, ensure that the output values are recorded as needed. Typically it's reasonable to avoid creating ChanOp objects in a loop as well.

func ChanBlocking

func ChanBlocking[T any](ch chan T) ChanOp[T]

ChanBlocking produces a blocking Send instance. All Send/Check/Ignore operations will block until the context is canceled, the channel is canceled, or the send succeeds.

func ChanNonBlocking

func ChanNonBlocking[T any](ch chan T) ChanOp[T]

ChanNonBlocking produces a send instance that performs a non-blocking send.

The Send() method, for non-blocking sends, will return ErrSkipedNonBlockingSend if the channel was full and the object was not sent.

func (ChanOp[T]) Cap

func (op ChanOp[T]) Cap() int

Cap returns the current capacity of the channel.

func (ChanOp[T]) Close

func (op ChanOp[T]) Close()

Close closes the underlying channel.

This swallows any panic encountered when calling close() on the underlying channel, which makes it safe to call on nil or already-closed channels: the result in all cases (that the channel is closed when Close() returns, is the same in all cases.)

func (ChanOp[T]) Len

func (op ChanOp[T]) Len() int

Len returns the current length of the channel.

func (ChanOp[T]) Receive

func (op ChanOp[T]) Receive() ChanReceive[T]

Receive returns a ChanReceive object that acts on the same underlying sender.

func (ChanOp[T]) Send

func (op ChanOp[T]) Send() ChanSend[T]

Send returns a ChanSend object that acts on the same underlying channel.

type ChanReceive

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

ChanReceive wraps a channel fore <-chan T operations. It is the type returned by the ChanReceive() method on ChannelOp. The primary method is Read(), with other methods provided as "self-documenting" helpers.

func ChanBlockingReceive

func ChanBlockingReceive[T any](ch <-chan T) ChanReceive[T]

ChanBlockingReceive returns a Chan wrapper for <-chan T operation, that will block while waiting for new items to be sent through the channel.

func ChanNonBlockingReceive

func ChanNonBlockingReceive[T any](ch <-chan T) ChanReceive[T]

ChanNonBlockingReceive returns a non-blocking wrapper for <-chan T objects, for which read operations will return early when reading from an empty channel.

func (ChanReceive[T]) Check

func (ro ChanReceive[T]) Check(ctx context.Context) (T, bool)

Check performs the read operation and converts the error into an "ok" value, returning true if receive was successful and false otherwise.

func (ChanReceive[T]) Drop

func (ro ChanReceive[T]) Drop(ctx context.Context) bool

Drop performs a read operation and drops the response. If an item was dropped (e.g. Read would return an error), Drop() returns false, and true when the Drop was successful.

func (ChanReceive[T]) Force

func (ro ChanReceive[T]) Force(ctx context.Context) (out T)

Force ignores the error returning only the value from Read. This is either the value sent through the channel, or the zero value for T. Because zero values can be sent through channels, Force does not provide a way to distinguish between "channel-closed" and "received a zero value".

func (ChanReceive[T]) Ignore

func (ro ChanReceive[T]) Ignore(ctx context.Context)

Ignore reads one item from the channel and discards it.

func (ChanReceive[T]) Iterator

func (ro ChanReceive[T]) Iterator(ctx context.Context) iter.Seq[T]

Iterator provides access to the contents of the channel as a new-style standard library iterator. For ChanRecieve objects in non-blocking mode, iteration ends when there are no items in the channel. In blocking mode, iteration ends when the context is canceled or the channel is closed.

func (ChanReceive[T]) Ok

func (ro ChanReceive[T]) Ok() bool

Ok attempts to read from a channel returns false when the channel has been closed and true otherwise.

func (ChanReceive[T]) Read

func (ro ChanReceive[T]) Read(ctx context.Context) (T, error)

Read performs the read operation according to the blocking/non-blocking semantics of the receive operation.

In general errors are either: io.EOF if channel is closed; a context cancellation error if the context passed to Read() is canceled, or ErrSkippedNonBlockingChannelOperation in the non-blocking case if the channel was empty.

In all cases when Read() returns an error, the return value is the zero value for T.

type ChanSend

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

ChanSend provides access to channel send operations, and is contstructed by the ChanSend() method on the channel operation. The primary method is Write(), with other methods provided for clarity.

func BlockingSend

func BlockingSend[T any](ch chan<- T) ChanSend[T]

BlockingSend returns a Chan wrapper for chan<- T operation, that will block when sending into a channel that is full or that doesn't have a listener.

func NonBlockingSend

func NonBlockingSend[T any](ch chan<- T) ChanSend[T]

NonBlockingSend returns a non-blocking wrapper for <-chan T objects, for which read operations will return early when reading from an empty channel.

func (ChanSend[T]) Check

func (sm ChanSend[T]) Check(ctx context.Context, it T) bool

Check performs a send and returns true when the send was successful and false otherwise.

func (ChanSend[T]) Ignore

func (sm ChanSend[T]) Ignore(ctx context.Context, it T)

Ignore performs a send and omits the error.

func (ChanSend[T]) Signal

func (sm ChanSend[T]) Signal(ctx context.Context)

Signal attempts to sends the Zero value of T through the channel and returns when: the send succeeds, the channel is full and this is a non-blocking send, the context is canceled, or the channel is closed.

func (ChanSend[T]) Write

func (sm ChanSend[T]) Write(ctx context.Context, it T) (err error)

Write sends the item into the channel captured by Blocking/NonBlocking returning the appropriate error.

The returned error is nil if the send was successful, and an io.EOF if the channel is closed (or nil) rather than a panic (as with the equivalent direct operation.) The error value is a context cancelation error when the context is canceled, and for non-blocking sends, if the channel did not accept the write, ErrSkippedNonBlockingChannelOperation is returned.

func (ChanSend[T]) Zero

func (sm ChanSend[T]) Zero(ctx context.Context) error

Zero sends the zero value of T through the channel.

type Integers

type Integers interface {
	SignedInteger | UnsignedInteger
}

Integers are the set of singed and unsinged integers as used by this package.

type Map

type Map[K comparable, V any] map[K]V

Map is just a generic type wrapper around a map, mostly for the purpose of being able to interact with other related types and provide a improved/alterate ergonomics.

All normal map operations are still accessible, these methods exist to provide accessible function objects for use in contexts where that may be useful and to improve the readability of some call sites, where default map access may be awkward.

func NewMap

func NewMap[K comparable, V any](in map[K]V) Map[K, V]

NewMap provides a constructor to return a stw.Map without specifying types.

func (Map[K, V]) Check

func (m Map[K, V]) Check(key K) bool

Check returns true if the value K is in the map.

func (Map[K, V]) Delete

func (m Map[K, V]) Delete(k K)

Delete removes a key from the map.

func (Map[K, V]) Ensure

func (m Map[K, V]) Ensure(key K) bool

Ensure set's sets the provided key in the map to the zero value for the value type.

func (Map[K, V]) Extend

func (m Map[K, V]) Extend(seq iter.Seq2[K, V])

Extend adds a sequence of key value pairs to the map.

func (Map[K, V]) Get

func (m Map[K, V]) Get(key K) V

Get returns the value from the map, and is the same thing as:

foo := mp[key]

If the key is not present in the map, as with a normal map, this is the zero value for V.

func (Map[K, V]) Iterator

func (m Map[K, V]) Iterator() iter.Seq2[K, V]

Iterator returns an iterator to the key-value pairs of the map.

func (Map[K, V]) Keys

func (m Map[K, V]) Keys() iter.Seq[K]

Keys provides an iterator over just the keys in the map.

func (Map[K, V]) Len

func (m Map[K, V]) Len() int

Len returns the length. It is equivalent to len(Map), but is provided for consistency.

func (Map[K, V]) Load

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

Load returns the value in the map for the key, and an "ok" value which is true if that item is present in the map.

func (Map[K, V]) Set

func (m Map[K, V]) Set(k K, v V) bool

Set adds a key value pair directly to the map.

func (Map[K, V]) Store

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

Store adds a key value pair directly to the map.

func (Map[K, V]) Values

func (m Map[K, V]) Values() iter.Seq[V]

Values provides an iterator over just the values in the map.

type SignedInteger

type SignedInteger interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

SignedInteger are all of the primitive signed integer types in go.

type Slice

type Slice[T any] []T

Slice is just a local wrapper around a slice, providing a similarly expressive interface to the Map and Pair types in the fun package.

func DefaultSlice

func DefaultSlice[T any](input []T, args ...int) Slice[T]

DefaultSlice takes a slice value and returns it if it's non-nil. If the slice is nil, it returns a slice of the specified length (and capacity,) as specified.

func MergeSlices

func MergeSlices[T any](sls ...[]T) Slice[T]

MergeSlices takes a variadic set of arguments which are all slices, and returns a single slice, that contains all items in the input slice.

func NewSlice

func NewSlice[T any](in []T) Slice[T]

NewSlice produces a slice object as a convenience constructor to avoid needing to specify types.

func SlicePtrs

func SlicePtrs[T any](in []T) Slice[*T]

SlicePtrs converts a slice of values to a slice of values. This is a helper for NewSlice(in).Ptrs().

func SliceRefs

func SliceRefs[T any](in []*T) Slice[T]

SliceRefs converts a slice of pointers to a slice of values, replacing all nil pointers with the zero type for that value.

func SliceSparseRefs

func SliceSparseRefs[T any](in []*T) Slice[T]

SliceSparseRefs converts a slice of pointers to a slice of objects, dropping nil values. from the output slice.

func SliceWithCapacity

func SliceWithCapacity[T any](n int) Slice[T]

SliceWithCapacity constructs a new (wrapped) slice object with a length of 0 but the specificed capacity.

func Variadic

func Variadic[T any](in ...T) Slice[T]

Variadic constructs a slice of type T from a sequence of variadic elements.

func (*Slice[T]) Append

func (s *Slice[T]) Append(in ...T) *Slice[T]

Append adds the items from the input slice to the root slice.

func (Slice[T]) Cap

func (s Slice[T]) Cap() int

Cap returns the capacity of the slice.

func (Slice[T]) Copy

func (s Slice[T]) Copy() Slice[T]

Copy performs a shallow copy of the Slice.

func (*Slice[T]) Empty

func (s *Slice[T]) Empty()

Empty re-slices the slice, to omit all items, but retain the allocation.

func (*Slice[T]) Extend

func (s *Slice[T]) Extend(seq iter.Seq[T]) *Slice[T]

Extend adds the items from the input slice to the root slice.

func (Slice[T]) FillTo

func (s Slice[T]) FillTo(length int) Slice[T]

FillTo appends zero values to the slice until it reaches the specified length, and returns the resulting slice.

func (*Slice[T]) Grow

func (s *Slice[T]) Grow(size int)

Grow adds zero items to the slice until it reaches the desired size.

func (*Slice[T]) GrowCapacity

func (s *Slice[T]) GrowCapacity(size int)

GrowCapacity extends the capacity of the slice (by adding zero items and the ).

func (Slice[T]) Index

func (s Slice[T]) Index(index int) T

Index returns the item at the specified index.

If the provided index is not within the bounds of the slice the operation panics.

func (Slice[T]) IsEmpty

func (s Slice[T]) IsEmpty() bool

IsEmpty returns true when there are no items in the slice (or it is nil.

func (Slice[T]) Last

func (s Slice[T]) Last() int

Last returns the index of the last element in the slice. Empty slices have `-1` last items.

func (Slice[T]) Len

func (s Slice[T]) Len() int

Len returns the length of the slice.

func (*Slice[T]) Prepend

func (s *Slice[T]) Prepend(in ...T) *Slice[T]

Prepend adds the items to beginning of the slice.

func (Slice[T]) Ptr

func (s Slice[T]) Ptr(index int) *T

Ptr provides a pointer to the item at the provided index.

func (Slice[T]) Ptrs

func (s Slice[T]) Ptrs() []*T

Ptrs converts a slice in to a slice of pointers to the values in the original slice.

func (*Slice[T]) Push

func (s *Slice[T]) Push(in T)

Push adds a single item to the end of the slice.

func (*Slice[T]) PushMany

func (s *Slice[T]) PushMany(in ...T)

PushMany adds all of the items to the end of the slice.

func (*Slice[T]) Reset

func (s *Slice[T]) Reset()

Reset constructs a new empty slice releasing the original allocation.

func (*Slice[T]) Reslice

func (s *Slice[T]) Reslice(start, end int)

Reslice modifies the slice to set the new start and end indexes.

Slicing operations, can lead to panics if the indexes are out of bounds.

func (*Slice[T]) ResliceBeginning

func (s *Slice[T]) ResliceBeginning(start int)

ResliceBeginning moves the "beginning" of the slice to the specified index.

Slicing operations, can lead to panics if the indexes are out of bounds.

func (*Slice[T]) ResliceEnd

func (s *Slice[T]) ResliceEnd(end int)

ResliceEnd moves the "end" of the slice to the specified index.

Slicing operations, can lead to panics if the indexes are out of bounds.

func (Slice[T]) Sort

func (s Slice[T]) Sort(cp func(a, b T) bool)

Sort reorders the slice using the provided com parator function, which should return true if a is less than b and, false otherwise. The slice is sorted in "lowest" to "highest" order.

func (*Slice[T]) Truncate

func (s *Slice[T]) Truncate(n int)

Truncate removes the last n items from the end of the list.

Slicing operations, can lead to panics if the indexes are out of bounds.

func (Slice[T]) Zero

func (s Slice[T]) Zero()

Zero replaces all items in the slice with the zero value for the type T.

func (Slice[T]) ZeroRange

func (s Slice[T]) ZeroRange(start, end int)

ZeroRange replaces values between the specified indexes (inclusive) with the zero value of the type. If the indexes provided are outside of the bounds of the slice, an invariant violation panic is raised.

type UnsignedInteger

type UnsignedInteger interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

UnsignedInteger are all of the primitive signed integer types in go.

Jump to

Keyboard shortcuts

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