utils

package
v0.0.0-...-571cdb7 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alloc

func Alloc[T any](v T) *T

Alloc moves value to heap.

func ForEach

func ForEach[T any](ctx context.Context, ch <-chan T, handler func(T) error) error

ForEach is a helper function that reads from a channel and calls a handler for each item. this avoids needing a lot of for/select boilerplate everywhere.

func GenBytes

func GenBytes(rng *rand.Rand, n int) []byte

GenBytes generates a random byte slice.

func GenMap

func GenMap[K comparable, V any](rng *rand.Rand, genK GenF[K], genV GenF[V]) map[K]V

GenMap generates a map of small random length.

func GenMapN

func GenMapN[K comparable, V any](rng *rand.Rand, n int, genK GenF[K], genV GenF[V]) map[K]V

GenMapN generates a map of n elements.

func GenSlice

func GenSlice[T any](rng *rand.Rand, gen GenF[T]) []T

GenSlice generates a slice of small random length.

func GenSliceN

func GenSliceN[T any](rng *rand.Rand, n int, gen GenF[T]) []T

GenSliceN generates a slice of n elements.

func GenString

func GenString(rng *rand.Rand, n int) string

GenString generates a random string of length n.

func GenTimestamp

func GenTimestamp(rng *rand.Rand) time.Time

GenTimestamp generates a random timestamp.

func GetWSEndpoint

func GetWSEndpoint(endpoint string) string

func IgnoreCancel

func IgnoreCancel(err error) error

IgnoreCancel returns nil if the error is context.Canceled, err otherwise.

func ProtoClone

func ProtoClone[T proto.Message](item T) T

ProtoClone clones a proto.Message object.

func ProtoEqual

func ProtoEqual[T proto.Message](a, b T) bool

ProtoEqual compares two proto.Message objects.

func Recv

func Recv[T any](ctx context.Context, ch <-chan T) (zero T, err error)

Recv receives a value from a channel or returns an error if the context is canceled.

func RecvOrClosed

func RecvOrClosed[T any](ctx context.Context, ch <-chan T) (T, bool, error)

RecvOrClosed receives a value from a channel, returns false if channel got closed, or returns an error if the context is canceled.

func Send

func Send[T any](ctx context.Context, ch chan<- T, v T) error

Send a value to channel or returns an error if the context is canceled.

func SendOrDrop

func SendOrDrop[T any](ch chan<- T, v T) error

SendOrDrop send a value to channel if not full or drop the item if the channel is full.

func Sleep

func Sleep(ctx context.Context, d time.Duration) error

Sleep sleeps for a duration or until the context is canceled.

func SleepUntil

func SleepUntil(ctx context.Context, t time.Time) error

SleepUntil sleeps until deadline t or until the context is canceled.

func Slice

func Slice[T any](v ...T) []T

Slice constructs a slice. It is a syntax sugar for `[]T{v...}`, which avoids spelling out T. Not very useful if you need to spell out T to construct the elements: in that case you might prefer the []T{{...},{...}} syntax instead.

func TestDiff

func TestDiff[T any](want, got T) error

TestDiff generates a human-readable diff between two objects.

func TestEqual

func TestEqual[T any](a, b T) bool

TestEqual is a more robust replacement for reflect.DeepEqual for tests.

func TestRng

func TestRng() *rand.Rand

TestRng returns a deterministic random number generator.

func TestRngSplit

func TestRngSplit(rng *rand.Rand) *rand.Rand

TestRngSplit returns a new random number splitted from the given one. This is a very primitive splitting, known to result with dependent randomness. If that ever causes a problem, we can switch to SplitMix.

func WaitFor

func WaitFor(ctx context.Context, interval time.Duration, check func() bool) error

WaitFor polls a check function until it returns true or the context is canceled.

func WaitForWithTimeout

func WaitForWithTimeout(ctx context.Context, interval, timeout time.Duration, check func() bool) error

WaitForWithTimeout polls a check function until it returns true, the context is canceled, or the timeout is reached.

func WithTimeout

func WithTimeout(ctx context.Context, d time.Duration, f func(ctx context.Context) error) error

WithTimeout executes a function with a timeout.

func WithTimeout1

func WithTimeout1[R any](ctx context.Context, d time.Duration, f func(ctx context.Context) (R, error)) (R, error)

WithTimeout1 executes a function with a timeout.

func Zero

func Zero[T any]() (zero T)

Zero returns a zero value of type T.

Types

type AtomicRecv

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

AtomicRecv is a read-only reference to AtomicWatch.

func (AtomicRecv) Iter

func (w AtomicRecv) Iter(ctx context.Context, f func(ctx context.Context, v T) error) error

Iter executes sequentially the function f on each value of the atomic watch. Context passed to f is canceled when the next value is available. Exits when the returned error is different from nil and context.Canceled, or when the context passed to Iter is canceled (after f exits).

func (AtomicRecv) Load

func (w AtomicRecv) Load() T

Load returns the current value of the atomic watch. Does not do any locking.

func (AtomicRecv) Wait

