Documentation ¶
Index ¶
- Constants
- func All[T any](xs []T, pred func(T) bool) bool
- func AllMapItems[T any, K comparable](xs map[K]T, pred func(T) bool) bool
- func Any[T any](xs []T, pred func(T) bool) bool
- func AnyMapItem[T any, K comparable](xs map[K]T, pred func(T) bool) bool
- func ByteSlice[T ByteArray](v T) []byte
- func ChainOption[A, B any](f func(A) Option[B]) func(Option[A]) Option[B]
- func Collect[T any](c chan T) []T
- func CollectBatch[V any](ctx context.Context, values <-chan V, batchSize int, ...) error
- func CopyAll[T Copyable[T]](xs []T) []T
- func CopyAllErr[T CopyableErr[T]](xs []T) ([]T, error)
- func CopySlice[T any](slice []T) []T
- func Count[T any](xs []T, pred func(T) bool) int
- func CountMapItems[T any, K comparable](xs map[K]T, pred func(T) bool) int
- func ElimOption[A, B any](o Option[A], b func() B, f func(A) B) B
- func Enumerate[T any](items []T, f func(int, T))
- func EnumerateMap[T any, K comparable](items map[K]T, f func(K, T))
- func ErrorAs[Target error](err error) bool
- func Filter[T any](s []T, f func(T) bool) []T
- func FilterMap[T any, K comparable](s map[K]T, f func(T) bool) []T
- func First[T any](xs []*T, pred func(*T) bool) (*T, error)
- func FlatMap[I, O any, S []I](s S, f func(I) []O) []O
- func FlatMapErr[I, O any, S []I](s S, f func(I) ([]O, error)) ([]O, error)
- func ForEach[T any](items []T, f func(T))
- func ForEachErr[T any](s []T, f func(T) error) error
- func ForEachMapItem[T any, K comparable](items map[K]T, f func(K, T))
- func IsCanceled(err error) bool
- func IsRpcErr(err error, candidate error) bool
- func Last[T any](xs []*T, pred func(*T) bool) (*T, error)
- func LiftA2Option[A, B, C any](f func(A, B) C) func(Option[A], Option[B]) Option[C]
- func MakeSlice[T any](items ...T) []T
- func Map[I, O any, S []I](s S, f func(I) O) []O
- func MapErr[I, O any, S []I](s S, f func(I) (O, error)) ([]O, error)
- func MapLeft[L any, R any, O any](f func(L) O) func(Either[L, R]) Option[O]
- func MapOption[A, B any](f func(A) B) func(Option[A]) Option[B]
- func MapOptionZ[A, B any](o Option[A], f func(A) B) B
- func MapRight[L any, R any, O any](f func(R) O) func(Either[L, R]) Option[O]
- func NotAny[T any](xs []T, pred func(T) bool) bool
- func NotAnyMapItem[T any, K comparable](xs map[K]T, pred func(T) bool) bool
- func ParSlice[V any](ctx context.Context, s []V, f ErrFunc[V]) error
- func Ptr[T any](v T) *T
- func RecvOrTimeout[T any](c <-chan T, timeout time.Duration) (*T, error)
- func RecvResp[T any](r <-chan T, e <-chan error, q <-chan struct{}) (T, error)
- func Reduce[T any, V any, S []V](s S, f Reducer[T, V]) T
- func SendAll[T any](c chan<- T, msgs ...T)
- func SendOrQuit[T any, Q any](c chan<- T, msg T, quit chan Q) bool
- func SetDiff[T comparable](a, b []T) []T
- func ToArray[T ByteArray](v []byte) T
- type ByteArray
- type ConcurrentQueue
- type ContextGuard
- func (g *ContextGuard) CtxBlocking() (context.Context, func())
- func (g *ContextGuard) CtxBlockingCustomTimeout(timeout time.Duration) (context.Context, func())
- func (g *ContextGuard) WithCtxQuit() (context.Context, func())
- func (g *ContextGuard) WithCtxQuitCustomTimeout(timeout time.Duration) (context.Context, func())
- func (g *ContextGuard) WithCtxQuitNoTimeout() (context.Context, func())
- type Copyable
- type CopyableErr
- type CriticalError
- type Either
- type ErrFunc
- type Event
- type EventDistributor
- type EventPublisher
- type EventReceiver
- type Option
- func (o Option[A]) Alt(o2 Option[A]) Option[A]
- func (o Option[A]) IsNone() bool
- func (o Option[A]) IsSome() bool
- func (o Option[A]) UnwrapOr(a A) A
- func (o Option[A]) UnwrapOrErr(err error) (A, error)
- func (o Option[A]) UnwrapOrFunc(f func() A) A
- func (o Option[A]) UnwrapOrFuncErr(f func() (A, error)) (A, error)
- func (o Option[A]) UnwrapToPtr() *A
- func (o Option[A]) WhenSome(f func(A))
- type Reducer
- type Set
- func (s Set[T]) Add(e T)
- func (s Set[T]) Contains(e T) bool
- func (s Set[T]) Diff(other Set[T]) Set[T]
- func (s Set[T]) Equal(other Set[T]) bool
- func (s Set[T]) Intersect(other Set[T]) Set[T]
- func (s Set[T]) Remove(e T)
- func (s Set[T]) Subset(other Set[T]) bool
- func (s Set[T]) ToSlice() []T
- func (s Set[T]) Union(other Set[T]) Set[T]
Constants ¶
const (
// DefaultQueueSize is the default size to use for concurrent queues.
DefaultQueueSize = 10
)
Variables ¶
This section is empty.
Functions ¶
func AllMapItems ¶ added in v0.3.3
func AllMapItems[T any, K comparable](xs map[K]T, pred func(T) bool) bool
AllMapItems returns true if the passed predicate returns true for all items in the map.
func AnyMapItem ¶ added in v0.3.3
func AnyMapItem[T any, K comparable](xs map[K]T, pred func(T) bool) bool
AnyMapItem returns true if the passed predicate returns true for any item in the map.
func ByteSlice ¶
ByteSlice takes a byte array, and returns a slice. This is useful when a function returns an array, but a slice is wanted. Without this, then an intermediate variable is needed.
func ChainOption ¶ added in v0.4.0
ChainOption transforms a function A -> Option[B] into one that accepts an Option[A] as an argument.
ChainOption : (A -> Option[B]) -> Option[A] -> Option[B].
func Collect ¶
func Collect[T any](c chan T) []T
Collect receives all values from a channel and returns them as a slice.
NOTE: This function closes the channel to be able to collect all items at once.
func CollectBatch ¶ added in v0.3.0
func CollectBatch[V any](ctx context.Context, values <-chan V, batchSize int, cb func(ctx context.Context, batch []V) error) error
CollectBatch reads from the given channel and returns batchSize items at a time and a boolean that indicates whether we expect more items to be sent on the channel. If the context is canceled, the function returns the items that have been read so far and the context's error.
NOTE: The channel MUST be closed for this function to return.
func CopyAll ¶
func CopyAll[T Copyable[T]](xs []T) []T
CopyAll creates a new slice where each item of the slice is a deep copy of the elements of the input slice.
func CopyAllErr ¶
func CopyAllErr[T CopyableErr[T]](xs []T) ([]T, error)
CopyAllErr creates a new slice where each item of the slice is a deep copy of the elements of the input slice. This is identical to CopyAll, but should be used in cases where the copy method can return an error.
func CopySlice ¶
func CopySlice[T any](slice []T) []T
CopySlice returns a copy of the given slice. Does a shallow copy of the slice itself, not the underlying elements.
func CountMapItems ¶ added in v0.3.3
func CountMapItems[T any, K comparable](xs map[K]T, pred func(T) bool) int
CountMapItems returns the number of items in the map that match the predicate.
func ElimOption ¶ added in v0.4.0
ElimOption is the universal Option eliminator. It can be used to safely handle all possible values inside the Option by supplying two continuations.
ElimOption : (Option[A], () -> B, A -> B) -> B.
func Enumerate ¶
Enumerate is a generic enumeration function. The closure will be called for each item in the passed slice, receiving both the index number as well as the item itself.
func EnumerateMap ¶ added in v0.3.3
func EnumerateMap[T any, K comparable](items map[K]T, f func(K, T))
EnumerateMap is a generic enumeration function. The closure will be called for each key and item in the passed-in map.
func ErrorAs ¶ added in v0.4.0
ErrorAs behaves the same as `errors.As` except there's no need to declare the target error as a variable first. Instead of writing:
var targetErr *TargetErr errors.As(err, &targetErr)
We can write:
lnutils.ErrorAs[*TargetErr](err)
To save us from declaring the target error variable.
func Filter ¶
Filter applies the given predicate function to each element of the given slice and generates a new slice containing only the elements for which the predicate returned true.
func FilterMap ¶ added in v0.3.1
func FilterMap[T any, K comparable](s map[K]T, f func(T) bool) []T
FilterMap applies the given predicate function to each element of the given map and generates a new slice containing only the elements for which the predicate returned true.
func First ¶
First returns the first item in the slice that matches the predicate, or an error if none matches.
func FlatMap ¶ added in v0.4.0
func FlatMap[I, O any, S []I](s S, f func(I) []O) []O
FlatMap applies the given mapping function to each element of the given slice and concatenates the results into a new slice.
func FlatMapErr ¶ added in v0.4.0
FlatMapErr applies the given mapping function to each element of the given slice, concatenates the results into a new slice, and returns an error if the mapping function fails.
func ForEach ¶
func ForEach[T any](items []T, f func(T))
ForEach is a generic implementation of a for-each (map with side effects). This can be used to ensure that any normal for-loop don't run into bugs due to loop variable scoping.
func ForEachErr ¶
ForEachErr will iterate through all items in the passed slice, calling the function f on each slice. If a call to f fails, then the function returns an error immediately.
This function can be used instead of the normal range loop to ensure that a loop scoping bug isn't introduced.
func ForEachMapItem ¶ added in v0.3.3
func ForEachMapItem[T any, K comparable](items map[K]T, f func(K, T))
ForEachMapItem is a generic implementation of a for-each (map with side effects). This can be used to ensure that any normal for-loop don't run into bugs due to loop variable scoping.
func IsCanceled ¶
IsCanceled returns true if the passed error is a gRPC error with the context.Canceled error as the cause.
func IsRpcErr ¶ added in v0.4.0
IsRpcErr returns true if the given error is a gRPC error with the given candidate error as the cause.
func Last ¶ added in v0.4.0
Last returns the last item in the slice that matches the predicate, or an error if none matches.
func LiftA2Option ¶ added in v0.4.0
LiftA2Option transforms a pure function (A, B) -> C into one that will operate in an Option context. For the returned function, if either of its arguments are None, then the result will be None.
LiftA2Option : ((A, B) -> C) -> (Option[A], Option[B]) -> Option[C].
func MakeSlice ¶ added in v0.3.0
func MakeSlice[T any](items ...T) []T
MakeSlice is a generic function shorthand for making a slice out of a set of elements. This can be used to avoid having to specify the type of the slice as well as the types of the elements.
func Map ¶
func Map[I, O any, S []I](s S, f func(I) O) []O
Map applies the given mapping function to each element of the given slice and generates a new slice.
func MapErr ¶
MapErr applies the given fallible mapping function to each element of the given slice and generates a new slice. This is identical to Map, but returns early if any single mapping fails.
func MapOption ¶ added in v0.4.0
MapOption transforms a pure function A -> B into one that will operate inside the Option context.
MapOption : (A -> B) -> Option[A] -> Option[B].
func MapOptionZ ¶ added in v0.4.0
MapOptionZ transforms a pure function A -> B into one that will operate inside the Option context. Unlike MapOption, this function will return the default/zero argument of the return type if the Option is empty.
func NotAny ¶ added in v0.3.3
NotAny returns true if the passed predicate returns false for all items in the slice.
func NotAnyMapItem ¶ added in v0.3.3
func NotAnyMapItem[T any, K comparable](xs map[K]T, pred func(T) bool) bool
NotAnyMapItem returns true if the passed predicate returns false for all items in the map.
func ParSlice ¶
ParSlice can be used to execute a function on each element of a slice in parallel. This function is fully blocking and will wait for all goroutines to either succeed, or for the first to error out. Active goroutines limited with number of CPU. Context will be passed in executable func and canceled the first time a function passed returns a non-nil error. Returns the first non-nil error (if any).
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns the pointer of the given value. This is useful in instances where a function returns the value, but a pointer is wanted. Without this, then an intermediate variable is needed.
func RecvOrTimeout ¶
RecvOrTimeout attempts to recv over chan c, returning the value. If the timeout passes before the recv succeeds, an error is returned
func RecvResp ¶
RecvResp takes three channels: a response channel, an error channel and a quit channel. If either of these channels are sent on, then the function will exit with that response. This can be used to wait for a response, error, or a quit signal.
func Reduce ¶
Reduce takes a slice of something, and a reducer, and produces a final accumulated value.
func SendAll ¶
func SendAll[T any](c chan<- T, msgs ...T)
SendAll attempts to send all messages through channel c.
TODO(roasbeef): add non-blocking variant?
func SendOrQuit ¶
SendOrQuit attempts to and a message through channel c. If this succeeds, then bool is returned. Otherwise if a quit signal is received first, then false is returned.
func SetDiff ¶
func SetDiff[T comparable](a, b []T) []T
SetDiff returns all the items that are in the first set but not in the second.
Types ¶
type ByteArray ¶
type ByteArray interface { ~[32]byte }
ByteArray is a type constraint for type that reduces down to a fixed sized array.
type ConcurrentQueue ¶
type ConcurrentQueue[T any] struct { // contains filtered or unexported fields }
ConcurrentQueue is a typed concurrent-safe FIFO queue with unbounded capacity. Clients interact with the queue by pushing items into the in channel and popping items from the out channel. There is a goroutine that manages moving items from the in channel to the out channel in the correct order that must be started by calling Start().
func NewConcurrentQueue ¶
func NewConcurrentQueue[T any](bufferSize int) *ConcurrentQueue[T]
NewConcurrentQueue constructs a ConcurrentQueue. The bufferSize parameter is the capacity of the output channel. When the size of the queue is below this threshold, pushes do not incur the overhead of the less efficient overflow structure.
func (*ConcurrentQueue[T]) ChanIn ¶
func (cq *ConcurrentQueue[T]) ChanIn() chan<- T
ChanIn returns a channel that can be used to push new items into the queue.
func (*ConcurrentQueue[T]) ChanOut ¶
func (cq *ConcurrentQueue[T]) ChanOut() <-chan T
ChanOut returns a channel that can be used to pop items from the queue.
func (*ConcurrentQueue[T]) Start ¶
func (cq *ConcurrentQueue[T]) Start()
Start begins a goroutine that manages moving items from the in channel to the out channel. The queue tries to move items directly to the out channel minimize overhead, but if the out channel is full it pushes items to an overflow queue. This must be called before using the queue.
func (*ConcurrentQueue[T]) Stop ¶
func (cq *ConcurrentQueue[T]) Stop()
Stop ends the goroutine that moves items from the in channel to the out channel. This does not clear the queue state, so the queue can be restarted without dropping items.
type ContextGuard ¶
ContextGuard is an embeddable struct that provides a wait group and main quit channel that can be used to create guarded contexts.
func (*ContextGuard) CtxBlocking ¶
func (g *ContextGuard) CtxBlocking() (context.Context, func())
CtxBlocking is used to create a cancellable context that will NOT be cancelled if the main quit signal is triggered, to block shutdown of important tasks. The context will be cancelled if the timeout is reached.
func (*ContextGuard) CtxBlockingCustomTimeout ¶
func (g *ContextGuard) CtxBlockingCustomTimeout( timeout time.Duration) (context.Context, func())
CtxBlockingCustomTimeout is used to create a cancellable context with a custom timeout that will NOT be cancelled if the main quit signal is triggered, to block shutdown of important tasks. The context will be cancelled if the timeout is reached.
func (*ContextGuard) WithCtxQuit ¶
func (g *ContextGuard) WithCtxQuit() (context.Context, func())
WithCtxQuit is used to create a cancellable context that will be cancelled if the main quit signal is triggered or after the default timeout occurred.
func (*ContextGuard) WithCtxQuitCustomTimeout ¶
func (g *ContextGuard) WithCtxQuitCustomTimeout( timeout time.Duration) (context.Context, func())
WithCtxQuitCustomTimeout is used to create a cancellable context that will be cancelled if the main quit signal is triggered or after the given timeout occurred.
func (*ContextGuard) WithCtxQuitNoTimeout ¶
func (g *ContextGuard) WithCtxQuitNoTimeout() (context.Context, func())
WithCtxQuitNoTimeout is used to create a cancellable context that will be cancelled if the main quit signal is triggered.
type Copyable ¶
type Copyable[T any] interface { Copy() T }
Copyable is a generic interface for a type that's able to return a deep copy of itself.
type CopyableErr ¶
CopyableErr is a generic interface for a type that's able to return a deep copy of itself. This is identical to Copyable, but should be used in cases where the copy method can return an error.
type CriticalError ¶ added in v0.4.0
type CriticalError struct {
Err error
}
CriticalError is an error type that should be used for errors that are critical and should cause the application to exit.
func NewCriticalError ¶ added in v0.4.0
func NewCriticalError(err error) *CriticalError
NewCriticalError creates a new CriticalError instance.
func (*CriticalError) Error ¶ added in v0.4.0
func (e *CriticalError) Error() string
Error implements the error interface.
func (*CriticalError) Unwrap ¶ added in v0.4.0
func (e *CriticalError) Unwrap() error
Unwrap implements the errors.Wrapper interface.
type Either ¶ added in v0.4.0
Either is a type that can be either left or right.
type ErrFunc ¶
ErrFunc is a type def for a function that takes a context (to allow early cancellation) and a series of value returning an error. This is typically used a closure to perform concurrent work over a homogeneous slice of values.
type EventDistributor ¶
type EventDistributor[T any] struct { // contains filtered or unexported fields }
EventDistributor is a struct type that helps to distribute events to multiple subscribers.
func NewEventDistributor ¶
func NewEventDistributor[T any]() *EventDistributor[T]
NewEventDistributor creates a new event distributor of the declared type.
func (*EventDistributor[T]) NotifySubscribers ¶
func (d *EventDistributor[T]) NotifySubscribers(events ...T)
NotifySubscribers sends the given events to all subscribers.
func (*EventDistributor[T]) RegisterSubscriber ¶
func (d *EventDistributor[T]) RegisterSubscriber(subscriber *EventReceiver[T])
RegisterSubscriber adds a new subscriber for receiving events.
func (*EventDistributor[T]) RemoveSubscriber ¶
func (d *EventDistributor[T]) RemoveSubscriber( subscriber *EventReceiver[T]) error
RemoveSubscriber removes the given subscriber and also stops it from processing events.
type EventPublisher ¶
type EventPublisher[T any, Q any] interface { // RegisterSubscriber adds a new subscriber for receiving events. The // deliverExisting boolean indicates whether already existing items // should be sent to the NewItemCreated channel when the subscription is // started. An optional deliverFrom can be specified to indicate from // which timestamp/index/marker onward existing items should be // delivered on startup. If deliverFrom is nil/zero/empty then all // existing items will be delivered. RegisterSubscriber(receiver *EventReceiver[T], deliverExisting bool, deliverFrom Q) error // RemoveSubscriber removes the given subscriber and also stops it from // processing events. RemoveSubscriber(subscriber *EventReceiver[T]) error }
EventPublisher is an interface type for a component that offers event based subscriptions for publishing events.
type EventReceiver ¶
type EventReceiver[T any] struct { // NewItemCreated is sent to when a new item was created successfully. NewItemCreated *ConcurrentQueue[T] // ItemRemoved is sent to when an existing item was removed. ItemRemoved *ConcurrentQueue[T] // contains filtered or unexported fields }
EventReceiver is a struct type that holds two queues for new and removed items respectively.
func NewEventReceiver ¶
func NewEventReceiver[T any](queueSize int) *EventReceiver[T]
NewEventReceiver creates a new event receiver with concurrent queues of the given size.
func (*EventReceiver[T]) ID ¶
func (e *EventReceiver[T]) ID() uint64
ID returns the internal process-unique ID of the subscription.
func (*EventReceiver[T]) Stop ¶
func (e *EventReceiver[T]) Stop()
Stop stops the receiver from processing events.
type Option ¶ added in v0.4.0
type Option[A any] struct { // contains filtered or unexported fields }
Option[A] represents a value which may or may not be there. This is very often preferable to nil-able pointers.
func FlattenOption ¶ added in v0.4.0
FlattenOption joins multiple layers of Options together such that if any of the layers is None, then the joined value is None. Otherwise the innermost Some value is returned.
FlattenOption : Option[Option[A]] -> Option[A].
func MaybeSome ¶ added in v0.4.0
MaybeSome constructs an option from a pointer.
MaybeSome : *A -> Option[A].
func Some ¶ added in v0.4.0
Some trivially injects a value into an optional context.
Some : A -> Option[A].
func (Option[A]) Alt ¶ added in v0.4.0
Alt chooses the left Option if it is full, otherwise it chooses the right option. This can be useful in a long chain if you want to choose between many different ways of producing the needed value.
Alt : Option[A] -> Option[A] -> Option[A].
func (Option[A]) IsNone ¶ added in v0.4.0
IsNone returns true if the Option is empty
IsNone : Option[A] -> bool.
func (Option[A]) IsSome ¶ added in v0.4.0
IsSome returns true if the Option contains a value
IsSome : Option[A] -> bool.
func (Option[A]) UnwrapOr ¶ added in v0.4.0
func (o Option[A]) UnwrapOr(a A) A
UnwrapOr is used to extract a value from an option, and we supply the default value in the case when the Option is empty.
UnwrapOr : (Option[A], A) -> A.
func (Option[A]) UnwrapOrErr ¶ added in v0.4.0
UnwrapOrErr is used to extract a value from an option, if the option is empty, then the specified error is returned directly.
func (Option[A]) UnwrapOrFunc ¶ added in v0.4.0
func (o Option[A]) UnwrapOrFunc(f func() A) A
UnwrapOrFunc is used to extract a value from an option, and we supply a thunk to be evaluated in the case when the Option is empty.
func (Option[A]) UnwrapOrFuncErr ¶ added in v0.4.0
UnwrapOrFuncErr is used to extract a value from an option, and we supply a thunk to be evaluated in the case when the Option is empty.
func (Option[A]) UnwrapToPtr ¶ added in v0.4.0
func (o Option[A]) UnwrapToPtr() *A
UnwrapPtr is used to extract a reference to a value from an option, and we supply an empty pointer in the case when the Option is empty.
func (Option[A]) WhenSome ¶ added in v0.4.0
func (o Option[A]) WhenSome(f func(A))
WhenSome is used to conditionally perform a side-effecting function that accepts a value of the type that parameterizes the option. If this function performs no side effects, WhenSome is useless.
WhenSome : (Option[A], A -> ()) -> ().
type Reducer ¶
type Reducer[T, V any] func(accum T, value V) T
Reducer represents a function that takes an accumulator and the value, then returns a new accumulator.
type Set ¶
type Set[T comparable] map[T]struct{}
Set is a generic set using type params that supports the following operations: diff, union, intersection, and subset.
func NewSet ¶
func NewSet[T comparable](elems ...T) Set[T]
NewSet returns a new set with the given elements.