### Capacity Planning Example with Reservation Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Calculate and set initial capacity for a ClashMap, considering expected entries, shard count, and shard padding. Includes an example of reserving additional capacity. ```rust use clashmap::ClashMap; // Expected: 10 million entries, 64 threads let expected_entries = 10_000_000; let shards = 256; // 4x parallelism (64 * 4) let capacity_per_shard = (expected_entries + shards - 1) / shards; // ~40,000 let map = ClashMap::with_capacity_and_shard_amount( capacity_per_shard * shards, shards ); // Reserve additional capacity for growth map.try_reserve(expected_entries / 10).ok(); ``` -------------------------------- ### Minimal ClashMap Setup Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Creates a new ClashMap with default capacity and shard settings. ```rust use clashmap::ClashMap; // Minimal setup let map: ClashMap = ClashMap::new(); ``` -------------------------------- ### Non-Blocking Access with Fallback to Blocking Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Illustrates how to perform non-blocking access using `try_get` and fall back to blocking `get` if the shard is locked. This ensures data access while handling potential contention. ```rust use clashmap::{ClashMap, try_result::TryResult}; let map = ClashMap::new(); map.insert("key", 42); // Try non-blocking, fall back to blocking let value = match map.try_get("key") { TryResult::Present(r) => Some(*r), TryResult::Absent => None, TryResult::Locked => { eprintln!("Shard locked, using blocking access"); map.get("key").map(|r| *r) } }; ``` -------------------------------- ### Tune Shard Count for Workloads Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Examples of initializing ClashMap with different shard counts to optimize for read-heavy, write-heavy, or low-parallelism workloads. ```rust use clashmap::ClashMap; // Read-heavy workload: use default (allows concurrent reads) let map = ClashMap::new(); // Write-heavy, high contention: increase shards to reduce write conflicts let map = ClashMap::with_shard_amount(128); // Write-heavy, sparse keys: use default, high shards waste memory let map = ClashMap::new(); // Low parallelism (single-threaded or 2-4 threads): use fewer shards to save memory let map = ClashMap::with_shard_amount(4); ``` -------------------------------- ### Serde Serialization/Deserialization with ClashMap Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Example of deriving Serialize and Deserialize for a struct containing a ClashMap, enabled by the 'serde' feature. ```rust #[cfg(feature = "serde")] { use serde::{Serialize, Deserialize}; use clashmap::ClashMap; #[derive(Serialize, Deserialize)] struct MyData { map: ClashMap, } } ``` -------------------------------- ### Core Operations Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Details the fundamental methods for interacting with the ClashMap, including getting, inserting, removing, and checking for keys. ```APIDOC ## Core Operations ### `get(key)` Retrieves a reference to the value associated with the key. Acquires a read lock and may block. ### `get_mut(key)` Retrieves a mutable reference to the value associated with the key. Acquires a write lock and may block. ### `try_get(key)` Attempts to retrieve a reference to the value associated with the key without blocking. Returns `TryResult`. ### `try_get_mut(key)` Attempts to retrieve a mutable reference to the value associated with the key without blocking. Returns `TryResult`. ### `insert(key, value)` Inserts a key-value pair into the map. Acquires a write lock and may block. Returns the previous value if the key already existed. ### `remove(key)` Removes a key-value pair from the map. Acquires a write lock and may block. Returns the removed key-value pair if the key existed. ### `contains_key(key)` Checks if the map contains the specified key. Acquires a read lock and may block. ``` -------------------------------- ### Panicking on Downcast Failure with >> Operator Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Using the `>>` operator (equivalent to `get().unwrap()`) on a non-existent key will panic. Use `get()` with pattern matching for safe access. ```rust use clashmap::ClashMap; let map = ClashMap::new(); map.insert("exists", 42); // ✗ Panics: unwrap() on None let value = (&map >> &"nonexistent"); // Calls get("nonexistent").unwrap() // thread 'main' panicked at 'called `Option::unwrap()` on a `None` value' ``` -------------------------------- ### get Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Retrieves an immutable reference to a value associated with a given key. ```APIDOC ## `get(&self, key: &Q) -> Option>` ### Description Returns an immutable reference to a value by key. ### Method `get` ### Parameters #### Path Parameters - **key** (&Q) - Required - Key to look up ### Return `Option>` - A reference wrapper holding the read lock ### Requires Q: Hash + Equivalent + ?Sized ### Locking May deadlock if called while holding a mutable reference ``` -------------------------------- ### Safe Access with ClashMap::get() Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Safely access values in a `ClashMap` using `get()` and pattern matching (`if let Some(...)`) to avoid panics when a key might not exist. ```rust use clashmap::ClashMap; let map = ClashMap::new(); map.insert("exists", 42); // ✓ Safe: pattern match if let Some(r) = map.get("exists") { println!("Value: {}", *r); } ``` -------------------------------- ### Immutable Iterator Shard Locking Example Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONCURRENCY_AND_PATTERNS.md Demonstrates immutable iteration where other threads can modify different shards concurrently without blocking. ```rust let map = ClashMap::new(); map.insert("a", 1); map.insert("b", 2); let mut iter = map.iter(); let r1 = iter.next().unwrap(); // Lock on shard with "a" // Safe: other threads can still modify other shards map.insert("c", 3); // Different shard, not blocked println!("{}", r1.key()); // Still valid ``` -------------------------------- ### Try Get Mutable Reference (Non-blocking) Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Attempts to get a mutable reference without blocking. Returns `TryResult::Locked` if the shard is unavailable. ```rust use clashmap::try_result::TryResult; let map = ClashMap::new(); map.insert("count", 1); match map.try_get_mut("count") { TryResult::Present(mut r) => *r += 1, TryResult::Locked => println!("Shard locked"), _ => {} } ``` -------------------------------- ### Try Get Immutable Reference (Non-blocking) Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Attempts to get an immutable reference without blocking. Returns `TryResult::Locked` if the shard is currently unavailable. ```rust use clashmap::try_result::TryResult; let map = ClashMap::new(); map.insert("key", 42); match map.try_get("key") { TryResult::Present(r) => println!("Value: {}", *r), TryResult::Absent => println!("Not found"), TryResult::Locked => println!("Shard is locked"), } ``` -------------------------------- ### Initialization Methods Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Provides various ways to initialize a ClashMap with different configurations for capacity, hasher, and shard amount. ```APIDOC ## Initialization ### `new()` Creates a new ClashMap with default capacity, hasher, and shard settings. ### `with_capacity(n)` Creates a new ClashMap with a specified initial capacity `n`. ### `with_shard_amount(n)` Creates a new ClashMap with a specified number of shards `n`. ### `with_hasher(s)` Creates a new ClashMap with a custom hasher `s`. ### `with_capacity_and_hasher(c, s)` Creates a new ClashMap with specified capacity `c` and hasher `s`. ### `with_hasher_and_shard_amount(s, n)` Creates a new ClashMap with a custom hasher `s` and shard amount `n`. ### `with_capacity_and_hasher_and_shard_amount(c, s, n)` Creates a new ClashMap with specified capacity `c`, hasher `s`, and shard amount `n`. ``` -------------------------------- ### ClashMap Get Locking Behavior Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Documents the locking behavior for the `get` method, indicating it may deadlock if called while holding a mutable reference into the map. ```rust pub fn get(&self, key: &Q) -> Option> where Q: Hash + Equivalent + ?Sized, { // "**Locking behaviour:** May deadlock if called when holding a mutable reference into the map." } ``` -------------------------------- ### Constructing a ClashMap Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Demonstrates various ways to create a new ClashMap instance, from minimal to pre-sized with custom shard amounts. ```rust ClashMap::new() // Minimal ClashMap::with_capacity(1000) // Pre-sized ClashMap::with_shard_amount(64) // Custom shards ClashMap::with_capacity_and_shard_amount(1000, 64) // Both ``` -------------------------------- ### ClashMap Shard Configuration Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Demonstrates how to create a ClashMap with default or explicit shard amounts. The default is calculated based on available parallelism. ```rust let map = ClashMap::new(); // Uses default shard amount let map = ClashMap::with_shard_amount(32); // Explicit shard count ``` -------------------------------- ### ClashMap with All Constructor Options Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Initializes a ClashMap with capacity, a custom hasher, and a specific shard amount. ```rust // All options let map = ClashMap::with_capacity_and_hasher_and_shard_amount(100, hasher, 32); ``` -------------------------------- ### Create ClashMap with All Parameters Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with capacity, custom hasher, and shard amount all specified. Provides maximum configuration flexibility. ```rust let hasher = RandomState::new(); let map = ClashMap::with_capacity_and_hasher_and_shard_amount(100, hasher, 32); ``` -------------------------------- ### Get Map Length Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Returns the total number of key-value pairs stored in the map across all its shards. ```rust let map = ClashMap::new(); map.insert("a", 1); map.insert("b", 2); assert_eq!(map.len(), 2); ``` -------------------------------- ### ClashMap Crate Dependencies Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/MODULE_STRUCTURE.md Lists the dependencies for the clashmap crate, including internal, direct, and optional dependencies. ```text clashmap (v1.3.0) ├── clashcore (v1.0.0) [internal dependency] ├── hashbrown (v0.15.0) [hash table implementation] ├── crossbeam-utils (v0.8) [cache padding, thread utilities] ├── replace_with (v0.1.7) [closure-based replacement] ├── [optional] rayon [parallel iteration] ├── [optional] serde [serialization] └── [optional] typesize [memory profiling] clashcore (v1.0.0) ├── lock_api (v0.4.10) [lock traits] ├── parking_lot_core (v0.9.10) [efficient spinlock] ├── crossbeam-utils (v0.8) [cache padding, utilities] ├── polonius-the-crab (v0.5.0) [borrow checker polyfill] └── [optional] typesize [memory profiling] ``` -------------------------------- ### Initialize ClashMap with a Custom Hasher Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Create a ClashMap instance using a custom hasher, such as RandomState for cryptographic security or FxHash for speed. Requires the custom hasher to implement BuildHasher. ```rust use clashmap::ClashMap; use std::collections::hash_map::RandomState; // Custom hasher example (requires implementing BuildHasher) let hasher = RandomState::new(); let map = ClashMap::with_hasher(hasher); ``` -------------------------------- ### Accessing Raw API Information Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Demonstrates how to access raw API information like shards, shard index, and shard hash using the 'raw-api' feature. ```rust #[cfg(feature = "raw-api")] { let shards = map.shards(); let shard_idx = map.determine_map("key"); let shard_hash = map.hash_usize("key"); } ``` -------------------------------- ### Get Immutable Reference to Value Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Retrieves an immutable reference to a value associated with a key. This method acquires a read lock. ```rust let map = ClashMap::new(); map.insert("key", 42); if let Some(r) = map.get("key") { println!("Value: {}", *r); } ``` -------------------------------- ### Construction Methods Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Methods for creating new ClashMap instances with various configurations. ```APIDOC ## Construction Methods ### Description Methods for creating new ClashMap instances with various configurations. ### Methods - `ClashMap::new()`: Creates a minimal ClashMap instance. - `ClashMap::with_capacity(capacity: usize)`: Creates a ClashMap instance with a pre-defined capacity. - `ClashMap::with_shard_amount(shards: usize)`: Creates a ClashMap instance with a custom number of shards. - `ClashMap::with_capacity_and_shard_amount(capacity: usize, shards: usize)`: Creates a ClashMap instance with both a pre-defined capacity and a custom number of shards. ``` -------------------------------- ### Enabling ClashMap Features in Cargo.toml Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Shows how to enable the 'serde' and 'rayon' features for ClashMap in your Cargo.toml file. ```toml [dependencies] clashmap = { version = "1.3", features = ["serde", "rayon"] } ``` -------------------------------- ### Initialize ClashMap with Capacity and Shard Amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Create a ClashMap instance with a specified initial capacity and number of shards. This is useful for pre-allocating memory and optimizing for specific thread counts. ```rust let map = ClashMap::with_capacity_and_shard_amount(1_000_000, 64); ``` -------------------------------- ### Non-Blocking Get Operation Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONCURRENCY_AND_PATTERNS.md Utilizes `try_get` for non-blocking retrieval of a value from ClashMap. This is useful for low-latency applications that cannot afford to block waiting for locks. ```rust use clashmap::try_result::TryResult; let map = ClashMap::new(); map.insert("key", 42); match map.try_get("key") { TryResult::Present(r) => println!("{}", *r), TryResult::Absent => println!("Not found"), TryResult::Locked => println!("Shard busy, retry later"), } ``` -------------------------------- ### Get Mutable Reference to Value Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Retrieves a mutable reference to a value associated with a key. This method acquires a write lock and should be used when modifying values. ```rust let map = ClashMap::new(); map.insert("count", 1); if let Some(mut r) = map.get_mut("count") { *r += 1; } ``` -------------------------------- ### Serialize and Deserialize ClashMap with Serde Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Demonstrates serializing a ClashMap to JSON and deserializing it back. Requires the `serde` feature to be enabled. Serialization order is non-deterministic. ```rust #[cfg(feature = "serde")] { use clashmap::ClashMap; use serde_json; let map = ClashMap::new(); map.insert("key", 42); let json = serde_json::to_string(&map).unwrap(); let deserialized: ClashMap = serde_json::from_str(&json).unwrap(); } ``` -------------------------------- ### Create New ClashMap Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with default settings. Use this for general-purpose concurrent hashmap needs. ```rust use clashmap::ClashMap; let map = ClashMap::new(); map.insert("key", "value"); ``` -------------------------------- ### Detect Locked Shard with Try Get Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONCURRENCY_AND_PATTERNS.md Uses `try_get` to attempt fetching a key, returning `TryResult::Locked` if the shard is currently held by another operation. ```rust use clashmap::try_result::TryResult; let mut retries = 0; loop { match map.try_get("key") { TryResult::Present(r) => { println!("Success on attempt {}", retries + 1); break; } TryResult::Locked => { retries += 1; if retries > 10 { eprintln!("High contention on shard"); break; } std::thread::yield_now(); } TryResult::Absent => { eprintln!("Key not found"); break; } } } ``` -------------------------------- ### Get Default Shard Amount Function Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/TYPES.md Defines the default_shard_amount function, which returns the default shard count based on available parallelism. This value is cached after the first call. ```rust pub fn default_shard_amount() -> usize ``` -------------------------------- ### ClashMap with Capacity and Shard Amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Configures a ClashMap with both an initial capacity hint and a custom number of shards. ```rust // Capacity + shards let map = ClashMap::with_capacity_and_shard_amount(1000, 64); ``` -------------------------------- ### Parallel Iteration with Rayon Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md This snippet demonstrates batch processing using parallel iteration provided by the 'rayon' feature. It maps and collects results concurrently. ```rust #[cfg(feature = "rayon")] { use rayon::prelude::*; let results: Vec<_> = data .par_iter() .map(|(key, value)| { map.entry(key).or_insert(Vec::new()).push(value); }) .collect(); } ``` -------------------------------- ### Get ClashMap capacity Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md The `capacity` method returns the number of key-value pairs the map can hold before it needs to reallocate memory. This can be used for performance optimizations by pre-allocating sufficient space. ```rust let map = ClashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### ClashMap Immutable Reference Guard Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Shows how to retrieve an immutable reference to a value in ClashMap using `get()`. The returned `Ref` guard holds the read lock until it goes out of scope. ```rust let map = ClashMap::new(); map.insert("key", 42); let r = map.get("key"); // Returns Option // Ref holds read lock until dropped match r { Some(entry) => println!("{}", *entry), // Deref to value None => println!("Not found"), } // Lock released when entry goes out of scope ``` -------------------------------- ### ClashMap Reservation with Explicit Error Handling Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Demonstrates how to use `try_reserve` with explicit error handling. This allows for pre-allocation of capacity and provides a fallback mechanism if allocation fails. ```rust use clashmap::ClashMap; let mut map: ClashMap> = ClashMap::new(); // Reserve with explicit error handling match map.try_reserve(100_000) { Ok(()) => { // Capacity guaranteed for ~100k more elements for i in 0..100_000 { map.insert(format!("key{}", i), vec![0u8; 1024]); } } Err(TryReserveError {}) => { eprintln!("Failed to allocate; using without pre-allocated space"); // Map continues to work, but may allocate more frequently } } ``` -------------------------------- ### Low-Latency Lookups with TryGet Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Illustrates how to perform non-blocking lookups using `try_get` to avoid contention on hot keys. It retries or returns a default value if the key is locked or absent. ```rust use clashmap::try_result::TryResult; // Avoid blocking on contended keys loop { match cache.try_get("hot_key") { TryResult::Present(r) => return *r, TryResult::Locked => std::thread::yield_now(), // Try again TryResult::Absent => return default_value(), } } ``` -------------------------------- ### Entry<'a, K, V> Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/TYPES.md Represents either an occupied or vacant entry in a ClashMap, allowing advanced manipulation. It can be used to get or insert values, modify existing entries, or retrieve keys. ```APIDOC ## Entry<'a, K, V> ### Description Represents either an occupied or vacant entry in a ClashMap, allowing advanced manipulation. ### Variants - **Occupied**: Entry exists in the map - **Vacant**: Entry does not exist in the map ### Methods - `and_modify(self, f: impl FnOnce(&mut V)) -> Self` — Applies function to value if occupied - `key(&self) -> &K` — Returns the key - `into_key(self) -> K` — Consumes entry, returning the key - `or_default(self) -> RefMut<'a, K, V>` where V: Default — Gets or inserts default - `or_insert(self, value: V) -> RefMut<'a, K, V>` — Gets or inserts value - `or_insert_with(self, f: impl FnOnce() -> V) -> RefMut<'a, K, V>` — Gets or inserts via closure - `or_try_insert_with(self, f: impl FnOnce() -> Result) -> Result, E>` — Gets or tries to insert - `insert(self, value: V) -> RefMut<'a, K, V>` — Sets value and returns reference - `insert_entry(self, value: V) -> OccupiedEntry<'a, K, V>` where K: Clone — Sets value and returns occupied entry ``` -------------------------------- ### Safe Closure Logic in ClashMap::alter Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Ensure closures used with `alter` do not panic to avoid process abortion. This example shows a safe closure that returns a value without panicking. ```rust use clashmap::ClashMap; let map = ClashMap::new(); map.insert("count", 5); // ✓ Safe: no panic risk map.alter("count", |_k, v| { if v > 0 { v * 2 } else { 1 } }); ``` -------------------------------- ### ClashMap Entry API for Atomic Operations Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Demonstrates the Entry API for atomically checking if a key exists and either updating its value or inserting a new one. This is analogous to `std::collections::HashMap`'s Entry API. ```rust match map.entry("counter") { clashmap::Entry::Occupied(mut e) => { e.insert(*e.get() + 1); } clashmap::Entry::Vacant(e) => { e.insert(1); } } ``` -------------------------------- ### Get or insert entry in ClashMap (immutable) Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md The `entry` method returns an `Entry` enum, which can be either `Occupied` or `Vacant`. This API allows for conditional insertion or modification of values based on key presence. ```rust let map = ClashMap::new(); match map.entry("key") { clashmap::Entry::Occupied(mut e) => { e.insert(20); } // This branch won't be taken on a new map clashmap::Entry::Vacant(e) => { e.insert(10); } // This branch will be taken } ``` -------------------------------- ### ClashMap::with_capacity_and_hasher_and_shard_amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with all three parameters specified: capacity, hasher, and shard amount. This offers the most control over the map's initialization. ```APIDOC ## ClashMap::with_capacity_and_hasher_and_shard_amount ### Description Creates a new ClashMap with all three parameters specified. ### Method `with_capacity_and_hasher_and_shard_amount(capacity: usize, hasher: S, shard_amount: usize)` ### Parameters #### Path Parameters - **capacity** (usize) - Required - Initial capacity - **hasher** (S) - Required - BuildHasher implementation - **shard_amount** (usize) - Required - Number of shards (must be power of 2) ### Return `ClashMap` ``` -------------------------------- ### Get or insert entry in ClashMap (mutable) Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md The `entry_mut` method provides mutable access to an entry, returning either `EntryMut::Occupied` or `EntryMut::Vacant`. This is used for modifying existing entries or inserting new ones when a mutable reference to the map is available. ```rust let mut map = ClashMap::new(); match map.entry_mut("key") { clashmap::EntryMut::Occupied(mut e) => { e.insert(20); } // This branch won't be taken on a new map clashmap::EntryMut::Vacant(e) => { e.insert(10); } // This branch will be taken } ``` -------------------------------- ### ClashMap::new Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a capacity of 0 and default RandomState hasher. This is a constructor for initializing an empty ClashMap. ```APIDOC ## ClashMap::new ### Description Creates a new ClashMap with a capacity of 0 and default `RandomState` hasher. ### Method `new()` ### Parameters None ### Return `ClashMap` where K: Eq + Hash, V: any ### Requires K: Eq + Hash ``` -------------------------------- ### Simple Thread-Safe Key-Value Store Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Demonstrates creating a thread-safe cache using ClashMap wrapped in an Arc. Multiple threads can safely insert data into the map. ```rust use clashmap::ClashMap; use std::sync::Arc; let cache = Arc::new(ClashMap::new()); // Spawn threads for i in 0..4 { let cache = Arc::clone(&cache); std::thread::spawn(move || { cache.insert(format!("key{}", i), i * 100); }); } ``` -------------------------------- ### Create ClashMap with Capacity and Custom Hasher Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a specified capacity and a custom hasher. Combines performance tuning with custom hashing logic. ```rust let hasher = RandomState::new(); let map = ClashMap::with_capacity_and_hasher(100, hasher); ``` -------------------------------- ### ClashMap with Capacity and Custom Hasher Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Configures a ClashMap with an initial capacity and a custom hash builder. ```rust // Capacity + custom hasher let map = ClashMap::with_capacity_and_hasher(100, hasher); ``` -------------------------------- ### ClashMap with Capacity Hint Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Initializes a ClashMap with a specified initial capacity per shard. ```rust // With capacity hint let map = ClashMap::with_capacity(1000); ``` -------------------------------- ### Cloning a ClashMap Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Demonstrates deep copying a ClashMap. Requires K, V, and S to implement Clone. ```rust let map1 = ClashMap::new(); map1.insert("key", 42); let map2 = map1.clone(); assert_eq!(*map2.get("key").unwrap(), 42); ``` -------------------------------- ### ClashMap::with_capacity_and_hasher Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with specified capacity and a custom hasher. Combines initial memory allocation with custom hashing. ```APIDOC ## ClashMap::with_capacity_and_hasher ### Description Creates a new ClashMap with capacity and custom hasher. ### Method `with_capacity_and_hasher(capacity: usize, hasher: S)` ### Parameters #### Path Parameters - **capacity** (usize) - Required - Initial capacity - **hasher** (S) - Required - BuildHasher implementation ### Return `ClashMap` ``` -------------------------------- ### ClashMap with Custom Hasher Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Initializes a ClashMap using a provided custom hash builder. ```rust use clashmap::ClashMap; use std::collections::hash_map::RandomState; // Custom hasher let hasher = RandomState::new(); let map = ClashMap::with_hasher(hasher); ``` -------------------------------- ### ClashMap::with_capacity_and_shard_amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with specified capacity and shard amount. This constructor allows fine-tuning of initial memory allocation and concurrency. ```APIDOC ## ClashMap::with_capacity_and_shard_amount ### Description Creates a new ClashMap with specified capacity and shard amount. ### Method `with_capacity_and_shard_amount(capacity: usize, shard_amount: usize)` ### Parameters #### Path Parameters - **capacity** (usize) - Required - Initial capacity - **shard_amount** (usize) - Required - Number of shards (must be power of 2) ### Return `ClashMap` ``` -------------------------------- ### Accessing Raw Shard API Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Demonstrates using the low-level shard access functions like `shards()` and `determine_map()`, enabled by the 'raw-api' feature. ```rust #[cfg(feature = "raw-api")] { use clashmap::ClashMap; let map = ClashMap::new(); let shard_count = map.shards().len(); let shard_idx = map.determine_map("key"); } ``` -------------------------------- ### into_shards Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Consumes the ClashMap and returns its internal shards as a boxed slice. This operation requires the `raw-api` feature. ```APIDOC ## `into_shards(self) -> Box<[Shard]>` Consumes the ClashMap and returns the inner shards. ### Return `Box<[CachePadded>>]>` ### Requires `raw-api` feature enabled ``` -------------------------------- ### Create ClashMap with Custom Hasher and Shard Amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a custom hasher and a specified shard amount. Allows for advanced control over hashing and concurrency. ```rust let hasher = RandomState::new(); let map = ClashMap::with_hasher_and_shard_amount(hasher, 32); ``` -------------------------------- ### ClashSet Constructors Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Constructors for creating a new ClashSet. ```APIDOC ## ClashSet Constructors ### `new() -> Self` Creates a new empty ClashSet. ### `with_capacity(capacity: usize) -> Self` Creates a ClashSet with specified capacity. ### `with_hasher(hasher: S) -> Self` Creates a ClashSet with a custom hasher. ### `with_capacity_and_hasher(capacity: usize, hasher: S) -> Self` Creates a ClashSet with capacity and custom hasher. ``` -------------------------------- ### Create ClashMap with Capacity Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a specified initial capacity. Useful for performance optimization when the approximate size is known. ```rust let map = ClashMap::with_capacity(100); ``` -------------------------------- ### ClashMap with Custom Hasher and Shard Amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Creates a ClashMap with a custom hash builder and a specified number of shards. ```rust // Shard count + custom hasher let map = ClashMap::with_hasher_and_shard_amount(hasher, 32); ``` -------------------------------- ### Thread-Safe Serialization with Serde Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONCURRENCY_AND_PATTERNS.md Shows how to serialize a ClashMap instance using the serde feature, even while other threads might be modifying it. The serialization provides a snapshot, but it is not an atomic operation. ```rust #[cfg(feature = "serde")] { use serde_json; let map = ClashMap::new(); map.insert("key", 42); // Safe to serialize while other threads are modifying let json = serde_json::to_string(&map).unwrap(); } ``` -------------------------------- ### Count Aggregation with Entry API Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Shows how to use the entry API of ClashMap for atomic count aggregation. It handles both existing and new entries efficiently. ```rust use clashmap::ClashMap; let counts = ClashMap::new(); // Increment atomically counts.entry("errors").or_insert(0).replace(counts.get("errors").map(|r| *r + 1).unwrap_or(1)); // Or simpler with entry API match counts.entry("errors") { clashmap::Entry::Occupied(mut e) => { e.insert(*e.get() + 1); } clashmap::Entry::Vacant(e) => { e.insert(1); } } ``` -------------------------------- ### ClashMap::with_capacity Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a specified initial capacity. This is useful for pre-allocating memory if the expected size is known. ```APIDOC ## ClashMap::with_capacity ### Description Creates a new ClashMap with a specified capacity. ### Method `with_capacity(capacity: usize)` ### Parameters #### Path Parameters - **capacity** (usize) - Required - Initial capacity hint ### Return `ClashMap` ``` -------------------------------- ### Insert into ClashSet Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Demonstrates inserting elements into a ClashSet and checking for duplicates. Use when you need set-like behavior with concurrent access. ```rust let set = ClashSet::new(); assert!(set.insert("a")); assert!(!set.insert("a")); ``` -------------------------------- ### Create ClashMap with Shard Amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a specified number of shards. The shard amount must be a power of two. This impacts concurrency performance. ```rust let map = ClashMap::with_shard_amount(32); ``` -------------------------------- ### entry_ref Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Provides entry API access for borrowed key references. Allows checking if a key exists and either accessing its value or inserting a new one. ```APIDOC ## `entry_ref(&self, key: &Q) -> EntryRef<'_, K, V>` Entry API for borrowed key references. ### Parameters #### Path Parameters - key (Q) - Required - Key to access ### Return `EntryRef<'_, K, V>` - Reference-based entry ### Requires Q: Hash + Equivalent + ?Sized, K: Clone + Hash ### Example ```rust let map = ClashMap::new(); match map.entry_ref("key") { clashmap::EntryRef::Occupied(e) => { println!("{:?}", e.get()); } clashmap::EntryRef::Vacant(e) => { e.insert(10); } } ``` ``` -------------------------------- ### Parallel Iteration with Rayon Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Shows how to perform parallel iteration over ClashMap entries using `par_iter` and `par_iter_mut`, enabled by the 'rayon' feature. ```rust #[cfg(feature = "rayon")] { use clashmap::ClashMap; use rayon::prelude::*; let map = ClashMap::new(); map.insert("a", 1); map.insert("b", 2); // Parallel iteration over references map.par_iter().for_each(|r| { println!("{}: {}", r.key(), r.value()); }); // Parallel iteration over mutable references map.par_iter_mut().for_each(|mut r| { *r.value_mut() += 1; }); } ``` -------------------------------- ### ClashTable Constructors Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Constructors for creating a new ClashTable. ```APIDOC ## ClashTable Constructors ### `new() -> Self` Creates a new empty ClashTable. ### `with_capacity(capacity: usize) -> Self` Creates a ClashTable with specified capacity. ### `with_shard_amount(shard_amount: usize) -> Self` Creates a ClashTable with specified shard count (must be power of 2). ### `with_capacity_and_shard_amount(capacity: usize, shard_amount: usize) -> Self` Creates a ClashTable with capacity and shard count. ``` -------------------------------- ### Access Methods Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Methods for retrieving values associated with keys from the ClashMap. ```APIDOC ## Access Methods ### Description Methods for retrieving values associated with keys from the ClashMap. ### Methods - `map.get(key)`: Returns an `Option` to the value associated with the key, if it exists. - `map.get_mut(key)`: Returns an `Option` to the mutable value associated with the key, if it exists. - `map.try_get(key)`: Attempts to retrieve a reference to the value, returning a `TryResult`. - `map.contains_key(key)`: Returns `true` if the map contains the specified key, `false` otherwise. ``` -------------------------------- ### Entry Operations Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Details the atomic entry API for efficient conditional insertion or modification of values based on key presence. ```APIDOC ## Entry Operations ### `entry(key)` Returns an `Entry` enum for the given key, allowing atomic checking and modification. Variants: `Occupied`, `Vacant`. ### `entry_ref(key)` Returns an `EntryRef` enum for the given key, similar to `entry` but for borrowed keys. Variants: `Occupied` (borrowed key), `Vacant`. ### `entry_mut(&mut self, key)` Returns an `EntryMut` enum for the given key, allowing mutable access and modification. Variants: `Occupied`, `Vacant`. ``` -------------------------------- ### EntryMut<'a, K, V> Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/TYPES.md Mutable variant of Entry, used when borrowing &mut self. It allows for modification of map entries when mutable access is required. ```APIDOC ## EntryMut<'a, K, V> ### Description Mutable variant of Entry, used when borrowing &mut self. ### Variants - **Occupied**: Entry exists in the map - **Vacant**: Entry does not exist in the map ### Usage This type is used by `ClashMap::entry_mut(&mut self, key: K) -> EntryMut<'_, K, V>`. ``` -------------------------------- ### Create Readonly Snapshot Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Shows how to create a read-only snapshot of the ClashMap using `into_read_only()`. This view is safe for concurrent read-only access without lock overhead. ```rust let map = ClashMap::new(); // ... populate ... let view = map.into_read_only(); // Now safe for concurrent readonly access without lock overhead let val = view.get("key"); ``` -------------------------------- ### Integrate with Typesize Crate Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Enable the 'typesize' feature to integrate ClashMap with the typesize crate for memory profiling. Requires K, V, and S to implement the TypeSize trait. ```rust #[cfg(feature = "typesize")] { use clashmap::ClashMap; use typesize::TypeSize; let map = ClashMap::new(); map.insert("a", vec![1, 2, 3]); println!("Extra size: {}", map.extra_size()); } ``` -------------------------------- ### Converting to a Read-Only View Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md The `into_read_only` method consumes the `ClashMap` and returns an immutable `ReadOnlyView` of its contents. ```rust let map = ClashMap::new(); map.insert("a", 1); let view = map.into_read_only(); ``` -------------------------------- ### Attempting to Reserve Capacity Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Use `try_reserve` to attempt to allocate additional capacity for the map. It returns an error if capacity overflows. ```rust let mut map: ClashMap = ClashMap::new(); map.try_reserve(100).expect("allocation failed"); ``` -------------------------------- ### ClashMap::with_hasher_and_shard_amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap with a custom hasher and a specified shard amount. This allows for customized hashing and concurrency tuning. ```APIDOC ## ClashMap::with_hasher_and_shard_amount ### Description Creates a new ClashMap with custom hasher and shard amount. ### Method `with_hasher_and_shard_amount(hasher: S, shard_amount: usize)` ### Parameters #### Path Parameters - **hasher** (S) - Required - BuildHasher implementation - **shard_amount** (usize) - Required - Number of shards (must be power of 2) ### Return `ClashMap` ``` -------------------------------- ### Iterating Over ClashMap Contents Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Demonstrates how to iterate over the elements of the ClashMap, including mutable and owning iterators. ```rust map.iter() // Iter map.iter_mut() // IterMut map.into_iter() // OwningIter<(K, V)> ``` -------------------------------- ### Create ClashMap with Custom Hasher Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Creates a new ClashMap using a provided custom hasher. This is useful for specialized hashing requirements. ```rust use std::collections::hash_map::RandomState; let hasher = RandomState::new(); let map = ClashMap::with_hasher(hasher); ``` -------------------------------- ### Shard Selection Algorithm Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONCURRENCY_AND_PATTERNS.md Calculates the shard index for a given hash and shard count. Preserves hashbrown's SIMD tag by shifting left by 7 bits. ```rust fn select_shard(hash: u64, shard_count: usize) -> usize { let shift = usize::BITS - shard_count.trailing_zeros(); let idx = (hash << 7) >> shift; // Left shift by 7 to preserve hashbrown SIMD tag idx } ``` -------------------------------- ### Accessing Elements in ClashMap Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Shows how to retrieve elements from the map using different methods, including mutable and fallible access. ```rust map.get(key) // Option map.get_mut(key) // Option map.try_get(key) // TryResult map.contains_key(key) // bool ``` -------------------------------- ### Handle TryReserveError with Exponential Backoff Retry Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Provides a strategy for retrying capacity reservation using exponential backoff. If `try_reserve` fails, the requested capacity is halved, and the attempt is retried until successful or the capacity becomes too small. ```rust use clashmap::ClashMap; let mut map: ClashMap = ClashMap::new(); // Exponential backoff retry fn reserve_with_retry(map: &mut ClashMap, mut requested: usize) -> Result<(), ()> { loop { match map.try_reserve(requested) { Ok(()) => return Ok(()), Err(_) if requested > 1000 => { requested = requested / 2; eprintln!("Retrying with capacity: {}", requested); } Err(_) => return Err(()), } } } reserve_with_retry(&mut map, 10_000_000).ok(); ``` -------------------------------- ### Handle TryReserveError with Fallback Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/ERRORS.md Illustrates how to handle `TryReserveError` by implementing a graceful fallback mechanism. If reservation fails, it prints an error and continues using the map with its current capacity. ```rust use clashmap::ClashMap; let mut map: ClashMap = ClashMap::new(); // Attempt with graceful fallback match map.try_reserve(1_000_000) { Ok(()) => println!("Reserved successfully"), Err(TryReserveError {}) => { eprintln!("Failed to reserve 1M elements"); // Fallback: use map as-is, capacity() may be less than expected println!("Continuing with current capacity: {}", map.capacity()); } } ``` -------------------------------- ### ClashMap with Custom Shard Amount Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Creates a ClashMap with a specific number of shards, useful for fine-tuning contention. ```rust // Custom shard count (for fine-tuning contention) let map = ClashMap::with_shard_amount(64); ``` -------------------------------- ### RefMut Methods Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Methods available on the mutable reference wrapper RefMut. ```APIDOC ## RefMut Methods ### `key(&self) -> &K` Returns the key. ### `value(&self) -> &V` Returns an immutable reference to the value. ### `value_mut(&mut self) -> &mut V` Returns a mutable reference to the value. ### `pair(&self) -> (&K, &V)` Returns key-value pair. ### `pair_mut(&mut self) -> (&K, &mut V)` Returns key and mutable value. ### `downgrade(self) -> Ref<'a, K, V>` Converts a RefMut into an immutable Ref. ### `map(self, f: F) -> RefMut<'a, K, T>` Transforms the value using a closure. ### `try_map(self, f: F) -> Result, Self>` Attempts to transform the value, returning Ok with new RefMut or Err with original. ``` -------------------------------- ### Non-blocking Entry Access Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Use `try_entry` for non-blocking entry access. It returns `Some(Entry)` if the shard is not locked, otherwise `None`. ```rust if let Some(entry) = map.try_entry("key") { entry.or_insert(10); } ``` -------------------------------- ### try_entry Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/API_REFERENCE.md Provides non-blocking entry access. Returns None if the shard is locked, otherwise returns an Entry for modification. ```APIDOC ## `try_entry(&self, key: K) -> Option>` Non-blocking entry access. Returns None if shard is locked. ### Parameters #### Path Parameters - key (K) - Required - Key to access ### Return `Option>` - Entry if shard not locked ### Requires K: Eq + Hash ### Example ```rust if let Some(entry) = map.try_entry("key") { entry.or_insert(10); } ``` ``` -------------------------------- ### ClashMap Public Exports Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/MODULE_STRUCTURE.md Lists the public exports from the clashmap crate's lib.rs file, including modules and re-exported types. ```rust pub mod iter; pub mod iter_set; pub mod mapref; pub mod setref; pub mod tableref; pub mod try_result; pub mod rayon; pub use clashcore::lock::{RwLock, RawRwLock}; pub use clashcore::sharded::ClashCollection; pub use map::ClashMap; pub use mapref::entry::{Entry, OccupiedEntry, VacantEntry}; pub use mapref::entry_ref::{EntryRef, VacantEntryRef}; pub use read_only::ReadOnlyView; pub use set::ClashSet; pub use table::ClashTable; pub struct TryReserveError; ``` -------------------------------- ### Enable Aggressive Inlining Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/CONFIGURATION.md Add the 'inline' feature to the clashmap dependency for more aggressive function inlining. This can improve runtime performance but will increase compile times. ```toml [dependencies] clashmap = { version = "1.3", features = ["inline"] } ``` -------------------------------- ### Iteration Methods Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Methods for iterating over the elements within the ClashMap. ```APIDOC ## Iteration Methods ### Description Methods for iterating over the elements within the ClashMap. ### Methods - `map.iter()`: Returns an iterator over references to the map's elements (`Iter`). - `map.iter_mut()`: Returns an iterator over mutable references to the map's elements (`IterMut`). - `map.into_iter()`: Returns an iterator that takes ownership of the map and its elements (`OwningIter<(K, V)>`). ``` -------------------------------- ### Inspection Methods Source: https://github.com/conradludgate/clashmap/blob/main/_autodocs/INDEX.md Methods for inspecting the current state and properties of the ClashMap. ```APIDOC ## Inspection Methods ### Description Methods for inspecting the current state and properties of the ClashMap. ### Methods - `map.len()`: Returns the number of elements in the map as a `usize`. - `map.is_empty()`: Returns `true` if the map contains no elements, `false` otherwise. - `map.capacity()`: Returns the current capacity of the map as a `usize`. ```