func (w AtomicRecv) Wait(ctx context.Context, pred func(T) bool) (T, error)

Wait waits for the value of the atomic watch to satisfy the predicate. Does not do any locking.

type AtomicSend

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

func NewAtomicSend

func NewAtomicSend[T any](value T) (w AtomicSend[T])

func (*AtomicSend) Iter

func (w *AtomicSend) Iter(ctx context.Context, f func(ctx context.Context, v T) error) error

Iter executes sequentially the function f on each value of the atomic watch. Context passed to f is canceled when the next value is available. Exits when the returned error is different from nil and context.Canceled, or when the context passed to Iter is canceled (after f exits).

func (*AtomicSend) Load

func (w *AtomicSend) Load() T

Load returns the current value of the atomic watch. Does not do any locking.

func (*AtomicSend[T]) Send

func (w *AtomicSend[T]) Send(value T)

Store updates the value of the atomic watch.

func (*AtomicSend[T]) Subscribe

func (w *AtomicSend[T]) Subscribe() AtomicRecv[T]

func (*AtomicSend[T]) Update

func (w *AtomicSend[T]) Update(f func(T) (T, bool))

Update conditionally updates the value of the atomic watch.

func (*AtomicSend) Wait

func (w *AtomicSend) Wait(ctx context.Context, pred func(T) bool) (T, error)

Wait waits for the value of the atomic watch to satisfy the predicate. Does not do any locking.

type AtomicWatch

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

AtomicWatch stores a pointer to an IMMUTABLE value. Loading and waiting for updates do NOT require locking. TODO(gprusak): remove mutex and rename to AtomicSend, this will allow for sharing a mutex across multiple AtomicSenders.

func NewAtomicWatch

func NewAtomicWatch[T any](value T) (w AtomicWatch[T])

NewAtomicWatch creates a new AtomicWatch with the given initial value.

func (*AtomicWatch) Iter

func (w *AtomicWatch) Iter(ctx context.Context, f func(ctx context.Context, v T) error) error

Iter executes sequentially the function f on each value of the atomic watch. Context passed to f is canceled when the next value is available. Exits when the returned error is different from nil and context.Canceled, or when the context passed to Iter is canceled (after f exits).

func (*AtomicWatch) Load

func (w *AtomicWatch) Load() T

Load returns the current value of the atomic watch. Does not do any locking.

func (*AtomicWatch[T]) Store

func (w *AtomicWatch[T]) Store(value T)

Store updates the value of the atomic watch.

func (*AtomicWatch[T]) Subscribe

func (w *AtomicWatch[T]) Subscribe() AtomicRecv[T]

Subscribe returns a view-only API of the atomic watch.

func (*AtomicWatch[T]) Update

func (w *AtomicWatch[T]) Update(f func(T) (T, bool))

Update conditionally updates the value of the atomic watch.

func (*AtomicWatch) Wait

func (w *AtomicWatch) Wait(ctx context.Context, pred func(T) bool) (T, error)

Wait waits for the value of the atomic watch to satisfy the predicate. Does not do any locking.

type Duration

type Duration time.Duration

Duration is a wrapper type around time.Duration that supports JSON marshaling/unmarshaling. nolint:recvcheck

func (Duration) Duration

func (d Duration) Duration() time.Duration

Duration returns the underlying time.Duration value.

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

MarshalText implements json.TextMarshaler interface to convert Duration to JSON string.

func (Duration) Seconds

func (d Duration) Seconds() float64

Seconds returns the underlying time.Duration value in seconds.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(b []byte) error

UnmarshalText implements json.TextUnmarshaler.

type GenF

type GenF[T any] = func(rng *rand.Rand) T

GenF is a function which generates T.

type Hash

type Hash [sha256.Size]byte

Hash is a SHA-256 hash.

func GenHash

func GenHash(rng *rand.Rand) Hash

GenHash generates a random Hash.

func GetHash

func GetHash(data []byte) Hash

GetHash computes a hash of the given data.

func ParseHash

func ParseHash(raw []byte) (Hash, error)

ParseHash parses a Hash from bytes.

func ProtoHash

func ProtoHash(a proto.Message) Hash

ProtoHash hashes a proto.Message object. TODO(gprusak): make it deterministic.

type Mutex

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

Mutex guards access to object of type T.

func NewMutex

func NewMutex[T any](value T) (m Mutex[T])

NewMutex creates a new Mutex with given object.

func (*Mutex[T]) Lock

func (m *Mutex[T]) Lock() iter.Seq[T]

Lock returns an iterator which locks the mutex and yields the guarded object. The mutex is unlocked when the iterator is done. If the mutex is nil, the iterator is a no-op.

type NoCompare

type NoCompare [0]func()

NoCompare may be added to structs which must not be used as map keys.

type NoCopy

type NoCopy struct{}

NoCopy may be added to structs which must not be copied after the first use.

See https://golang.org/issues/8005#issuecomment-190753527 for details.

Note that it must not be embedded, otherwise Lock and Unlock methods will be exported.

func (*NoCopy) Lock

