abstract

package module
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: MIT Imports: 31 Imported by: 2

README ΒΆ

abstract

Go Version GoDoc Build Coverage GoReport

A comprehensive Go library providing generic data structures, cryptographic utilities, concurrency helpers, and powerful abstractions to accelerate development and reduce boilerplate.

go get -u github.com/maxbolgarin/abstract

πŸš€ Overview

The abstract package provides a comprehensive collection of utilities and data structures designed to simplify common programming tasks in Go. It leverages Go's generics to provide type-safe, efficient implementations that work across different types while maintaining excellent performance.

🎯 Key Features
  • πŸ—‚οΈ Generic Data Structures: Maps, Sets, Stacks, Slices, LinkedLists with thread-safe variants
  • πŸ” Cryptographic Utilities: AES encryption, HMAC generation, ECDSA signing/verification
  • ⚑ Concurrency Tools: Futures/Promises, Worker pools, Rate limiting, Concurrent helpers
  • 🎲 Random Generation: Secure random strings, numbers, choices with customizable alphabets
  • πŸ“Š CSV Processing: Advanced table manipulation and data transformation
  • πŸ“ Mathematical Utilities: Generic math functions with type-safe constraints
  • πŸ†” ID Generation: Structured entity ID creation with type safety
  • ⏱️ Timing Utilities: Precise timing, lap timing, deadline management
  • πŸ”§ Type Constraints: Comprehensive type constraints for generic programming
βœ… Advantages
  • Clean Code: Focus on business logic, not boilerplate
  • Type Safety: Leverage Go's generics for compile-time type checking
  • Performance: Optimized implementations with minimal overhead
  • Concurrency: Built-in thread-safe alternatives for concurrent environments
  • Flexibility: Extensive customization options and extensible design
⚠️ Considerations
  • Learning Curve: Requires familiarity with Go generics and constraints
  • Complexity: Abstraction layers might add complexity for simple use cases
  • Memory Overhead: Thread-safe variants use mutexes which add memory overhead

πŸ“š Table of Contents

πŸ—‚οΈ Data Structures

All data structures provide both regular and thread-safe variants (prefixed with "Safe"). Thread-safe variants use RWMutex for concurrent access while maintaining performance.

Maps

Generic maps with enhanced functionality for key-value storage.

// Basic Map operations
m := abstract.NewMap[string, int]()
m.Set("apple", 5)
m.Set("banana", 3)

fmt.Println(m.Get("apple"))   // 5
fmt.Println(m.Has("orange"))  // false
fmt.Println(m.Keys())         // [apple, banana]
fmt.Println(m.Values())       // [5, 3]

// Thread-safe variant
safeMap := abstract.NewSafeMap[string, int]()
safeMap.Set("concurrent", 42)
value := safeMap.Get("concurrent") // Safe for concurrent access

// Advanced: EntityMap for objects with ordering
type User struct {
    id    string
    name  string
    order int
}

func (u User) GetID() string    { return u.id }
func (u User) GetName() string  { return u.name }
func (u User) GetOrder() int    { return u.order }
func (u User) SetOrder(o int) abstract.Entity[string] {
    return User{id: u.id, name: u.name, order: o}
}

entityMap := abstract.NewEntityMap[string, User]()
entityMap.Set(User{id: "1", name: "Alice", order: 1})
entityMap.Set(User{id: "2", name: "Bob", order: 2})

users := entityMap.AllOrdered() // Returns users in order
user, found := entityMap.LookupByName("Alice")
Sets

Efficient set implementation for unique value storage.

// String set
stringSet := abstract.NewSet[string]()
stringSet.Add("apple", "banana", "apple") // Duplicates ignored
fmt.Println(stringSet.Has("apple"))       // true
fmt.Println(stringSet.Len())              // 2

// Thread-safe set
safeSet := abstract.NewSafeSet[int]()
safeSet.Add(1, 2, 3)
safeSet.Remove(2)
values := safeSet.ToSlice() // [1, 3]

// Set operations
set1 := abstract.NewSet[int]()
set1.Add(1, 2, 3)
set2 := abstract.NewSet[int]()
set2.Add(3, 4, 5)

intersection := set1.Intersection(set2) // [3]
union := set1.Union(set2)               // [1, 2, 3, 4, 5]
Stacks

LIFO (Last In, First Out) data structure implementations.

// Basic stack
stack := abstract.NewStack[string]()
stack.Push("first")
stack.Push("second")
stack.Push("third")

fmt.Println(stack.Pop())  // "third"
fmt.Println(stack.Last()) // "second" (peek without removing)
fmt.Println(stack.Len())  // 2

// Thread-safe stack
safeStack := abstract.NewSafeStack[int]()
safeStack.Push(10, 20, 30)
value := safeStack.Pop() // 30

// UniqueStack - no duplicates
uniqueStack := abstract.NewUniqueStack[string]()
uniqueStack.Push("a", "b", "a") // Only adds "a" once
fmt.Println(uniqueStack.Len())  // 2
Slices

Enhanced slice operations with generic support.

// Basic slice operations
slice := abstract.NewSlice[int]()
slice.Append(1, 2, 3, 4, 5)
slice.Insert(2, 99)     // Insert 99 at index 2
fmt.Println(slice.Get(2)) // 99

value := slice.Pop()      // Remove and return last element
slice.Delete(0)          // Remove first element
slice.Reverse()          // Reverse in-place

// Thread-safe slice
safeSlice := abstract.NewSafeSlice[string]()
safeSlice.Append("hello", "world")
safeSlice.Sort() // Sorts in-place for comparable types

// Slice utilities
numbers := []int{1, 2, 3, 4, 5}
doubled := abstract.Map(numbers, func(x int) int { return x * 2 })
evens := abstract.Filter(numbers, func(x int) bool { return x%2 == 0 })
LinkedLists

Doubly linked list implementation with efficient insertion/deletion.

// Basic linked list
list := abstract.NewLinkedList[string]()
list.PushFront("first")
list.PushBack("last")
list.PushFront("new first")

fmt.Println(list.Front()) // "new first"
fmt.Println(list.Back())  // "last"
fmt.Println(list.Len())   // 3

// Iterate through list
for elem := list.Front(); elem != nil; elem = elem.Next() {
    fmt.Println(elem.Value)
}

// Thread-safe linked list
safeList := abstract.NewSafeLinkedList[int]()
safeList.PushBack(1, 2, 3)
value := safeList.PopFront() // 1

πŸ” Cryptographic Utilities

Secure cryptographic operations with best-practice implementations.

// AES Encryption
key := abstract.NewEncryptionKey()
plaintext := []byte("sensitive data")

// Encrypt
ciphertext, err := abstract.EncryptAES(plaintext, key)
if err != nil {
    log.Fatal(err)
}

// Decrypt
decrypted, err := abstract.DecryptAES(ciphertext, key)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Decrypted: %s\n", decrypted)

// HMAC Generation
hmacKey := abstract.NewHMACKey()
message := []byte("important message")
mac := abstract.GenerateHMAC(message, hmacKey)

// Verify HMAC
isValid := abstract.CheckHMAC(message, mac, hmacKey)
fmt.Printf("HMAC valid: %v\n", isValid)

