### Simple Get Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates a basic lookup using the Get operation. Ensure the map is initialized and the key is inserted before calling Get. ```go m := dlht.New[string, int](dlht.Options{}) m.Insert("score", 95) if value, found := m.Get("score"); found { fmt.Printf("Score: %d\n", value) } else { fmt.Println("Score not found") } ``` -------------------------------- ### Inline Get Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates using the Get operation with an inline map implementation. Ensure the map is initialized and the key is inserted. ```go m := dlht.NewInline[uint32](opts) m.Insert(0xDEADBEEF, 42) if value, found := m.Get(0xDEADBEEF); found { fmt.Printf("Value: %d\n", value) } ``` -------------------------------- ### Example Usage of Integer Constraint Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/configuration.md Shows how to use the `Integer` constraint with `NewInline`. Valid examples include built-in integer types and custom types aliased to them. Non-integer types will cause compilation errors. ```Go type Score uint32 type Count int64 m1 := dlht.NewInline[uint32](opts) // Valid: uint32 is Integer m2 := dlht.NewInline[Score](opts) // Valid: Score is ~uint32 m3 := dlht.NewInline[int16](opts) // Valid: int16 is Integer // Invalid: string is not Integer // m4 := dlht.NewInline[string](opts) // Compilation error ``` -------------------------------- ### DLHT Map InitialSize Rounding Examples Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/constructor.md Provides examples of how the InitialSize parameter is rounded up to the nearest power of two for bucket allocation. ```text // Examples of InitialSize rounding InitialSize: 1 → Bins: 1 (capacity: 15) InitialSize: 15 → Bins: 16 (capacity: 240) InitialSize: 16 → Bins: 16 (capacity: 240) InitialSize: 17 → Bins: 32 (capacity: 480) InitialSize: 100 → Bins: 128 (capacity: 1920) InitialSize: 1000→ Bins: 1024 (capacity: 15360) ``` -------------------------------- ### Simple Delete Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates how to delete a key and retrieve its old value. Ensure the map is initialized before use. ```go m := dlht.New[string, int](opts) m.Insert("name", 42) if oldVal, deleted := m.Delete("name"); deleted { fmt.Printf("Deleted name (was %d)\n", oldVal) } else { fmt.Println("name does not exist") } ``` -------------------------------- ### Example: Bit Flags using NewInline Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/constructor.md Illustrates using NewInline with a custom uint8 type as packed bit flags. It shows how to set and check flags within the map. ```go // Use uint8 as a packed bit flag type Flags uint8 const ( FlagActive Flags = 1 << 0 FlagVerified Flags = 1 << 1 FlagPremium Flags = 1 << 2 ) m := dlht.NewInline[Flags](dlht.Options{InitialSize: 512}) // Set flags m.Insert(12345, FlagActive|FlagVerified) // Check flags if flags, found := m.Get(12345); found { if flags&FlagPremium != 0 { fmt.Println("User has premium") } } ``` -------------------------------- ### Simple Update Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates how to use the Put operation to update an existing key's value. It checks the boolean return to confirm the update. ```go m := dlht.New[string, int](opts) m.Insert("score", 90) if oldScore, updated := m.Put("score", 95); updated { fmt.Printf("Updated score from %d to 95\n", oldScore) } else { fmt.Println("Score does not exist, not updated") } ``` -------------------------------- ### Quick Start: Using DLHT Map in Go Source: https://github.com/jeremiah-masters/dlht/blob/main/README.md Demonstrates basic usage of the DLHT map, including creation, insertion, retrieval, updates, deletion, iteration, and statistics retrieval. Ensure the 'github.com/jeremiah-masters/dlht' package is imported. ```go package main import ( "fmt" "github.com/jeremiah-masters/dlht" ) func main() { // Create a new DLHT Map m := dlht.New[string, int](dlht.Options{InitialSize: 64}) // Insert key-value pairs m.Insert("apple", 5) m.Insert("banana", 3) // Get values if value, found := m.Get("apple"); found { fmt.Printf("Found: apple = %d\n", value) } // Update values atomically if oldValue, updated := m.Put("apple", 10); updated { fmt.Printf("Updated apple: %d -> %d\n", oldValue, 10) } // Delete keys if oldValue, deleted := m.Delete("banana"); deleted { fmt.Printf("Deleted banana (old value: %d)\n", oldValue) } // Iterate every (key, value) currently in the map. m.Range(func(k string, v int) bool { fmt.Printf("%s = %d\n", k, v) return true // return false to stop early }) // Approximate entry count ssize := m.Size() fmt.Printf("Size: %d\n", size) // Get statistics stats := m.Stats() fmt.Printf("Load factor: %.3f\n", stats.LoadFactor) } ``` -------------------------------- ### Type-Safe Get with Error Checking Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Shows how to use Get with complex types like pointers, checking the 'found' boolean for safe access. ```go // With error checking m := dlht.New[string, *User](opts) if user, found := m.Get("alice@example.com"); found { fmt.Printf("User: %+v\n", user) } else { fmt.Println("User not found") } ``` -------------------------------- ### Example: Counter Map using NewInline Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/constructor.md Demonstrates using NewInline to create a map for counting event occurrences. It shows how to increment counters and retrieve results efficiently. ```go package main import ( "fmt" "github.com/jeremiah-masters/dlht" ) func main() { // Counters for event IDs m := dlht.NewInline[uint32](dlht.Options{InitialSize: 1024}) // Increment counters for i := 0; i < 100; i++ { eventID := uint64(i % 10) oldVal, _ := m.Get(eventID) m.Put(eventID, oldVal+1) } // Read results for i := range 10 { if count, found := m.Get(uint64(i)); found { fmt.Printf("Event %d: %d occurrences\n", i, count) } } } ``` -------------------------------- ### Bulk Delete Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Illustrates how to iterate over a list of keys and delete each one from the map. ```go keysToDelete := []string{"key1", "key2", "key3"} for _, key := range keysToDelete { if _, deleted := m.Delete(key); deleted { fmt.Printf("Deleted %s\n", key) } } ``` -------------------------------- ### Create Map with Initial Size Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/types.md Example of creating a new dlht map with a specified initial size for its buckets. ```go opts := dlht.Options{InitialSize: 1024} m := dlht.New[string, int](opts) // Starts with 1024 primary buckets ``` -------------------------------- ### Simple Insert Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates a basic insertion of a key-value pair. Checks the boolean return value to determine if the key was newly inserted or already existed. ```go m := dlht.New[string, int](dlht.Options{}) if oldValue, inserted := m.Insert("count", 1); inserted { fmt.Println("Inserted count = 1") } else { fmt.Printf("count already existed with value %d\n", oldValue) } ``` -------------------------------- ### Sum All Values Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md This example demonstrates how to sum all integer values in a map using the `Range` function. The `yield` function adds the current value to a running total and returns `true` to continue iteration. ```go m := dlht.New[string, int](opts) m.Insert("a", 10) m.Insert("b", 20) m.Insert("c", 30) total := 0 m.Range(func(key string, value int) bool { total += value return true // Continue iterating }) fmt.Printf("Sum: %d\n", total) // Output: Sum: 60 ``` -------------------------------- ### Collect All Keys Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md This example shows how to collect all keys from a map into a slice using the `Range` function. The `yield` function appends each key to a slice, and `true` is returned to ensure all keys are collected. ```go m := dlht.New[string, int](opts) m.Insert("alice", 1) m.Insert("bob", 2) m.Insert("charlie", 3) keys := []string{} m.Range(func(key string, value int) bool { keys = append(keys, key) return true }) fmt.Printf("Keys: %v\n", keys) ``` -------------------------------- ### Conditional Delete Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Shows how to delete a key and conditionally process the deleted value, such as a user object. ```go m := dlht.New[string, *User](opts) m.Insert("alice", &User{ID: 1, Name: "Alice"}) if user, deleted := m.Delete("alice"); deleted { fmt.Printf("Deleted user: %+v\n", user) } ``` -------------------------------- ### Find First Match Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md This example shows how to find the first map entry whose value matches a specific prefix using `Range`. The `yield` function checks the condition and returns `false` to stop iteration once a match is found. ```go m := dlht.New[int, string](opts) for i := range 100 { m.Insert(i, fmt.Sprintf("item-%d", i)) } // Find first value starting with "item-5" var found string m.Range(func(key int, value string) bool { if strings.HasPrefix(value, "item-5") { found = value return false // Stop iteration } return true // Continue iterating }) if found != "" { fmt.Printf("Found: %s\n", found) } ``` -------------------------------- ### DLHT Quick Start with Allocator-Based Implementation Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/README.md Demonstrates basic usage of the DLHT allocator-based hash table, including creation, insertion, retrieval, update, deletion, iteration, and statistics retrieval. Use this for generic key and value types. ```go package main import ( "fmt" "github.com/jeremiah-masters/dlht" ) func main() { // Create a new DLHT with allocator-based implementation m := dlht.New[string, int](dlht.Options{InitialSize: 64}) // Insert key-value pairs m.Insert("key1", 42) m.Insert("key2", 100) // Get values if value, found := m.Get("key1"); found { fmt.Printf("Found: key1 = %d\n", value) } // Update atomically if old, success := m.Put("key1", 84); success { fmt.Printf("Updated key1: %d -> 84\n", old) } // Delete if old, deleted := m.Delete("key2"); deleted { fmt.Printf("Deleted key2 (was %d)\n", old) } // Iterate m.Range(func(k string, v int) bool { fmt.Printf("%s = %d\n", k, v) return true // return false to stop }) // Statistics stats := m.Stats() fmt.Printf("Size: %d, Load Factor: %.3f\n", stats.Size, stats.LoadFactor) } ``` -------------------------------- ### Key Not Found (Get) Detection Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/errors.md Shows how to detect if a key was not found during a Get operation by checking the boolean return value. ```go if value, found := m.Get(key); !found { // Key not in map } ``` ```go m := dlht.New[string, int](opts) if value, found := m.Get("missing"); !found { fmt.Println("Key 'missing' not found") // value is 0 (zero value for int) } ``` -------------------------------- ### Monitor Map Size Growth Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md This example shows how to monitor the map's size dynamically as entries are inserted, particularly useful for observing growth patterns or triggering actions at specific size thresholds. ```go m := dlht.New[string, int](dlht.Options{InitialSize: 16}) for i := range 1000 { m.Insert(fmt.Sprintf("key%d", i), i) if i%100 == 0 { fmt.Printf("Size: %d\n", m.Size()) } } ``` -------------------------------- ### Early Exit Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md This example demonstrates how to stop iteration early by returning `false` from the `yield` function. The iteration stops once a specified condition (e.g., processing a certain number of entries) is met. ```go count := 0 m.Range(func(key K, value V) bool { count++ return count < 10 // Stop after 10 entries }) ``` -------------------------------- ### Print Map Statistics Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md Example of how to initialize a map, insert elements, and then print its statistics. This demonstrates accessing fields like Bins, Size, Capacity, LoadFactor, and Resizing. ```go m := dlht.New[string, int](dlht.Options{InitialSize: 64}) for i := range 100 { m.Insert(fmt.Sprintf("key%d", i), i) } stats := m.Stats() fmt.Printf("Bins: %d\n", stats.Bins) fmt.Printf("Size: %d\n", stats.Size) fmt.Printf("Capacity: %d\n", stats.Capacity) fmt.Printf("Load Factor: %.3f\n", stats.LoadFactor) fmt.Printf("Resizing: %v\n", stats.Resizing) ``` -------------------------------- ### Retrieve and Print Map Statistics Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/types.md Example of creating a map, inserting data, and then retrieving and printing its statistics. ```go m := dlht.New[string, int](dlht.Options{InitialSize: 64}) m.Insert("key1", 100) m.Insert("key2", 200) stats := m.Stats() fmt.Printf("Bins: %d, Size: %d, Load: %.3f\n", stats.Bins, stats.Size, stats.LoadFactor) // Output: Bins: 64, Size: 2, Load: 0.003 ``` -------------------------------- ### DLHT Quick Start with Inline-Optimized Implementation Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/README.md Demonstrates basic usage of the DLHT inline-optimized hash table for uint64 keys and integer values. This version is specialized for performance with these specific types. ```go m := dlht.NewInline[uint64](dlht.Options{InitialSize: 64}) m.Insert(12345, 999) if v, found := m.Get(12345); found { fmt.Printf("Found: %d\n", v) } ``` -------------------------------- ### Fully-Loaded Bucket Chain Example Source: https://github.com/jeremiah-masters/dlht/blob/main/design.md Illustrates a primary bucket and its associated link arena when fully loaded, showing the distribution of slots across primary, single, and pair link buckets. ```plaintext Primary Bucket (64B) Link Arena Overview ┌───────────────────────┐ ┌───────────────────────────────────────┐ │ Header: Ver=42 Bin=00 │ │ Index: [0][1][2][3][4][5][6] │ │ SlotStates: 10 10 10 │ │ [ ][ ][●][●][ ][●][ ] │ │ (all 3 slots Valid) │ │ ▲ ▲ ▲ │ ├───────────────────────┤ │ │ │ │ │ │ LinkMeta (64 bits): │ │ Pair─┼──┘ └─Single │ │ ┌─────────┬─────────┐ │ └───────────────┼───────────────────────┘ │ │PairStart│ Single │ │ │ │ │ 2 │ 5 │ │ │ │ └─────────┴─────────┘ │ ┌───────────────┘ ├───────────────────────┤ │ │ Slot[0]: K1, V1 │ │ Link Pair: Buckets [2,3] (8 slots) │ Slot[1]: K2, V2 │ │ ┌─────────────────┐ ┌─────────────────┐ │ Slot[2]: K3, V3 │ │ │ LinkBucket[2] │ │ LinkBucket[3] │ └───────────────────────┘ │ │ ┌────┬──────┐ │ │ ┌─────┬───────┐ │ └─┤ │ K4 │ V4 │ │ │ │ K8 │ V8 │ │ │ ├────┼──────┤ │ │ ├─────┼───────┤ │ │ │ K5 │ V5 │ │ │ │ K9 │ V9 │ │ │ ├────┼──────┤ │ │ ├─────┼───────┤ │ │ │ K6 │ V6 │ │ │ │ K10 │ V10 │ │ │ ├────┼──────┤ │ │ ├─────┼───────┤ │ │ │ K7 │ V7 │ │ │ │ K11 │ V11 │ │ │ └────┴──────┘ │ │ └─────┴───────┘ │ └─────────────────┘ └─────────────────┘ Single Link: Bucket [5] (4 slots) ┌─────────────────┐ │ LinkBucket[5] │ │ ┌─────┬──────┐ │ │ │ K12 │ V12 │ │ │ ├─────┼──────┤ │ │ │ K13 │ V13 │ │ │ ├─────┼──────┤ │ │ │ K14 │ V14 │ │ │ ├─────┼──────┤ │ │ │ K15 │ V15 │ │ │ └─────┴──────┘ │ └─────────────────┘ Total: 3 (primary) + 4 (single) + 8 (pair) = 15 slots maximum per bin ``` -------------------------------- ### Bulk Insert Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Illustrates inserting multiple key-value pairs from a slice. It iterates through the data and performs an insert for each item, checking the insertion status. ```go m := dlht.New[int, string](opts) users := []struct{ID int; Name string}{ {1, "Alice"}, {2, "Bob"}, {3, "Charlie"}, } for _, u := range users { if _, inserted := m.Insert(u.ID, u.Name); inserted { fmt.Printf("Inserted user %d\n", u.ID) } } ``` -------------------------------- ### Get with Default Value Handling Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Illustrates retrieving a value and assigning a default if the key is not found, using the 'found' boolean. ```go // With default value m := dlht.New[int, string](opts) key := 12345 var value string if v, found := m.Get(key); found { value = v } else { value = "unknown" } ``` -------------------------------- ### Example Usage of Key Constraint Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/configuration.md Demonstrates valid and invalid uses of the `Key` constraint for map keys. Ensure that custom types used as keys only contain comparable fields. ```Go // Valid key types m1 := dlht.New[string, int](opts) // string is comparable m2 := dlht.New[int64, string](opts) // int64 is comparable m3 := dlht.New[[16]byte, int](opts) // Array is comparable // Custom comparable type type UserID struct { ID int64 Tenant string } m4 := dlht.New[UserID, *User](opts) // Works if UserID only has comparable fields // Invalid: slice is not comparable // m5 := dlht.New[[]byte, int](opts) // Compilation error ``` -------------------------------- ### Example Usage of General Purpose Map Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/types.md Demonstrates creating a new Map for string keys and User pointers, inserting a user, and retrieving it. Ensure the key type is comparable and the value type can be any Go type. ```go type User struct { ID int64 Name string Email string } m := dlht.New[string, *User](dlht.Options{InitialSize: 256}) m.Insert("alice@example.com", &User{ID: 1, Name: "Alice"}) if user, found := m.Get("alice@example.com"); found { fmt.Printf("User: %s (%d)\n", user.Name, user.ID) } ``` -------------------------------- ### Plain Loads for Slot Keys in Get Operation Source: https://github.com/jeremiah-masters/dlht/blob/main/design.md Demonstrates the use of plain (non-atomic) loads for accessing slot keys within the Get operation. This is safe due to preceding acquire header loads and seqlock checks, optimizing performance by avoiding unnecessary serialization. ```go k0 := pb.Slots[0].Key // Plain load k1 := pb.Slots[1].Key // Plain load k2 := pb.Slots[2].Key // Plain load ``` -------------------------------- ### Inline Delete Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates deleting a key from an inline map where values are stored directly. ```go m := dlht.NewInline[uint32](opts) m.Insert(999, 42) if oldVal, deleted := m.Delete(999); deleted { fmt.Printf("Deleted 999 (was %d)\n", oldVal) } ``` -------------------------------- ### Go dlht Map Initialization and Operations Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/START_HERE.md Demonstrates creating a new dlht map with initial options, performing insert, get, and range operations, and accessing statistics. All operations are thread-safe. ```go package main import "github.com/jeremiah-masters/dlht" func main() { // Create a map m := dlht.New[string, int](dlht.Options{InitialSize: 64}) // Insert/Get/Delete/Put m.Insert("key1", 42) if v, found := m.Get("key1"); found { // Process v } // Thread-safe iteration m.Range(func(k string, v int) bool { println(k, v) return true // Continue }) // Statistics stats := m.Stats() println("Size:", stats.Size, "Load:", stats.LoadFactor) } ``` -------------------------------- ### Monitor Map Load Factor Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md Example demonstrating how to monitor the map's load factor during insertions and print a message when it exceeds a certain threshold (0.7). This is useful for dynamic scaling or performance tuning. ```go m := dlht.New[string, int](dlht.Options{InitialSize: 16}) for i := range 1000 { m.Insert(fmt.Sprintf("key%d", i), i) stats := m.Stats() if stats.LoadFactor > 0.7 { fmt.Printf("High load factor: %.3f\n", stats.LoadFactor) } } ``` -------------------------------- ### Resize Synchronization Example Source: https://github.com/jeremiah-masters/dlht/blob/main/design.md Illustrates the synchronization between a transfer thread publishing a new bin and an operation thread reading it. The `BinDoneTransfer` atomic store acts as a release point, and the subsequent header load acts as an acquire, ensuring visibility of writes to the new bin. ```go Transfer thread Operation thread ────────────────────────────────── ───────────────────────────────── // plain stores into newPb (the new-index bin) newSlot.Key = hash newSlot.Val = entry newPb.Header = ...SlotValid atomic.Store(&oldBin.Header, BinDoneTransfer) — release ─┐ │ synchronizes-with │ (when the acquire to │ the right observes │ BinDoneTransfer) └──▶ h := atomic.Load(&oldBin.Header) — acquire // h.getBinState() == BinDoneTransfer // ⇒ follow indexNext to newIdx, // re-attempt on newPb; the plain // writes above are visible here ``` -------------------------------- ### Inserting Only If New Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Shows how to use the Insert operation to add a value only if the key does not already exist. The boolean return value is used to check for pre-existence. ```go m := dlht.New[string, *User](opts) user := &User{ID: 1, Name: "Alice"} if _, inserted := m.Insert("alice", user); !inserted { fmt.Println("User alice already exists") } ``` -------------------------------- ### Atomic Increment Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Shows how to atomically increment a counter using the Put operation. The old value is retrieved and used in the update. ```go m := dlht.New[string, int](opts) m.Insert("counter", 0) if oldVal, updated := m.Put("counter", oldVal+1); updated { fmt.Printf("Counter incremented from %d to %d\n", oldVal, oldVal+1) } ``` -------------------------------- ### Example Usage of Inline Map Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/types.md Demonstrates creating a new inline Map for uint64 keys and Timestamp values, and inserting a timestamp. This map is optimized for integer values to reduce memory overhead. ```go type Timestamp uint64 // Count occurrences of IDs m := dlht.NewInline[Timestamp](dlht.Options{InitialSize: 1024}) m.Insert(12345, Timestamp(1719590400)) ``` -------------------------------- ### High Contention Insert Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Demonstrates inserting a large number of items concurrently across multiple goroutines. This tests the map's thread-safety and performance under high contention. ```go // Multiple threads inserting different keys var wg sync.WaitGroup m := dlht.New[int, int](dlht.Options{InitialSize: 16}) for workerID := range 10 { wg.Add(1) go func(id int) { defer wg.Done() for i := 0; i < 100; i++ { key := id*100 + i m.Insert(key, i) } }(workerID) } wg.Wait() fmt.Printf("Inserted %d items\n", m.Size()) ``` -------------------------------- ### DLHT Map Memory Estimation Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/constructor.md Calculates the estimated memory usage for a DLHT map with a specific initial size, including primary buckets, link arena, and per-entry overhead. ```go // Example: New[string, int](Options{InitialSize: 256}): // Primary buckets: 256 × 64 = 16 KB // Link arena: 256 × 64 = 16 KB // Per-entry: ~40 bytes × entries // Total: ~32 KB baseline + 40 × entries ``` -------------------------------- ### Get Function Signature Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Signature for the Get operation in Go. It retrieves a value by key and indicates if the key was found. ```go func (m *Map[K, V]) Get(key K) (V, bool) ``` -------------------------------- ### DLHT Constructor and Get Usage (No Error Returns) Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/errors.md DLHT constructors and the Get method do not return errors. Custom error types like NotFound or KeyExists are not available. ```go // These will not compile: m, err := dlht.New(opts) // No err return value, err := m.Get(key) // No err return if errors.Is(err, dlht.NotFound) { // No such type ``` -------------------------------- ### Concurrent Iteration and Mutation Example Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md This example demonstrates the thread safety of `Range` by iterating over a map while another goroutine concurrently inserts new elements. It uses `sync.WaitGroup` to coordinate the goroutines. ```go m := dlht.New[string, int](opts) for i := range 10 { m.Insert(fmt.Sprintf("key%d", i), i) } var wg sync.WaitGroup // Iterate while others mutate wg.Add(1) go func() { defer wg.Done() count := 0 m.Range(func(key string, value int) bool { count++ return true }) fmt.Printf("Saw %d entries\n", count) }() // Mutate while iterating wg.Add(1) go func() { defer wg.Done() for i := range 10, 20 { m.Insert(fmt.Sprintf("key%d", i), i) } }() wg.Wait() ``` -------------------------------- ### Initialize DLHT with Estimated Size Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Pre-allocate appropriately to avoid early resizes. Each bucket holds up to 15 entries; estimate accordingly. ```go expectedSize := 10000 buckets := nextPowerOf2(uint64(expectedSize) / 15) // 15 slots per bucket m := dlht.New[string, int](dlht.Options{InitialSize: buckets}) ``` -------------------------------- ### Initialize DLHT with Default Configuration Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Creates a map with 16 primary buckets. Use when the expected size is unknown or small. ```go m := dlht.New[string, int](dlht.Options{}) ``` -------------------------------- ### Get Map Size Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Retrieve the current number of entries in the map. This is useful for basic size checks. ```go size := m.Size() fmt.Printf("Map has %d entries\n", size) ``` -------------------------------- ### Basic DLHT Map Usage Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/constructor.md Demonstrates creating a new DLHT map with default and specified initial sizes, inserting a key-value pair, and retrieving it. ```go package main import ( "fmt" "github.com/jeremiah-masters/dlht" ) func main() { // Create with default size m := dlht.New[string, int](dlht.Options{}) // Create with specific size m := dlht.New[string, int](dlht.Options{InitialSize: 256}) // Insert and retrieve m.Insert("count", 42) if v, found := m.Get("count"); found { fmt.Printf("Count: %d\n", v) } } ``` -------------------------------- ### Get Source: https://github.com/jeremiah-masters/dlht/blob/main/README.md Retrieves a value associated with the given key. Returns the value and a boolean indicating if the key was found. ```APIDOC ## Get ### Description Retrieves a value associated with the given key. Returns the value and a boolean indicating if the key was found. ### Signature `Get(key K) (V, bool)` ### Parameters - **key** (K) - The key to look up. ``` -------------------------------- ### Initialize DLHT with Type-Specific Keys and Values Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Demonstrates creating maps with different key and value types, including custom structs and arrays as keys. ```go // String keys with integer values m1 := dlht.New[string, int](opts) // Integer IDs with complex values type UserID int64 type User struct { Name string Email string Active bool } m2 := dlht.New[UserID, *User](opts) // Array keys (cache keys) type CacheKey [32]byte m3 := dlht.New[CacheKey, []byte](opts) ``` -------------------------------- ### Contains Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Checks whether a key exists in the map without returning the value. This operation is equivalent to calling Get() and discarding the value. ```APIDOC ## Contains ### Description Checks whether a key exists in the map without returning the value. ### Method `Contains(key K) bool` ### Parameters #### Path Parameters - **key** (K) - Required - The key to check ### Return Type `bool` `true` if the key exists in the map, `false` otherwise. ### Behavior Equivalent to calling `Get()` and discarding the value. Implemented as: ```go _, found := m.Get(key) return found ``` ### Example ```go m := dlht.New[string, int](opts) m.Insert("alice", 1) if m.Contains("alice") { fmt.Println("Alice is in the map") } if !m.Contains("bob") { fmt.Println("Bob is not in the map") } ``` ### Performance Same as `Get()`: O(1) with high probability. ``` -------------------------------- ### Pre-allocate DLHT for Performance Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Shows how to pre-allocate a DLHT with an estimated size to avoid resizes during insertion, improving performance for large datasets. Confirms no resizes occurred via stats. ```go // Estimate 10K entries opts := dlht.Options{InitialSize: 1024} // ~15K capacity m := dlht.New[string, int](opts) // Insert 10K items for i := 0; i < 10000; i++ { m.Insert(fmt.Sprintf("key-%d", i), i) } // No resizes needed; stats confirm stats := m.Stats() fmt.Printf("Final load factor: %.3f\n", stats.LoadFactor) ``` -------------------------------- ### Check Key Existence with Contains Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/operations.md Use Contains to check if a key exists in the map without retrieving its value. This is equivalent to calling Get() and discarding the result. ```go func (m *Map[K, V]) Contains(key K) bool { _, found := m.Get(key) return found } ``` ```go m := dlht.New[string, int](opts) m.Insert("alice", 1) if m.Contains("alice") { fmt.Println("Alice is in the map") } if !m.Contains("bob") { fmt.Println("Bob is not in the map") } ``` -------------------------------- ### Generic Comparable Struct Keys Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Use a custom struct as a key in the map, provided it is comparable. This example demonstrates using a struct with string and int64 fields. ```go type Key struct { Org string ID int64 Type string } m := dlht.New[Key, *Data](opts) m.Insert(Key{"acme", 123, "user"}, &data) if v, found := m.Get(Key{"acme", 123, "user"}); found { process(v) } ``` -------------------------------- ### Migrate from sync.Map to DLHT Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Demonstrates the migration from Go's sync.Map to DLHT, highlighting the similar API for common operations like Store/Insert, Load/Get, Delete, and Range. ```go // Old code var m sync.Map // Migration m := dlht.New[string, interface{}](opts) // Type-specific values now possible // Usage: same API (mostly) // sync.Map: m.Store(k, v) → DLHT: m.Insert(k, v) // sync.Map: v, ok := m.Load(k) → DLHT: v, ok := m.Get(k) // sync.Map: m.Delete(k) → DLHT: m.Delete(k) // sync.Map: m.Range(fn) → DLHT: m.Range(fn) ``` -------------------------------- ### Filter Map Entries by Value Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md Iterate over all key-value pairs using `m.All()` and apply a condition to filter entries. This example collects values greater than 5. ```go // Collect entries with value > 5 filtered := []int{} for key, value := range m.All() { if value > 5 { filtered = append(filtered, value) } } ``` -------------------------------- ### Writing into the New Index with Plain Stores Source: https://github.com/jeremiah-masters/dlht/blob/main/design.md Demonstrates how writes into the new index are performed using plain stores after a bin transfer is complete. This is safe due to invariants ensuring each new bin has a single writer during the transfer process. ```go slot.Key = hash slot.Val = entry pb.Header = pb.Header.setSlotStateAndVersion(slotIndex, SlotValid) ``` -------------------------------- ### LinkMeta Structure Source: https://github.com/jeremiah-masters/dlht/blob/main/design.md The LinkMeta field (64 bits) in the primary bucket tracks attached link buckets, indicating the start of a link pair and the index for a single link. ```plaintext LinkMeta (64 bits) ┌────────────────────────────┬────────────────────────────┐ bit │ 63 32 │ 31 0 │ ├────────────────────────────┼────────────────────────────┤ │ PairStart │ Single │ │ (link pair index) │ (single link index) │ └────────────────────────────┴────────────────────────────┘ │ │ │ └─► Index into link arena │ (0 = NO_LINK, 1+ = valid) │ └─► Points to TWO consecutive buckets [PairStart] and [PairStart+1] ``` -------------------------------- ### String Keys (Common Usage) Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Utilize string types as keys, a common pattern for identifying resources like users or objects. ```go m := dlht.New[string, int](opts) m.Insert("user:12345", 1) m.Insert("user:67890", 2) ``` -------------------------------- ### Get Detailed Map Statistics Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/patterns.md Obtain comprehensive statistics about the map's internal state, including bin count, size, capacity, load factor, and resizing status. ```go stats := m.Stats() fmt.Printf("Bins: %d\n", stats.Bins) fmt.Printf("Size: %d\n", stats.Size) fmt.Printf("Capacity: %d\n", stats.Capacity) fmt.Printf("Load Factor: %.3f\n", stats.LoadFactor) fmt.Printf("Resizing: %v\n", stats.Resizing) ``` -------------------------------- ### Iterate Map Values Only Source: https://github.com/jeremiah-masters/dlht/blob/main/_autodocs/api-reference/iteration.md Use `Values()` to get an iterator that yields only the values from the map, suitable for loops where keys are not needed. This method internally calls `Range()` and filters out keys. ```go m := dlht.New[string, int](opts) m.Insert("apple", 5) m.Insert("banana", 3) m.Insert("cherry", 8) sum := 0 for value := range m.Values() { sum += value } fmt.Printf("Sum: %d\n", sum) ```