### Install abstract library Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Command to install the abstract package via the Go toolchain. ```bash go get -u github.com/maxbolgarin/abstract ``` -------------------------------- ### Generic Map Operations in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Demonstrates the creation and usage of generic maps, including basic operations like Set, Get, Has, Keys, Values, Len, Lookup, SetIfNotPresent, Swap, and Pop. It also shows the thread-safe variant `SafeMap` for concurrent access and a `Transform` function. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // Create a basic map m := abstract.NewMap[string, int]() m.Set("apple", 5) m.Set("banana", 3) m.Set("orange", 7) // Basic operations fmt.Println(m.Get("apple")) // 5 fmt.Println(m.Has("grape")) // false fmt.Println(m.Keys()) // [apple, banana, orange] fmt.Println(m.Values()) // [5, 3, 7] fmt.Println(m.Len()) // 3 // Lookup with existence check if value, ok := m.Lookup("banana"); ok { fmt.Println("Found:", value) // Found: 3 } // Conditional set m.SetIfNotPresent("grape", 10) fmt.Println(m.Get("grape")) // 10 // Swap and get old value old := m.Swap("apple", 100) fmt.Println("Old:", old, "New:", m.Get("apple")) // Old: 5 New: 100 // Pop removes and returns value val := m.Pop("orange") fmt.Println(val, m.Has("orange")) // 7 false // Thread-safe variant for concurrent access safeMap := abstract.NewSafeMap[string, int]() safeMap.Set("concurrent", 42) // Safe for concurrent goroutine access go func() { safeMap.Set("key1", 1) }() go func() { safeMap.Set("key2", 2) }() // Transform all values safeMap.Transform(func(k string, v int) int { return v * 2 }) } ``` -------------------------------- ### Go Precise Timing Measurements Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Provides utilities for precise timing measurements, including starting timers, calculating elapsed time in various units (seconds, minutes, milliseconds, microseconds), and using lap timing. Supports pausing, resuming, deadline management, and conditional timing checks. ```go // 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") } ``` -------------------------------- ### Run Staticcheck (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Executes staticcheck, a powerful static analysis tool for Go, to find bugs and style problems. This command requires staticcheck to be installed separately. ```bash staticcheck ./... ``` -------------------------------- ### Implement Rate Limiting in Go Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Provides an example of using RateProcessor to throttle task execution to a specific number of operations per second. It collects errors from processed tasks and waits for completion. ```go processor := abstract.NewRateProcessor(ctx, 10) for i := 0; i < 100; i++ { processor.AddTask(func(ctx context.Context) error { fmt.Printf("Processing item %d\n", i) return nil }) } errors := processor.Wait() ``` -------------------------------- ### Orderer and Memorizer Utilities in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Provides two helper structures: Orderer for managing and applying ordering of items with a callback, and Memorizer for thread-safe single value storage. The Orderer allows adding items, checking their presence, and getting the current order map, which is then applied via a callback and cleared. The Memorizer provides thread-safe Get, Set, and Pop operations for a single value. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // Orderer - track and apply ordering for items orderer := abstract.NewOrderer[string](func(order map[string]int) { fmt.Println("Applying order:", order) }) orderer.Add("item1") orderer.Add("item2") orderer.Add("item3") fmt.Printf("Has item2: %v\n", orderer.Has("item2")) // true fmt.Printf("Length: %d\n", orderer.Len()) // 3 fmt.Printf("Order map: %v\n", orderer.Get()) // map[item1:0 item2:1 item3:2] orderer.Apply() // Calls callback with order map, then clears fmt.Printf("After apply length: %d\n", orderer.Len()) // 0 // Memorizer - thread-safe single value container memo := abstract.NewMemorizer[string]() // Initially empty if _, ok := memo.Get(); !ok { fmt.Println("Memorizer is empty") } // Set a value memo.Set("important data") // Get the value if value, ok := memo.Get(); ok { fmt.Printf("Value: %s\n", value) // important data } // Pop retrieves and clears if value, ok := memo.Pop(); ok { fmt.Printf("Popped: %s\n", value) } // Now it's empty again if _, ok := memo.Get(); !ok { fmt.Println("Memorizer is empty after pop") } } ``` -------------------------------- ### Slice Operations (Go) Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Enhanced slice operations with generic support, including append, insert, get, pop, delete, reverse, and sorting for thread-safe slices. Also includes utility functions like Map and Filter. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // 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 }) fmt.Println("Doubled:", doubled) fmt.Println("Evens:", evens) } ``` -------------------------------- ### Periodic Task Execution with Context Cancellation in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Enables running functions periodically with support for context-aware cancellation. It offers several variants: StartUpdater (first execution after interval), StartUpdaterNow (immediate execution then periodic), StartUpdaterWithShutdown (with a cleanup callback), and StartUpdaterWithShutdownChan (using a shutdown channel). This is useful for background tasks that need to be managed gracefully. ```go package main import ( "context" "fmt" "log/slog" "time" "github.com/maxbolgarin/abstract" ) func main() { ctx, cancel := context.WithCancel(context.Background()) logger := slog.Default() // Start periodic updater (first execution after interval) abstract.StartUpdater(ctx, 500*time.Millisecond, logger, func() { fmt.Println("Periodic health check at", time.Now().Format("15:04:05.000")) }) // Start updater that executes immediately, then periodically abstract.StartUpdaterNow(ctx, 500*time.Millisecond, logger, func() { fmt.Println("Sync task at", time.Now().Format("15:04:05.000")) }) // Updater with shutdown handler abstract.StartUpdaterWithShutdown(ctx, 500*time.Millisecond, logger, func() { fmt.Println("Processing queue...") }, func() { fmt.Println("Cleanup: saving state before shutdown...") }, ) // Updater with shutdown channel shutdown := make(chan struct{}) abstract.StartUpdaterWithShutdownChan(ctx, 500*time.Millisecond, logger, shutdown, func() { fmt.Println("Task with channel control") }) // Let tasks run for a bit time.Sleep(2 * time.Second) // Stop via channel close(shutdown) // Stop all via context cancel() time.Sleep(100 * time.Millisecond) // Allow goroutines to finish fmt.Println("All updaters stopped") } ``` -------------------------------- ### Download Go Module Dependencies (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Downloads all the necessary dependencies required by the Go module. This command ensures that all external packages are available for building and running the project. ```bash go mod download ``` -------------------------------- ### Manage Time and Deadlines with Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Demonstrates how to use the abstract library for precise time tracking, including lap timing, pausing/resuming, and deadline management. It also covers custom formatting for elapsed time durations. ```go package main import ( "fmt" "time" "github.com/maxbolgarin/abstract" ) func main() { // Basic timer timer := abstract.StartTimer() time.Sleep(150 * time.Millisecond) fmt.Printf("Elapsed: %v\n", timer.ElapsedTime()) fmt.Printf("Milliseconds: %d\n", timer.ElapsedMilliseconds()) fmt.Printf("Seconds: %.3f\n", timer.ElapsedSeconds()) fmt.Printf("Formatted: %s\n", timer.FormatShort()) // "150ms" // Lap timing timer.Reset() time.Sleep(100 * time.Millisecond) lap1 := timer.Lap() time.Sleep(200 * time.Millisecond) lap2 := timer.Lap() time.Sleep(50 * time.Millisecond) lap3 := timer.Lap() fmt.Printf("Lap 1: %v\n", lap1) fmt.Printf("Lap 2: %v\n", lap2) fmt.Printf("Lap 3: %v\n", lap3) fmt.Printf("All lap durations: %v\n", timer.LapDurations()) // Pause and resume timer.Reset() time.Sleep(50 * time.Millisecond) timer.Pause() time.Sleep(100 * time.Millisecond) // This won't count timer.Resume() time.Sleep(50 * time.Millisecond) fmt.Printf("Elapsed (excluding pause): %v\n", timer.ElapsedTime()) // ~100ms // Check if duration has elapsed timer.Reset() for !timer.HasElapsed(200 * time.Millisecond) { time.Sleep(50 * time.Millisecond) fmt.Println("Still working...") } fmt.Println("200ms elapsed!") // Deadline management deadline := abstract.Deadline(500 * time.Millisecond) for !deadline.IsExpired() { remaining := deadline.TimeRemaining() fmt.Printf("Time remaining: %v\n", remaining) time.Sleep(100 * time.Millisecond) } fmt.Println("Deadline reached!") // Custom formatting timer = abstract.NewTimer(time.Now().Add(-1*time.Hour - 23*time.Minute - 45*time.Second)) formatted := timer.Format("%02d:%02d:%02d.%03d") fmt.Printf("Custom format: %s\n", formatted) // "01:23:45.XXX" } ``` -------------------------------- ### Build the Go Package (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Compiles the Go project, including all packages within the module. The '-v' flag provides verbose output during the build process. This command is used to create executable binaries or libraries. ```bash go build -v ./... ``` -------------------------------- ### Manage Context-Aware Worker Pools in Go Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Demonstrates how to initialize and manage a worker pool that supports context propagation, cancellation, and result retrieval. It includes task submission, result fetching, and graceful shutdown procedures. ```go ctx := context.Background() pool := abstract.NewContextPool[int](5, 100) pool.Start(ctx) defer pool.Shutdown(ctx) for i := 0; i < 10; i++ { i := i pool.Submit(ctx, func(ctx context.Context) (int, error) { select { case <-ctx.Done(): return 0, ctx.Err() default: return i * 2, nil } }) } results, errs := pool.FetchResults(ctx) ``` -------------------------------- ### Schedule Periodic Tasks in Go Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Demonstrates concurrent helper functions for executing tasks at fixed intervals, including immediate execution options and custom shutdown handlers. ```go abstract.StartUpdater(ctx, 30*time.Second, logger, func() { fmt.Println("Periodic health check") }) abstract.StartUpdaterWithShutdown(ctx, 10*time.Second, logger, func() { /* work */ }, func() { fmt.Println("Shutting down...") }, ) ``` -------------------------------- ### Concurrency Utilities Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Documentation for worker pools, job queues, and async primitives for managing concurrent tasks. ```APIDOC ## Concurrency Utilities ### Description Tools for managing background tasks, rate limiting, and asynchronous results. ### Key Components - **WorkerPool[T]**: Context-aware worker pool with result tracking. - **JobQueue**: Fire-and-forget job execution. - **RateProcessor**: Throttles task execution. - **Future[T]**: Container for asynchronous operation results. ### Methods - `Submit(task T)`: Adds a task to the pool. - `FetchResults()`: Retrieves completed task results. - `Wait()`: Blocks until tasks are completed. ``` -------------------------------- ### Run All Tests with Race Detection and Coverage (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Executes all tests within the project, enabling race detection to find concurrency bugs and generating a coverage profile for code coverage analysis. This command is useful for ensuring the overall health and correctness of the codebase. ```bash go test -v -race -coverprofile=coverage.txt ./... ``` -------------------------------- ### Implement Generic Maps Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Demonstrates usage of basic and thread-safe generic maps, as well as EntityMap for ordered object storage. These structures provide type-safe key-value management with optional concurrency support. ```go // 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") ``` -------------------------------- ### Execute Asynchronous Operations with Futures and Waiters in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Demonstrates how to use Future for returning values, Waiter for void side-effect operations, and WaiterSet for managing multiple concurrent tasks. These utilities support context-based cancellation, timeouts, and error handling. ```go package main import ( "context" "fmt" "log/slog" "time" "github.com/maxbolgarin/abstract" ) func main() { ctx := context.Background() logger := slog.Default() // Create a Future that runs an async operation future := abstract.NewFuture(ctx, logger, func(ctx context.Context) (string, error) { time.Sleep(100 * time.Millisecond) return "async result", nil }) // Block until result is ready result, err := future.Get(ctx) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Result:", result) // Future with timeout slowFuture := abstract.NewFuture(ctx, logger, func(ctx context.Context) (int, error) { time.Sleep(5 * time.Second) return 42, nil }) result2, err := slowFuture.GetWithTimeout(ctx, 100*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 { fmt.Println("Performing side effect...") return nil }) if err := waiter.Await(ctx); err != nil { fmt.Println("Waiter error:", err) } // WaiterSet for multiple parallel operations waiterSet := abstract.NewWaiterSet(logger) waiterSet.Add(ctx, func(ctx context.Context) error { time.Sleep(50 * time.Millisecond) return nil }) if err := waiterSet.Await(ctx); err != nil { fmt.Println("Some tasks failed:", err) } } ``` -------------------------------- ### Context-Aware Worker Pool Implementation Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Demonstrates the use of WorkerPool for executing tasks that require context propagation, cancellation support, and result retrieval. It manages worker lifecycle and provides metrics for monitoring pool state. ```go 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\n", i, errs[i]) } else { fmt.Printf("Task %d result: %d\n", i, result) } } // Monitor pool metrics fmt.Printf("Queue: %d, Running: %d, Finished: %d, Total: %d\n", 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\n", err) } ``` -------------------------------- ### Execute Fire-and-Forget Jobs in Go Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Shows the usage of ContextJobQueue for background tasks that do not require return values. It supports context-aware cancellation and provides methods for waiting on completion and monitoring metrics. ```go queue := abstract.NewContextJobQueue(5, 100) queue.Start(ctx) defer queue.StopNoWait() queue.Submit(ctx, func(ctx context.Context) { log.Printf("Processing item") }) waitCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) defer cancel() queue.Wait(waitCtx) ``` -------------------------------- ### Sign and Verify Data with ECDSA P-256 in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Illustrates the lifecycle of ECDSA digital signatures, including key pair generation, signing data, verifying signatures, and encoding/decoding keys to PEM format for storage. ```go package main import ( "fmt" "log" "github.com/maxbolgarin/abstract" ) func main() { privateKey, err := abstract.NewSigningKey() if err != nil { log.Fatal("Key generation failed:", err) } document := []byte("This document needs to be signed") signature, err := abstract.SignData(document, privateKey) if err != nil { log.Fatal("Signing failed:", err) } publicKey := &privateKey.PublicKey if abstract.VerifySign(document, signature, publicKey) { fmt.Println("Signature verification successful") } pemPrivate, _ := abstract.EncodePrivateKey(privateKey) fmt.Printf("Private key (PEM):\n%s\n", pemPrivate) } ``` -------------------------------- ### Perform AES-256-GCM Encryption and Decryption in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Demonstrates how to generate a secure key, encrypt plaintext data, and perform authenticated decryption. It also highlights the library's built-in tampering detection which triggers an error if the ciphertext is modified. ```go package main import ( "fmt" "log" "github.com/maxbolgarin/abstract" ) func main() { key := abstract.NewEncryptionKey() defer func() { for i := range key { key[i] = 0 } }() plaintext := []byte("This is sensitive data that needs encryption") ciphertext, err := abstract.EncryptAES(plaintext, key) if err != nil { log.Fatal("Encryption failed:", err) } fmt.Printf("Original: %s\n", plaintext) fmt.Printf("Encrypted length: %d bytes\n", len(ciphertext)) decrypted, err := abstract.DecryptAES(ciphertext, key) if err != nil { log.Fatal("Decryption failed:", err) } fmt.Printf("Decrypted: %s\n", decrypted) ciphertext[10] ^= 0xFF _, err = abstract.DecryptAES(ciphertext, key) if err != nil { fmt.Println("Tampering detected:", err) } } ``` -------------------------------- ### Run Go Vet (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Analyzes Go source code for suspicious constructs and potential errors that the Go compiler might miss. Running 'go vet' helps identify common programming mistakes and improve code quality. ```bash go vet ./... ``` -------------------------------- ### Generate Type-Safe Entity IDs with Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Shows how to register entity types and generate unique, prefixed IDs. Includes functionality for extracting entity types, type checking, and using builder patterns for efficient bulk ID generation. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) // Register entity types (must be exactly 4 characters by default) var ( UserEntity = abstract.RegisterEntityType("USER") PostEntity = abstract.RegisterEntityType("POST") CommentEntity = abstract.RegisterEntityType("CMNT") ) func main() { // Generate IDs with entity type prefix userID := abstract.NewID(UserEntity) postID := abstract.NewID(PostEntity) commentID := abstract.NewID(CommentEntity) fmt.Printf("User ID: %s\n", userID) // e.g., "USERa1b2c3d4e5f6" fmt.Printf("Post ID: %s\n", postID) // e.g., "POST9z8y7x6w5v4u" fmt.Printf("Comment ID: %s\n", commentID) // e.g., "CMNTx1y2z3w4v5u6" // Extract entity type from ID entityType := abstract.FetchEntityType(userID) fmt.Printf("Entity type: %s\n", entityType) // "USER" // Type checking based on ID prefix switch abstract.FetchEntityType(postID) { case UserEntity: fmt.Println("It's a user") case PostEntity: fmt.Println("It's a post") // This will print case CommentEntity: fmt.Println("It's a comment") } // Convert ID to different entity type adminID := abstract.FromID(userID, abstract.RegisterEntityType("ADMN")) fmt.Printf("Admin ID: %s\n", adminID) // Keeps random part, changes prefix // Test IDs (uses "00x0" prefix) testID := abstract.NewTestID() fmt.Printf("Test ID: %s\n", testID) // "00x0..." // Builder pattern for repeated ID generation userBuilder := abstract.WithEntityType(UserEntity) postBuilder := abstract.WithEntityType(PostEntity) // Generate multiple IDs efficiently users := make([]string, 5) for i := range users { users[i] = userBuilder.NewID() } fmt.Printf("User IDs: %v\n", users) posts := make([]string, 3) for i := range posts { posts[i] = postBuilder.NewID() } fmt.Printf("Post IDs: %v\n", posts) } ``` -------------------------------- ### Format Go Code (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Applies standard Go formatting to all files within the current module. This ensures consistent code style across the project, making it more readable and maintainable. ```bash go fmt ./... ``` -------------------------------- ### Implement Generic Sets Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Demonstrates usage of generic sets for unique value storage, including thread-safe variants and set operations like intersection and union. ```go // 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] ``` -------------------------------- ### Generate and Verify HMAC-SHA-512/256 in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Shows how to generate message authentication codes and verify them using constant-time comparison to prevent timing attacks. It also covers keyed hashing with custom tags. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { key := abstract.NewHMACKey() message := []byte("Important message that needs integrity verification") mac := abstract.GenerateHMAC(message, key) fmt.Printf("HMAC: %x\n", mac) if abstract.CheckHMAC(message, mac, key) { fmt.Println("HMAC verification successful - message is authentic") } hash := abstract.HashHMAC("session-token", []byte("user123:session456")) fmt.Printf("Hash with tag: %x\n", hash) } ``` -------------------------------- ### Stack Implementations (Go) Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Provides LIFO (Last In, First Out) data structure implementations. Includes basic, thread-safe, and unique element stacks. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // 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 } ``` -------------------------------- ### Concurrency Tools: Futures and Promises (Go) Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Utilities for asynchronous operations and parallel processing. Includes Futures for managing asynchronous results and Waiters for synchronizing void operations, along with WaiterSets for multiple tasks. ```go package main import ( "context" "fmt" "log" "time" "github.com/maxbolgarin/abstract" ) func main() { ctx := context.Background() // Dummy logger for example logger := log.Default() // Basic Future 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 // Create a new future that will definitely timeout for demonstration futureTimeout := abstract.NewFuture(ctx, logger, func(ctx context.Context) (string, error) { time.Sleep(200 * time.Millisecond) // Longer than timeout return "this won't be returned", nil }) result, err = futureTimeout.GetWithTimeout(ctx, 50*time.Millisecond) if err == abstract.ErrTimeout { fmt.Println("Operation timed out as expected") } else if err != nil { log.Fatalf("Unexpected error: %v", err) } else { fmt.Printf("Unexpected success with result: %s\n", result) } // Waiter for void operations waiter := abstract.NewWaiter(ctx, logger, func(ctx context.Context) error { fmt.Println("Waiter performing work...") time.Sleep(50 * time.Millisecond) // Simulate work fmt.Println("Waiter finished work.") return nil }) err = waiter.Await(ctx) if err != nil { log.Fatalf("Waiter failed: %v", err) } // WaiterSet for multiple operations waiterSet := abstract.NewWaiterSet(logger) waiterSet.Add(ctx, func(ctx context.Context) error { fmt.Println("Task 1 started") time.Sleep(70 * time.Millisecond) fmt.Println("Task 1 finished") return nil }) waiterSet.Add(ctx, func(ctx context.Context) error { fmt.Println("Task 2 started") time.Sleep(30 * time.Millisecond) fmt.Println("Task 2 finished") return nil }) fmt.Println("Waiting for WaiterSet tasks...") err = waiterSet.Await(ctx) // Wait for all tasks if err != nil { log.Fatalf("WaiterSet failed: %v", err) } fmt.Println("All WaiterSet tasks completed.") } ``` -------------------------------- ### Generic Set Operations in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Illustrates the use of generic sets for storing unique values and performing set operations. Includes methods like `NewSetFromItems`, `Add`, `Len`, `Has`, `Values`, `Delete`, `Union`, `Intersection`, `Difference`, and `SymmetricDifference`. A thread-safe variant `SafeSet` is also shown. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // Create a set from items set := abstract.NewSetFromItems("apple", "banana", "orange") // Add elements (duplicates ignored) set.Add("grape", "apple") // apple already exists fmt.Println(set.Len()) // 4 fmt.Println(set.Has("banana")) // true // Get all values fmt.Println(set.Values()) // [apple, banana, orange, grape] // Remove elements set.Delete("banana") fmt.Println(set.Has("banana")) // false // Set operations set1 := abstract.NewSetFromItems(1, 2, 3, 4) set2 := abstract.NewSetFromItems(3, 4, 5, 6) // Union: all elements from both sets union := set1.Union(set2.Raw()) fmt.Println(union.Values()) // [1, 2, 3, 4, 5, 6] // Intersection: common elements intersection := set1.Intersection(set2.Raw()) fmt.Println(intersection.Values()) // [3, 4] // Difference: elements in set1 but not in set2 diff := set1.Difference(set2.Raw()) fmt.Println(diff.Values()) // [1, 2] // Symmetric difference: elements in either but not both symDiff := set1.SymmetricDifference(set2.Raw()) fmt.Println(symDiff.Values()) // [1, 2, 5, 6] // Thread-safe set safeSet := abstract.NewSafeSet[string]() safeSet.Add("concurrent", "safe", "access") } ``` -------------------------------- ### Run Tests for a Specific File (Bash) Source: https://github.com/maxbolgarin/abstract/blob/main/CLAUDE.md Runs tests specifically for a single file, such as 'workerpool_test.go', while still enabling verbose output and race detection. This is helpful for quickly testing changes in a particular module without running the entire test suite. ```bash go test -v -race -run TestWorkerPool ./workerpool_test.go ``` -------------------------------- ### Go Structured ID Generation Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Enables structured and type-safe ID generation using entity types. Covers registering entity types, generating unique IDs, testing IDs, and performing ID operations like fetching entity types and converting IDs. Supports configuring entity type size and using a builder pattern for repeated ID generation. ```go // 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") ``` -------------------------------- ### Generic Slices in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Provides enhanced slice operations with generic support and thread-safe variants. Supports creating slices from items, basic access, appending, prepending, popping, deleting by index, truncating, transforming values, and changing specific elements. Includes iteration support for Go 1.23+. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // Create slice from items slice := abstract.NewSliceFromItems(1, 2, 3, 4, 5) // Basic operations fmt.Println(slice.Get(2)) // 3 fmt.Println(slice.Len()) // 5 // Append and prepend slice.Append(6, 7) slice.AddFront(0) fmt.Println(slice.Raw()) // [0, 1, 2, 3, 4, 5, 6, 7] // Pop last element last := slice.Pop() fmt.Println(last) // 7 // Delete by index slice.Delete(0) fmt.Println(slice.Raw()) // [1, 2, 3, 4, 5, 6] // Truncate to size slice.Truncate(4) fmt.Println(slice.Raw()) // [1, 2, 3, 4] // Transform all values slice.Transform(func(v int) int { return v * 2 }) fmt.Println(slice.Raw()) // [2, 4, 6, 8] // Change single value slice.Change(1, func(v int) int { return v + 100 }) fmt.Println(slice.Raw()) // [2, 104, 6, 8] // Iterate with Go 1.23+ iterators for v := range slice.Iter() { fmt.Printf("%d ", v) } // Output: 2 104 6 8 // Thread-safe slice safeSlice := abstract.NewSafeSlice[string]() safeSlice.Append("hello", "world") } ``` -------------------------------- ### Go Generic Functions with Type Constraints (Average, Clamp, IsEven, AbsoluteValue) Source: https://context7.com/maxbolgarin/abstract/llms.txt Demonstrates generic functions in Go utilizing type constraints from the 'abstract' library. These functions include Average for numerical slices, Clamp for ordering values, IsEven for integer checks, and AbsoluteValue for signed numbers. They require the 'abstract' package and ensure compile-time type safety. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) // Generic function using Number constraint 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)) } // Generic function using Ordered constraint func Clamp[T abstract.Ordered](value, min, max T) T { if value < min { return min } if value > max { return max } return value } // Generic function using Integer constraint func IsEven[T abstract.Integer](n T) bool { return n%2 == 0 } // Generic function using Signed constraint func AbsoluteValue[T abstract.Signed](x T) T { if x < 0 { return -x } return x } func main() { // Number constraint works with int, float32, float64, etc. intAvg := Average([]int{1, 2, 3, 4, 5}) floatAvg := Average([]float64{1.5, 2.5, 3.5}) fmt.Printf("Int average: %d\n", intAvg) // 3 fmt.Printf("Float average: %.2f\n", floatAvg) // 2.50 // Ordered constraint works with numbers and strings clampedInt := Clamp(15, 10, 20) clampedStr := Clamp("m", "a", "z") fmt.Printf("Clamped int: %d\n", clampedInt) // 15 fmt.Printf("Clamped str: %s\n", clampedStr) // m // Integer constraint for modulo operations fmt.Printf("4 is even: %v\n", IsEven(4)) // true fmt.Printf("7 is even: %v\n", IsEven(7)) // false fmt.Printf("uint(10) even: %v\n", IsEven(uint(10))) // true // Signed constraint for negative number operations fmt.Printf("Abs(-42): %d\n", AbsoluteValue(-42)) // 42 // fmt.Printf("Abs(-3.14): %.2f\n", AbsoluteValue(-3.14)) // Won't compile - Float not Signed } ``` -------------------------------- ### Generic Worker Pool V2 Implementation Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Provides a simplified interface for generic worker pools. It supports task submission with timeouts and bulk result fetching. ```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\n", errors[i]) } else { fmt.Printf("Task result: %v\n", 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\n", pool.Submitted(), pool.Running(), pool.Finished()) // Fetch all results (including tasks submitted after call) allResults, allErrors := pool.FetchAllResults(10 * time.Second) ``` -------------------------------- ### Generate Cryptographically Secure Random Data in Go Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Covers the generation of random strings, numbers, booleans, and choices using secure methods. It also includes utilities for shuffling slices and generating random network addresses. ```go token := abstract.GetRandomString(32) pin := abstract.GetRandomNumeric(6) dice := abstract.GetRandomInt(1, 6) colors := []string{"red", "green", "blue"} color, _ := abstract.GetRandomChoice(colors) cards := []string{"A", "K", "Q"} abstract.ShuffleSlice(cards) ``` -------------------------------- ### Doubly Linked Lists in Go Source: https://context7.com/maxbolgarin/abstract/llms.txt Implements a doubly linked list with efficient insertion and deletion at both ends. Supports adding elements to the front and back, peeking at the front and back elements, and removing elements from either end. Includes a thread-safe variant for concurrent access. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { list := abstract.NewLinkedList[string]() // Add to front and back list.PushBack("middle") list.PushFront("first") list.PushBack("last") fmt.Println(list.Len()) // 3 // Peek at front and back if front, ok := list.Front(); ok { fmt.Println("Front:", front) // Front: first } if back, ok := list.Back(); ok { fmt.Println("Back:", back) // Back: last } // Pop from front if val, ok := list.PopFront(); ok { fmt.Println("Popped front:", val) // Popped front: first } // Pop from back if val, ok := list.PopBack(); ok { fmt.Println("Popped back:", val) // Popped back: last } fmt.Println(list.Len()) // 1 // Thread-safe linked list safeList := abstract.NewSafeLinkedList[int]() safeList.PushBack(1) safeList.PushBack(2) safeList.PushFront(0) // Safe for concurrent access go func() { safeList.PushBack(3) }() go func() { safeList.PopFront() }() } ``` -------------------------------- ### LinkedList Implementations (Go) Source: https://github.com/maxbolgarin/abstract/blob/main/README.md Doubly linked list implementation with efficient insertion and deletion at both ends. Supports basic operations, iteration, and a thread-safe version. ```go package main import ( "fmt" "github.com/maxbolgarin/abstract" ) func main() { // Basic linked list list := abstract.NewLinkedList[string]() list.PushFront("first") list.PushBack("last") list.PushFront("new first") fmt.Println(list.Front()) fmt.Println(list.Back()) fmt.Println(list.Len()) // 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 fmt.Println("Popped from safe list:", value) } ```