func (*NoCopy) Lock()

Lock implements sync.Locker.

func (*NoCopy) Unlock

func (*NoCopy) Unlock()

Unlock implements sync.Locker.

type Option

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

Option type inspired https://pkg.go.dev/github.com/samber/mo.

func MapOpt

func MapOpt[T, R any](o Option[T], f func(T) R) Option[R]

MapOpt applies a function to the value if present, returning a new Option.

func None

func None[T any]() (zero Option[T])

None creates an Option without a value.

func Some

func Some[T any](value T) Option[T]

Some creates an Option with a value.

func (Option[T]) Get

func (o Option[T]) Get() (T, bool)

Get unpacks the value from the Option, returning true if it was present.

func (Option[T]) IsPresent

func (o Option[T]) IsPresent() bool

IsPresent checks if the Option contains a value.

func (Option[T]) MarshalJSON

func (o Option[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. Note that it is defined on value, not pointer, because json.Marshal cannot call pointer methods on fields (i.e. it is broken by design).

func (*Option[T]) Or

func (o *Option[T]) Or(def T) T

Or returns the value if present, otherwise returns the default value.

func (*Option[T]) UnmarshalJSON

func (o *Option[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type ProtoConv

type ProtoConv[T any, P ProtoMessage] struct {
	Encode func(T) P
	Decode func(P) (T, error)
}

ProtoConv is a pair of functions to encode and decode between a type and a ProtoMessage.

func (ProtoConv[T, P]) DecodeOpt

func (c ProtoConv[T, P]) DecodeOpt(p P) (Option[T], error)

DecodeOpt decodes a ProtoMessage into a T, returning nil if p is nil.

func (ProtoConv[T, P]) DecodeReq

func (c ProtoConv[T, P]) DecodeReq(p P) (T, error)

DecodeReq decodes a ProtoMessage into a T, returning an error if p is nil.

func (ProtoConv[T, P]) DecodeSlice

func (c ProtoConv[T, P]) DecodeSlice(p []P) ([]T, error)

DecodeSlice decodes a slice of P into a slice of T.

func (ProtoConv[T, P]) EncodeOpt

func (c ProtoConv[T, P]) EncodeOpt(mv Option[T]) P

EncodeOpt encodes Option[T], mapping None to Zero[P]().

func (ProtoConv[T, P]) EncodeSlice

func (c ProtoConv[T, P]) EncodeSlice(t []T) []P

EncodeSlice encodes a slice of T into a slice of P.

func (ProtoConv[T, P]) Test

func (c ProtoConv[T, P]) Test(want T) error

Test tests whether reencoding a value is an identity operation.

type ProtoMessage

type ProtoMessage interface {
	comparable
	proto.Message
}

ProtoMessage is comparable proto.Message.

type ReadOnly

type ReadOnly struct{}

ReadOnly - if a struct embeds ReadOnly, its private fields will be compared by TestEqual.

type Semaphore

type Semaphore struct {
	// contains filtered or unexported fields
}

Semaphore provides a way to bound concurrenct access to a resource.

func NewSemaphore

func NewSemaphore(n int) *Semaphore

NewSemaphore constructs a new semaphore with n permits.

func (*Semaphore) Acquire

func (s *Semaphore) Acquire(ctx context.Context) (relase func(), err error)

Acquire acquires a permit from the semaphore. Blocks until a permit is available.

type Watch

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

Watch stores a value of type T. Essentially a mutex, that can be awaited for updates.

func NewWatch

func NewWatch[T any](val T) Watch[T]

NewWatch constructs a new watch with the given value. Note that value in the watch cannot be changed, so T should be a pointer type if updates are required.

func (*Watch[T]) Lock

func (w *Watch[T]) Lock() iter.Seq2[T, *WatchCtrl]

Lock returns an iterator which locks the watch and yields the guarded object. The watch is unlocked when the iterator is done. If the watch is nil, the iterator is a no-op. Additionally the WatchCtrl object is provided to the yield function: * to unlock -> wait for the update -> lock again, call ctrl.Wait(ctx) * to signal an update, call ctrl.Updated().

type WatchCtrl

type WatchCtrl struct {
	// contains filtered or unexported fields
}

WatchCtrl controls the locked object in a Watch. It is provided only in the iterator returned by Lock(). Should NOT be stored anywhere.

func (*WatchCtrl) Updated

func (c *WatchCtrl) Updated()

Updated signals waiters that the value in the watch has been updated.

func (*WatchCtrl) Wait

func (c *WatchCtrl) Wait(ctx context.Context) error

Wait waits for the value in the watch to be updated. Should be called only after locking the watch, i.e. within Lock() iterator. It unlocks -> waits for the update -> locks again.

func (*WatchCtrl) WaitUntil

func (c *WatchCtrl) WaitUntil(ctx context.Context, pred func() bool) error

WaitUntil waits for the value in the watch to satisfy the predicate. Should be called only after locking the watch, i.e. within Lock() iterator. The predicate is evaluated under the lock, so it can access the guarded object.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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