// ECDSA Signing
privateKey, err := abstract.NewSigningKey()
if err != nil {
    log.Fatal(err)
}

signature, err := abstract.SignData(message, privateKey)
if err != nil {
    log.Fatal(err)
}

// Verify signature
publicKey := &privateKey.PublicKey
isValid = abstract.VerifySign(message, signature, publicKey)
fmt.Printf("Signature valid: %v\n", isValid)

// Key encoding/decoding
pemPrivateKey, _ := abstract.EncodePrivateKey(privateKey)
pemPublicKey, _ := abstract.EncodePublicKey(publicKey)

decodedPrivate, _ := abstract.DecodePrivateKey(pemPrivateKey)
decodedPublic, _ := abstract.DecodePublicKey(pemPublicKey)

⚑ Concurrency Tools

Powerful concurrency utilities for async operations and parallel processing.

Futures and Promises
// Basic Future
ctx := context.Background()
future := abstract.NewFuture(ctx, logger, func(ctx context.Context) (string, error) {
    time.Sleep(100 * time.Millisecond)
    return "async result", nil
})

result, err := future.Get(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Result: %s\n", result)

// Future with timeout
result, err = future.GetWithTimeout(ctx, 50*time.Millisecond)
if err == abstract.ErrTimeout {
    fmt.Println("Operation timed out")
}

// Waiter for void operations
waiter := abstract.NewWaiter(ctx, logger, func(ctx context.Context) error {
    // Perform some work
    return nil
})
err = waiter.Await(ctx)

// WaiterSet for multiple operations
waiterSet := abstract.NewWaiterSet(logger)
waiterSet.Add(ctx, func(ctx context.Context) error {
    // Task 1
    return nil
})
waiterSet.Add(ctx, func(ctx context.Context) error {
    // Task 2
    return nil
})
err = waiterSet.Await(ctx) // Wait for all tasks
Worker Pools

For tasks that need context propagation, cancellation support, and return values.

ctx := context.Background()

// Create context-aware worker pool
pool := abstract.NewWorkerPool[int](5, 100) // 5 workers, queue capacity 100
pool.Start(ctx)
defer pool.Shutdown(ctx)

// Submit context-aware tasks
for i := 0; i < 10; i++ {
    i := i
    ok := pool.Submit(ctx, func(ctx context.Context) (int, error) {
        // Task can check context cancellation
        select {
        case <-ctx.Done():
            return 0, ctx.Err()
        default:
            // Do work
            return i * 2, nil
        }
    })
    if !ok {
        fmt.Println("Failed to submit task")
    }
}

// Fetch results
results, errs := pool.FetchResults(ctx)
for i, result := range results {
    if errs[i] != nil {
        fmt.Printf("Task %d error: %v
", i, errs[i])
    } else {
        fmt.Printf("Task %d result: %d
", i, result)
    }
}

// Monitor pool metrics
fmt.Printf("Queue: %d, Running: %d, Finished: %d, Total: %d
",
    pool.TasksInQueue(), pool.OnFlyRunningTasks(), 
    pool.FinishedTasks(), pool.TotalTasks())

// Graceful shutdown with timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := pool.Shutdown(shutdownCtx); err != nil {
    fmt.Printf("Shutdown error: %v
", err)
}
JobQueue - Fire-and-Forget Job Execution

For side-effect tasks without return values (logging, notifications, cleanup, etc.).

ctx := context.Background()

// Create job queue
queue := abstract.NewJobQueue(5, 100) // 5 workers, queue capacity 100
queue.Start(ctx)
defer queue.StopNoWait()

// Submit fire-and-forget tasks
for i := 0; i < 100; i++ {
    i := i
    ok := queue.Submit(ctx, func(ctx context.Context) {
        // Perform side-effect work
        log.Printf("Processing item %d", i)
        
        // Can still respect context cancellation
        select {
        case <-ctx.Done():
            return
        default:
            // Continue work
        }
    })
    if !ok {
        fmt.Println("Failed to submit task")
    }
}

// Wait for all tasks to complete
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()

if err := queue.Wait(waitCtx); err != nil {
    fmt.Printf("Wait error: %v
", err)
}

// Monitor queue metrics
fmt.Printf("Pending: %d, Running: %d, Finished: %d
",
    queue.PendingTasks(), queue.OnFlyRunningTasks(), queue.FinishedTasks())

// Graceful shutdown
if err := queue.Shutdown(ctx); err != nil {
    fmt.Printf("Shutdown error: %v
", err)
}
WorkerPoolV2 - Simple Generic Worker Pool
// Create generic worker pool
pool := abstract.NewWorkerPoolV2[string](5, 100) // 5 workers, queue capacity 100
pool.Start()
defer pool.Stop()

// Submit tasks
for i := 0; i < 10; i++ {
    i := i // Capture loop variable
    task := func() (string, error) {
        return fmt.Sprintf("Task %d result", i), nil
    }
    
    if !pool.Submit(task) {
        fmt.Println("Failed to submit task")
    }
}

// Fetch results (waits for all submitted tasks at call time)
results, errors := pool.FetchResults(5 * time.Second)
for i, result := range results {
    if errors[i] != nil {
        fmt.Printf("Task error: %v
", errors[i])
    } else {
        fmt.Printf("Task result: %v
", result)
    }
}

// Submit with timeout
if !pool.Submit(task, 100*time.Millisecond) {
    fmt.Println("Task submission timed out")
}

// Monitor pool status
fmt.Printf("Submitted: %d, Running: %d, Finished: %d
", 
    pool.Submitted(), pool.Running(), pool.Finished())

// Fetch all results (including tasks submitted after call)
allResults, allErrors := pool.FetchAllResults(10 * time.Second)
```go
// Create generic worker pool
pool := abstract.NewWorkerPoolV2[string](5, 100) // 5 workers, queue capacity 100
pool.Start()
defer pool.Stop()

// Submit tasks
for i := 0; i < 10; i++ {
    i := i // Capture loop variable
    task := func() (string, error) {
        return fmt.Sprintf("Task %d result", i), nil
    }
    
    if !pool.Submit(task) {
        fmt.Println("Failed to submit task")
    }
}

// Fetch results (waits for all submitted tasks at call time)
results, errors := pool.FetchResults(5 * time.Second)
for i, result := range results {
    if errors[i] != nil {
        fmt.Printf("Task error: %v
", errors[i])
    } else {
        fmt.Printf("Task result: %v
", result)
    }
}

// Submit with timeout
if !pool.Submit(task, 100*time.Millisecond) {
    fmt.Println("Task submission timed out")
}

// Monitor pool status
fmt.Printf("Submitted: %d, Running: %d, Finished: %d
", 
    pool.Submitted(), pool.Running(), pool.Finished())

// Fetch all results (including tasks submitted after call)
allResults, allErrors := pool.FetchAllResults(10 * time.Second)
ContextPool - Context-Aware Worker Pool

For tasks that need context propagation, cancellation support, and return values.

ctx := context.Background()

// Create context-aware worker pool
pool := abstract.NewContextPool[int](5, 100) // 5 workers, queue capacity 100
pool.Start(ctx)
defer pool.Shutdown(ctx)

// Submit context-aware tasks
for i := 0; i < 10; i++ {
    i := i
    ok := pool.Submit(ctx, func(ctx context.Context) (int, error) {
        // Task can check context cancellation
        select {
        case <-ctx.Done():
            return 0, ctx.Err()
        default:
            // Do work
            return i * 2, nil
        }
    })
    if !ok {
        fmt.Println("Failed to submit task")
    }
}

// Fetch results
results, errs := pool.FetchResults(ctx)
for i, result := range results {
    if errs[i] != nil {
        fmt.Printf("Task %d error: %v
", i, errs[i])
    } else {
        fmt.Printf("Task %d result: %d
", i, result)
    }
}

// Monitor pool metrics
fmt.Printf("Queue: %d, Running: %d, Finished: %d, Total: %d
",
    pool.TasksInQueue(), pool.OnFlyRunningTasks(), 
    pool.FinishedTasks(), pool.TotalTasks())

// Graceful shutdown with timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := pool.Shutdown(shutdownCtx); err != nil {
    fmt.Printf("Shutdown error: %v
", err)
}
ContextJobQueue - Fire-and-Forget Job Execution

For side-effect tasks without return values (logging, notifications, cleanup, etc.).

ctx := context.Background()

// Create job queue
queue := abstract.NewContextJobQueue(5, 100) // 5 workers, queue capacity 100
queue.Start(ctx)
defer queue.StopNoWait()

// Submit fire-and-forget tasks
for i := 0; i < 100; i++ {
    i := i
    ok := queue.Submit(ctx, func(ctx context.Context) {
        // Perform side-effect work
        log.Printf("Processing item %d", i)
        
        // Can still respect context cancellation
        select {
        case <-ctx.Done():
            return
        default:
            // Continue work
        }
    })
    if !ok {
        fmt.Println("Failed to submit task")
    }
}

// Wait for all tasks to complete
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()

if err := queue.Wait(waitCtx); err != nil {
    fmt.Printf("Wait error: %v
", err)
}

// Monitor queue metrics
fmt.Printf("Pending: %d, Running: %d, Finished: %d
",
    queue.PendingTasks(), queue.OnFlyRunningTasks(), queue.FinishedTasks())

// Graceful shutdown
if err := queue.Shutdown(ctx); err != nil {
    fmt.Printf("Shutdown error: %v
", err)
}
Rate Limiting
// Rate-limited processing
ctx := context.Background()
processor := abstract.NewRateProcessor(ctx, 10) // Max 10 operations per second

// Add rate-limited tasks
for i := 0; i < 100; i++ {
    i := i
    processor.AddTask(func(ctx context.Context) error {
        // This will be rate-limited
        fmt.Printf("Processing item %d\n", i)
        return nil
    })
}

// Wait for completion
errors := processor.Wait()
if len(errors) > 0 {
    fmt.Printf("Encountered %d errors\n", len(errors))
}
Concurrent Helpers
// Periodic updater
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

abstract.StartUpdater(ctx, 30*time.Second, logger, func() {
    fmt.Println("Periodic health check")
})

// Immediate execution, then periodic
abstract.StartUpdaterNow(ctx, time.Minute, logger, func() {
    fmt.Println("Sync operation")
})

// With shutdown handler
abstract.StartUpdaterWithShutdown(ctx, 10*time.Second, logger, 
    func() {
        // Periodic work
    },
    func() {
        fmt.Println("Shutting down...")
    },
)

🎲 Random Generation

Cryptographically secure random generation with multiple character sets.

// Basic random strings
token := abstract.GetRandomString(32)        // Hexadecimal
sessionID := abstract.GetRandomAlphaNumeric(16) // Letters + numbers
pin := abstract.GetRandomNumeric(6)          // Numbers only
code := abstract.GetRandomLowerAlpha(8)      // Lowercase letters
id := abstract.GetRandomUpperAlpha(4)        // Uppercase letters

// Custom alphabet
customAlphabet := []byte("!@#$%^&*")
symbols := abstract.GetRandomStringWithAlphabet(8, customAlphabet)

// Random numbers and choices
dice := abstract.GetRandomInt(1, 6)
coinFlip := abstract.GetRandomBool()

colors := []string{"red", "green", "blue", "yellow"}
color, ok := abstract.GetRandomChoice(colors)
if ok {
    fmt.Printf("Random color: %s\n", color)
}

// Shuffle operations
cards := []string{"A", "K", "Q", "J", "10", "9", "8", "7"}
abstract.ShuffleSlice(cards)
fmt.Printf("Shuffled: %v\n", cards)

// Random network addresses (for testing)
addr := abstract.GetRandListenAddress() // ":12345" (random port)

πŸ“Š CSV Processing

Advanced CSV table manipulation with indexing and querying capabilities.

// Load CSV from file
table, err := abstract.NewCSVTableFromFilePath("data.csv")
if err != nil {
    log.Fatal(err)
}

// Create from data
data := map[string]map[string]string{
    "user1": {"name": "Alice", "age": "30", "city": "NYC"},
    "user2": {"name": "Bob", "age": "25", "city": "LA"},
}
table = abstract.NewCSVTableFromMap(data, "userID")

// Query operations
row := table.Row("user1")
value := table.Value("user1", "name") // "Alice"
exists := table.Has("user3")          // false

// Find operations
criteria := map[string]string{"city": "NYC"}
foundID, foundRow := table.FindRow(criteria)
allNYCUsers := table.Find(criteria)

// Modifications
table.AddRow("user3", map[string]string{
    "name": "Charlie",
    "age": "35",
    "city": "Chicago",
})

table.UpdateRow("user1", map[string]string{
    "age": "31",
})

table.AppendColumn("country", []string{"USA", "USA", "USA"})
table.DeleteColumn("age")
table.DeleteRow("user2")

// Export
csvBytes := table.Bytes()
fmt.Printf("CSV Data:\n%s", csvBytes)

// Thread-safe operations
safeTable := abstract.NewCSVTableSafe(records)
safeTable.AddRow("concurrent", map[string]string{
    "name": "Thread Safe",
    "value": "42",
})

πŸ“ Mathematical Utilities

Generic mathematical functions with type-safe constraints.

// Type-safe arithmetic
result := abstract.Min(1, 2, 3, 4, 5)     // 1
maximum := abstract.Max(3.14, 2.71, 1.41) // 3.14
absolute := abstract.Abs(-42)             // 42
power := abstract.Pow(2, 3)               // 8
rounded := abstract.Round(3.7)            // 4

// String conversions
str := abstract.Itoa(42)        // "42"
num, err := abstract.Atoi[int]("123") // 123

// Type constraints in action
func Average[T abstract.Number](values []T) T {
    if len(values) == 0 {
        return 0
    }
    
    var sum T
    for _, v := range values {
        sum += v
    }
    return sum / T(len(values))
}

// Usage with different numeric types
intAvg := Average([]int{1, 2, 3, 4, 5})           // 3
floatAvg := Average([]float64{1.5, 2.5, 3.5})     // 2.5

πŸ†” ID Generation

Structured, type-safe ID generation with entity types.

// Register entity types
const (
    UserEntity  = abstract.RegisterEntityType("USER")
    PostEntity  = abstract.RegisterEntityType("POST")
    AdminEntity = abstract.RegisterEntityType("ADMN")
)

// Generate IDs
userID := abstract.NewID(UserEntity)   // "USERa1b2c3d4e5f6"
postID := abstract.NewID(PostEntity)   // "POST9z8y7x6w5v4u"
adminID := abstract.NewID(AdminEntity) // "ADMNx1y2z3w4v5u6"

// Test IDs
testID := abstract.NewTestID() // "00x0" + random

// ID operations
entityType := abstract.FetchEntityType(userID) // "USER"
convertedID := abstract.FromID(userID, AdminEntity) // Convert user ID to admin ID

// Builder pattern for repeated ID generation
userBuilder := abstract.WithEntityType(UserEntity)
postBuilder := abstract.WithEntityType(PostEntity)

// Generate multiple IDs of the same type
users := make([]string, 10)
for i := range users {
    users[i] = userBuilder.NewID()
}

// Configure entity type size
abstract.SetEntitySize(5) // Use 5-character entity types
longEntity := abstract.RegisterEntityType("USERS")

⏱️ Timing Utilities

Precise timing measurements with advanced features.

// Basic timing
timer := abstract.StartTimer()
time.Sleep(100 * time.Millisecond)
elapsed := timer.ElapsedTime()
fmt.Printf("Elapsed: %v\n", elapsed)

// Different time units
seconds := timer.ElapsedSeconds()
minutes := timer.ElapsedMinutes()
milliseconds := timer.ElapsedMilliseconds()
microseconds := timer.ElapsedMicroseconds()

// Lap timing
timer.Reset()
doWork1()
lap1 := timer.Lap()
doWork2()
lap2 := timer.Lap()
doWork3()
lap3 := timer.Lap()

fmt.Printf("Lap 1: %v, Lap 2: %v, Lap 3: %v\n", lap1, lap2, lap3)

// Pause and resume
timer.Pause()
time.Sleep(time.Second) // This won't count
timer.Resume()

// Deadline management
deadlineTimer := abstract.Deadline(5 * time.Minute)
for !deadlineTimer.IsExpired() {
    // Do work with deadline
    remaining := deadlineTimer.TimeRemaining()
    fmt.Printf("Time remaining: %v\n", remaining)
    time.Sleep(time.Second)
}

// Formatting
formatted := timer.Format("%02d:%02d:%02d.%03d") // "00:01:23.456"
short := timer.FormatShort()                     // "1m23s" or "456ms"

// Conditional timing
if timer.HasElapsed(30 * time.Second) {
    fmt.Println("30 seconds have passed")
}

πŸ”§ Type Constraints

Comprehensive type constraints for generic programming.

// Numeric constraints
func AddNumbers[T abstract.Number](a, b T) T {
    return a + b
}

// Works with integers and floats
intResult := AddNumbers(5, 3)        // 8
floatResult := AddNumbers(3.14, 2.86) // 6.0

// Ordered types (support comparison)
func Clamp[T abstract.Ordered](value, min, max T) T {
    if value < min {
        return min
    }
    if value > max {
        return max
    }
    return value
}

clamped := Clamp(15, 10, 20)    // 15
clamped = Clamp(5, 10, 20)      // 10
clamped = Clamp("m", "a", "z")  // "m"

// Integer-specific operations
func IsEven[T abstract.Integer](n T) bool {
    return n%2 == 0
}

even := IsEven(4)    // true
odd := IsEven(7)     // false

// Signed integer operations
func AbsInt[T abstract.Signed](x T) T {
    if x < 0 {
        return -x
    }
    return x
}

positive := AbsInt(-42) // 42

// Available constraints:
// - abstract.Signed: ~int | ~int8 | ~int16 | ~int32 | ~int64
// - abstract.Unsigned: ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
// - abstract.Integer: Signed | Unsigned
// - abstract.Float: ~float32 | ~float64
// - abstract.Complex: ~complex64 | ~complex128
// - abstract.Number: Integer | Float
// - abstract.Ordered: Integer | Float | ~string

πŸ› οΈ Installation

go get -u github.com/maxbolgarin/abstract

Requirements:

  • Go 1.23 or higher
  • Dependencies: github.com/maxbolgarin/lang v1.5.0

πŸ“– API Reference

Core Data Structures
Type Description Safe Alternative Key Methods
Map[K, V] Generic key-value map SafeMap[K, V] Get, Set, Delete, Keys, Values, Has
Set[T] Unique value collection SafeSet[T] Add, Remove, Has, Union, Intersection
Stack[T] LIFO data structure SafeStack[T] Push, Pop, Last, Len
UniqueStack[T] LIFO without duplicates SafeUniqueStack[T] Push, Pop, Last, Has
Slice[T] Enhanced slice operations SafeSlice[T] Append, Get, Insert, Delete, Sort
LinkedList[T] Doubly linked list SafeLinkedList[T] PushFront, PushBack, PopFront, PopBack
EntityMap[K, T] Map with entity ordering SafeEntityMap[K, T] Set, AllOrdered, LookupByName
OrderedPairs[K, V] Ordered key-value pairs SafeOrderedPairs[K, V] Add, Get, Keys, Rand
Utility Types
Type Description Key Methods
Orderer[T] Order management Add, Apply, Get, Clear
Memorizer[T] Thread-safe single value store Set, Get, Pop
CSVTable CSV data manipulation Row, Find, AddRow, UpdateRow
Timer Precise timing measurements ElapsedTime, Lap, Pause, Resume
WorkerPool[T] Context-aware worker pool with results Start, Submit, FetchResults, FetchAllResults, Shutdown, TasksInQueue, OnFlyRunningTasks
JobQueue Fire-and-forget job execution Start, Submit, Wait, Shutdown, TasksInQueue, OnFlyRunningTasks, PendingTasks
WorkerPoolV2[T] Simple generic task processing Submit, FetchResults, FetchAllResults, Submitted, Running, Finished, Stop
RateProcessor Rate-limited processing AddTask, Wait
Future[T] Async operation result Get, GetWithTimeout
Function Categories
Category Functions
Math Min, Max, Abs, Pow, Round, Itoa, Atoi
Random GetRandomString, GetRandomInt, GetRandomBool, GetRandomChoice, ShuffleSlice
Crypto EncryptAES, DecryptAES, GenerateHMAC, SignData, VerifySign
Timing StartTimer, Deadline, StartUpdater, StartCycle
ID Gen NewID, RegisterEntityType, FetchEntityType, WithEntityType
CSV NewCSVTableFromFilePath, NewCSVTableFromMap, NewCSVTableFromReader

🀝 Contributing

We welcome contributions! Please feel free to:

  1. Report bugs and issues
  2. Suggest new features
  3. Submit pull requests
  4. Improve documentation

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.


Happy coding with abstract! πŸŽ‰

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 ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
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

func Atoi[T Number](s string) (T, error)

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

func CheckHMAC(data, suppliedMAC []byte, key *[32]byte) bool

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

func DecodePublicKey(encodedKey []byte) (*ecdsa.PublicKey, error)

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

func DecodeSignatureJWT(b64sig string) ([]byte, error)

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

func DecryptAES(ciphertext []byte, key *[32]byte) (plaintext []byte, err error)

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

func EncodePublicKey(key *ecdsa.PublicKey) ([]byte, error)

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

func EncodeSignatureJWT(sig []byte) string

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

func EncryptAES(plaintext []byte, key *[32]byte) (ciphertext []byte, err error)

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

func GenerateHMAC(data []byte, key *[32]byte) []byte

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

func GetRandomAlphaNumeric(n int) string

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 ΒΆ

func GetRandomBytes(n int) []byte

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

func GetRandomBytesFast(n int) []byte

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

func GetRandomChoice[T any](slice []T) (T, bool)

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

func GetRandomInt(min, max int) int

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

func GetRandomLowerAlpha(n int) string

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

func GetRandomNumeric(n int) string

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 ΒΆ

func GetRandomString(n int) string

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

func GetRandomStringFast(n int) string

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

func GetRandomStringWithAlphabet(n int, alphabet []byte) string

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

func GetRandomUpperAlpha(n int) string

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

func HashHMAC(tag string, data []byte) []byte

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

func Itoa[T Number](i T) string

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

func StartCycle(ctx context.Context, l lang.Logger, f func())

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

func StartCycleWithChan[T any](ctx context.Context, l lang.Logger, c <-chan T, f func(T))

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

func StartCycleWithShutdown(ctx context.Context, l lang.Logger, shutdown <-chan struct{}, f func())

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 ΒΆ

func StartUpdater(ctx context.Context, interval time.Duration, l lang.Logger, f func())

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 ΒΆ

func StartUpdaterNow(ctx context.Context, interval time.Duration, l lang.Logger, f func())

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

func VerifySign(data, signature []byte, pubkey *ecdsa.PublicKey) bool

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

func (b Builder) NewID() string

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

func NewCSVTable(records [][]string) *CSVTable

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

func NewCSVTableFromFilePath(path string) (*CSVTable, error)

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

func NewCSVTableFromMap(data map[string]map[string]string, idColumnName ...string) *CSVTable

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

func NewCSVTableFromReader(reader io.Reader) (*CSVTable, error)

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

func (t *CSVTable) AddRow(id string, row map[string]string)

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

func (t *CSVTable) All() map[string]map[string]string

All returns all rows in the table as a map of ID to row data.

func (*CSVTable) AllIDs ΒΆ added in v1.11.0

func (t *CSVTable) AllIDs() []string

AllIDs returns a slice of all row IDs in the table.

func (*CSVTable) AllRows ΒΆ added in v1.11.0

func (t *CSVTable) AllRows() []map[string]string

AllRows returns all rows in the table as a slice of row data maps.

func (*CSVTable) AllSorted ΒΆ added in v1.12.1

func (t *CSVTable) AllSorted() [][]string

AllSorted returns all rows in the table as a slice of maps, preserving the original order.

func (*CSVTable) AppendColumn ΒΆ added in v1.11.0

func (t *CSVTable) AppendColumn(column string, values []string)

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) Bytes ΒΆ added in v1.11.0

func (t *CSVTable) Bytes() []byte

Bytes returns the table as a CSV-formatted byte slice.

func (*CSVTable) Copy ΒΆ added in v1.11.0

func (t *CSVTable) Copy() *CSVTable

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

func (t *CSVTable) DeleteColumn(column string)

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

func (t *CSVTable) DeleteColumns(columns ...string)

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

func (t *CSVTable) DeleteRow(id string) bool

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

func (t *CSVTable) Find(criteria map[string]string) map[string]map[string]string

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

func (t *CSVTable) FindRow(criteria map[string]string) (string, map[string]string)

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

func (t *CSVTable) Has(slug string) bool

Has returns true if a row with the given ID exists in the table.

func (*CSVTable) Headers ΒΆ added in v1.11.0

func (t *CSVTable) Headers() []string

Headers returns a copy of the headers for the table.

func (*CSVTable) LookupRow ΒΆ added in v1.11.0

func (t *CSVTable) LookupRow(slug string) (map[string]string, bool)

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

func (t *CSVTable) LookupRowSorted(id string) ([]string, bool)

RowSorted returns a map of ID to row data in the original sorted order.

func (*CSVTable) Row ΒΆ added in v1.11.0

func (t *CSVTable) Row(slug string) map[string]string

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

func (t *CSVTable) RowSorted(id string) []string

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

func (t *CSVTable) UpdateColumn(column string, values []string)

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.

func (*CSVTable) UpdateRow ΒΆ added in v1.13.0

func (t *CSVTable) UpdateRow(id string, row map[string]string) bool

UpdateRow updates an existing row with the given ID and data. Only updates the columns that are provided in the row map. Returns true if the row was found and updated, false otherwise.

func (*CSVTable) Value ΒΆ added in v1.11.0

func (t *CSVTable) Value(slug, key string) string

Value returns the value for the given ID and key. If no row with that ID exists, or if the key doesn't exist in that row, returns an empty string.

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) Find ΒΆ added in v1.13.0

func (t *CSVTableSafe) Find(criteria map[string]string) map[string]map[string]string

Find finds all rows that match the given criteria.

func (*CSVTableSafe) FindRow ΒΆ added in v1.13.0

func (t *CSVTableSafe) FindRow(criteria map[string]string) (string, map[string]string)

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 ΒΆ

func (s *EntityMap[K, T]) ChangeOrder(draft map[K]int)

ChangeOrder changes the order of the values.

func (*EntityMap[K, T]) Delete ΒΆ

func (s *EntityMap[K, T]) Delete(keys ...K) (deleted bool)

Delete deletes values for the provided keys. It reorders all remaining values.

func (*EntityMap[K, T]) LookupByName ΒΆ

func (s *EntityMap[K, T]) LookupByName(name string) (T, bool)

LookupByName returns the value for the provided name. It is not case-sensetive according to name.

func (*EntityMap[K, T]) NextOrder ΒΆ

func (s *EntityMap[K, T]) NextOrder() int

NextOrder returns the next order.

func (*EntityMap[K, T]) Set ΒΆ

func (s *EntityMap[K, T]) Set(info T) int

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

func (s *EntityMap[K, T]) SetManualOrder(info T) int

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 ΒΆ

type Float interface {
	~float32 | ~float64
}

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.

func (*Future[T]) Get ΒΆ

func (f *Future[T]) Get(ctx context.Context) (T, error)

Get will wait for the result of the underlying future or returns without it if the context is canceled.

func (*Future[T]) GetWithTimeout ΒΆ

func (f *Future[T]) GetWithTimeout(ctx context.Context, timeout time.Duration) (T, error)

GetWithTimeout will wait for the result of the underlying future or returns without it if the context is canceled, it also wait for the result for the provided timeout.

type Integer ΒΆ

type Integer interface {
	Signed | Unsigned
}

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

func NewJobQueue(workers int, queueCapacity int, logger ...lang.Logger) *JobQueue

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

func (q *JobQueue) FinishedTasks() int

FinishedTasks returns the number of completed tasks.

func (*JobQueue) IsQueueStarted ΒΆ added in v1.18.0

func (q *JobQueue) IsQueueStarted() bool

IsQueueStarted returns true if the job queue has been started.

func (*JobQueue) OnFlyRunningTasks ΒΆ added in v1.18.0

func (q *JobQueue) OnFlyRunningTasks() int

OnFlyRunningTasks returns the number of currently executing tasks.

func (*JobQueue) PendingTasks ΒΆ added in v1.18.0

func (q *JobQueue) PendingTasks() int

PendingTasks returns the total number of tasks that are either queued or running.

func (*JobQueue) Shutdown ΒΆ added in v1.18.0

func (q *JobQueue) 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 (*JobQueue) Start ΒΆ added in v1.18.0

func (q *JobQueue) Start(ctx context.Context)

Start launches the worker goroutines.

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

func (q *JobQueue) Submit(ctx context.Context, task func(ctx context.Context)) bool

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

func (q *JobQueue) TasksInQueue() int

TasksInQueue returns the number of tasks in the queue waiting to be executed.

func (*JobQueue) TotalTasks ΒΆ added in v1.18.0

func (q *JobQueue) TotalTasks() int

TotalTasks returns the total number of tasks submitted to the queue.

func (*JobQueue) Wait ΒΆ added in v1.18.0

func (q *JobQueue) Wait(ctx context.Context) error

Wait blocks until all submitted tasks have been completed or the context is done. Returns nil if all tasks completed successfully, or context error if cancelled.

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

func (p *LegacyWorkerPool) SubmitWait(task Task, timeout time.Duration) (any, error)

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 ΒΆ

func (m *Map[K, V]) Delete(keys ...K) (deleted bool)

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]) Has ΒΆ

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

Has returns true if the key is present in the map, false otherwise.

func (*Map[K, V]) IsEmpty ΒΆ

func (m *Map[K, V]) IsEmpty() bool

IsEmpty returns true if the map is empty. It is safe for concurrent/parallel use.

func (*Map[K, V]) Iter ΒΆ added in v1.9.0

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

Iter returns an iterator over the map.

func (*Map[K, V]) IterKeys ΒΆ added in v1.9.0

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

IterKeys returns an iterator over the map keys.

func (*Map[K, V]) IterValues ΒΆ added in v1.9.0

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

IterValues returns an iterator over the map values.

func (*Map[K, V]) Keys ΒΆ

func (m *Map[K, V]) Keys() []K

Keys returns a slice of keys of the map.

func (*Map[K, V]) Len ΒΆ

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

Len returns the length of the map.

func (*Map[K, V]) Lookup ΒΆ

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

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]) Range ΒΆ

func (m *Map[K, V]) Range(f func(K, V) bool) bool

Range calls the provided function for each key-value pair in the map.

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]) Set ΒΆ

func (m *Map[K, V]) Set(key K, value V)

Set sets the value to the 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.

func (*Map[K, V]) Transform ΒΆ

func (m *Map[K, V]) Transform(f func(K, V) V)

Transform transforms all values of the map using provided function.

func (*Map[K, V]) Values ΒΆ

func (m *Map[K, V]) Values() []V

Values returns a slice of values of the map.

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

func (m *MapOfMaps[K1, K2, V]) Delete(outerKey K1, innerKeys ...K2) bool

Delete removes nested keys and returns true if any were deleted.

func (*MapOfMaps[K1, K2, V]) DeleteMap ΒΆ added in v1.14.0

func (m *MapOfMaps[K1, K2, V]) DeleteMap(outerKeys ...K1) bool

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

func (m *MapOfMaps[K1, K2, V]) Has(outerKey K1, innerKey K2) bool

Has returns true if the nested keys are present, false otherwise.

func (*MapOfMaps[K1, K2, V]) HasMap ΒΆ added in v1.14.0

func (m *MapOfMaps[K1, K2, V]) HasMap(outerKey K1) bool

HasMap returns true if the outer key is present, false otherwise.

func (*MapOfMaps[K1, K2, V]) IsEmpty ΒΆ added in v1.14.0

func (m *MapOfMaps[K1, K2, V]) IsEmpty() bool

IsEmpty returns true if there are no nested key-value pairs.

func (*MapOfMaps[K1, K2, V]) Len ΒΆ added in v1.14.0

func (m *MapOfMaps[K1, K2, V]) Len() int

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

func (m *MapOfMaps[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.

func (*MapOfMaps[K1, K2, V]) LookupMap ΒΆ added in v1.14.0

func (m *MapOfMaps[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.

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

func (m *MapOfMaps[K1, K2, V]) OuterLen() int

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

func (m *MapOfMaps[K1, K2, V]) Range(f func(K1, K2, V) bool) bool

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.

func (*MapOfMaps[K1, K2, V]) Swap ΒΆ added in v1.14.0

func (m *MapOfMaps[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.

func (*MapOfMaps[K1, K2, V]) Transform ΒΆ added in v1.14.0

func (m *MapOfMaps[K1, K2, V]) Transform(f func(K1, K2, V) V)

Transform transforms all values across all inner maps using the provided function.

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 ΒΆ

func NewMemorizer[T any]() *Memorizer[T]

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 ΒΆ

func (m *Memorizer[T]) Get() (T, bool)

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.

func (*Memorizer[T]) Pop ΒΆ

func (m *Memorizer[T]) Pop() (T, bool)

Pop retrieves the value from the Memorizer and marks it as unset. This method is thread-safe and atomically retrieves and clears the value.

Returns:

  • The stored value (or zero value if not set).
  • A boolean indicating whether the value was set before popping.

func (*Memorizer[T]) Set ΒΆ

func (m *Memorizer[T]) Set(c T)

Set stores a value in the Memorizer and marks it as set. This method is thread-safe.

Parameters:

  • c: The value to store in the memorizer.

type Number ΒΆ

type Number interface {
	Integer | Float
}

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 ΒΆ

type Ordered interface {
	Integer | Float | ~string
}

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 ΒΆ

type OrderedPairs[K Ordered, V any] struct {
	// contains filtered or unexported fields
}

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 ΒΆ

func (m *Orderer[T]) Get() map[T]int

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

func (m *Orderer[T]) Has(id T) bool

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

func (m *Orderer[T]) IsEmpty() bool

IsEmpty returns true if the orderer is empty. This method is thread-safe.

Returns:

  • True if the orderer is empty, false otherwise.

func (*Orderer[T]) Len ΒΆ added in v1.17.0

func (m *Orderer[T]) Len() int

Len returns the number of items in the orderer. This method is thread-safe.

Returns:

  • The number of items in the orderer.

func (*Orderer[T]) Rewrite ΒΆ added in v1.17.0

func (m *Orderer[T]) Rewrite(items ...T)

Rewrite rewrites the order of the items in the orderer. This method is thread-safe.

Parameters:

  • items: The items to rewrite the order of.

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 Result ΒΆ added in v1.11.0

type Result struct {
	Value any
	Err   error
}

Result represents the outcome of a task execution.

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

func (p *SafeLegacyWorkerPool) SubmitWait(task Task, timeout time.Duration) (any, error)

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 ΒΆ

func (m *SafeMap[K, V]) Delete(keys ...K) (deleted bool)

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 ΒΆ

func (m *SafeMap[K, V]) Has(key K) bool

Has returns true if key is present in the map, false otherwise. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) IsEmpty ΒΆ

func (m *SafeMap[K, V]) IsEmpty() bool

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

func (m *SafeMap[K, V]) Iter() iter.Seq2[K, V]

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

func (m *SafeMap[K, V]) IterKeys() iter.Seq[K]

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

func (m *SafeMap[K, V]) IterValues() iter.Seq[V]

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 ΒΆ

func (m *SafeMap[K, V]) Len() int

Len returns the length of the map. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Lookup ΒΆ

func (m *SafeMap[K, V]) Lookup(key K) (V, bool)

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 ΒΆ

func (m *SafeMap[K, V]) Range(f func(K, V) bool) bool

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.

func (*SafeMap[K, V]) Transform ΒΆ

func (m *SafeMap[K, V]) Transform(upd func(K, V) V)

Update updates the map using provided function. It is safe for concurrent/parallel use.

func (*SafeMap[K, V]) Values ΒΆ

func (m *SafeMap[K, V]) Values() []V

Values returns a slice of values of the map. 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 ΒΆ

func (m *SafeSet[K]) Delete(keys ...K) (deleted bool)

Delete removes keys from the set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Difference ΒΆ added in v1.9.0

func (m *SafeSet[K]) Difference(set map[K]struct{}) *Set[K]

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 ΒΆ

func (m *SafeSet[K]) Has(key K) bool

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

func (m *SafeSet[K]) Intersection(set map[K]struct{}) *Set[K]

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 ΒΆ

func (m *SafeSet[K]) IsEmpty() bool

Empty returns true if the set is empty. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Iter ΒΆ added in v1.9.0

func (m *SafeSet[K]) Iter() iter.Seq[K]

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 ΒΆ

func (m *SafeSet[K]) Len() int

Len returns the number of keys in set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Range ΒΆ

func (m *SafeSet[K]) Range(f func(K) bool) bool

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

func (m *SafeSet[K]) SymmetricDifference(set map[K]struct{}) *Set[K]

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.

func (*SafeSet[K]) Union ΒΆ added in v1.9.0

func (m *SafeSet[K]) Union(set map[K]struct{}) *Set[K]

Union returns a new set with the union of the current set and the provided set. It is safe for concurrent/parallel use.

func (*SafeSet[K]) Values ΒΆ

func (m *SafeSet[K]) Values() []K

Values returns a slice of values of the set. 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 ΒΆ

func NewSafeSlice[T any](data ...[]T) *SafeSlice[T]

NewSafeSlice returns a new SafeSlice with empty slice.

func NewSafeSliceFromItems ΒΆ added in v1.3.0

func NewSafeSliceFromItems[T any](data ...T) *SafeSlice[T]

NewSafeSliceFromItems returns a new SafeSlice with the provided items.

func NewSafeSliceWithSize ΒΆ

func NewSafeSliceWithSize[T any](size int) *SafeSlice[T]

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

func (s *SafeSlice[T]) Change(index int, f func(T) T)

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]) Copy ΒΆ

func (s *SafeSlice[T]) Copy() []T

Copy returns a copy of the slice.

func (*SafeSlice[T]) Delete ΒΆ

func (s *SafeSlice[T]) Delete(index int) bool

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 ΒΆ

func (s *SafeSlice[T]) Get(index int) T

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 ΒΆ

func (s *SafeSlice[T]) IsEmpty() bool

IsEmpty returns true if the slice is empty. It is safe for concurrent/parallel use.

func (*SafeSlice[T]) Iter ΒΆ added in v1.9.0

func (s *SafeSlice[T]) Iter() iter.Seq[T]

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

func (s *SafeSlice[T]) Iter2() iter.Seq2[int, T]

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 ΒΆ

func (s *SafeSlice[T]) Len() int

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]) Range ΒΆ

func (s *SafeSlice[T]) Range(f func(T) bool) bool

Range calls the provided function for each element in the slice.

func (*SafeSlice[T]) Raw ΒΆ added in v1.8.0

func (s *SafeSlice[T]) Raw() []T

Raw returns the underlying slice.

func (*SafeSlice[T]) Transform ΒΆ

func (s *SafeSlice[T]) Transform(f func(T) T)

Transform transforms all values of the slice using provided function.

func (*SafeSlice[T]) Truncate ΒΆ

func (s *SafeSlice[T]) Truncate(size int)

Truncate truncates the slice to the provided size.

type SafeStack ΒΆ

type SafeStack[T any] struct {
	*Stack[T]
	sync.Mutex
}

SafeStack is a simple stack data structure that is thread-safe.

func NewSafeStack ΒΆ

func NewSafeStack[T any](data ...[]T) *SafeStack[T]

NewSafeStack creates a new SafeStack.

func NewSafeStackWithCapacity ΒΆ

func NewSafeStackWithCapacity[T any](capacity int) *SafeStack[T]

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]) IsEmpty ΒΆ

func (s *SafeStack[T]) IsEmpty() bool

IsEmpty returns true if the stack is empty.

func (*SafeStack[T]) Last ΒΆ

func (s *SafeStack[T]) Last() T

Last returns the last item in the stack.

func (*SafeStack[T]) Len ΒΆ

func (s *SafeStack[T]) Len() int

Len returns the number of items 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 ΒΆ

func (s *SafeStack[T]) PopOK() (T, bool)

PopOK is like Pop but also returns a boolean indicating if the operation was successful.

func (*SafeStack[T]) Push ΒΆ

func (s *SafeStack[T]) Push(item T)

Push adds an item to the top of the stack.

func (*SafeStack[T]) Raw ΒΆ

func (s *SafeStack[T]) Raw() []T

Raw returns the underlying slice of the stack.

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]) Add ΒΆ

func (m *Set[K]) Add(key ...K)

Add adds keys to the set.

func (*Set[K]) Clear ΒΆ

func (m *Set[K]) Clear()

Clear creates a new map using make without 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 ΒΆ

func (m *Set[K]) Delete(keys ...K) (deleted bool)

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

func (m *Set[K]) Difference(set map[K]struct{}) *Set[K]

Difference returns a new set with the difference of the current set and the provided set.

func (*Set[K]) Has ΒΆ

func (m *Set[K]) Has(key K) bool

Has returns true if the key is present in the set, false otherwise.

func (*Set[K]) Intersection ΒΆ added in v1.9.0

func (m *Set[K]) Intersection(set map[K]struct{}) *Set[K]

Intersection returns a new set with the intersection of the current set and the provided set.

func (*Set[K]) IsEmpty ΒΆ

func (m *Set[K]) IsEmpty() bool

IsEmpty returns true if the set is empty. It is safe for concurrent/parallel use.

func (*Set[K]) Iter ΒΆ added in v1.9.0

func (m *Set[K]) Iter() iter.Seq[K]

Iter returns a channel that yields each key in the set.

func (*Set[K]) Len ΒΆ

func (m *Set[K]) Len() int

Len returns the length of the set.

func (*Set[K]) Range ΒΆ

func (m *Set[K]) Range(f func(K) bool) bool

Range calls the provided function for each key in the set.

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

func (m *Set[K]) SymmetricDifference(set map[K]struct{}) *Set[K]

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.

func (*Set[K]) Union ΒΆ added in v1.9.0

func (m *Set[K]) Union(set map[K]struct{}) *Set[K]

Union returns a new set with the union of the current set and the provided set.

func (*Set[K]) Values ΒΆ

func (m *Set[K]) Values() []K

Keys returns a slice of keys of the set.

type Signed ΒΆ

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

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 NewSlice ΒΆ

func NewSlice[T any](data ...[]T) *Slice[T]

NewSlice returns a new Slice with empty slice.

func NewSliceFromItems ΒΆ added in v1.3.0

func NewSliceFromItems[T any](data ...T) *Slice[T]

NewSliceFromItems returns a new Slice with the provided items.

func NewSliceWithSize ΒΆ

func NewSliceWithSize[T any](size int) *Slice[T]

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

func (s *Slice[T]) Change(index int, f func(T) T)

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]) Copy ΒΆ

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

Copy returns a copy of the slice.

func (*Slice[T]) Delete ΒΆ

func (s *Slice[T]) Delete(index int) bool

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 ΒΆ

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

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 ΒΆ

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

IsEmpty returns true if the slice is empty. It is safe for concurrent/parallel use.

func (*Slice[T]) Iter ΒΆ added in v1.9.0

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

Iter returns an iterator over the slice values.

func (*Slice[T]) Iter2 ΒΆ added in v1.9.0

func (s *Slice[T]) Iter2() iter.Seq2[int, T]

Iter2 returns an iterator over the slice values and their indexes.

func (*Slice[T]) Len ΒΆ

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

Len returns the length of the slice.

func (*Slice[T]) Pop ΒΆ

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

Pop removes the last element of the slice and returns it.

func (*Slice[T]) Range ΒΆ

func (s *Slice[T]) Range(f func(T) bool) bool

Range calls the provided function for each element in the slice.

func (*Slice[T]) Raw ΒΆ added in v1.8.0

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

Raw returns the underlying slice.

func (*Slice[T]) Transform ΒΆ

func (s *Slice[T]) Transform(f func(T) T)

Transform transforms all values of the slice using provided function.

func (*Slice[T]) Truncate ΒΆ

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

Truncate truncates the slice to the provided size.

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 NewStack ΒΆ

func NewStack[T any](data ...[]T) *Stack[T]

NewStack creates a new Stack.

func NewStackWithCapacity ΒΆ

func NewStackWithCapacity[T any](capacity int) *Stack[T]

NewStackWithCapacity creates a new Stack with a specified capacity.

func (*Stack[T]) Clear ΒΆ

func (s *Stack[T]) Clear()

Clear removes all items from the stack.

func (*Stack[T]) IsEmpty ΒΆ

func (s *Stack[T]) IsEmpty() bool

IsEmpty returns true if the stack is empty.

func (*Stack[T]) Last ΒΆ

func (s *Stack[T]) Last() T

Last returns the last item in the stack.

func (*Stack[T]) Len ΒΆ

func (s *Stack[T]) Len() int

Len returns the number of items in the stack.

func (*Stack[T]) Pop ΒΆ

func (s *Stack[T]) Pop() T

Pop removes and returns the top item from the stack.

func (*Stack[T]) PopOK ΒΆ

func (s *Stack[T]) PopOK() (T, bool)

PopOK is like Pop but also returns a boolean indicating if the operation was successful.

func (*Stack[T]) Push ΒΆ

func (s *Stack[T]) Push(item T)

Push adds an item to the top of the stack.

func (*Stack[T]) Raw ΒΆ

func (s *Stack[T]) Raw() []T

Raw returns the underlying slice of the stack.

type Task ΒΆ added in v1.11.0

type Task func() (any, error)

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

func Deadline(duration time.Duration) Timer

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

func NewTimer(start time.Time) Timer

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

func (t Timer) ElapsedHours() float64

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

func (t Timer) ElapsedMicroseconds() int64

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

func (t Timer) ElapsedMilliseconds() int64

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

func (t Timer) ElapsedMinutes() float64

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

func (t Timer) ElapsedNanoseconds() int64

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

func (t Timer) ElapsedSeconds() float64

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 ΒΆ

func (t Timer) ElapsedTime() time.Duration

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

func (t Timer) Format(layout string) string

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

func (t Timer) FormatShort() string

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

func (t Timer) HasElapsed(duration time.Duration) bool

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

func (t Timer) IsExpired() bool

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

func (t Timer) IsPaused() bool

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

func (t *Timer) Lap() time.Duration

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

func (t Timer) LapDurations() []time.Duration

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

func (t Timer) Laps() []time.Time

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

func (t *Timer) Pause() bool

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

func (t *Timer) Resume() bool

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

func (t *Timer) SetDeadline(deadline time.Time)

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

func (t *Timer) SetDeadlineDuration(duration time.Duration)

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

func (t Timer) String() string

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 ΒΆ

func (t Timer) Time() time.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

func (t Timer) TimeRemaining() time.Duration

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 ΒΆ

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

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 ΒΆ

func NewWaiter(ctx context.Context, l lang.Logger, foo func(context.Context) error) *Waiter

NewFutureVoid returns a new started void future, it creates a goroutine that will run the passed function and remember it's error.

func (*Waiter) Await ΒΆ

func (f *Waiter) Await(ctx context.Context) error

Await will wait for the result of the underlying future or returns without it if the context is canceled.

func (*Waiter) AwaitWithTimeout ΒΆ

func (f *Waiter) AwaitWithTimeout(ctx context.Context, timeout time.Duration) error

AwaitWithTimeout will wait for the result of the underlying future or returns without it if the context is canceled, it also wait for the result for the provided timeout.

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 ΒΆ

func NewWaiterSet(l lang.Logger, ws ...*Waiter) *WaiterSet

NewWaiterSet returns new WaiterSet with added Waiter, that were started earlier.

func (*WaiterSet) Add ΒΆ

func (s *WaiterSet) Add(ctx context.Context, foo func(ctx context.Context) error)

Add adds a new Waiter to the WaiterSet and starts it in a separate goroutine.

func (*WaiterSet) Await ΒΆ

func (s *WaiterSet) Await(ctx context.Context) error

Await will wait for the result of all underlying functions or returns without it if the context is canceled.

func (*WaiterSet) AwaitWithTimeout ΒΆ

func (s *WaiterSet) AwaitWithTimeout(ctx context.Context, timeout time.Duration) error

AwaitWithTimeout will wait for the result of all underlying functions or returns without it if the context is canceled, it also wait for the result for the provided timeout.

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

func NewWorkerPool[T any](workers int, queueCapacity int, logger ...lang.Logger) *WorkerPool[T]

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

func (p *WorkerPool[T]) Submit(ctx context.Context, task func(ctx context.Context) (T, error)) 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 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.

Jump to

Keyboard shortcuts

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