Documentation
ΒΆ
Overview ΒΆ
Package abstract provides a comprehensive collection of abstract data structures, utilities, and helper functions designed to simplify common programming tasks in Go.
The package includes:
- Generic data structures: Map, Set, Stack, Slice, LinkedList with both regular and thread-safe variants - Cryptographic utilities: AES encryption/decryption, HMAC generation, ECDSA signing/verification - Concurrency helpers: Future/Promise patterns, Worker pools, Rate limiting - Random generation: Secure random strings, numbers, and choices with various character sets - CSV processing: Table manipulation and data transformation - Mathematical utilities: Type-safe numeric operations with generic constraints - ID generation: Structured entity ID creation with type safety - Timing utilities: Precise timing measurements and deadline management
All data structures provide both regular and thread-safe variants (prefixed with "Safe"). The thread-safe variants use RWMutex for concurrent access while maintaining performance.
Example usage:
// Create a thread-safe map
m := abstract.NewSafeMap[string, int]()
m.Set("key", 42)
// Generate secure random strings
token := abstract.GetRandomString(32)
// Use futures for concurrent operations
future := abstract.NewFuture(ctx, logger, func(ctx context.Context) (string, error) {
return "result", nil
})
result, err := future.Get(ctx)
Copy paste from https://github.com/gtank/cryptopasta/tree/master
Index ΒΆ
- Variables
- func Abs[T Number](x T) T
- func Atoi[T Number](s string) (T, error)
- func CheckHMAC(data, suppliedMAC []byte, key *[32]byte) bool
- func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error)
- func DecodePublicKey(encodedKey []byte) (*ecdsa.PublicKey, error)
- func DecodeSignatureJWT(b64sig string) ([]byte, error)
- func DecryptAES(ciphertext []byte, key *[32]byte) (plaintext []byte, err error)
- func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
- func EncodePublicKey(key *ecdsa.PublicKey) ([]byte, error)
- func EncodeSignatureJWT(sig []byte) string
- func EncryptAES(plaintext []byte, key *[32]byte) (ciphertext []byte, err error)
- func FromID(id string, t EntityType) string
- func GenerateHMAC(data []byte, key *[32]byte) []byte
- func GetRandListenAddress() (port string)
- func GetRandomAlphaNumeric(n int) string
- func GetRandomBool() bool
- func GetRandomBytes(n int) []byte
- func GetRandomBytesFast(n int) []byte
- func GetRandomChoice[T any](slice []T) (T, bool)
- func GetRandomInt(min, max int) int
- func GetRandomLowerAlpha(n int) string
- func GetRandomNumeric(n int) string
- func GetRandomString(n int) string
- func GetRandomStringFast(n int) string
- func GetRandomStringWithAlphabet(n int, alphabet []byte) string
- func GetRandomUpperAlpha(n int) string
- func HashHMAC(tag string, data []byte) []byte
- func Itoa[T Number](i T) string
- func Max[T Number](xs ...T) T
- func Min[T Number](xs ...T) T
- func NewEncryptionKey() *[32]byte
- func NewHMACKey() *[32]byte
- func NewID(entityType EntityType) string
- func NewSigningKey() (*ecdsa.PrivateKey, error)
- func NewTestID() string
- func Pow[T1, T2 Number](x T1, y T2) T1
- func Round[T Number](f T) T
- func SetEntitySize(size int)
- func ShuffleSlice[T any](slice []T)
- func SignData(data []byte, privkey *ecdsa.PrivateKey) ([]byte, error)
- func StartCycle(ctx context.Context, l lang.Logger, f func())
- func StartCycleWithChan[T any](ctx context.Context, l lang.Logger, c <-chan T, f func(T))
- func StartCycleWithChanAndShutdown[T any](ctx context.Context, l lang.Logger, c <-chan T, shutdown <-chan struct{}, ...)
- func StartCycleWithShutdown(ctx context.Context, l lang.Logger, shutdown <-chan struct{}, f func())
- func StartUpdater(ctx context.Context, interval time.Duration, l lang.Logger, f func())
- func StartUpdaterNow(ctx context.Context, interval time.Duration, l lang.Logger, f func())
- func StartUpdaterWithShutdown(ctx context.Context, interval time.Duration, l lang.Logger, f func(), ...)
- func StartUpdaterWithShutdownChan(ctx context.Context, interval time.Duration, l lang.Logger, c chan struct{}, ...)
- func VerifySign(data, signature []byte, pubkey *ecdsa.PublicKey) bool
- type Builder
- type CSVTable
- func (t *CSVTable) AddRow(id string, row map[string]string)
- func (t *CSVTable) All() map[string]map[string]string
- func (t *CSVTable) AllIDs() []string
- func (t *CSVTable) AllRows() []map[string]string
- func (t *CSVTable) AllSorted() [][]string
- func (t *CSVTable) AppendColumn(column string, values []string)
- func (t *CSVTable) Bytes() []byte
- func (t *CSVTable) Copy() *CSVTable
- func (t *CSVTable) DeleteColumn(column string)
- func (t *CSVTable) DeleteColumns(columns ...string)
- func (t *CSVTable) DeleteRow(id string) bool
- func (t *CSVTable) Find(criteria map[string]string) map[string]map[string]string
- func (t *CSVTable) FindRow(criteria map[string]string) (string, map[string]string)
- func (t *CSVTable) Has(slug string) bool
- func (t *CSVTable) Headers() []string
- func (t *CSVTable) LookupRow(slug string) (map[string]string, bool)
- func (t *CSVTable) LookupRowSorted(id string) ([]string, bool)
- func (t *CSVTable) Row(slug string) map[string]string
- func (t *CSVTable) RowSorted(id string) []string
- func (t *CSVTable) Sort(column string, direction SortDirection) *CSVTable
- func (t *CSVTable) UpdateColumn(column string, values []string)
- func (t *CSVTable) UpdateRow(id string, row map[string]string) bool
- func (t *CSVTable) Value(slug, key string) string
- type CSVTableSafe
- func (t *CSVTableSafe) AddRow(id string, row map[string]string)
- func (t *CSVTableSafe) All() map[string]map[string]string
- func (t *CSVTableSafe) AllIDs() []string
- func (t *CSVTableSafe) AllRows() []map[string]string
- func (t *CSVTableSafe) AllSorted() [][]string
- func (t *CSVTableSafe) AppendColumn(column string, values []string)
- func (t *CSVTableSafe) Bytes() []byte
- func (t *CSVTableSafe) Copy() *CSVTableSafe
- func (t *CSVTableSafe) DeleteColumn(column string)
- func (t *CSVTableSafe) DeleteColumns(columns ...string)
- func (t *CSVTableSafe) DeleteRow(id string) bool
- func (t *CSVTableSafe) Find(criteria map[string]string) map[string]map[string]string
- func (t *CSVTableSafe) FindRow(criteria map[string]string) (string, map[string]string)
- func (t *CSVTableSafe) Has(slug string) bool
- func (t *CSVTableSafe) Headers() []string
- func (t *CSVTableSafe) LookupRow(slug string) (map[string]string, bool)
- func (t *CSVTableSafe) LookupRowSorted(id string) ([]string, bool)
- func (t *CSVTableSafe) Row(slug string) map[string]string
- func (t *CSVTableSafe) RowSorted(id string) []string
- func (t *CSVTableSafe) Sort(column string, direction SortDirection)
- func (t *CSVTableSafe) Unwrap() *CSVTable
- func (t *CSVTableSafe) UpdateColumn(column string, values []string)
- func (t *CSVTableSafe) UpdateRow(id string, row map[string]string) bool
- func (t *CSVTableSafe) Value(slug, key string) string
- type Complex
- type Entity
- type EntityMap
- func (s *EntityMap[K, T]) AllOrdered() []T
- func (s *EntityMap[K, T]) ChangeOrder(draft map[K]int)
- func (s *EntityMap[K, T]) Delete(keys ...K) (deleted bool)
- func (s *EntityMap[K, T]) LookupByName(name string) (T, bool)
- func (s *EntityMap[K, T]) NextOrder() int
- func (s *EntityMap[K, T]) Set(info T) int
- func (s *EntityMap[K, T]) SetManualOrder(info T) int
- type EntityType
- type Float
- type Future
- type Integer
- type JobQueue
- func (q *JobQueue) FinishedTasks() int
- func (q *JobQueue) IsQueueStarted() bool
- func (q *JobQueue) OnFlyRunningTasks() int
- func (q *JobQueue) PendingTasks() int
- func (q *JobQueue) Shutdown(ctx context.Context) error
- func (q *JobQueue) Start(ctx context.Context)
- func (q *JobQueue) StopNoWait()
- func (q *JobQueue) Submit(ctx context.Context, task func(ctx context.Context)) bool
- func (q *JobQueue) TasksInQueue() int
- func (q *JobQueue) TotalTasks() int
- func (q *JobQueue) Wait(ctx context.Context) error
- type LegacyWorkerPool
- func (p *LegacyWorkerPool) IsStopped() bool
- func (p *LegacyWorkerPool) Results() <-chan Result
- func (p *LegacyWorkerPool) RunningWorkers() int
- func (p *LegacyWorkerPool) Start()
- func (p *LegacyWorkerPool) Stop()
- func (p *LegacyWorkerPool) StopAndWait(timeout time.Duration) bool
- func (p *LegacyWorkerPool) Submit(task Task, timeout time.Duration) bool
- func (p *LegacyWorkerPool) SubmitWait(task Task, timeout time.Duration) (any, error)
- func (p *LegacyWorkerPool) Wait()
- type LinkedList
- type Map
- func (m *Map[K, V]) Change(key K, f func(K, V) V)
- func (m *Map[K, V]) Clear()
- func (m *Map[K, V]) Copy() map[K]V
- func (m *Map[K, V]) Delete(keys ...K) (deleted bool)
- func (m *Map[K, V]) Get(key K) V
- func (m *Map[K, V]) Has(key K) bool
- func (m *Map[K, V]) IsEmpty() bool
- func (m *Map[K, V]) Iter() iter.Seq2[K, V]
- func (m *Map[K, V]) IterKeys() iter.Seq[K]
- func (m *Map[K, V]) IterValues() iter.Seq[V]
- func (m *Map[K, V]) Keys() []K
- func (m *Map[K, V]) Len() int
- func (m *Map[K, V]) Lookup(key K) (V, bool)
- func (m *Map[K, V]) Pop(key K) V
- func (m *Map[K, V]) Range(f func(K, V) bool) bool
- func (m *Map[K, V]) Raw() map[K]V
- func (m *Map[K, V]) Set(key K, value V)
- func (m *Map[K, V]) SetIfNotPresent(key K, value V) V
- func (m *Map[K, V]) Swap(key K, value V) V
- func (m *Map[K, V]) Transform(f func(K, V) V)
- func (m *Map[K, V]) Values() []V
- type MapOfMaps
- func (m *MapOfMaps[K1, K2, V]) AllKeys() []K2
- func (m *MapOfMaps[K1, K2, V]) AllValues() []V
- func (m *MapOfMaps[K1, K2, V]) Change(outerKey K1, innerKey K2, f func(K1, K2, V) V)
- func (m *MapOfMaps[K1, K2, V]) Clear()
- func (m *MapOfMaps[K1, K2, V]) Copy() map[K1]map[K2]V
- func (m *MapOfMaps[K1, K2, V]) Delete(outerKey K1, innerKeys ...K2) bool
- func (m *MapOfMaps[K1, K2, V]) DeleteMap(outerKeys ...K1) bool
- func (m *MapOfMaps[K1, K2, V]) Get(outerKey K1, innerKey K2) V
- func (m *MapOfMaps[K1, K2, V]) GetMap(outerKey K1) map[K2]V
- func (m *MapOfMaps[K1, K2, V]) Has(outerKey K1, innerKey K2) bool
- func (m *MapOfMaps[K1, K2, V]) HasMap(outerKey K1) bool
- func (m *MapOfMaps[K1, K2, V]) IsEmpty() bool
- func (m *MapOfMaps[K1, K2, V]) Len() int
- func (m *MapOfMaps[K1, K2, V]) Lookup(outerKey K1, innerKey K2) (V, bool)
- func (m *MapOfMaps[K1, K2, V]) LookupMap(outerKey K1) (map[K2]V, bool)
- func (m *MapOfMaps[K1, K2, V]) OuterKeys() []K1
- func (m *MapOfMaps[K1, K2, V]) OuterLen() int
- func (m *MapOfMaps[K1, K2, V]) Pop(outerKey K1, innerKey K2) V
- func (m *MapOfMaps[K1, K2, V]) PopMap(outerKey K1) map[K2]V
- func (m *MapOfMaps[K1, K2, V]) Range(f func(K1, K2, V) bool) bool
- func (m *MapOfMaps[K1, K2, V]) Raw() map[K1]map[K2]V
- func (m *MapOfMaps[K1, K2, V]) Refill(raw map[K1]map[K2]V)
- func (m *MapOfMaps[K1, K2, V]) Set(outerKey K1, innerKey K2, value V)
- func (m *MapOfMaps[K1, K2, V]) SetIfNotPresent(outerKey K1, innerKey K2, value V) V
- func (m *MapOfMaps[K1, K2, V]) SetMap(outerKey K1, innerMap map[K2]V)
- func (m *MapOfMaps[K1, K2, V]) Swap(outerKey K1, innerKey K2, value V) V
- func (m *MapOfMaps[K1, K2, V]) Transform(f func(K1, K2, V) V)
- type Memorizer
- type Number
- type Ordered
- type OrderedPairs
- type Orderer
- type RateProcessor
- type Result
- type SafeEntityMap
- func (s *SafeEntityMap[K, T]) AllOrdered() []T
- func (s *SafeEntityMap[K, T]) ChangeOrder(draft map[K]int)
- func (s *SafeEntityMap[K, T]) Delete(keys ...K) (deleted bool)
- func (s *SafeEntityMap[K, T]) LookupByName(name string) (T, bool)
- func (s *SafeEntityMap[K, T]) NextOrder() int
- func (s *SafeEntityMap[K, T]) Set(info T) int
- func (s *SafeEntityMap[K, T]) SetManualOrder(info T) int
- type SafeLegacyWorkerPool
- func (p *SafeLegacyWorkerPool) IsStopped() bool
- func (p *SafeLegacyWorkerPool) RunningWorkers() int
- func (p *SafeLegacyWorkerPool) Start()
- func (p *SafeLegacyWorkerPool) Stop()
- func (p *SafeLegacyWorkerPool) StopAndWait(timeout time.Duration) bool
- func (p *SafeLegacyWorkerPool) Submit(task Task, timeout time.Duration) bool
- func (p *SafeLegacyWorkerPool) SubmitWait(task Task, timeout time.Duration) (any, error)
- type SafeLinkedList
- func (l *SafeLinkedList[T]) Back() (T, bool)
- func (l *SafeLinkedList[T]) Front() (T, bool)
- func (l *SafeLinkedList[T]) Len() int
- func (l *SafeLinkedList[T]) PopBack() (T, bool)
- func (l *SafeLinkedList[T]) PopFront() (T, bool)
- func (l *SafeLinkedList[T]) PushBack(data T)
- func (l *SafeLinkedList[T]) PushFront(data T)
- type SafeMap
- func (m *SafeMap[K, V]) Change(key K, f func(K, V) V)
- func (m *SafeMap[K, V]) Clear()
- func (m *SafeMap[K, V]) Copy() map[K]V
- func (m *SafeMap[K, V]) Delete(keys ...K) (deleted bool)
- func (m *SafeMap[K, V]) Get(key K) V
- func (m *SafeMap[K, V]) Has(key K) bool
- func (m *SafeMap[K, V]) IsEmpty() bool
- func (m *SafeMap[K, V]) Iter() iter.Seq2[K, V]
- func (m *SafeMap[K, V]) IterKeys() iter.Seq[K]
- func (m *SafeMap[K, V]) IterValues() iter.Seq[V]
- func (m *SafeMap[K, V]) Keys() []K
- func (m *SafeMap[K, V]) Len() int
- func (m *SafeMap[K, V]) Lookup(key K) (V, bool)
- func (m *SafeMap[K, V]) Pop(key K) V
- func (m *SafeMap[K, V]) Range(f func(K, V) bool) bool
- func (m *SafeMap[K, V]) Raw() map[K]V
- func (m *SafeMap[K, V]) Refill(raw map[K]V)
- func (m *SafeMap[K, V]) Set(key K, value V)
- func (m *SafeMap[K, V]) SetIfNotPresent(key K, value V) V
- func (m *SafeMap[K, V]) Swap(key K, value V) V
- func (m *SafeMap[K, V]) Transform(upd func(K, V) V)
- func (m *SafeMap[K, V]) Values() []V
- type SafeMapOfMaps
- func (m *SafeMapOfMaps[K1, K2, V]) AllKeys() []K2
- func (m *SafeMapOfMaps[K1, K2, V]) AllValues() []V
- func (m *SafeMapOfMaps[K1, K2, V]) Change(outerKey K1, innerKey K2, f func(K1, K2, V) V)
- func (m *SafeMapOfMaps[K1, K2, V]) Clear()
- func (m *SafeMapOfMaps[K1, K2, V]) Copy() map[K1]map[K2]V
- func (m *SafeMapOfMaps[K1, K2, V]) Delete(outerKey K1, innerKeys ...K2) bool
- func (m *SafeMapOfMaps[K1, K2, V]) DeleteMap(outerKeys ...K1) bool
- func (m *SafeMapOfMaps[K1, K2, V]) Get(outerKey K1, innerKey K2) V
- func (m *SafeMapOfMaps[K1, K2, V]) GetMap(outerKey K1) map[K2]V
- func (m *SafeMapOfMaps[K1, K2, V]) Has(outerKey K1, innerKey K2) bool
- func (m *SafeMapOfMaps[K1, K2, V]) HasMap(outerKey K1) bool
- func (m *SafeMapOfMaps[K1, K2, V]) IsEmpty() bool
- func (m *SafeMapOfMaps[K1, K2, V]) Len() int
- func (m *SafeMapOfMaps[K1, K2, V]) Lookup(outerKey K1, innerKey K2) (V, bool)
- func (m *SafeMapOfMaps[K1, K2, V]) LookupMap(outerKey K1) (map[K2]V, bool)
- func (m *SafeMapOfMaps[K1, K2, V]) OuterKeys() []K1
- func (m *SafeMapOfMaps[K1, K2, V]) OuterLen() int
- func (m *SafeMapOfMaps[K1, K2, V]) Pop(outerKey K1, innerKey K2) V
- func (m *SafeMapOfMaps[K1, K2, V]) PopMap(outerKey K1) map[K2]V
- func (m *SafeMapOfMaps[K1, K2, V]) Range(f func(K1, K2, V) bool) bool
- func (m *SafeMapOfMaps[K1, K2, V]) Raw() map[K1]map[K2]V
- func (m *SafeMapOfMaps[K1, K2, V]) Refill(raw map[K1]map[K2]V)
- func (m *SafeMapOfMaps[K1, K2, V]) Set(outerKey K1, innerKey K2, value V)
- func (m *SafeMapOfMaps[K1, K2, V]) SetIfNotPresent(outerKey K1, innerKey K2, value V) V
- func (m *SafeMapOfMaps[K1, K2, V]) SetMap(outerKey K1, innerMap map[K2]V)
- func (m *SafeMapOfMaps[K1, K2, V]) Swap(outerKey K1, innerKey K2, value V) V
- func (m *SafeMapOfMaps[K1, K2, V]) Transform(f func(K1, K2, V) V)
- type SafeOrderedPairs
- type SafeSet
- func (m *SafeSet[K]) Add(key ...K)
- func (m *SafeSet[K]) Clear()
- func (m *SafeSet[K]) Copy() map[K]struct{}
- func (m *SafeSet[K]) Delete(keys ...K) (deleted bool)
- func (m *SafeSet[K]) Difference(set map[K]struct{}) *Set[K]
- func (m *SafeSet[K]) Has(key K) bool
- func (m *SafeSet[K]) Intersection(set map[K]struct{}) *Set[K]
- func (m *SafeSet[K]) IsEmpty() bool
- func (m *SafeSet[K]) Iter() iter.Seq[K]
- func (m *SafeSet[K]) Len() int
- func (m *SafeSet[K]) Range(f func(K) bool) bool
- func (m *SafeSet[K]) Raw() map[K]struct{}
- func (m *SafeSet[K]) SymmetricDifference(set map[K]struct{}) *Set[K]
- func (m *SafeSet[K]) Transform(f func(K) K)
- func (m *SafeSet[K]) Union(set map[K]struct{}) *Set[K]
- func (m *SafeSet[K]) Values() []K
- type SafeSlice
- func (s *SafeSlice[T]) AddFront(v ...T)
- func (s *SafeSlice[T]) Append(v ...T)
- func (s *SafeSlice[T]) Change(index int, f func(T) T)
- func (s *SafeSlice[T]) Clear()
- func (s *SafeSlice[T]) Copy() []T
- func (s *SafeSlice[T]) Delete(index int) bool
- func (s *SafeSlice[T]) Get(index int) T
- func (s *SafeSlice[T]) IsEmpty() bool
- func (s *SafeSlice[T]) Iter() iter.Seq[T]
- func (s *SafeSlice[T]) Iter2() iter.Seq2[int, T]
- func (s *SafeSlice[T]) Len() int
- func (s *SafeSlice[T]) Pop() T
- func (s *SafeSlice[T]) Range(f func(T) bool) bool
- func (s *SafeSlice[T]) Raw() []T
- func (s *SafeSlice[T]) Transform(f func(T) T)
- func (s *SafeSlice[T]) Truncate(size int)
- type SafeStack
- type SafeUniqueStack
- func (ss *SafeUniqueStack[T]) Clear()
- func (ss *SafeUniqueStack[T]) IsEmpty() bool
- func (ss *SafeUniqueStack[T]) Last() T
- func (ss *SafeUniqueStack[T]) Len() int
- func (ss *SafeUniqueStack[T]) Pop() T
- func (ss *SafeUniqueStack[T]) PopOK() (T, bool)
- func (ss *SafeUniqueStack[T]) Push(item T)
- func (ss *SafeUniqueStack[T]) Raw() []T
- func (ss *SafeUniqueStack[T]) Remove(item T) bool
- type Set
- func (m *Set[K]) Add(key ...K)
- func (m *Set[K]) Clear()
- func (m *Set[K]) Copy() map[K]struct{}
- func (m *Set[K]) Delete(keys ...K) (deleted bool)
- func (m *Set[K]) Difference(set map[K]struct{}) *Set[K]
- func (m *Set[K]) Has(key K) bool
- func (m *Set[K]) Intersection(set map[K]struct{}) *Set[K]
- func (m *Set[K]) IsEmpty() bool
- func (m *Set[K]) Iter() iter.Seq[K]
- func (m *Set[K]) Len() int
- func (m *Set[K]) Range(f func(K) bool) bool
- func (m *Set[K]) Raw() map[K]struct{}
- func (m *Set[K]) SymmetricDifference(set map[K]struct{}) *Set[K]
- func (m *Set[K]) Transform(f func(K) K)
- func (m *Set[K]) Union(set map[K]struct{}) *Set[K]
- func (m *Set[K]) Values() []K
- type Signed
- type Slice
- func (s *Slice[T]) AddFront(v ...T)
- func (s *Slice[T]) Append(v ...T)
- func (s *Slice[T]) Change(index int, f func(T) T)
- func (s *Slice[T]) Clear()
- func (s *Slice[T]) Copy() []T
- func (s *Slice[T]) Delete(index int) bool
- func (s *Slice[T]) Get(index int) T
- func (s *Slice[T]) IsEmpty() bool
- func (s *Slice[T]) Iter() iter.Seq[T]
- func (s *Slice[T]) Iter2() iter.Seq2[int, T]
- func (s *Slice[T]) Len() int
- func (s *Slice[T]) Pop() T
- func (s *Slice[T]) Range(f func(T) bool) bool
- func (s *Slice[T]) Raw() []T
- func (s *Slice[T]) Transform(f func(T) T)
- func (s *Slice[T]) Truncate(size int)
- type SortDirection
- type Stack
- type Task
- type Timer
- func (t Timer) ElapsedHours() float64
- func (t Timer) ElapsedMicroseconds() int64
- func (t Timer) ElapsedMilliseconds() int64
- func (t Timer) ElapsedMinutes() float64
- func (t Timer) ElapsedNanoseconds() int64
- func (t Timer) ElapsedSeconds() float64
- func (t Timer) ElapsedTime() time.Duration
- func (t Timer) Format(layout string) string
- func (t Timer) FormatShort() string
- func (t Timer) HasElapsed(duration time.Duration) bool
- func (t Timer) IsExpired() bool
- func (t Timer) IsPaused() bool
- func (t *Timer) Lap() time.Duration
- func (t Timer) LapDurations() []time.Duration
- func (t Timer) Laps() []time.Time
- func (t *Timer) Pause() bool
- func (t *Timer) Reset()
- func (t *Timer) Resume() bool
- func (t *Timer) SetDeadline(deadline time.Time)
- func (t *Timer) SetDeadlineDuration(duration time.Duration)
- func (t Timer) String() string
- func (t Timer) Time() time.Time
- func (t Timer) TimeRemaining() time.Duration
- type UniqueStack
- func (s *UniqueStack[T]) Clear()
- func (s *UniqueStack[T]) IsEmpty() bool
- func (s *UniqueStack[T]) Last() T
- func (s *UniqueStack[T]) Len() int
- func (s *UniqueStack[T]) Pop() T
- func (s *UniqueStack[T]) PopOK() (T, bool)
- func (s *UniqueStack[T]) Push(item T)
- func (s *UniqueStack[T]) Raw() []T
- func (s *UniqueStack[T]) Remove(item T) bool
- type Unsigned
- type Waiter
- type WaiterSet
- type WorkerPool
- func (p *WorkerPool[T]) FetchAllResults(ctx context.Context) ([]T, []error)
- func (p *WorkerPool[T]) FetchResults(ctx context.Context) ([]T, []error)
- func (p *WorkerPool[T]) FinishedTasks() int
- func (p *WorkerPool[T]) IsPoolStarted() bool
- func (p *WorkerPool[T]) OnFlyRunningTasks() int
- func (p *WorkerPool[T]) Shutdown(ctx context.Context) error
- func (p *WorkerPool[T]) Start(ctx context.Context)
- func (p *WorkerPool[T]) StopNoWait()
- func (p *WorkerPool[T]) Submit(ctx context.Context, task func(ctx context.Context) (T, error)) bool
- func (p *WorkerPool[T]) TasksInQueue() int
- func (p *WorkerPool[T]) TotalTasks() int
- type WorkerPoolV2
- func (p *WorkerPoolV2[T]) FetchAllResults(timeoutRaw ...time.Duration) ([]T, []error)
- func (p *WorkerPoolV2[T]) FetchResults(timeoutRaw ...time.Duration) ([]T, []error)
- func (p *WorkerPoolV2[T]) Finished() int
- func (p *WorkerPoolV2[T]) IsStopped() bool
- func (p *WorkerPoolV2[T]) Running() int
- func (p *WorkerPoolV2[T]) Start()
- func (p *WorkerPoolV2[T]) Stop()
- func (p *WorkerPoolV2[T]) Submit(task func() (T, error), timeoutRaw ...time.Duration) bool
- func (p *WorkerPoolV2[T]) Submitted() int
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ErrTimeout = errors.New("timeout")
Functions ΒΆ
func Abs ΒΆ added in v1.5.0
func Abs[T Number](x T) T
Abs returns the absolute value of the provided numeric value. This function works with any numeric type and returns the same type.
Parameters:
- x: The numeric value to get the absolute value of.
Returns:
- The absolute value of the input.
Example usage:
abs := Abs(-5) // 5 abs := Abs(3.14) // 3.14 abs := Abs(-2.71) // 2.71
func Atoi ΒΆ added in v1.5.0
Atoi converts a string to a numeric value of the specified type. This is a generic version of strconv.Atoi that works with any numeric type.
Parameters:
- s: The string to convert.
Returns:
- The numeric value as the specified type.
- An error if the string cannot be converted.
Example usage:
val, err := Atoi[int]("42") // 42, nil
val, err := Atoi[float64]("99") // 99.0, nil
val, err := Atoi[int8]("300") // 44, nil (overflow)
func CheckHMAC ΒΆ added in v1.11.0
CheckHMAC securely verifies an HMAC against a message using the shared secret key. This function uses constant-time comparison to prevent timing attacks.
Security considerations:
- Uses constant-time comparison to prevent timing attacks
- Both the data and key must match exactly for verification to succeed
- Returns false for any invalid input (empty data, empty MAC, nil key)
Parameters:
- data: The original data that was authenticated
- suppliedMAC: The HMAC to verify
- key: The same 32-byte key used to generate the HMAC
Returns:
- true if the HMAC is valid for the given data and key, false otherwise
Example usage:
key := NewHMACKey()
data := []byte("message")
mac := GenerateHMAC(data, key)
// Verify the MAC
if CheckHMAC(data, mac, key) {
fmt.Println("HMAC verification successful")
} else {
fmt.Println("HMAC verification failed - data may be tampered")
}
func DecodePrivateKey ΒΆ added in v1.11.0
func DecodePrivateKey(encodedKey []byte) (*ecdsa.PrivateKey, error)
DecodePrivateKey decodes a PEM-encoded ECDSA private key from bytes. The input should be a PEM block with type "EC PRIVATE KEY".
Security considerations:
- Private keys should be stored securely and never shared
- Consider encrypting private keys when storing them
- Zero out the key material when no longer needed
Parameters:
- encodedKey: PEM-encoded private key bytes
Returns:
- An ECDSA private key ready for signing operations
- An error if the key cannot be decoded or is not an ECDSA key
Example usage:
pemData := []byte(`-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIK9...
-----END EC PRIVATE KEY-----`)
privKey, err := DecodePrivateKey(pemData)
if err != nil {
log.Fatal(err)
}
defer func() {
privKey.D.SetInt64(0) // Zero out the private key
}()
func DecodePublicKey ΒΆ added in v1.11.0
DecodePublicKey decodes a PEM-encoded ECDSA public key from bytes. The input should be a PEM block with type "PUBLIC KEY".
Parameters:
- encodedKey: PEM-encoded public key bytes
Returns:
- An ECDSA public key ready for signature verification
- An error if the key cannot be decoded or is not an ECDSA key
Example usage:
pemData := []byte(`-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----`)
pubKey, err := DecodePublicKey(pemData)
if err != nil {
log.Fatal(err)
}
func DecodeSignatureJWT ΒΆ added in v1.11.0
DecodeSignatureJWT decodes a JWT-encoded ECDSA signature. This is the reverse operation of EncodeSignatureJWT.
Parameters:
- b64sig: Base64url-encoded signature string from JWT
Returns:
- The raw ECDSA signature bytes
- An error if the signature cannot be decoded
Example usage:
jwtSig := "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9..."
signature, err := DecodeSignatureJWT(jwtSig)
if err != nil {
log.Fatal(err)
}
// Use signature with VerifySign
func DecryptAES ΒΆ added in v1.11.0
DecryptAES decrypts data that was encrypted with EncryptAES using 256-bit AES-GCM. This function both decrypts the data and verifies its authenticity.
The input must be in the format: nonce || ciphertext || tag where || indicates concatenation (as produced by EncryptAES).
Security considerations:
- Automatically verifies the authentication tag before decryption
- Returns an error if the data has been tampered with
- Uses constant-time operations to prevent timing attacks
Parameters:
- ciphertext: The encrypted data (as returned by EncryptAES)
- key: The same 32-byte key used for encryption
Returns:
- plaintext: The decrypted data
- error: Any error that occurred during decryption or authentication
Example usage:
key := NewEncryptionKey()
ciphertext, _ := EncryptAES([]byte("secret"), key)
plaintext, err := DecryptAES(ciphertext, key)
if err != nil {
log.Fatal("Decryption failed:", err)
}
fmt.Printf("Decrypted: %s\n", plaintext)
func EncodePrivateKey ΒΆ added in v1.11.0
func EncodePrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
EncodePrivateKey encodes an ECDSA private key to PEM format. The output should be stored securely and protected from unauthorized access.
Security considerations:
- The encoded private key should be stored securely
- Consider encrypting the PEM data before storage
- Never share or transmit private keys over insecure channels
Parameters:
- key: The ECDSA private key to encode
Returns:
- PEM-encoded private key bytes
- An error if the key cannot be encoded
Example usage:
privKey, _ := NewSigningKey()
pemData, err := EncodePrivateKey(privKey)
if err != nil {
log.Fatal(err)
}
// Store pemData securely
func EncodePublicKey ΒΆ added in v1.11.0
EncodePublicKey encodes an ECDSA public key to PEM format. The output is suitable for storage, transmission, or sharing.
Parameters:
- key: The ECDSA public key to encode
Returns:
- PEM-encoded public key bytes
- An error if the key cannot be encoded
Example usage:
privKey, _ := NewSigningKey()
pubKey := &privKey.PublicKey
pemData, err := EncodePublicKey(pubKey)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Public key:\n%s", pemData)
func EncodeSignatureJWT ΒΆ added in v1.11.0
EncodeSignatureJWT encodes an ECDSA signature for use in JWT tokens. This follows the JWT specification (RFC 7515, Appendix A.3.1) for ECDSA signature encoding.
Parameters:
- sig: The raw ECDSA signature bytes
Returns:
- Base64url-encoded signature string suitable for JWT, or empty string if sig is empty
Example usage:
signature, _ := SignData([]byte("data"), privKey)
jwtSig := EncodeSignatureJWT(signature)
// Use jwtSig in JWT token
func EncryptAES ΒΆ added in v1.11.0
EncryptAES encrypts data using 256-bit AES-GCM (Galois/Counter Mode). This provides both confidentiality and authenticity - it hides the content and ensures the data hasn't been tampered with.
The output format is: nonce || ciphertext || tag where || indicates concatenation.
Security considerations:
- Uses AES-256-GCM which is a NIST-approved authenticated encryption mode
- Generates a unique nonce for each encryption operation
- Provides both encryption and authentication
- The same key should never be used to encrypt more than 2^32 messages
Parameters:
- plaintext: The data to encrypt (can be any length)
- key: A 32-byte encryption key (use NewEncryptionKey() to generate)
Returns:
- ciphertext: The encrypted data with nonce and authentication tag
- error: Any error that occurred during encryption
Example usage:
key := NewEncryptionKey()
plaintext := []byte("confidential message")
ciphertext, err := EncryptAES(plaintext, key)
if err != nil {
log.Fatal(err)
}
func FromID ΒΆ added in v1.10.1
func FromID(id string, t EntityType) string
FromID converts an existing ID to use a different entity type. This function replaces the entity type prefix of an ID while preserving the random portion (or as much as possible).
Parameters:
- id: The existing ID to convert
- t: The new EntityType to use
Returns:
- A new ID with the specified entity type prefix
Example usage:
userType := RegisterEntityType("USER")
adminType := RegisterEntityType("ADMN")
userID := NewID(userType) // "USERa1b2c3d4e5f6"
adminID := FromID(userID, adminType) // "ADMNa1b2c3d4e5f6"
// Useful for type conversions or migrations
func promoteUserToAdmin(userID string) string {
return FromID(userID, AdminEntity)
}
func GenerateHMAC ΒΆ added in v1.11.0
GenerateHMAC produces a symmetric signature using HMAC-SHA-512/256. This creates a message authentication code that can be used to verify both the integrity and authenticity of a message.
Security considerations:
- Uses SHA-512/256 which provides 256-bit security
- The key should be at least 32 bytes for optimal security
- Different keys produce different MACs for the same data
Parameters:
- data: The data to authenticate
- key: A 32-byte secret key (use NewHMACKey() to generate)
Returns:
- A 32-byte HMAC, or nil if data is empty or key is nil
Example usage:
key := NewHMACKey()
data := []byte("important message")
mac := GenerateHMAC(data, key)
// Later, verify the MAC
if CheckHMAC(data, mac, key) {
fmt.Println("Message is authentic")
}
func GetRandListenAddress ΒΆ
func GetRandListenAddress() (port string)
GetRandListenAddress generates a random TCP port number in the range 10000-62999 and returns it as a string formatted for network listening (e.g., ":12345").
Note: This function uses math/rand, not crypto/rand, as it's intended for development and testing purposes where cryptographic security is not required.
Returns:
- A string in the format ":XXXXX" where XXXXX is a random port number
Example usage:
addr := GetRandListenAddress() // ":45123"
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
func GetRandomAlphaNumeric ΒΆ added in v1.12.0
GetRandomAlphaNumeric returns a cryptographically secure random string containing letters (both cases) and numbers (0-9, a-z, A-Z).
Security considerations:
- Uses crypto/rand for secure random generation
- Provides good entropy with 62 possible characters per position
- Suitable for user-facing identifiers and codes
Parameters:
- n: The length of the random string to generate
Returns:
- A random string of length n containing letters and numbers
Example usage:
userID := GetRandomAlphaNumeric(12) // "Ab3Cd5Ef7Gh9" token := GetRandomAlphaNumeric(20) // "aB3cD5eF7gH9iJ2kL4"
func GetRandomBool ΒΆ added in v1.12.0
func GetRandomBool() bool
GetRandomBool returns a cryptographically secure random boolean value.
Security considerations:
- Uses crypto/rand for secure random generation when available
- Falls back to math/rand with time-based seed if crypto/rand fails
- Provides unbiased true/false selection
Returns:
- A random boolean value (true or false)
Example usage:
coinFlip := GetRandomBool() // true or false
if GetRandomBool() {
fmt.Println("Random event occurred")
}
// Use in feature flags or random decisions
enableFeature := GetRandomBool()
func GetRandomBytes ΒΆ
GetRandomBytes returns cryptographically secure random bytes of the specified length using hexadecimal characters (0-9, a-f).
Security considerations:
- Uses crypto/rand for secure random generation when available
- Falls back to math/rand with time-based seed if crypto/rand fails
- Each byte is masked to ensure uniform distribution across the alphabet
Parameters:
- n: The number of random bytes to generate
Returns:
- A byte slice of length n containing random hexadecimal characters
Example usage:
randomBytes := GetRandomBytes(16)
fmt.Printf("Random bytes: %x\n", randomBytes)
func GetRandomBytesFast ΒΆ added in v1.15.0
GetRandomBytesFast returns a non-cryptographically secure random byte slice of the specified length. This function uses a simple LCG (linear congruential generator) for performance reasons.
Note: This function is NOT cryptographically secure and should only be used for non-security purposes.
Parameters:
- n: The length of the random byte slice to generate
Returns:
- A random byte slice of length n
Example usage:
randomBytes := GetRandomBytesFast(16)
fmt.Printf("Random bytes: %x\n", randomBytes)
func GetRandomChoice ΒΆ added in v1.12.0
GetRandomChoice returns a random element from the provided slice. This function uses math/rand for performance reasons.
Parameters:
- slice: The slice to choose from
Returns:
- A random element from the slice and true if successful
- The zero value for the type and false if the slice is empty
Example usage:
colors := []string{"red", "green", "blue", "yellow"}
color, ok := GetRandomChoice(colors)
if ok {
fmt.Printf("Random color: %s\n", color)
}
numbers := []int{1, 2, 3, 4, 5}
number, _ := GetRandomChoice(numbers)
fmt.Printf("Random number: %d\n", number)
func GetRandomInt ΒΆ added in v1.12.0
GetRandomInt returns a cryptographically secure random integer in the specified range [min, max]. The range is inclusive on both ends.
Security considerations:
- Uses crypto/rand for secure random generation when available
- Falls back to math/rand with time-based seed if crypto/rand fails
- Automatically swaps min and max if min > max
- Returns min if min equals max
Parameters:
- min: The minimum value (inclusive)
- max: The maximum value (inclusive)
Returns:
- A random integer in the range [min, max]
Example usage:
dice := GetRandomInt(1, 6) // Random number 1-6 percent := GetRandomInt(0, 100) // Random percentage 0-100 port := GetRandomInt(8000, 9000) // Random port in range
func GetRandomLowerAlpha ΒΆ added in v1.12.0
GetRandomLowerAlpha returns a cryptographically secure random string containing only lowercase letters (a-z).
Security considerations:
- Uses crypto/rand for secure random generation
- Suitable for generating case-sensitive identifiers
Parameters:
- n: The length of the random string to generate
Returns:
- A random string of length n containing only lowercase letters
Example usage:
code := GetRandomLowerAlpha(8) // "abcdefgh" id := GetRandomLowerAlpha(16) // "qwertyuiopasdfgh"
func GetRandomNumeric ΒΆ added in v1.12.0
GetRandomNumeric returns a cryptographically secure random string containing only numeric digits (0-9).
Security considerations:
- Uses crypto/rand for secure random generation
- Lower entropy than alphanumeric strings (10 vs 62 characters)
- Suitable for numeric codes and identifiers
Parameters:
- n: The length of the random string to generate
Returns:
- A random string of length n containing only digits
Example usage:
pin := GetRandomNumeric(4) // "1234" code := GetRandomNumeric(8) // "87654321" id := GetRandomNumeric(12) // "123456789012"
func GetRandomString ΒΆ
GetRandomString returns a cryptographically secure random string of the specified length using hexadecimal characters (0-9, a-f).
Security considerations:
- Uses crypto/rand for secure random generation when available
- Falls back to math/rand with time-based seed if crypto/rand fails
- Suitable for generating tokens, session IDs, and other security-sensitive identifiers
Parameters:
- n: The length of the random string to generate
Returns:
- A random string of length n containing hexadecimal characters
Example usage:
sessionID := GetRandomString(32) // "a1b2c3d4e5f6..." token := GetRandomString(16) // "f1e2d3c4b5a6..."
func GetRandomStringFast ΒΆ added in v1.15.0
GetRandomStringFast returns a non-cryptographically secure random string of the specified length. This function uses a simple LCG (linear congruential generator) for performance reasons.
Note: This function is NOT cryptographically secure and should only be used for non-security purposes.
Parameters:
- n: The length of the random string to generate
Returns:
- A random string of length n
Example usage:
randomString := GetRandomStringFast(10) // "a1b2c3d4e5" token := GetRandomStringFast(20) // "f1e2d3c4b5a6..."
func GetRandomStringWithAlphabet ΒΆ added in v1.12.0
GetRandomStringWithAlphabet returns a cryptographically secure random string using characters from the specified alphabet.
Security considerations:
- Uses crypto/rand for secure random generation when available
- Falls back to math/rand with time-based seed if crypto/rand fails
- Uses modulo operation to ensure uniform distribution across the alphabet
- Returns empty string if alphabet is empty
Parameters:
- n: The length of the random string to generate
- alphabet: A byte slice containing the characters to use
Returns:
- A random string of length n using characters from the alphabet
Example usage:
// Generate a random string with custom alphabet
customAlphabet := []byte("!@#$%^&*")
symbols := GetRandomStringWithAlphabet(8, customAlphabet)
// Generate a random password
passwordChars := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*")
password := GetRandomStringWithAlphabet(12, passwordChars)
func GetRandomUpperAlpha ΒΆ added in v1.12.0
GetRandomUpperAlpha returns a cryptographically secure random string containing only uppercase letters (A-Z).
Security considerations:
- Uses crypto/rand for secure random generation
- Suitable for generating case-sensitive identifiers
Parameters:
- n: The length of the random string to generate
Returns:
- A random string of length n containing only uppercase letters
Example usage:
code := GetRandomUpperAlpha(6) // "ABCDEF" id := GetRandomUpperAlpha(12) // "QWERTYUIOPAS"
func HashHMAC ΒΆ added in v1.11.0
HashHMAC generates a keyed hash of data using HMAC-SHA-512/256. This is suitable for data integrity verification and key derivation, but NOT for password hashing (use bcrypt, scrypt, or Argon2 for passwords).
The tag parameter serves as the HMAC key and should describe the purpose of the hash to ensure domain separation between different uses.
Security considerations:
- Uses SHA-512/256 which provides 256-bit security
- The tag acts as a key, so different tags produce different hashes
- Suitable for integrity verification and key derivation
- NOT suitable for password hashing
Parameters:
- tag: A descriptive string that serves as the HMAC key (e.g., "session-token", "api-key")
- data: The data to hash
Returns:
- A 32-byte hash of the data, or nil if data is empty
Example usage:
hash := HashHMAC("user-session", []byte("user123:session456"))
// Use hash for integrity verification or as a derived key
func Itoa ΒΆ added in v1.5.0
Itoa converts a numeric value to its string representation. This is a generic version of strconv.Itoa that works with any numeric type.
Parameters:
- i: The numeric value to convert.
Returns:
- The string representation of the numeric value.
Example usage:
str := Itoa(42) // "42" str := Itoa(3.14) // "3" str := Itoa(int64(99)) // "99"
func Max ΒΆ added in v1.5.0
func Max[T Number](xs ...T) T
Max returns the maximum value from the provided values. If no values are provided, returns the zero value for the type.
Parameters:
- xs: Variable number of values to compare.
Returns:
- The maximum value among the provided values.
Example usage:
max := Max(1, 2, 3) // 3 max := Max(3.14, 2.71, 1.41) // 3.14 max := Max[int]() // 0 (zero value)
func Min ΒΆ added in v1.5.0
func Min[T Number](xs ...T) T
Min returns the minimum value from the provided values. If no values are provided, returns the zero value for the type.
Parameters:
- xs: Variable number of values to compare.
Returns:
- The minimum value among the provided values.
Example usage:
min := Min(1, 2, 3) // 1 min := Min(3.14, 2.71, 1.41) // 1.41 min := Min[int]() // 0 (zero value)
func NewEncryptionKey ΒΆ added in v1.11.0
func NewEncryptionKey() *[32]byte
NewEncryptionKey generates a cryptographically secure random 256-bit key for use with EncryptAES and DecryptAES functions.
Security considerations:
- Uses crypto/rand for secure random generation
- Panics if the system's secure random number generator fails
- The returned key should be kept secret and stored securely
Returns:
- A pointer to a 32-byte array containing the encryption key
Example usage:
key := NewEncryptionKey()
defer func() { // Zero out the key when done
for i := range key {
key[i] = 0
}
}()
encrypted, err := EncryptAES([]byte("secret data"), key)
if err != nil {
log.Fatal(err)
}
func NewHMACKey ΒΆ added in v1.11.0
func NewHMACKey() *[32]byte
NewHMACKey generates a cryptographically secure random 256-bit key for use with HMAC operations.
Security considerations:
- Uses crypto/rand for secure random generation
- Panics if the system's secure random number generator fails
- The returned key should be kept secret and stored securely
Returns:
- A pointer to a 32-byte array containing the HMAC key
Example usage:
key := NewHMACKey()
defer func() { // Zero out the key when done
for i := range key {
key[i] = 0
}
}()
mac := GenerateHMAC([]byte("message"), key)
func NewID ΒΆ added in v1.10.1
func NewID(entityType EntityType) string
NewID generates a new unique identifier with the specified entity type prefix. The ID consists of the entity type followed by a random string of defaultIDSize length.
Parameters:
- entityType: The EntityType to use as a prefix for the ID
Returns:
- A unique identifier string in the format: entityType + randomString
Example usage:
userType := RegisterEntityType("USER")
postType := RegisterEntityType("POST")
userID := NewID(userType) // "USERa1b2c3d4e5f6"
postID := NewID(postType) // "POST9z8y7x6w5v4u"
// Use in your application
type User struct {
ID string
Name string
}
user := User{
ID: NewID(userType),
Name: "John Doe",
}
func NewSigningKey ΒΆ added in v1.11.0
func NewSigningKey() (*ecdsa.PrivateKey, error)
NewSigningKey generates a new random P-256 ECDSA private key for digital signatures. P-256 is a NIST-approved elliptic curve that provides 128-bit security.
Security considerations:
- Uses crypto/rand for secure random generation
- P-256 provides 128-bit security level
- The private key should be stored securely and never shared
- Consider using hardware security modules for key storage in production
Returns:
- A new ECDSA private key
- An error if key generation fails
Example usage:
privKey, err := NewSigningKey()
if err != nil {
log.Fatal(err)
}
defer func() {
privKey.D.SetInt64(0) // Zero out the private key
}()
// Use the key for signing
signature, _ := SignData([]byte("document"), privKey)
func NewTestID ΒΆ added in v1.10.1
func NewTestID() string
NewTestID generates a new test identifier using the TestIDEntity type. This is a convenience function for testing and development purposes.
Returns:
- A test identifier string in the format: "00x0" + randomString
Example usage:
testID := NewTestID() // "00x0a1b2c3d4e5f6"
// Use in tests
func TestUserCreation(t *testing.T) {
user := User{
ID: NewTestID(),
Name: "Test User",
}
// ... test logic
}
func Pow ΒΆ added in v1.5.0
func Pow[T1, T2 Number](x T1, y T2) T1
Pow returns the value x raised to the power of y. This function works with any numeric types and returns the same type as the base.
Parameters:
- x: The base value.
- y: The exponent value.
Returns:
- The result of x raised to the power of y.
Example usage:
result := Pow(2, 3) // 8 result := Pow(2.0, 0.5) // 1.414... (square root of 2) result := Pow(10, -1) // 0.1
func Round ΒΆ added in v1.5.0
func Round[T Number](f T) T
Round returns the nearest integer to the input value, rounding half away from zero. This function works with any numeric type and returns the same type.
Parameters:
- f: The numeric value to round.
Returns:
- The rounded value as the same type as the input.
Example usage:
rounded := Round(3.7) // 4.0 rounded := Round(-2.3) // -2.0 rounded := Round(42) // 42
func SetEntitySize ΒΆ added in v1.10.0
func SetEntitySize(size int)
SetEntitySize configures the required length for entity type identifiers. This should be called before registering any entity types and should be consistent across your entire application.
Parameters:
- size: The required length for entity type identifiers
Example usage:
func init() {
SetEntitySize(5) // Use 5-character entity types
UserEntity := RegisterEntityType("USER_")
AdminEntity := RegisterEntityType("ADMIN")
}
func ShuffleSlice ΒΆ added in v1.12.0
func ShuffleSlice[T any](slice []T)
ShuffleSlice randomly shuffles the elements in the provided slice in-place. This function modifies the original slice using the Fisher-Yates shuffle algorithm.
Note: This function uses math/rand for performance reasons. For cryptographically secure shuffling, consider using crypto/rand with a custom implementation.
Parameters:
- slice: The slice to shuffle (modified in-place)
Example usage:
cards := []string{"A", "K", "Q", "J", "10", "9", "8", "7"}
ShuffleSlice(cards)
fmt.Printf("Shuffled cards: %v\n", cards)
numbers := []int{1, 2, 3, 4, 5}
ShuffleSlice(numbers)
fmt.Printf("Shuffled numbers: %v\n", numbers)
func SignData ΒΆ added in v1.11.0
func SignData(data []byte, privkey *ecdsa.PrivateKey) ([]byte, error)
SignData creates a digital signature for arbitrary data using ECDSA. The signature can be verified using VerifySign with the corresponding public key.
Security considerations:
- Uses SHA-256 for hashing the data before signing
- Includes protection against signature malleability attacks
- The signature is deterministic for the same data and key
- Uses secure random nonce generation
Parameters:
- data: The data to sign (will be hashed with SHA-256)
- privkey: The ECDSA private key for signing
Returns:
- A signature that can be verified with VerifySign
- An error if signing fails or inputs are invalid
Example usage:
privKey, _ := NewSigningKey()
data := []byte("document to sign")
signature, err := SignData(data, privKey)
if err != nil {
log.Fatal(err)
}
// Verify with the public key
pubKey := &privKey.PublicKey
if VerifySign(data, signature, pubKey) {
fmt.Println("Signature is valid")
}
func StartCycle ΒΆ added in v1.7.0
StartCycle starts a panic-safe goroutine that continuously executes a function in a tight loop until the context is canceled.
Warning: This creates a high-CPU usage pattern. Use with caution and ensure the function either includes appropriate delays or processes work efficiently. Consider using StartUpdater with a small interval instead if periodic execution is acceptable.
Parameters:
- ctx: Context for cancellation and timeout control
- l: Logger for panic recovery and error handling
- f: Function to execute continuously
Example usage:
StartCycle(ctx, logger, func() {
// Process available work or include a small delay
if work := getNextWork(); work != nil {
processWork(work)
} else {
time.Sleep(10 * time.Millisecond) // Prevent 100% CPU usage
}
})
func StartCycleWithChan ΒΆ added in v1.7.0
StartCycleWithChan starts a panic-safe goroutine that processes values from a channel, executing the provided function for each received value until the context is canceled or the channel is closed.
This is useful for implementing worker patterns where you need to process items from a queue or channel continuously.
Parameters:
- ctx: Context for cancellation and timeout control
- l: Logger for panic recovery and error handling
- c: Channel to receive values from
- f: Function to execute for each received value
Example usage:
workChan := make(chan WorkItem, 100)
StartCycleWithChan(ctx, logger, workChan, func(item WorkItem) {
fmt.Printf("Processing work item: %v\n", item)
// Process the work item
item.Process()
})
// Send work to be processed
workChan <- WorkItem{ID: "task1", Data: "some data"}
func StartCycleWithChanAndShutdown ΒΆ added in v1.7.0
func StartCycleWithChanAndShutdown[T any](ctx context.Context, l lang.Logger, c <-chan T, shutdown <-chan struct{}, f func(T))
StartCycleWithChanAndShutdown starts a panic-safe goroutine that processes values from a channel until the context is canceled, the channel is closed, or a shutdown signal is received.
This provides the most control over the lifecycle of a channel processing goroutine.
Parameters:
- ctx: Context for cancellation and timeout control
- l: Logger for panic recovery and error handling
- c: Channel to receive values from
- shutdown: Channel that signals shutdown when closed or receives a value
- f: Function to execute for each received value
Example usage:
workChan := make(chan Task, 50)
shutdown := make(chan struct{})
StartCycleWithChanAndShutdown(ctx, logger, workChan, shutdown, func(task Task) {
fmt.Printf("Processing task: %v\n", task.ID)
task.Execute()
})
// Graceful shutdown
close(shutdown)
func StartCycleWithShutdown ΒΆ added in v1.7.0
StartCycleWithShutdown starts a panic-safe goroutine that continuously executes a function until either the context is canceled or the shutdown channel is signaled.
This provides additional control over stopping the cycle independently of context cancellation.
Parameters:
- ctx: Context for cancellation and timeout control
- l: Logger for panic recovery and error handling
- shutdown: Channel that signals shutdown when closed or receives a value
- f: Function to execute continuously
Example usage:
shutdown := make(chan struct{})
StartCycleWithShutdown(ctx, logger, shutdown, func() {
// Continuous processing with controlled shutdown
processNextItem()
})
// Stop the cycle when needed
close(shutdown)
func StartUpdater ΒΆ
StartUpdater starts a panic-safe goroutine that executes a function periodically at the specified interval. The goroutine gracefully stops when the context is canceled.
This function is useful for creating background tasks that need to run at regular intervals, such as health checks, data cleanup, or periodic synchronization.
Parameters:
- ctx: Context for cancellation and timeout control
- interval: Duration between function executions
- l: Logger for panic recovery and error handling
- f: Function to execute periodically
Example usage:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
StartUpdater(ctx, 30*time.Second, logger, func() {
fmt.Println("Performing periodic health check...")
// Health check logic here
})
// Updater will stop when context is canceled
time.Sleep(5*time.Minute)
cancel() // Gracefully stops the updater
func StartUpdaterNow ΒΆ
StartUpdaterNow starts a panic-safe goroutine that executes a function immediately and then continues to execute it periodically at the specified interval.
This is useful when you want to ensure the first execution happens right away instead of waiting for the first interval to pass.
Parameters:
- ctx: Context for cancellation and timeout control
- interval: Duration between subsequent function executions
- l: Logger for panic recovery and error handling
- f: Function to execute immediately and then periodically
Example usage:
StartUpdaterNow(ctx, 1*time.Minute, logger, func() {
fmt.Println("Syncing data...") // Executes immediately
// Data synchronization logic
})
// Function runs immediately, then every minute thereafter
func StartUpdaterWithShutdown ΒΆ
func StartUpdaterWithShutdown(ctx context.Context, interval time.Duration, l lang.Logger, f func(), shutdown func())
StartUpdaterWithShutdown starts a panic-safe goroutine that executes a function periodically and runs a shutdown function when the context is canceled.
This pattern is useful when you need to perform cleanup operations when the periodic task is stopped.
Parameters:
- ctx: Context for cancellation and timeout control
- interval: Duration between function executions
- l: Logger for panic recovery and error handling
- f: Function to execute periodically
- shutdown: Function to execute when context is canceled
Example usage:
StartUpdaterWithShutdown(ctx, 10*time.Second, logger,
func() {
// Periodic work
processQueue()
},
func() {
// Cleanup when stopping
fmt.Println("Shutting down queue processor...")
saveState()
},
)
func StartUpdaterWithShutdownChan ΒΆ
func StartUpdaterWithShutdownChan(ctx context.Context, interval time.Duration, l lang.Logger, c chan struct{}, f func())
StartUpdaterWithShutdownChan starts a panic-safe goroutine that executes a function periodically and stops when either the context is canceled or the shutdown channel receives a signal.
This provides an additional way to stop the updater without canceling the context, which can be useful in complex applications where you want fine-grained control.
Parameters:
- ctx: Context for cancellation and timeout control
- interval: Duration between function executions
- l: Logger for panic recovery and error handling
- c: Channel that signals shutdown when closed or receives a value
- f: Function to execute periodically
Example usage:
shutdown := make(chan struct{})
StartUpdaterWithShutdownChan(ctx, 5*time.Second, logger, shutdown, func() {
fmt.Println("Periodic task running...")
})
// Later, signal shutdown
close(shutdown) // Stops the updater
func VerifySign ΒΆ added in v1.11.0
VerifySign verifies an ECDSA signature against the original data. This function checks both the mathematical validity and authenticity of the signature.
Security considerations:
- Uses SHA-256 for hashing the data (must match SignData)
- Includes protection against signature malleability attacks
- Returns false for any invalid input or tampered signatures
- Uses constant-time operations where possible
Parameters:
- data: The original data that was signed
- signature: The signature to verify (as returned by SignData)
- pubkey: The ECDSA public key corresponding to the private key used for signing
Returns:
- true if the signature is valid for the given data and public key, false otherwise
Example usage:
privKey, _ := NewSigningKey()
data := []byte("signed document")
signature, _ := SignData(data, privKey)
// Verify the signature
pubKey := &privKey.PublicKey
if VerifySign(data, signature, pubKey) {
fmt.Println("Signature verification successful")
} else {
fmt.Println("Signature verification failed")
}
Types ΒΆ
type Builder ΒΆ added in v1.10.0
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a convenient way to generate IDs of a specific entity type. It encapsulates an EntityType and provides methods to generate IDs without needing to pass the entity type each time.
Example usage:
userType := RegisterEntityType("USER")
userBuilder := WithEntityType(userType)
// Generate multiple user IDs
user1ID := userBuilder.NewID() // "USERa1b2c3d4e5f6"
user2ID := userBuilder.NewID() // "USERx9y8z7w6v5u4"
user3ID := userBuilder.NewID() // "USERm3n4o5p6q7r8"
func WithEntityType ΒΆ added in v1.10.1
func WithEntityType(t EntityType) Builder
WithEntityType creates a new Builder for the specified entity type. This is a factory function that returns a Builder configured to generate IDs of the specified type.
Parameters:
- t: The EntityType to use for ID generation
Returns:
- A Builder instance configured for the specified entity type
Example usage:
userType := RegisterEntityType("USER")
postType := RegisterEntityType("POST")
userBuilder := WithEntityType(userType)
postBuilder := WithEntityType(postType)
// Use builders to generate IDs
users := make([]User, 5)
for i := range users {
users[i] = User{
ID: userBuilder.NewID(),
Name: fmt.Sprintf("User %d", i+1),
}
}
func (Builder) NewID ΒΆ added in v1.10.1
NewID generates a new ID using the Builder's configured entity type. This method provides a convenient way to generate multiple IDs of the same type without repeatedly specifying the entity type.
Returns:
- A new ID string with the Builder's entity type prefix
Example usage:
userBuilder := WithEntityType(RegisterEntityType("USER"))
// Generate multiple user IDs
for i := 0; i < 10; i++ {
userID := userBuilder.NewID()
fmt.Printf("Generated user ID: %s\n", userID)
}
// Use in struct initialization
type UserService struct {
idBuilder Builder
}
func NewUserService() *UserService {
return &UserService{
idBuilder: WithEntityType(RegisterEntityType("USER")),
}
}
func (s *UserService) CreateUser(name string) User {
return User{
ID: s.idBuilder.NewID(),
Name: name,
}
}
type CSVTable ΒΆ added in v1.11.0
type CSVTable struct {
// contains filtered or unexported fields
}
CSVTable represents a table of data from a CSV file where the first column is used as the ID for each row, and the remaining columns are stored with row order preserved.
func NewCSVTable ΒΆ added in v1.11.0
NewCSVTable creates a new CSVTable from the given records. The first row is considered the header row, and the first column is used as the ID for each row. If the records are empty or if there are not enough headers (< 2), returns an empty table.
func NewCSVTableFromFilePath ΒΆ added in v1.11.0
NewCSVTableFromFilePath creates a new CSVTable from a file at the given path. Returns an error if the file cannot be opened or parsed.
func NewCSVTableFromMap ΒΆ added in v1.13.0
NewCSVTableFromMap creates a new CSVTable from a map structure. The outer map keys become row IDs, and the inner map keys become column headers. An ID column is automatically added as the first column. If idColumnName is provided, it will be used as the ID column name.
func NewCSVTableFromReader ΒΆ added in v1.11.0
NewCSVTableFromReader creates a new CSVTable from any io.Reader that contains CSV data. Returns an error if the CSV data cannot be parsed.
func (*CSVTable) AddRow ΒΆ added in v1.11.0
AddRow adds a new row to the table with the given ID and data. If the row has no data, it will not be added.
func (*CSVTable) All ΒΆ added in v1.11.0
All returns all rows in the table as a map of ID to row data.
func (*CSVTable) AllRows ΒΆ added in v1.11.0
AllRows returns all rows in the table as a slice of row data maps.
func (*CSVTable) AllSorted ΒΆ added in v1.12.1
AllSorted returns all rows in the table as a slice of maps, preserving the original order.
func (*CSVTable) AppendColumn ΒΆ added in v1.11.0
AppendColumn adds a new column to the table with the given name and values. Values are assigned to rows in order. If there are more rows than values, the remaining rows will not have a value for this column.
func (*CSVTable) Copy ΒΆ added in v1.11.0
Copy creates a deep copy of the CSVTable. This is useful if you need to modify the data without affecting the original.
func (*CSVTable) DeleteColumn ΒΆ added in v1.13.0
DeleteColumn removes the specified column from the table. This affects both the headers and the data in each row.
func (*CSVTable) DeleteColumns ΒΆ added in v1.11.0
DeleteColumns removes the specified columns from the table. This affects both the headers and the data in each row.
func (*CSVTable) DeleteRow ΒΆ added in v1.13.0
DeleteRow removes the row with the specified ID from the table. Returns true if the row was found and deleted, false otherwise.
func (*CSVTable) Find ΒΆ added in v1.13.0
Find finds all rows that match the given criteria. The criteria is a map of column names to values that must match. Returns a map of row IDs to row data for all matching rows.
func (*CSVTable) FindRow ΒΆ added in v1.13.0
FindRow finds the first row that matches the given criteria. The criteria is a map of column names to values that must match. Returns the row ID and data if found, empty string and nil if not found.
func (*CSVTable) Has ΒΆ added in v1.11.0
Has returns true if a row with the given ID exists in the table.
func (*CSVTable) LookupRow ΒΆ added in v1.11.0
LookupRow returns the data for the row with the given ID and a boolean indicating if the row exists.
func (*CSVTable) LookupRowSorted ΒΆ added in v1.12.1
RowSorted returns a map of ID to row data in the original sorted order.
func (*CSVTable) Row ΒΆ added in v1.11.0
Row returns the data for the row with the given ID. If no row with that ID exists, returns an empty map.
func (*CSVTable) RowSorted ΒΆ added in v1.12.1
RowSorted returns a map of ID to row data in the original sorted order.
func (*CSVTable) Sort ΒΆ added in v1.12.0
func (t *CSVTable) Sort(column string, direction SortDirection) *CSVTable
Sort reorders the table rows based on the values in the specified column. If the column does not exist, no sorting is performed. The direction parameter determines whether sorting is done in ascending or descending order.
func (*CSVTable) UpdateColumn ΒΆ added in v1.13.0
UpdateColumn updates all values in the specified column. Values are assigned to rows in order. If there are more rows than values, the remaining rows will keep their existing values.
type CSVTableSafe ΒΆ added in v1.11.0
type CSVTableSafe struct {
// contains filtered or unexported fields
}
CSVTableSafe is a thread-safe wrapper around CSVTable that provides synchronized access to the underlying data using a mutex.
func NewCSVTableSafe ΒΆ added in v1.11.0
func NewCSVTableSafe(records [][]string) *CSVTableSafe
NewCSVTableSafe creates a new thread-safe CSVTable from records.
func NewCSVTableSafeFromFilePath ΒΆ added in v1.11.0
func NewCSVTableSafeFromFilePath(path string) (*CSVTableSafe, error)
NewCSVTableSafeFromFilePath creates a new thread-safe CSVTable from a file path.
func NewCSVTableSafeFromMap ΒΆ added in v1.13.0
func NewCSVTableSafeFromMap(data map[string]map[string]string, idColumnName ...string) *CSVTableSafe
NewCSVTableSafeFromMap creates a new thread-safe CSVTable from a map structure.
func NewCSVTableSafeFromReader ΒΆ added in v1.11.0
func NewCSVTableSafeFromReader(reader io.Reader) (*CSVTableSafe, error)
NewCSVTableSafeFromReader creates a new thread-safe CSVTable from a reader.
func (*CSVTableSafe) AddRow ΒΆ added in v1.11.0
func (t *CSVTableSafe) AddRow(id string, row map[string]string)
AddRow adds a new row to the table in a thread-safe manner.
func (*CSVTableSafe) All ΒΆ added in v1.11.0
func (t *CSVTableSafe) All() map[string]map[string]string
All returns a copy of all rows in the table.
func (*CSVTableSafe) AllIDs ΒΆ added in v1.11.0
func (t *CSVTableSafe) AllIDs() []string
AllIDs returns a copy of all row IDs in the table.
func (*CSVTableSafe) AllRows ΒΆ added in v1.11.0
func (t *CSVTableSafe) AllRows() []map[string]string
AllRows returns a copy of all rows as a slice of maps.
func (*CSVTableSafe) AllSorted ΒΆ added in v1.12.1
func (t *CSVTableSafe) AllSorted() [][]string
AllSorted returns all rows in the table as a slice of maps, preserving the original order.
func (*CSVTableSafe) AppendColumn ΒΆ added in v1.11.0
func (t *CSVTableSafe) AppendColumn(column string, values []string)
AppendColumn adds a new column to the table in a thread-safe manner.
func (*CSVTableSafe) Bytes ΒΆ added in v1.11.0
func (t *CSVTableSafe) Bytes() []byte
Bytes returns the table as a CSV-formatted byte slice.
func (*CSVTableSafe) Copy ΒΆ added in v1.11.0
func (t *CSVTableSafe) Copy() *CSVTableSafe
Copy creates a deep copy of the CSVTableSafe, including its internal table.
func (*CSVTableSafe) DeleteColumn ΒΆ added in v1.13.0
func (t *CSVTableSafe) DeleteColumn(column string)
DeleteColumn removes the specified column from the table.
func (*CSVTableSafe) DeleteColumns ΒΆ added in v1.11.0
func (t *CSVTableSafe) DeleteColumns(columns ...string)
DeleteColumns removes the specified columns from the table.
func (*CSVTableSafe) DeleteRow ΒΆ added in v1.13.0
func (t *CSVTableSafe) DeleteRow(id string) bool
DeleteRow removes the row with the specified ID from the table.
func (*CSVTableSafe) FindRow ΒΆ added in v1.13.0
FindRow finds the first row that matches the given criteria.
func (*CSVTableSafe) Has ΒΆ added in v1.11.0
func (t *CSVTableSafe) Has(slug string) bool
Has returns true if a row with the given ID exists in the table.
func (*CSVTableSafe) Headers ΒΆ added in v1.11.0
func (t *CSVTableSafe) Headers() []string
Headers returns a copy of the headers for the table.
func (*CSVTableSafe) LookupRow ΒΆ added in v1.11.0
func (t *CSVTableSafe) LookupRow(slug string) (map[string]string, bool)
LookupRow returns a copy of the row with the given ID and whether it exists.
func (*CSVTableSafe) LookupRowSorted ΒΆ added in v1.12.1
func (t *CSVTableSafe) LookupRowSorted(id string) ([]string, bool)
LookupRowSorted returns a map of ID to row data in the original sorted order.
func (*CSVTableSafe) Row ΒΆ added in v1.11.0
func (t *CSVTableSafe) Row(slug string) map[string]string
Row returns a copy of the row with the given ID.
func (*CSVTableSafe) RowSorted ΒΆ added in v1.12.1
func (t *CSVTableSafe) RowSorted(id string) []string
RowSorted returns a map of ID to row data in the original sorted order.
func (*CSVTableSafe) Sort ΒΆ added in v1.12.0
func (t *CSVTableSafe) Sort(column string, direction SortDirection)
Sort reorders the table rows in a thread-safe manner based on the values in the specified column.
func (*CSVTableSafe) Unwrap ΒΆ added in v1.11.0
func (t *CSVTableSafe) Unwrap() *CSVTable
Unwrap returns the underlying CSVTable. WARNING: This breaks thread safety. Only use when you're sure no other goroutines are accessing the table.
func (*CSVTableSafe) UpdateColumn ΒΆ added in v1.13.0
func (t *CSVTableSafe) UpdateColumn(column string, values []string)
UpdateColumn updates all values in the specified column.
func (*CSVTableSafe) UpdateRow ΒΆ added in v1.13.0
func (t *CSVTableSafe) UpdateRow(id string, row map[string]string) bool
UpdateRow updates an existing row with the given ID and data.
func (*CSVTableSafe) Value ΒΆ added in v1.11.0
func (t *CSVTableSafe) Value(slug, key string) string
Value returns the value for the given ID and key.
type Complex ΒΆ
type Complex interface {
~complex64 | ~complex128
}
Complex is a constraint that permits any complex numeric type. This constraint is useful for generic functions that need to work with complex numbers while maintaining type safety. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.
Example usage:
func ComplexAbs[T Complex](x T) float64 {
return cmplx.Abs(complex128(x))
}
type Entity ΒΆ
type Entity[K comparable] interface { GetID() K GetName() string GetOrder() int SetOrder(int) Entity[K] }
Entity is an interface for an object that has an ID, a name, and an order.
type EntityMap ΒΆ
type EntityMap[K comparable, T Entity[K]] struct { *Map[K, T] }
EntityMap is a map of entities. It has all methods of Map with some new ones. It is not safe for concurrent/parallel, use SafeEntityMap if you need it. This map MUST be initialized with NewEntityMap or NewEntityMapWithSize. Otherwise, it will panic.
func NewEntityMap ΒΆ
func NewEntityMap[K comparable, T Entity[K]](raw ...map[K]T) *EntityMap[K, T]
NewEntityMap returns a new EntityMap from the provided map.
func NewEntityMapWithSize ΒΆ
func NewEntityMapWithSize[K comparable, T Entity[K]](size int) *EntityMap[K, T]
NewEntityMapWithSize returns a new EntityMap with the provided size.
func (*EntityMap[K, T]) AllOrdered ΒΆ
func (s *EntityMap[K, T]) AllOrdered() []T
AllOrdered returns all values in order.
func (*EntityMap[K, T]) ChangeOrder ΒΆ
ChangeOrder changes the order of the values.
func (*EntityMap[K, T]) Delete ΒΆ
Delete deletes values for the provided keys. It reorders all remaining values.
func (*EntityMap[K, T]) LookupByName ΒΆ
LookupByName returns the value for the provided name. It is not case-sensetive according to name.
func (*EntityMap[K, T]) Set ΒΆ
Set sets the value for the provided key. It sets last order to the entity's order, so it adds to the end of the list. It sets the same order of existing entity in case of conflict. If the entity is not valid, it returns -1. It returns the order of the entity.
func (*EntityMap[K, T]) SetManualOrder ΒΆ added in v1.4.0
SetManualOrder sets the value for the provided key. Better to use EntityMap.Set to prevent from order errors. It returns the order of the entity.
type EntityType ΒΆ added in v1.10.0
type EntityType string
EntityType represents a type identifier for entities in the system. It's used as a prefix for generated IDs to ensure type safety and easy identification of entity types from their IDs.
Example usage:
userType := RegisterEntityType("USER")
adminType := RegisterEntityType("ADMN")
userID := NewID(userType) // "USER" + random string
adminID := NewID(adminType) // "ADMN" + random string
const ( // TestIDEntity is a predefined EntityType for testing purposes. // It uses "00x0" as the type identifier. TestIDEntity EntityType = "00x0" )
func FetchEntityType ΒΆ added in v1.10.0
func FetchEntityType(id string) EntityType
FetchEntityType extracts the entity type from an ID. This function returns the entity type prefix from an ID string.
Parameters:
- id: The ID string to extract the entity type from
Returns:
- The EntityType extracted from the ID prefix
Example usage:
userType := RegisterEntityType("USER")
userID := NewID(userType) // "USERa1b2c3d4e5f6"
extractedType := FetchEntityType(userID) // "USER"
// Use for type checking or routing
func handleEntity(id string) {
entityType := FetchEntityType(id)
switch entityType {
case "USER":
handleUser(id)
case "POST":
handlePost(id)
case "ADMN":
handleAdmin(id)
}
}
func RegisterEntityType ΒΆ added in v1.10.0
func RegisterEntityType(entityType string) EntityType
RegisterEntityType creates a new EntityType with the specified identifier. The identifier must be exactly entityTypeSize characters long.
This function is typically called during application initialization to define the entity types used in your system.
Parameters:
- entityType: A string identifier for the entity type (must be exactly entityTypeSize characters)
Returns:
- An EntityType that can be used with NewID() and other ID functions
Panics:
- If the entityType length doesn't match entityTypeSize
Example usage:
const (
UserEntity = RegisterEntityType("USER")
PostEntity = RegisterEntityType("POST")
AdminEntity = RegisterEntityType("ADMN")
)
// Or in init function:
func init() {
UserEntity = RegisterEntityType("USER")
PostEntity = RegisterEntityType("POST")
}
func (EntityType) String ΒΆ added in v1.10.0
func (e EntityType) String() string
String returns the string representation of the EntityType. This method allows EntityType to be used as a string in contexts where string representation is needed.
Returns:
- The string value of the EntityType
type Float ΒΆ
Float is a constraint that permits any floating-point type. This constraint is useful for generic functions that need to work with floating-point numbers while maintaining type safety. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.
Example usage:
func IsNaN[T Float](x T) bool {
return math.IsNaN(float64(x))
}
type Future ΒΆ
type Future[T any] struct { // contains filtered or unexported fields }
Future is used for running a function in a separate goroutine with returning the result.
How to use:
f1 := abstract.NewFuture(ctx, slog.Default(), func(context.Context) (string, error) {
// TODO: some code
return "some result", nil
})
result, err := f1.Get(ctx)
func NewFuture ΒΆ
func NewFuture[T any](ctx context.Context, l lang.Logger, foo func(ctx context.Context) (T, error)) *Future[T]
NewFuture returns a new started future, it creates a goroutine that will run the passed function and remember it's result and error.
type Integer ΒΆ
Integer is a constraint that permits any integer type, both signed and unsigned. This constraint is useful for generic functions that need to work with any integer type while maintaining type safety. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.
Example usage:
func IsEven[T Integer](x T) bool {
return x%2 == 0
}
type JobQueue ΒΆ added in v1.18.0
type JobQueue struct {
// contains filtered or unexported fields
}
JobQueue manages a pool of workers that execute context-aware tasks without return values. It's optimized for fire-and-forget operations with task tracking and wait capabilities.
func NewJobQueue ΒΆ added in v1.18.0
NewJobQueue creates a new context-aware job queue with the specified number of workers and task queue capacity.
func (*JobQueue) FinishedTasks ΒΆ added in v1.18.0
FinishedTasks returns the number of completed tasks.
func (*JobQueue) IsQueueStarted ΒΆ added in v1.18.0
IsQueueStarted returns true if the job queue has been started.
func (*JobQueue) OnFlyRunningTasks ΒΆ added in v1.18.0
OnFlyRunningTasks returns the number of currently executing tasks.
func (*JobQueue) PendingTasks ΒΆ added in v1.18.0
PendingTasks returns the total number of tasks that are either queued or running.
func (*JobQueue) Shutdown ΒΆ added in v1.18.0
Shutdown signals all workers to stop after completing their current tasks. It waits for all in-flight and queued tasks to complete or until the context is done.
func (*JobQueue) StopNoWait ΒΆ added in v1.18.0
func (q *JobQueue) StopNoWait()
StopNoWait signals all workers to stop after completing their current tasks. It does not wait for them to complete.
func (*JobQueue) Submit ΒΆ added in v1.18.0
Submit adds a task to the queue and returns true if the task was accepted. Returns false if the queue is stopped or the context is done.
func (*JobQueue) TasksInQueue ΒΆ added in v1.18.0
TasksInQueue returns the number of tasks in the queue waiting to be executed.
func (*JobQueue) TotalTasks ΒΆ added in v1.18.0
TotalTasks returns the total number of tasks submitted to the queue.
type LegacyWorkerPool ΒΆ added in v1.18.0
type LegacyWorkerPool struct {
// contains filtered or unexported fields
}
LegacyWorkerPool manages a pool of workers that process tasks concurrently. Deprecated: Use WorkerPool for new code. This implementation is kept for backward compatibility.
func NewLegacyWorkerPool ΒΆ added in v1.18.0
func NewLegacyWorkerPool(workers, queueCapacity int) *LegacyWorkerPool
NewLegacyWorkerPool creates a new legacy worker pool with the specified number of workers and task queue capacity. Deprecated: Use NewWorkerPool for new code. This implementation is kept for backward compatibility.
func (*LegacyWorkerPool) IsStopped ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) IsStopped() bool
IsStopped returns true if the worker pool has been stopped.
func (*LegacyWorkerPool) Results ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) Results() <-chan Result
Results returns the channel that receives results from completed tasks.
func (*LegacyWorkerPool) RunningWorkers ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) RunningWorkers() int
RunningWorkers returns the number of worker goroutines.
func (*LegacyWorkerPool) Start ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) Start()
Start launches the worker goroutines.
func (*LegacyWorkerPool) Stop ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) Stop()
Stop signals all workers to stop after completing their current tasks. It does not wait for them to complete.
func (*LegacyWorkerPool) StopAndWait ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) StopAndWait(timeout time.Duration) bool
StopAndWait stops the worker pool and waits for all workers to complete. It returns true if workers completed within the timeout, false otherwise.
func (*LegacyWorkerPool) Submit ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) Submit(task Task, timeout time.Duration) bool
Submit adds a task to the pool and returns true if the task was accepted. Returns false if the pool is stopped or the task queue is full and the timeout is reached.
func (*LegacyWorkerPool) SubmitWait ΒΆ added in v1.18.0
SubmitWait adds a task to the pool and waits for its completion, returning the result. If the timeout is reached before the task can be submitted or completed, it returns an error.
func (*LegacyWorkerPool) Wait ΒΆ added in v1.18.0
func (p *LegacyWorkerPool) Wait()
Wait blocks until all workers have completed their tasks. This should only be called after Stop() or when all tasks have been submitted.
type LinkedList ΒΆ
type LinkedList[T any] struct { // contains filtered or unexported fields }
LinkedList is an implementation of a generic doubly linked list.
func NewLinkedList ΒΆ
func NewLinkedList[T any]() *LinkedList[T]
NewLinkedList creates a new linked list.
func (*LinkedList[T]) Back ΒΆ
func (l *LinkedList[T]) Back() (T, bool)
Back returns the last element of the linked list.
func (*LinkedList[T]) Front ΒΆ
func (l *LinkedList[T]) Front() (T, bool)
Front returns the first element of the linked list.
func (*LinkedList[T]) Len ΒΆ
func (l *LinkedList[T]) Len() int
Len returns the number of elements in the linked list.
func (*LinkedList[T]) PopBack ΒΆ
func (l *LinkedList[T]) PopBack() (T, bool)
PopBack removes an element from the back of the linked list and returns it.
func (*LinkedList[T]) PopFront ΒΆ
func (l *LinkedList[T]) PopFront() (T, bool)
PopFront removes an element from the front of the linked list and returns it.
func (*LinkedList[T]) PushBack ΒΆ added in v1.1.0
func (l *LinkedList[T]) PushBack(data T)
PushBack adds an element to the back of the linked list.
func (*LinkedList[T]) PushFront ΒΆ added in v1.1.0
func (l *LinkedList[T]) PushFront(data T)
PushFront adds an element to the front of the linked list.
type Map ΒΆ
type Map[K comparable, V any] struct { // contains filtered or unexported fields }
Map is used like a common map.
func NewMap ΒΆ
func NewMap[K comparable, V any](raw ...map[K]V) *Map[K, V]
NewMap returns a Map with an empty map.
func NewMapFromPairs ΒΆ
func NewMapFromPairs[K comparable, V any](pairs ...any) *Map[K, V]
NewMapFromPairs returns a Map with a map inited using the provided pairs.
func NewMapWithSize ΒΆ
func NewMapWithSize[K comparable, V any](size int) *Map[K, V]
NewMapWithSize returns a Map with a map inited using the provided size.
func (*Map[K, V]) Change ΒΆ added in v1.7.0
func (m *Map[K, V]) Change(key K, f func(K, V) V)
Change changes the value for the provided key using provided function.
func (*Map[K, V]) Clear ΒΆ added in v1.9.0
func (m *Map[K, V]) Clear()
Clear creates a new map using make without size.
func (*Map[K, V]) Copy ΒΆ
func (m *Map[K, V]) Copy() map[K]V
Copy returns another map that is a copy of the underlying map.
func (*Map[K, V]) Delete ΒΆ
Delete removes keys and associated values from the map, does nothing if the key is not present in the map, returns true if the key was deleted
func (*Map[K, V]) Get ΒΆ
func (m *Map[K, V]) Get(key K) V
Get returns the value for the provided key or the default type value if the key is not present in the map.
func (*Map[K, V]) IsEmpty ΒΆ
IsEmpty returns true if the map is empty. It is safe for concurrent/parallel use.
func (*Map[K, V]) IterValues ΒΆ added in v1.9.0
IterValues returns an iterator over the map values.
func (*Map[K, V]) Lookup ΒΆ
Lookup returns the value for the provided key and true if the key is present in the map, the default value and false otherwise.
func (*Map[K, V]) Pop ΒΆ
func (m *Map[K, V]) Pop(key K) V
Pop returns the value for the provided key and deletes it from map or default type value if key is not present.
func (*Map[K, V]) Raw ΒΆ added in v1.8.0
func (m *Map[K, V]) Raw() map[K]V
Raw returns the underlying map.
func (*Map[K, V]) SetIfNotPresent ΒΆ
func (m *Map[K, V]) SetIfNotPresent(key K, value V) V
SetIfNotPresent sets the value to the map if the key is not present, returns the old value if the key was set, new value otherwise.
func (*Map[K, V]) Swap ΒΆ
func (m *Map[K, V]) Swap(key K, value V) V
Swap swaps the values for the provided keys and returns the old value.
type MapOfMaps ΒΆ added in v1.14.0
type MapOfMaps[K1 comparable, K2 comparable, V comparable] struct { // contains filtered or unexported fields }
MapOfMaps is a nested map structure that maps keys to maps. It provides methods to work both at the outer level and with nested key-value pairs.
func NewMapOfMaps ΒΆ added in v1.14.0
func NewMapOfMaps[K1 comparable, K2 comparable, V comparable](raw ...map[K1]map[K2]V) *MapOfMaps[K1, K2, V]
NewMapOfMaps returns a new MapOfMaps with an empty map.
func NewMapOfMapsWithSize ΒΆ added in v1.14.0
func NewMapOfMapsWithSize[K1 comparable, K2 comparable, V comparable](size int) *MapOfMaps[K1, K2, V]
NewMapOfMapsWithSize returns a new MapOfMaps with the provided size.
func (*MapOfMaps[K1, K2, V]) AllKeys ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) AllKeys() []K2
AllKeys returns a slice of all nested keys across all inner maps.
func (*MapOfMaps[K1, K2, V]) AllValues ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) AllValues() []V
AllValues returns a slice of all values across all inner maps.
func (*MapOfMaps[K1, K2, V]) Change ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Change(outerKey K1, innerKey K2, f func(K1, K2, V) V)
Change changes the value for the provided nested keys using the provided function.
func (*MapOfMaps[K1, K2, V]) Clear ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Clear()
Clear creates a new empty nested map structure.
func (*MapOfMaps[K1, K2, V]) Copy ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Copy() map[K1]map[K2]V
Copy returns a deep copy of the nested map structure.
func (*MapOfMaps[K1, K2, V]) Delete ΒΆ added in v1.14.0
Delete removes nested keys and returns true if any were deleted.
func (*MapOfMaps[K1, K2, V]) DeleteMap ΒΆ added in v1.14.0
DeleteMap removes the entire inner map for the provided outer key and returns true if deleted.
func (*MapOfMaps[K1, K2, V]) Get ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Get(outerKey K1, innerKey K2) V
Get returns the value for the provided nested keys or the default type value if not present.
func (*MapOfMaps[K1, K2, V]) GetMap ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) GetMap(outerKey K1) map[K2]V
GetMap returns the inner map for the provided outer key or nil if not present.
func (*MapOfMaps[K1, K2, V]) Has ΒΆ added in v1.14.0
Has returns true if the nested keys are present, false otherwise.
func (*MapOfMaps[K1, K2, V]) HasMap ΒΆ added in v1.14.0
HasMap returns true if the outer key is present, false otherwise.
func (*MapOfMaps[K1, K2, V]) IsEmpty ΒΆ added in v1.14.0
IsEmpty returns true if there are no nested key-value pairs.
func (*MapOfMaps[K1, K2, V]) Len ΒΆ added in v1.14.0
Len returns the total number of nested key-value pairs across all inner maps.
func (*MapOfMaps[K1, K2, V]) Lookup ΒΆ added in v1.14.0
Lookup returns the value for the provided nested keys and true if present, default value and false otherwise.
func (*MapOfMaps[K1, K2, V]) LookupMap ΒΆ added in v1.14.0
LookupMap returns the inner map for the provided outer key and true if present, nil and false otherwise.
func (*MapOfMaps[K1, K2, V]) OuterKeys ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) OuterKeys() []K1
OuterKeys returns a slice of all outer keys.
func (*MapOfMaps[K1, K2, V]) OuterLen ΒΆ added in v1.14.0
OuterLen returns the number of outer keys (inner maps).
func (*MapOfMaps[K1, K2, V]) Pop ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Pop(outerKey K1, innerKey K2) V
Pop returns the value for the provided nested keys and deletes it or default value if not present.
func (*MapOfMaps[K1, K2, V]) PopMap ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) PopMap(outerKey K1) map[K2]V
PopMap returns the inner map for the provided outer key and deletes it or nil if not present.
func (*MapOfMaps[K1, K2, V]) Range ΒΆ added in v1.14.0
Range calls the provided function for each nested key-value pair.
func (*MapOfMaps[K1, K2, V]) Raw ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Raw() map[K1]map[K2]V
Raw returns the underlying nested map structure.
func (*MapOfMaps[K1, K2, V]) Refill ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Refill(raw map[K1]map[K2]V)
Refill creates a new nested map structure with values from the provided one.
func (*MapOfMaps[K1, K2, V]) Set ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) Set(outerKey K1, innerKey K2, value V)
Set sets the value for the provided nested keys.
func (*MapOfMaps[K1, K2, V]) SetIfNotPresent ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) SetIfNotPresent(outerKey K1, innerKey K2, value V) V
SetIfNotPresent sets the value if the nested keys are not present, returns the old value if present, new value otherwise.
func (*MapOfMaps[K1, K2, V]) SetMap ΒΆ added in v1.14.0
func (m *MapOfMaps[K1, K2, V]) SetMap(outerKey K1, innerMap map[K2]V)
SetMap sets the inner map for the provided outer key.
type Memorizer ΒΆ
type Memorizer[T any] struct { // contains filtered or unexported fields }
Memorizer is a thread-safe container that holds a single item of any type. It's useful for scenarios where you need to store and retrieve a single value safely across multiple goroutines, with the ability to check if the value has been set.
Example usage:
memo := NewMemorizer[string]()
memo.Set("important value")
if value, ok := memo.Get(); ok {
fmt.Println("Value:", value)
}
func NewMemorizer ΒΆ
NewMemorizer creates a new Memorizer instance for the specified type. The memorizer starts empty (isSet = false).
Returns:
- A new Memorizer instance ready for use.
func (*Memorizer[T]) Get ΒΆ
Get retrieves the value from the Memorizer along with a boolean indicating whether the value has been set. This method is thread-safe.
Returns:
- The stored value (or zero value if not set).
- A boolean indicating whether the value has been set.
type Number ΒΆ
Number is a constraint that permits any numeric type (integers and floats). This constraint is useful for generic mathematical operations that work with both integer and floating-point types.
Example usage:
func Square[T Number](x T) T {
return x * x
}
type Ordered ΒΆ
Ordered is a constraint that permits any ordered type: any type that supports the comparison operators < <= >= >. This constraint is essential for sorting operations and comparisons. If future releases of Go add new ordered types, this constraint will be modified to include them.
Example usage:
func Clamp[T Ordered](x, min, max T) T {
if x < min {
return min
}
if x > max {
return max
}
return x
}
type OrderedPairs ΒΆ
OrderedPairs is a data structure that behaves like a map but remembers the order in which the items were added. It is also possible to get a random value or key from the structure. It allows duplicate keys. It is NOT safe for concurrent/parallel use.
The type parameter K must implement the Ordered interface.
func NewOrderedPairs ΒΆ
func NewOrderedPairs[K Ordered, V any](pairs ...any) *OrderedPairs[K, V]
NewOrderedPairs creates a new OrderedPairs from the provided pairs. It allows duplicate keys.
func (*OrderedPairs[K, V]) Add ΒΆ
func (m *OrderedPairs[K, V]) Add(key K, value V)
Add adds a key-value pair to the structure. It allows duplicate keys.
func (*OrderedPairs[K, V]) Get ΒΆ
func (m *OrderedPairs[K, V]) Get(key K) (res V)
Get returns the value associated with the key.
func (*OrderedPairs[K, V]) Keys ΒΆ
func (m *OrderedPairs[K, V]) Keys() []K
Keys returns a slice of all keys in the structure.
func (*OrderedPairs[K, V]) Rand ΒΆ
func (m *OrderedPairs[K, V]) Rand() V
Rand returns a random value from the structure.
func (*OrderedPairs[K, V]) RandKey ΒΆ
func (m *OrderedPairs[K, V]) RandKey() K
RandKey returns a random key from the structure.
type Orderer ΒΆ
type Orderer[T comparable] struct { // contains filtered or unexported fields }
Orderer is a struct that holds an order of comparable items and provides methods to manage ordering operations in a thread-safe manner. It's useful for scenarios where you need to track the order of items and apply ordering operations atomically.
Example usage:
orderer := NewOrderer[string](func(order map[string]int) {
// Apply the order to your data structure
fmt.Println("Applying order:", order)
})
orderer.Add("item1")
orderer.Add("item2")
orderer.Apply() // Calls the callback with the current order
func NewOrderer ΒΆ
func NewOrderer[T comparable](f func(order map[T]int)) *Orderer[T]
NewOrderer creates a new Orderer with the specified callback function. The callback function is called when Apply() is invoked, receiving the current order mapping as a parameter.
Parameters:
- f: A callback function that receives the order mapping when Apply() is called.
Returns:
- A new Orderer instance ready for use.
func (*Orderer[T]) Add ΒΆ
func (m *Orderer[T]) Add(ids ...T)
Add adds items to the orderer with the next available order index. The order index is determined by the current number of items in the orderer. This method is thread-safe.
Parameters:
- ids: The items to add to the orderer.
func (*Orderer[T]) Apply ΒΆ
func (m *Orderer[T]) Apply()
Apply applies the current order using the callback function and then clears the order mapping. This method is thread-safe. If the order mapping is empty, the callback is not called.
func (*Orderer[T]) Clear ΒΆ
func (m *Orderer[T]) Clear()
Clear removes all items from the orderer without calling the callback. This method is thread-safe.
func (*Orderer[T]) Get ΒΆ
Get returns a copy of the current order mapping. This method is thread-safe and returns a snapshot of the current state.
Returns:
- A map containing the current order mapping.
func (*Orderer[T]) Has ΒΆ added in v1.17.0
Has returns true if the item is in the orderer. This method is thread-safe.
Parameters:
- id: The item to check.
Returns:
- True if the item is in the orderer, false otherwise.
func (*Orderer[T]) IsEmpty ΒΆ added in v1.17.0
IsEmpty returns true if the orderer is empty. This method is thread-safe.
Returns:
- True if the orderer is empty, false otherwise.
type RateProcessor ΒΆ added in v1.6.0
type RateProcessor struct {
// contains filtered or unexported fields
}
RateProcessor manages a pool of workers to process tasks with rate limiting. It ensures that tasks are processed at a controlled rate, preventing system overload while maintaining high throughput.
The rate processor is useful for scenarios where you need to:
- Limit API calls per second
- Control database query rates
- Manage external service interactions
- Prevent overwhelming downstream systems
Example usage:
ctx := context.Background()
processor := NewRateProcessor(ctx, 10) // Max 10 tasks per second
// Add tasks
for i := 0; i < 100; i++ {
task := func(ctx context.Context) error {
// API call or other rate-limited operation
return makeAPICall(ctx, i)
}
processor.AddTask(task)
}
// Wait for completion and get any errors
errors := processor.Wait()
if len(errors) > 0 {
fmt.Printf("Encountered %d errors during processing\n", len(errors))
}
func NewRateProcessor ΒΆ added in v1.6.0
func NewRateProcessor(ctx context.Context, maxPerSecond int) *RateProcessor
NewRateProcessor creates and starts a new RateProcessor with the specified maximum tasks per second rate limit.
Parameters:
- ctx: Context for controlling the lifecycle of worker goroutines
- maxPerSecond: Maximum number of tasks to process per second
Returns:
- A configured and started RateProcessor ready to accept tasks
Example usage:
// Create a processor that handles max 5 tasks per second processor := NewRateProcessor(ctx, 5) defer processor.Wait() // Ensure cleanup
func (*RateProcessor) AddTask ΒΆ added in v1.6.0
func (p *RateProcessor) AddTask(task func(context.Context) error)
AddTask adds a task to the worker pool's task queue. The task will be executed by one of the workers when a rate limit slot becomes available.
Note: This method will block if the task queue is full. Consider using a separate goroutine or adding timeout logic if non-blocking behavior is required.
Parameters:
- task: Function to execute with rate limiting applied
Example usage:
processor.AddTask(func(ctx context.Context) error {
response, err := http.Get("https://api.example.com/data")
if err != nil {
return fmt.Errorf("API call failed: %w", err)
}
defer response.Body.Close()
// Process response...
return nil
})
func (*RateProcessor) Wait ΒΆ added in v1.6.0
func (p *RateProcessor) Wait() []error
Wait closes the task queue and waits for all workers to complete their current tasks. It returns all errors that occurred during task execution.
This method should be called when no more tasks will be added to ensure proper cleanup and to retrieve any errors that occurred.
Returns:
- A slice of all errors that occurred during task processing
Example usage:
// Add all tasks...
for _, task := range tasks {
processor.AddTask(task)
}
// Wait for completion and handle errors
if errors := processor.Wait(); len(errors) > 0 {
for i, err := range errors {
log.Printf("Task error %d: %v", i+1, err)
}
}
type SafeEntityMap ΒΆ
type SafeEntityMap[K comparable, T Entity[K]] struct { *SafeMap[K, T] }
SafeEntityMap is a thread-safe map of entities. It is safe for concurrent/parallel use. This map MUST be initialized with NewSafeEntityMap or NewSafeEntityMapWithSize. Otherwise, it will panic.
func NewSafeEntityMap ΒΆ
func NewSafeEntityMap[K comparable, T Entity[K]](raw ...map[K]T) *SafeEntityMap[K, T]
NewSafeEntityMap returns a new SafeEntityMap from the provided map.
func NewSafeEntityMapWithSize ΒΆ
func NewSafeEntityMapWithSize[K comparable, T Entity[K]](size int) *SafeEntityMap[K, T]
NewSafeEntityMapWithSize returns a new SafeEntityMap with the provided size.
func (*SafeEntityMap[K, T]) AllOrdered ΒΆ
func (s *SafeEntityMap[K, T]) AllOrdered() []T
AllOrdered returns all values in the map sorted by their order. It is safe for concurrent/parallel use.
func (*SafeEntityMap[K, T]) ChangeOrder ΒΆ
func (s *SafeEntityMap[K, T]) ChangeOrder(draft map[K]int)
ChangeOrder changes the order of the values in the map based on the provided map. It is safe for concurrent/parallel use.
func (*SafeEntityMap[K, T]) Delete ΒΆ
func (s *SafeEntityMap[K, T]) Delete(keys ...K) (deleted bool)
Delete deletes values for the provided keys. It reorders all remaining values. It is safe for concurrent/parallel use.
func (*SafeEntityMap[K, T]) LookupByName ΒΆ
func (s *SafeEntityMap[K, T]) LookupByName(name string) (T, bool)
LookupByName returns the value for the provided name. It is safe for concurrent/parallel use.
func (*SafeEntityMap[K, T]) NextOrder ΒΆ
func (s *SafeEntityMap[K, T]) NextOrder() int
NextOrder returns the next order number. It is safe for concurrent/parallel use.
func (*SafeEntityMap[K, T]) Set ΒΆ
func (s *SafeEntityMap[K, T]) Set(info T) int
Set sets the value for the provided key. If the key is not present in the map, it will be added. It sets last order to the entity's order. It sets the same order of existing entity in case of conflict. It returns the order of the entity. If the entity is not valid, it returns -1. It is safe for concurrent/parallel use.
func (*SafeEntityMap[K, T]) SetManualOrder ΒΆ added in v1.4.0
func (s *SafeEntityMap[K, T]) SetManualOrder(info T) int
SetManualOrder sets the value for the provided key. Better to use SafeEntityMap.Set to prevent from order errors. It returns the order of the entity. It is safe for concurrent/parallel use.
type SafeLegacyWorkerPool ΒΆ added in v1.18.0
type SafeLegacyWorkerPool struct {
*LegacyWorkerPool
// contains filtered or unexported fields
}
SafeLegacyWorkerPool is a thread-safe variant of LegacyWorkerPool. Deprecated: Use WorkerPool for new code.
func NewSafeLegacyWorkerPool ΒΆ added in v1.18.0
func NewSafeLegacyWorkerPool(workers, queueCapacity int) *SafeLegacyWorkerPool
NewSafeLegacyWorkerPool creates a new SafeLegacyWorkerPool. Deprecated: Use WorkerPool for new code.
func (*SafeLegacyWorkerPool) IsStopped ΒΆ added in v1.18.0
func (p *SafeLegacyWorkerPool) IsStopped() bool
IsStopped returns true if the worker pool has been stopped in a thread-safe manner.
func (*SafeLegacyWorkerPool) RunningWorkers ΒΆ added in v1.18.0
func (p *SafeLegacyWorkerPool) RunningWorkers() int
RunningWorkers returns the number of worker goroutines in a thread-safe manner.
func (*SafeLegacyWorkerPool) Start ΒΆ added in v1.18.0
func (p *SafeLegacyWorkerPool) Start()
Start launches the worker goroutines in a thread-safe manner.
func (*SafeLegacyWorkerPool) Stop ΒΆ added in v1.18.0
func (p *SafeLegacyWorkerPool) Stop()
Stop signals all workers to stop in a thread-safe manner.
func (*SafeLegacyWorkerPool) StopAndWait ΒΆ added in v1.18.0
func (p *SafeLegacyWorkerPool) StopAndWait(timeout time.Duration) bool
StopAndWait stops the worker pool and waits for all workers to complete in a thread-safe manner.
func (*SafeLegacyWorkerPool) Submit ΒΆ added in v1.18.0
func (p *SafeLegacyWorkerPool) Submit(task Task, timeout time.Duration) bool
Submit adds a task to the pool in a thread-safe manner.
func (*SafeLegacyWorkerPool) SubmitWait ΒΆ added in v1.18.0
SubmitWait adds a task to the pool and waits for its completion in a thread-safe manner.
type SafeLinkedList ΒΆ
type SafeLinkedList[T any] struct { *LinkedList[T] // contains filtered or unexported fields }
SafeLinkedList is a thread-safe variant of the LinkedList type. It uses a mutex to protect the underlying structure.
func NewSafeLinkedList ΒΆ
func NewSafeLinkedList[T any]() *SafeLinkedList[T]
NewSafeLinkedList creates a new SafeLinkedList.
func (*SafeLinkedList[T]) Back ΒΆ
func (l *SafeLinkedList[T]) Back() (T, bool)
Back returns the last element of the linked list. It is safe for concurrent/parallel use.
func (*SafeLinkedList[T]) Front ΒΆ
func (l *SafeLinkedList[T]) Front() (T, bool)
Front returns the first element of the linked list. It is safe for concurrent/parallel use.
func (*SafeLinkedList[T]) Len ΒΆ
func (l *SafeLinkedList[T]) Len() int
Len returns the number of elements in the linked list. It is safe for concurrent/parallel use.
func (*SafeLinkedList[T]) PopBack ΒΆ
func (l *SafeLinkedList[T]) PopBack() (T, bool)
PopBack removes an element from the back of the linked list and returns it. It is safe for concurrent/parallel use.
func (*SafeLinkedList[T]) PopFront ΒΆ
func (l *SafeLinkedList[T]) PopFront() (T, bool)
PopFront removes an element from the front of the linked list and returns it. It is safe for concurrent/parallel use.
func (*SafeLinkedList[T]) PushBack ΒΆ added in v1.1.0
func (l *SafeLinkedList[T]) PushBack(data T)
PushBack adds an element to the back of the linked list. It is safe for concurrent/parallel use.
func (*SafeLinkedList[T]) PushFront ΒΆ added in v1.1.0
func (l *SafeLinkedList[T]) PushFront(data T)
PushFront adds an element to the front of the linked list. It is safe for concurrent/parallel use.
type SafeMap ΒΆ
type SafeMap[K comparable, V any] struct { // contains filtered or unexported fields }
SafeMap is used like a common map, but it is protected with RW mutex, so it can be used in many goroutines.
func NewSafeMap ΒΆ
func NewSafeMap[K comparable, V any](raw ...map[K]V) *SafeMap[K, V]
NewSafeMap returns a new SafeMap with empty map.
func NewSafeMapFromPairs ΒΆ
func NewSafeMapFromPairs[K comparable, V any](pairs ...any) *SafeMap[K, V]
NewSafeMapFromPairs returns a SafeMap with a map inited using the provided pairs.
func NewSafeMapWithSize ΒΆ
func NewSafeMapWithSize[K comparable, V any](size int) *SafeMap[K, V]
NewSafeMapWithSize returns a new SafeMap with map inited using provided size.
func (*SafeMap[K, V]) Change ΒΆ added in v1.7.0
func (m *SafeMap[K, V]) Change(key K, f func(K, V) V)
Change changes the value for the provided key using provided function. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Clear ΒΆ
func (m *SafeMap[K, V]) Clear()
Clear creates a new map using make without size.
func (*SafeMap[K, V]) Copy ΒΆ
func (m *SafeMap[K, V]) Copy() map[K]V
Copy returns a new map that is a copy of the underlying map. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Delete ΒΆ
Delete removes keys and associated values from map, does nothing if key is not present in map, returns true if key was deleted. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Get ΒΆ
func (m *SafeMap[K, V]) Get(key K) V
Get returns the value for the provided key or default type value if key is not present in the map. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Has ΒΆ
Has returns true if key is present in the map, false otherwise. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) IsEmpty ΒΆ
IsEmpty returns true if the map is empty. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Iter ΒΆ added in v1.9.0
Iter returns an iterator over the map. It is safe for concurrent/parallel use. DON'T USE SAFE MAP METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!
func (*SafeMap[K, V]) IterKeys ΒΆ added in v1.9.0
IterKeys returns an iterator over the map keys. It is safe for concurrent/parallel use. DON'T USE SAFE MAP METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!
func (*SafeMap[K, V]) IterValues ΒΆ added in v1.9.0
IterValues returns an iterator over the map values. It is safe for concurrent/parallel use. DON'T USE SAFE MAP METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!
func (*SafeMap[K, V]) Keys ΒΆ
func (m *SafeMap[K, V]) Keys() []K
Keys returns a slice of keys of the map. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Len ΒΆ
Len returns the length of the map. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Lookup ΒΆ
Lookup returns the value for the provided key and true if key is present in the map, default value and false otherwise. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Pop ΒΆ
func (m *SafeMap[K, V]) Pop(key K) V
Pop returns the value for the provided key and deletes it from map or default type value if key is not present. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Range ΒΆ
Range calls the provided function for each key-value pair in the map. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Raw ΒΆ added in v1.8.0
func (m *SafeMap[K, V]) Raw() map[K]V
Raw returns the underlying map.
func (*SafeMap[K, V]) Refill ΒΆ
func (m *SafeMap[K, V]) Refill(raw map[K]V)
Refill creates a new map with values from the provided one.
func (*SafeMap[K, V]) Set ΒΆ
func (m *SafeMap[K, V]) Set(key K, value V)
Set sets the value to the map. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) SetIfNotPresent ΒΆ
func (m *SafeMap[K, V]) SetIfNotPresent(key K, value V) V
SetIfNotPresent sets the value to the map if the key is not present, returns the old value if the key was set, new value otherwise. It is safe for concurrent/parallel use.
func (*SafeMap[K, V]) Swap ΒΆ
func (m *SafeMap[K, V]) Swap(key K, value V) V
Swap swaps the values for the provided keys and returns the old value. It is safe for concurrent/parallel use.
type SafeMapOfMaps ΒΆ added in v1.14.0
type SafeMapOfMaps[K1 comparable, K2 comparable, V comparable] struct { // contains filtered or unexported fields }
SafeMapOfMaps is a thread-safe version of MapOfMaps.
func NewSafeMapOfMaps ΒΆ added in v1.14.0
func NewSafeMapOfMaps[K1 comparable, K2 comparable, V comparable](raw ...map[K1]map[K2]V) *SafeMapOfMaps[K1, K2, V]
NewSafeMapOfMaps returns a new SafeMapOfMaps with an empty map.
func NewSafeMapOfMapsWithSize ΒΆ added in v1.14.0
func NewSafeMapOfMapsWithSize[K1 comparable, K2 comparable, V comparable](size int) *SafeMapOfMaps[K1, K2, V]
NewSafeMapOfMapsWithSize returns a new SafeMapOfMaps with the provided size.
func (*SafeMapOfMaps[K1, K2, V]) AllKeys ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) AllKeys() []K2
AllKeys returns a slice of all nested keys across all inner maps. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) AllValues ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) AllValues() []V
AllValues returns a slice of all values across all inner maps. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Change ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Change(outerKey K1, innerKey K2, f func(K1, K2, V) V)
Change changes the value for the provided nested keys using the provided function. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Clear ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Clear()
Clear creates a new empty nested map structure. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Copy ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Copy() map[K1]map[K2]V
Copy returns a deep copy of the nested map structure. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Delete ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Delete(outerKey K1, innerKeys ...K2) bool
Delete removes nested keys and returns true if any were deleted. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) DeleteMap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) DeleteMap(outerKeys ...K1) bool
DeleteMap removes the entire inner map for the provided outer key and returns true if deleted. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Get ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Get(outerKey K1, innerKey K2) V
Get returns the value for the provided nested keys or the default type value if not present. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) GetMap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) GetMap(outerKey K1) map[K2]V
GetMap returns the inner map for the provided outer key or nil if not present. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Has ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Has(outerKey K1, innerKey K2) bool
Has returns true if the nested keys are present, false otherwise. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) HasMap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) HasMap(outerKey K1) bool
HasMap returns true if the outer key is present, false otherwise. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) IsEmpty ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) IsEmpty() bool
IsEmpty returns true if there are no nested key-value pairs. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Len ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Len() int
Len returns the total number of nested key-value pairs across all inner maps. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Lookup ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Lookup(outerKey K1, innerKey K2) (V, bool)
Lookup returns the value for the provided nested keys and true if present, default value and false otherwise. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) LookupMap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) LookupMap(outerKey K1) (map[K2]V, bool)
LookupMap returns the inner map for the provided outer key and true if present, nil and false otherwise. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) OuterKeys ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) OuterKeys() []K1
OuterKeys returns a slice of all outer keys. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) OuterLen ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) OuterLen() int
OuterLen returns the number of outer keys (inner maps). It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Pop ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Pop(outerKey K1, innerKey K2) V
Pop returns the value for the provided nested keys and deletes it or default value if not present. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) PopMap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) PopMap(outerKey K1) map[K2]V
PopMap returns the inner map for the provided outer key and deletes it or nil if not present. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Range ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Range(f func(K1, K2, V) bool) bool
Range calls the provided function for each nested key-value pair. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Raw ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Raw() map[K1]map[K2]V
Raw returns the underlying nested map structure. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Refill ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Refill(raw map[K1]map[K2]V)
Refill creates a new nested map structure with values from the provided one. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Set ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Set(outerKey K1, innerKey K2, value V)
Set sets the value for the provided nested keys. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) SetIfNotPresent ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) SetIfNotPresent(outerKey K1, innerKey K2, value V) V
SetIfNotPresent sets the value if the nested keys are not present, returns the old value if present, new value otherwise. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) SetMap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) SetMap(outerKey K1, innerMap map[K2]V)
SetMap sets the inner map for the provided outer key. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Swap ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Swap(outerKey K1, innerKey K2, value V) V
Swap swaps the value for the provided nested keys and returns the old value. It is safe for concurrent/parallel use.
func (*SafeMapOfMaps[K1, K2, V]) Transform ΒΆ added in v1.14.0
func (m *SafeMapOfMaps[K1, K2, V]) Transform(f func(K1, K2, V) V)
Transform transforms all values across all inner maps using the provided function. It is safe for concurrent/parallel use.
type SafeOrderedPairs ΒΆ
type SafeOrderedPairs[K Ordered, V any] struct { *OrderedPairs[K, V] // contains filtered or unexported fields }
SafeOrderedPairs is a thread-safe variant of the OrderedPairs type. It uses a RW mutex to protect the underlying structure. This map MUST be initialized with NewSafeOrderedPairs or NewSafeOrderedPairsWithSize. Otherwise, it will panic.
The type parameter K must implement the Ordered interface.
func NewSafeOrderedPairs ΒΆ
func NewSafeOrderedPairs[K Ordered, V any](pairs ...any) *SafeOrderedPairs[K, V]
NewSafeOrderedPairs returns a new SafeOrderedPairs from the provided pairs. It is a thread-safe variant of the NewOrderedPairs function.
func (*SafeOrderedPairs[K, V]) Add ΒΆ
func (s *SafeOrderedPairs[K, V]) Add(key K, value V)
Add adds a key-value pair to the structure. It allows duplicate keys. It is a thread-safe variant of the Add method.
func (*SafeOrderedPairs[K, V]) Get ΒΆ
func (s *SafeOrderedPairs[K, V]) Get(key K) (res V)
Get returns the value associated with the key. It is a thread-safe variant of the Get method.
func (*SafeOrderedPairs[K, V]) Rand ΒΆ
func (s *SafeOrderedPairs[K, V]) Rand() V
Rand returns a random value from the structure. It is a thread-safe variant of the Rand method.
func (*SafeOrderedPairs[K, V]) RandKey ΒΆ
func (s *SafeOrderedPairs[K, V]) RandKey() K
RandKey returns a random key from the structure. It is a thread-safe variant of the RandKey method.
type SafeSet ΒΆ
type SafeSet[K comparable] struct { // contains filtered or unexported fields }
SafeSet is used like a set, but it is protected with RW mutex, so it can be used in many goroutines.
func NewSafeSet ΒΆ
func NewSafeSet[K comparable](data ...[]K) *SafeSet[K]
NewSafeSet returns a new SafeSet with empty set.
func NewSafeSetFromItems ΒΆ added in v1.3.0
func NewSafeSetFromItems[K comparable](data ...K) *SafeSet[K]
NewSafeSetFromItems returns a new SafeSet with empty set.
func NewSafeSetWithSize ΒΆ
func NewSafeSetWithSize[K comparable](size int) *SafeSet[K]
NewSafeSetWithSize returns a new SafeSet with empty set.
func (*SafeSet[K]) Add ΒΆ
func (m *SafeSet[K]) Add(key ...K)
Add adds keys to the set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Clear ΒΆ
func (m *SafeSet[K]) Clear()
Clear removes all keys from the set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Copy ΒΆ added in v1.9.0
func (m *SafeSet[K]) Copy() map[K]struct{}
Copy returns a copy of the set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Delete ΒΆ
Delete removes keys from the set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Difference ΒΆ added in v1.9.0
Difference returns a new set with the difference of the current set and the provided set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Has ΒΆ
Has returns true if key is present in the set, false otherwise. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Intersection ΒΆ added in v1.9.0
Intersection returns a new set with the intersection of the current set and the provided set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) IsEmpty ΒΆ
Empty returns true if the set is empty. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Iter ΒΆ added in v1.9.0
Iter returns a channel that yields each key in the set. It is safe for concurrent/parallel use. DON'T USE SAFE SET METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!
func (*SafeSet[K]) Len ΒΆ
Len returns the number of keys in set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Range ΒΆ
Range calls the provided function for each key in the set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Raw ΒΆ added in v1.9.0
func (m *SafeSet[K]) Raw() map[K]struct{}
Raw returns the underlying map.
func (*SafeSet[K]) SymmetricDifference ΒΆ added in v1.9.0
SymmetricDifference returns a new set with the symmetric difference of the current set and the provided set. It is safe for concurrent/parallel use.
func (*SafeSet[K]) Transform ΒΆ
func (m *SafeSet[K]) Transform(f func(K) K)
Transform transforms all values of the set using provided function. It is safe for concurrent/parallel use.
type SafeSlice ΒΆ
type SafeSlice[T any] struct { // contains filtered or unexported fields }
SafeSlice is used like a common slice, but it is protected with RW mutex, so it can be used in many goroutines.
func NewSafeSlice ΒΆ
NewSafeSlice returns a new SafeSlice with empty slice.
func NewSafeSliceFromItems ΒΆ added in v1.3.0
NewSafeSliceFromItems returns a new SafeSlice with the provided items.
func NewSafeSliceWithSize ΒΆ
NewSafeSliceWithSize returns a new SafeSlice with slice inited using the provided size.
func (*SafeSlice[T]) AddFront ΒΆ added in v1.9.0
func (s *SafeSlice[T]) AddFront(v ...T)
AddFront adds a new elements to the front of the slice.
func (*SafeSlice[T]) Append ΒΆ
func (s *SafeSlice[T]) Append(v ...T)
Append adds a new element to the end of the slice.
func (*SafeSlice[T]) Change ΒΆ added in v1.7.0
Change changes the value for the provided key using provided function.
func (*SafeSlice[T]) Clear ΒΆ
func (s *SafeSlice[T]) Clear()
Clear creates a new slice using make without size.
func (*SafeSlice[T]) Delete ΒΆ
Delete removes the key and associated value from the slice, does nothing if the key is not present in the slice, returns true if the key was deleted.
func (*SafeSlice[T]) Get ΒΆ
Get returns the value for the provided key or the default type value if the key is not present in the slice.
func (*SafeSlice[T]) IsEmpty ΒΆ
IsEmpty returns true if the slice is empty. It is safe for concurrent/parallel use.
func (*SafeSlice[T]) Iter ΒΆ added in v1.9.0
Iter returns an iterator over the slice values. It is safe for concurrent/parallel use. DON'T USE SAFE SLICE METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!
func (*SafeSlice[T]) Iter2 ΒΆ added in v1.9.0
Iter2 returns an iterator over the slice values and their indexes. It is safe for concurrent/parallel use. DON'T USE SAFE SLICE METHOD INSIDE LOOP TO PREVENT FROM DEADLOCK!
func (*SafeSlice[T]) Len ΒΆ
Len returns the length of the slice. It is safe for concurrent/parallel use.
func (*SafeSlice[T]) Pop ΒΆ
func (s *SafeSlice[T]) Pop() T
Pop removes the last element of the slice and returns it.
func (*SafeSlice[T]) Raw ΒΆ added in v1.8.0
func (s *SafeSlice[T]) Raw() []T
Raw returns the underlying slice.
type SafeStack ΒΆ
SafeStack is a simple stack data structure that is thread-safe.
func NewSafeStack ΒΆ
NewSafeStack creates a new SafeStack.
func NewSafeStackWithCapacity ΒΆ
NewSafeStackWithCapacity creates a new SafeStack with a specified capacity.
func (*SafeStack[T]) Clear ΒΆ
func (s *SafeStack[T]) Clear()
Clear removes all items from the stack.
func (*SafeStack[T]) Last ΒΆ
func (s *SafeStack[T]) Last() T
Last returns the last item in the stack.
func (*SafeStack[T]) Pop ΒΆ
func (s *SafeStack[T]) Pop() T
Pop removes and returns the top item from the stack.
func (*SafeStack[T]) PopOK ΒΆ
PopOK is like Pop but also returns a boolean indicating if the operation was successful.
type SafeUniqueStack ΒΆ
type SafeUniqueStack[T comparable] struct { // contains filtered or unexported fields }
SafeUniqueStack is a thread-safe UniqueStack.
func NewSafeUniqueStack ΒΆ
func NewSafeUniqueStack[T comparable](data ...[]T) *SafeUniqueStack[T]
NewSafeUniqueStack creates a new SafeUniqueStack.
func NewSafeUniqueStackWithCapacity ΒΆ
func NewSafeUniqueStackWithCapacity[T comparable](cap int) *SafeUniqueStack[T]
NewSafeUniqueStackWithCapacity creates a new SafeUniqueStack with a specified capacity.
func (*SafeUniqueStack[T]) Clear ΒΆ
func (ss *SafeUniqueStack[T]) Clear()
Clear removes all items from the stack.
func (*SafeUniqueStack[T]) IsEmpty ΒΆ
func (ss *SafeUniqueStack[T]) IsEmpty() bool
IsEmpty checks if the stack is empty.
func (*SafeUniqueStack[T]) Last ΒΆ
func (ss *SafeUniqueStack[T]) Last() T
Last returns the last item in the stack without removing it.
func (*SafeUniqueStack[T]) Len ΒΆ
func (ss *SafeUniqueStack[T]) Len() int
Len returns the number of items in the stack.
func (*SafeUniqueStack[T]) Pop ΒΆ
func (ss *SafeUniqueStack[T]) Pop() T
Pop removes and returns the last item from the stack.
func (*SafeUniqueStack[T]) PopOK ΒΆ
func (ss *SafeUniqueStack[T]) PopOK() (T, bool)
PopOK is like Pop but also returns a boolean indicating if the operation was successful.
func (*SafeUniqueStack[T]) Push ΒΆ
func (ss *SafeUniqueStack[T]) Push(item T)
Push adds an item to the stack if it is not already present.
func (*SafeUniqueStack[T]) Raw ΒΆ
func (ss *SafeUniqueStack[T]) Raw() []T
Raw returns a copy of the underlying data slice (non-concurrent safe operation).
func (*SafeUniqueStack[T]) Remove ΒΆ
func (ss *SafeUniqueStack[T]) Remove(item T) bool
Remove deletes a specific item from the stack, if it exists.
type Set ΒΆ
type Set[K comparable] struct { // contains filtered or unexported fields }
Set represents a data structure that behaves like a common map but is more lightweight. It is used to store unique keys without associated values.
func NewSet ΒΆ
func NewSet[K comparable](data ...[]K) *Set[K]
NewSet returns a Set inited using the provided data.
func NewSetFromItems ΒΆ added in v1.3.0
func NewSetFromItems[K comparable](data ...K) *Set[K]
NewSetFromItems returns a Set inited using the provided data.
func NewSetWithSize ΒΆ
func NewSetWithSize[K comparable](size int) *Set[K]
NewSetWithSize returns a Set with a map inited using the provided size.
func (*Set[K]) Copy ΒΆ added in v1.9.0
func (m *Set[K]) Copy() map[K]struct{}
Copy returns a copy of the set.
func (*Set[K]) Delete ΒΆ
Delete removes the keys from the set, does nothing if the key is not present in the set.
func (*Set[K]) Difference ΒΆ added in v1.9.0
Difference returns a new set with the difference of the current set and the provided set.
func (*Set[K]) Intersection ΒΆ added in v1.9.0
Intersection returns a new set with the intersection of the current set and the provided set.
func (*Set[K]) IsEmpty ΒΆ
IsEmpty returns true if the set is empty. It is safe for concurrent/parallel use.
func (*Set[K]) Raw ΒΆ added in v1.9.0
func (m *Set[K]) Raw() map[K]struct{}
Raw returns the underlying map.
func (*Set[K]) SymmetricDifference ΒΆ added in v1.9.0
SymmetricDifference returns a new set with the symmetric difference of the current set and the provided set.
func (*Set[K]) Transform ΒΆ
func (m *Set[K]) Transform(f func(K) K)
Transform transforms all values of the set using provided function.
type Signed ΒΆ
Signed is a constraint that permits any signed integer type. This constraint is useful for generic functions that need to work with signed integers while maintaining type safety. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.
Example usage:
func AbsInt[T Signed](x T) T {
if x < 0 {
return -x
}
return x
}
type Slice ΒΆ
type Slice[T any] struct { // contains filtered or unexported fields }
Slice is used like a common slice.
func NewSliceFromItems ΒΆ added in v1.3.0
NewSliceFromItems returns a new Slice with the provided items.
func NewSliceWithSize ΒΆ
NewSliceWithSize returns a new Slice with slice inited using the provided size.
func (*Slice[T]) AddFront ΒΆ added in v1.9.0
func (s *Slice[T]) AddFront(v ...T)
AddFront adds a new elements to the front of the slice.
func (*Slice[T]) Append ΒΆ
func (s *Slice[T]) Append(v ...T)
Append adds a new element to the end of the slice.
func (*Slice[T]) Change ΒΆ added in v1.7.0
Change changes the value for the provided key using provided function.
func (*Slice[T]) Clear ΒΆ
func (s *Slice[T]) Clear()
Clear creates a new slice using make without size.
func (*Slice[T]) Delete ΒΆ
Delete removes the key and associated value from the slice, does nothing if the key is not present in the slice, returns true if the key was deleted.
func (*Slice[T]) Get ΒΆ
Get returns the value for the provided key or the default type value if the key is not present in the slice.
func (*Slice[T]) IsEmpty ΒΆ
IsEmpty returns true if the slice is empty. It is safe for concurrent/parallel use.
func (*Slice[T]) Iter2 ΒΆ added in v1.9.0
Iter2 returns an iterator over the slice values and their indexes.
func (*Slice[T]) Pop ΒΆ
func (s *Slice[T]) Pop() T
Pop removes the last element of the slice and returns it.
func (*Slice[T]) Raw ΒΆ added in v1.8.0
func (s *Slice[T]) Raw() []T
Raw returns the underlying slice.
type SortDirection ΒΆ added in v1.12.0
type SortDirection int
SortDirection represents the sorting direction (ascending or descending)
const ( // ASCSort sorts in ascending order ASCSort SortDirection = iota // DESCSort sorts in descending order DESCSort )
type Stack ΒΆ
type Stack[T any] struct { // contains filtered or unexported fields }
Stack is a simple stack data structure.
func NewStackWithCapacity ΒΆ
NewStackWithCapacity creates a new Stack with a specified capacity.
func (*Stack[T]) Pop ΒΆ
func (s *Stack[T]) Pop() T
Pop removes and returns the top item from the stack.
type Task ΒΆ added in v1.11.0
Task represents a function that can be executed by workers in the pool.
type Timer ΒΆ
type Timer struct {
// contains filtered or unexported fields
}
Timer provides precise timing measurements with support for pausing, lap timing, and deadline management. It's useful for performance monitoring, benchmarking, and creating time-based operations.
Features:
- Precise elapsed time calculation
- Pause and resume functionality
- Lap timing for interval measurements
- Deadline tracking with expiration checks
- Multiple time unit conversions
- Human-readable formatting
Example usage:
timer := StartTimer()
// Do some work...
time.Sleep(100 * time.Millisecond)
lap1 := timer.Lap() // Record first lap
// More work...
time.Sleep(200 * time.Millisecond)
lap2 := timer.Lap() // Record second lap
fmt.Printf("Total elapsed: %v\n", timer.ElapsedTime())
fmt.Printf("Formatted: %s\n", timer.FormatShort())
func Deadline ΒΆ added in v1.11.0
Deadline creates a new timer with a deadline set to the specified duration from now. This is useful for creating timers with built-in expiration functionality.
Parameters:
- duration: Time duration until the deadline
Returns:
- A new Timer with the deadline set
Example usage:
// Create a timer that expires in 5 minutes
timer := Deadline(5 * time.Minute)
for !timer.IsExpired() {
// Do work until deadline is reached
doWork()
time.Sleep(1 * time.Second)
remaining := timer.TimeRemaining()
fmt.Printf("Time remaining: %v\n", remaining)
}
fmt.Println("Deadline reached!")
func NewTimer ΒΆ added in v1.15.0
NewTimer creates a new Timer with the specified start time. This is useful for creating timers with a specific starting point.
Parameters:
- start: The time.Time when the timer should start
Returns:
- A new Timer instance with the specified start time
Example usage:
startTime := time.Now()
timer := NewTimer(startTime)
fmt.Printf("Timer started at: %v\n", startTime)
func StartTimer ΒΆ
func StartTimer() Timer
StartTimer creates and starts a new Timer at the current moment. The timer begins tracking elapsed time immediately upon creation.
Returns:
- A new Timer instance started at the current time
Example usage:
timer := StartTimer()
// Perform operations...
processData()
fmt.Printf("Processing took: %v\n", timer.ElapsedTime())
func (Timer) ElapsedHours ΒΆ added in v1.11.0
ElapsedHours returns the elapsed time as a floating-point number of hours. Suitable for very long-running operations and daily reporting.
Returns:
- Elapsed time in hours as a float64
Example usage:
timer := StartTimer()
// ... very long operation ...
hours := timer.ElapsedHours()
fmt.Printf("Process ran for %.2f hours\n", hours)
func (Timer) ElapsedMicroseconds ΒΆ added in v1.11.0
ElapsedMicroseconds returns the elapsed time in microseconds. Useful for high-precision timing measurements and performance analysis.
Returns:
- Elapsed time in microseconds as an int64
Example usage:
timer := StartTimer()
performCriticalOperation()
us := timer.ElapsedMicroseconds()
fmt.Printf("Critical operation took %d ΞΌs\n", us)
func (Timer) ElapsedMilliseconds ΒΆ added in v1.11.0
ElapsedMilliseconds returns the elapsed time in milliseconds. Useful for performance measurements and when millisecond precision is needed.
Returns:
- Elapsed time in milliseconds as an int64
Example usage:
timer := StartTimer()
processRequest()
ms := timer.ElapsedMilliseconds()
fmt.Printf("Request processed in %d ms\n", ms)
func (Timer) ElapsedMinutes ΒΆ added in v1.11.0
ElapsedMinutes returns the elapsed time as a floating-point number of minutes. Useful for longer-running operations and user-friendly time displays.
Returns:
- Elapsed time in minutes as a float64
Example usage:
timer := StartTimer()
// ... long-running operation ...
minutes := timer.ElapsedMinutes()
fmt.Printf("Operation took %.1f minutes\n", minutes)
func (Timer) ElapsedNanoseconds ΒΆ added in v1.11.0
ElapsedNanoseconds returns the elapsed time in nanoseconds. Provides the highest precision timing available for ultra-precise measurements.
Returns:
- Elapsed time in nanoseconds as an int64
Example usage:
timer := StartTimer()
quickOperation()
ns := timer.ElapsedNanoseconds()
fmt.Printf("Quick operation: %d ns\n", ns)
func (Timer) ElapsedSeconds ΒΆ added in v1.11.0
ElapsedSeconds returns the elapsed time as a floating-point number of seconds. This is convenient for calculations and when precise fractional seconds are needed.
Returns:
- Elapsed time in seconds as a float64
Example usage:
timer := StartTimer()
time.Sleep(1500 * time.Millisecond)
seconds := timer.ElapsedSeconds() // ~1.5
fmt.Printf("Elapsed: %.2f seconds\n", seconds)
func (Timer) ElapsedTime ΒΆ
ElapsedTime returns the total time that has elapsed since the timer started, excluding any time spent in a paused state.
Returns:
- Duration representing the elapsed time
Example usage:
timer := StartTimer()
time.Sleep(100 * time.Millisecond)
elapsed := timer.ElapsedTime()
fmt.Printf("Elapsed: %v\n", elapsed) // ~100ms
func (Timer) Format ΒΆ added in v1.11.0
Format returns the elapsed time formatted according to a custom layout. The layout uses Go's standard time formatting with placeholders for hours, minutes, seconds, and milliseconds.
Parameters:
- layout: Format string with placeholders for time components
Returns:
- Formatted string representation of elapsed time
Example usage:
timer := StartTimer()
time.Sleep(1*time.Hour + 23*time.Minute + 45*time.Second + 678*time.Millisecond)
formatted := timer.Format("%02d:%02d:%02d.%03d") // "01:23:45.678"
fmt.Printf("Elapsed: %s\n", formatted)
func (Timer) FormatShort ΒΆ added in v1.11.0
FormatShort returns a human-readable string representation of elapsed time. The format automatically adjusts based on the duration magnitude for optimal readability.
Format examples:
- Less than 1 second: "123ms"
- Less than 1 minute: "12.34s"
- Less than 1 hour: "12m34s"
- 1 hour or more: "1h23m45s"
Returns:
- Human-readable formatted time string
Example usage:
timer := StartTimer()
time.Sleep(2*time.Minute + 30*time.Second)
fmt.Printf("Elapsed: %s\n", timer.FormatShort()) // "2m30s"
func (Timer) HasElapsed ΒΆ added in v1.11.0
HasElapsed checks if a specified duration has elapsed since the timer started. This is useful for implementing timeouts and periodic checks.
Parameters:
- duration: The duration to check against
Returns:
- true if the specified duration has elapsed, false otherwise
Example usage:
timer := StartTimer()
for !timer.HasElapsed(30 * time.Second) {
// Do work until 30 seconds have elapsed
doWork()
time.Sleep(100 * time.Millisecond)
}
fmt.Println("30 seconds have passed!")
func (Timer) IsExpired ΒΆ added in v1.11.0
IsExpired returns true if the deadline has passed. If no deadline is set, always returns false.
Returns:
- true if deadline has been reached, false otherwise
Example usage:
timer := Deadline(1 * time.Minute)
// Process items until deadline
for !timer.IsExpired() {
if processNextItem() {
fmt.Printf("Processed item, %v remaining\n", timer.TimeRemaining())
} else {
break // No more items
}
}
if timer.IsExpired() {
fmt.Println("Deadline reached, stopping processing")
}
func (Timer) IsPaused ΒΆ added in v1.11.0
IsPaused returns whether the timer is currently in a paused state.
Returns:
- true if the timer is paused, false if actively running
Example usage:
timer := StartTimer()
timer.Pause()
if timer.IsPaused() {
fmt.Println("Timer is currently paused")
timer.Resume()
}
func (*Timer) Lap ΒΆ added in v1.11.0
Lap records the current time as a lap point and returns the duration since the last lap (or start time for the first lap).
Returns:
- Duration since the previous lap or start time
Example usage:
timer := StartTimer()
// Phase 1
doPhase1()
phase1Duration := timer.Lap()
// Phase 2
doPhase2()
phase2Duration := timer.Lap()
fmt.Printf("Phase 1: %v, Phase 2: %v\n", phase1Duration, phase2Duration)
func (Timer) LapDurations ΒΆ added in v1.11.0
LapDurations returns the durations between consecutive laps. The first duration is measured from the start time to the first lap.
Returns:
- A slice of durations representing the time for each lap interval
Example usage:
timer := StartTimer()
// ... work phase 1 ...
timer.Lap()
// ... work phase 2 ...
timer.Lap()
durations := timer.LapDurations()
for i, duration := range durations {
fmt.Printf("Lap %d duration: %v\n", i+1, duration)
}
func (Timer) Laps ΒΆ added in v1.11.0
Laps returns a copy of all recorded lap times. The returned slice can be safely modified without affecting the timer.
Returns:
- A slice of time.Time values representing when each lap was recorded
Example usage:
timer := StartTimer()
timer.Lap() // Lap 1
timer.Lap() // Lap 2
laps := timer.Laps()
for i, lap := range laps {
fmt.Printf("Lap %d recorded at: %v\n", i+1, lap)
}
func (*Timer) Pause ΒΆ added in v1.11.0
Pause pauses the timer, stopping the accumulation of elapsed time. Subsequent calls to elapsed time methods will not include time after the pause until Resume() is called.
Returns:
- true if the timer was successfully paused, false if already paused
Example usage:
timer := StartTimer()
// ... do work ...
if timer.Pause() {
fmt.Println("Timer paused")
// ... timer is not counting during this period ...
time.Sleep(5 * time.Second) // This won't count toward elapsed time
timer.Resume()
fmt.Println("Timer resumed")
}
func (*Timer) Reset ΒΆ added in v1.11.0
func (t *Timer) Reset()
Reset resets the timer to the current time, clearing all recorded data. This includes laps, pause history, and deadline information.
Example usage:
timer := StartTimer() // ... some operations ... timer.Reset() // Start timing fresh // ... new operations to time ...
func (*Timer) Resume ΒΆ added in v1.11.0
Resume resumes the timer if it was paused, continuing the accumulation of elapsed time from where it left off.
Returns:
- true if the timer was successfully resumed, false if not paused
Example usage:
timer := StartTimer()
timer.Pause()
// ... do non-timed work ...
if timer.Resume() {
fmt.Println("Timer resumed, continuing to track time")
// ... timer continues counting elapsed time ...
}
func (*Timer) SetDeadline ΒΆ added in v1.11.0
SetDeadline sets an absolute deadline time for the timer. This allows for precise deadline management with specific target times.
Parameters:
- deadline: The absolute time when the deadline occurs
Example usage:
timer := StartTimer()
// Set deadline to midnight tomorrow
tomorrow := time.Now().Add(24 * time.Hour)
midnight := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 0, 0, 0, 0, tomorrow.Location())
timer.SetDeadline(midnight)
fmt.Printf("Deadline set for: %v\n", midnight)
func (*Timer) SetDeadlineDuration ΒΆ added in v1.11.0
SetDeadlineDuration sets a deadline relative to the current time. This is equivalent to calling SetDeadline(time.Now().Add(duration)).
Parameters:
- duration: Duration from now until the deadline
Example usage:
timer := StartTimer()
timer.SetDeadlineDuration(10 * time.Minute) // Deadline in 10 minutes
// Check deadline status periodically
for !timer.IsExpired() {
processTask()
fmt.Printf("Time remaining: %v\n", timer.TimeRemaining())
}
func (Timer) String ΒΆ added in v1.15.0
String returns a human-readable string representation of the elapsed time. This is a convenience method that calls FormatShort() for easy output.
Returns:
- Human-readable formatted time string
Example usage:
timer := StartTimer()
time.Sleep(100 * time.Millisecond)
fmt.Printf("Elapsed: %s\n", timer.String()) // "100ms"
func (Timer) Time ΒΆ
Time returns the time when the timer was started. This is useful for absolute time references and calculations.
Returns:
- The time.Time when the timer was started
Example usage:
timer := StartTimer()
startTime := timer.Time()
fmt.Printf("Timer started at: %v\n", startTime.Format(time.RFC3339))
func (Timer) TimeRemaining ΒΆ added in v1.11.0
TimeRemaining returns the time remaining until the deadline. If no deadline is set or the deadline has passed, returns zero duration.
Returns:
- Duration remaining until deadline, or 0 if expired/no deadline
Example usage:
timer := Deadline(30 * time.Second)
for timer.TimeRemaining() > 0 {
remaining := timer.TimeRemaining()
fmt.Printf("Countdown: %v\n", remaining)
time.Sleep(1 * time.Second)
}
fmt.Println("Time's up!")
type UniqueStack ΒΆ
type UniqueStack[T comparable] struct { // contains filtered or unexported fields }
UniqueStack is a stack that doesn't allow duplicates.
func NewUniqueStack ΒΆ
func NewUniqueStack[T comparable](data ...[]T) *UniqueStack[T]
NewUniqueStack creates a new UniqueStack.
func NewUniqueStackWithCapacity ΒΆ
func NewUniqueStackWithCapacity[T comparable](cap int) *UniqueStack[T]
NewUniqueStackWithCapacity creates a new UniqueStack with a specified capacity.
func (*UniqueStack[T]) Clear ΒΆ
func (s *UniqueStack[T]) Clear()
Clear removes all items from the stack.
func (*UniqueStack[T]) IsEmpty ΒΆ
func (s *UniqueStack[T]) IsEmpty() bool
IsEmpty returns true if the stack is empty.
func (*UniqueStack[T]) Last ΒΆ
func (s *UniqueStack[T]) Last() T
Last returns the last item in the stack.
func (*UniqueStack[T]) Len ΒΆ
func (s *UniqueStack[T]) Len() int
Len returns the number of items in the stack.
func (*UniqueStack[T]) Pop ΒΆ
func (s *UniqueStack[T]) Pop() T
Pop removes the last item from the stack and returns it.
func (*UniqueStack[T]) PopOK ΒΆ
func (s *UniqueStack[T]) PopOK() (T, bool)
PopOK is like Pop, but returns a boolean indicating whether the stack was empty.
func (*UniqueStack[T]) Push ΒΆ
func (s *UniqueStack[T]) Push(item T)
Push adds an item to the stack. If the item is already present in the stack, it moves it to the top of the stack.
func (*UniqueStack[T]) Raw ΒΆ
func (s *UniqueStack[T]) Raw() []T
Raw returns the underlying slice of the stack.
func (*UniqueStack[T]) Remove ΒΆ
func (s *UniqueStack[T]) Remove(item T) bool
Remove removes an item from the stack.
type Unsigned ΒΆ
Unsigned is a constraint that permits any unsigned integer type. This constraint is useful for generic functions that need to work with unsigned integers while maintaining type safety. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.
Example usage:
func NextPowerOfTwo[T Unsigned](x T) T {
if x == 0 {
return 1
}
return T(1) << (64 - bits.LeadingZeros64(uint64(x-1)))
}
type Waiter ΒΆ
type Waiter struct {
// contains filtered or unexported fields
}
Waiter is used for running a function in a separate goroutine with returning the error.
How to use:
w := abstract.NewWaiter(ctx, slog.Default(), func(context.Context) error {
// TODO: some code
return nil
})
err := w.Await(ctx)
func NewWaiter ΒΆ
NewFutureVoid returns a new started void future, it creates a goroutine that will run the passed function and remember it's error.
type WaiterSet ΒΆ
type WaiterSet struct {
// contains filtered or unexported fields
}
WaiterSet is used for running many functions, each in a separate goroutine with returning a combined error.
How to use:
ws := abstract.NewWaiterSet(slog.Default())
ws.Add(ctx, func(context.Context) error {
// TODO: some code 1
return nil
})
ws.Add(ctx, func(context.Context) error {
// TODO: some code 2
return nil
})
err := ws.Await(ctx) // Wait for completion of all added functions
func NewWaiterSet ΒΆ
NewWaiterSet returns new WaiterSet with added Waiter, that were started earlier.
func (*WaiterSet) Add ΒΆ
Add adds a new Waiter to the WaiterSet and starts it in a separate goroutine.
type WorkerPool ΒΆ added in v1.11.0
type WorkerPool[T any] struct { // contains filtered or unexported fields }
WorkerPool manages a pool of workers that process context-aware tasks concurrently. It provides advanced metrics and graceful shutdown capabilities.
func NewWorkerPool ΒΆ added in v1.11.0
NewWorkerPool creates a new context-aware worker pool with the specified number of workers and task queue capacity.
func (*WorkerPool[T]) FetchAllResults ΒΆ added in v1.18.0
func (p *WorkerPool[T]) FetchAllResults(ctx context.Context) ([]T, []error)
FetchAllResults fetches all results from the pool. It waits until all submitted tasks have finished and returns their results. If the context is done before all results are fetched, it returns fetched results and errors.
func (*WorkerPool[T]) FetchResults ΒΆ added in v1.18.0
func (p *WorkerPool[T]) FetchResults(ctx context.Context) ([]T, []error)
FetchResults fetches results from the pool. It returns when the number of results is equal to the number of finished tasks AT THE TIME OF CALL! If the context is done before all results are fetched, it returns the results and errors collected so far. If some tasks are added after the call to FetchResults, they will not be fetched by this method (use FetchAllResults instead).
func (*WorkerPool[T]) FinishedTasks ΒΆ added in v1.18.0
func (p *WorkerPool[T]) FinishedTasks() int
FinishedTasks returns the number of finished tasks waiting to be fetched.
func (*WorkerPool[T]) IsPoolStarted ΒΆ added in v1.18.0
func (p *WorkerPool[T]) IsPoolStarted() bool
IsPoolStarted returns true if the worker pool has been started.
func (*WorkerPool[T]) OnFlyRunningTasks ΒΆ added in v1.18.0
func (p *WorkerPool[T]) OnFlyRunningTasks() int
OnFlyRunningTasks returns the number of currently executing tasks.
func (*WorkerPool[T]) Shutdown ΒΆ added in v1.18.0
func (p *WorkerPool[T]) Shutdown(ctx context.Context) error
Shutdown signals all workers to stop after completing their current tasks. It waits for all in-flight and queued tasks to complete or until the context is done.
func (*WorkerPool[T]) Start ΒΆ added in v1.11.0
func (p *WorkerPool[T]) Start(ctx context.Context)
Start launches the worker goroutines.
func (*WorkerPool[T]) StopNoWait ΒΆ added in v1.18.0
func (p *WorkerPool[T]) StopNoWait()
StopNoWait signals all workers to stop after completing their current tasks. It does not wait for them to complete.
func (*WorkerPool[T]) Submit ΒΆ added in v1.11.0
Submit adds a task to the pool and returns true if the task was accepted. Returns false if the pool is stopped or the context is done.
func (*WorkerPool[T]) TasksInQueue ΒΆ added in v1.18.0
func (p *WorkerPool[T]) TasksInQueue() int
TasksInQueue returns the number of tasks in the queue.
func (*WorkerPool[T]) TotalTasks ΒΆ added in v1.18.0
func (p *WorkerPool[T]) TotalTasks() int
TotalTasks returns the total number of tasks submitted to the pool.
type WorkerPoolV2 ΒΆ added in v1.16.0
type WorkerPoolV2[T any] struct { // contains filtered or unexported fields }
WorkerPool manages a pool of workers that process tasks concurrently.
func NewWorkerPoolV2 ΒΆ added in v1.16.0
func NewWorkerPoolV2[T any](workers, queueCapacity int) *WorkerPoolV2[T]
NewWorkerPool creates a new worker pool with the specified number of workers and task queue capacity.
func (*WorkerPoolV2[T]) FetchAllResults ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) FetchAllResults(timeoutRaw ...time.Duration) ([]T, []error)
FetchAllResults fetches all results from the pool. It returns when the number of results is equal to the number of submitted tasks! If the timeout is reached before the number of results is equal to the number of submitted tasks, it returns fetched results and errors. If some tasks are added after the call to FetchAllResults, they will be fetched by this method
func (*WorkerPoolV2[T]) FetchResults ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) FetchResults(timeoutRaw ...time.Duration) ([]T, []error)
FetchResults fetches results from the pool. It returns when the number of results is equal to the number of submitted tasks AT THE TIME OF CALL! If the timeout is reached before the number of results is equal to the number of submitted tasks, it returns the results and errors. If some tasks are added after the call to FetchResults, they will not be fetched by this method (use FetchAllResults instead)
func (*WorkerPoolV2[T]) Finished ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) Finished() int
Finished returns the number of finished tasks.
func (*WorkerPoolV2[T]) IsStopped ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) IsStopped() bool
IsStopped returns true if the worker pool has been stopped.
func (*WorkerPoolV2[T]) Running ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) Running() int
Running returns the number of running worker goroutines.
func (*WorkerPoolV2[T]) Start ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) Start()
Start launches the worker goroutines.
func (*WorkerPoolV2[T]) Stop ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) Stop()
Stop signals all workers to stop after completing their current tasks. It does not wait for them to complete.
func (*WorkerPoolV2[T]) Submit ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) Submit(task func() (T, error), timeoutRaw ...time.Duration) bool
Submit adds a task to the pool and returns true if the task was accepted. Returns false if the pool is stopped or the task queue is full and the timeout is reached.
func (*WorkerPoolV2[T]) Submitted ΒΆ added in v1.16.0
func (p *WorkerPoolV2[T]) Submitted() int
Submitted returns the number of submitted tasks.