### Initialize DashMap with Custom Hasher (Rust) Source: https://context7.com/xacrimon/dashmap/llms.txt Shows how to create a DashMap using a custom hash builder, such as `RandomState`. This allows for specialized hashing strategies. The examples demonstrate initializing with just a hasher, or with hasher combined with capacity and shard count for performance tuning. ```rust use dashmap::DashMap; use std::collections::hash_map::RandomState; use std::hash::BuildHasher; // Use custom hasher let hasher = RandomState::new(); let map = DashMap::with_hasher(hasher); map.insert("key", "value"); // With capacity and hasher let map = DashMap::with_capacity_and_hasher(1000, RandomState::new()); // With shard amount and hasher for fine control let map = DashMap::with_hasher_and_shard_amount(RandomState::new(), 16); // Full control over capacity, hasher, and shards let map = DashMap::with_capacity_and_hasher_and_shard_amount( 1000, RandomState::new(), 32, ); map.insert(42, "answer"); ``` -------------------------------- ### Reading Values from DashMap (Rust) Source: https://context7.com/xacrimon/dashmap/llms.txt Explains how to read values from a DashMap. Includes methods for getting immutable references (`get`), mutable references (`get_mut`), non-blocking checks (`try_get`), and checking for key existence (`contains_key`). ```rust use dashmap::DashMap; let map = DashMap::new(); map.insert("rust", "fast"); map.insert("go", "simple"); // Get immutable reference if let Some(value) = map.get("rust") { assert_eq!(*value, "fast"); // value is a Ref guard, automatically releases lock when dropped } // Get mutable reference if let Some(mut value) = map.get_mut("go") { *value = "concurrent"; } assert_eq!(*map.get("go").unwrap(), "concurrent"); // Non-blocking try operations match map.try_get("rust") { dashmap::try_result::TryResult::Present(val) => println!("{}", *val), dashmap::try_result::TryResult::Absent => println!("Not found"), dashmap::try_result::TryResult::Locked => println!("Shard locked, try later"), } // Check existence without locking value assert!(map.contains_key("rust")); ``` -------------------------------- ### DashMap Advanced Entry API: Manipulate, Insert, and Compute Entries Source: https://context7.com/xacrimon/dashmap/llms.txt Demonstrates advanced entry manipulation in DashMap, including modifying existing entries, inserting default values if absent, and computing values with error handling. It shows how to get a mutable reference to an entry or insert a new one. ```rust use dashmap::DashMap; let map = DashMap::new(); // Complex entry manipulation let entry = map.entry("user_id"); entry .and_modify(|id| *id += 1) .or_insert(1000); // Pattern: increment counter or initialize let mut counter_ref = map .entry("page_views") .or_insert(0); *counter_ref += 1; // Pattern: try to compute value, handle errors let result = map.entry("config").or_try_insert_with(|| { load_config().map_err(|e| format!("Config error: {}", e)) }); match result { Ok(config_ref) => println!("Config loaded"), Err(e) => println!("Failed: {}", e), } // Insert and get entry let occupied = map.entry("status").insert_entry("active".to_string()); assert_eq!(occupied.key(), &"status"); fn load_config() -> Result { Ok("loaded".to_string()) } ``` -------------------------------- ### Iterating Over DashMap Entries (Rust) Source: https://context7.com/xacrimon/dashmap/llms.txt Provides examples of iterating over the entries in a DashMap. It includes immutable iteration using `&map` and `iter()`, mutable iteration with `iter_mut()`, and consuming iteration by taking ownership of the map. ```rust use dashmap::DashMap; let map = DashMap::new(); map.insert("x", 10); map.insert("y", 20); map.insert("z", 30); // Immutable iteration for entry in &map { println!("{}: {}", entry.key(), entry.value()); } // Explicit immutable iterator for entry in map.iter() { let (key, value) = entry.pair(); println!("{}: {}", key, value); } // Mutable iteration map.iter_mut().for_each(|mut entry| { *entry.value_mut() *= 2; }); assert_eq!(*map.get("x").unwrap(), 20); // Consuming iteration let owned_map = DashMap::new(); owned_map.insert(1, "one"); owned_map.insert(2, "two"); for (key, value) in owned_map { println!("{}: {}", key, value); } ``` -------------------------------- ### Creating and Sharing DashMaps in Rust Source: https://context7.com/xacrimon/dashmap/llms.txt Demonstrates various ways to initialize a DashMap, including with default settings, a specific capacity, or a custom shard amount. It also shows how to share a DashMap across threads using Arc for safe concurrent access. ```rust use dashmap::DashMap; use std::sync::Arc; use std::thread; // Create a new empty DashMap let map = DashMap::new(); // Create with specific capacity let map = DashMap::with_capacity(100); // Create with custom shard amount for fine-tuned concurrency let map = DashMap::with_shard_amount(32); // Share across threads using Arc let map = Arc::new(DashMap::new()); let map_clone = Arc::clone(&map); thread::spawn(move || { map_clone.insert("key", "value"); }); map.insert("another", "entry"); ``` -------------------------------- ### DashMap Capacity Management: Reserve and Shrink Source: https://context7.com/xacrimon/dashmap/llms.txt Details capacity management in DashMap, showing how to reserve memory for future insertions and shrink the map's capacity to fit its current size. It also demonstrates checking the map's capacity and size. ```rust use dashmap::DashMap; let mut map = DashMap::new(); assert_eq!(map.capacity(), 0); // Reserve capacity map.try_reserve(100).expect("Failed to allocate"); assert!(map.capacity() >= 100); // Populate map for i in 0..10 { map.insert(i, i * 2); } // Shrink to fit current size map.shrink_to_fit(); assert!(map.capacity() >= map.len()); // Check size assert_eq!(map.len(), 10); assert!(!map.is_empty()); ``` -------------------------------- ### Inserting and Updating Entries in DashMap (Rust) Source: https://context7.com/xacrimon/dashmap/llms.txt Covers insertion and update operations for DashMap. It shows basic `insert`, conditional insertion using the `entry` API with `and_modify` and `or_insert`, and lazy initialization with `or_insert_with`. ```rust use dashmap::DashMap; let map = DashMap::new(); // Basic insert - returns old value if key existed let old = map.insert("name", "Alice"); assert_eq!(old, None); let old = map.insert("name", "Bob"); assert_eq!(old, Some("Alice")); // Entry API for conditional insertion map.entry("counter") .and_modify(|v| *v += 1) .or_insert(0); // or_insert returns mutable reference to value let mut ref_mut = map.entry("score").or_insert(100); *ref_mut += 50; assert_eq!(*map.get("score").unwrap(), 150); // or_insert_with for lazy initialization map.entry("expensive") .or_insert_with(|| { // Only computed if key doesn't exist expensive_computation() }); fn expensive_computation() -> i32 { 42 } ``` -------------------------------- ### DashSet: Concurrent HashSet Operations and Thread Safety Source: https://context7.com/xacrimon/dashmap/llms.txt Illustrates the usage of DashSet, a concurrent HashSet, focusing on thread-safe insertions, set operations like contains and remove, and iteration. It shows how to use `Arc` to share the DashSet across multiple threads for concurrent access. ```rust use dashmap::DashSet; use std::sync::Arc; use std::thread; // Create concurrent set let set = Arc::new(DashSet::new()); // Spawn threads to insert values let handles: Vec<_> = (0..4) .map(|i| { let set = Arc::clone(&set); thread::spawn(move || { for j in 0..25 { set.insert(i * 25 + j); } }) }) .collect(); for handle in handles { handle.join().unwrap(); } // Set operations assert_eq!(set.len(), 100); assert!(set.contains(&50)); // Insert returns false if already present assert!(!set.insert(50)); assert!(set.insert(200)); // Remove from set let removed = set.remove(&50); assert_eq!(removed, Some(50)); // Iteration for item in set.iter() { println!("{}", *item); } // Retain matching items set.retain(|&value| value < 100); assert_eq!(set.len(), 99); // 0-99 minus the removed 50 ``` -------------------------------- ### DashMap Thread-Safe Counter Pattern Source: https://context7.com/xacrimon/dashmap/llms.txt Demonstrates a common pattern for implementing thread-safe counters using DashMap. Multiple threads concurrently increment counters identified by keys, ensuring data integrity without explicit locking. ```rust use dashmap::DashMap; use std::sync::Arc; use std::thread; let counters = Arc::new(DashMap::new()); // Spawn multiple threads incrementing various counters let handles: Vec<_> = (0..10) .map(|thread_id| { let counters = Arc::clone(&counters); thread::spawn(move || { for i in 0..100 { let counter_key = i % 5; // 5 different counters counters .entry(counter_key) .and_modify(|count| *count += 1) .or_insert(1); } }) }) .collect(); for handle in handles { handle.join().unwrap(); } // Each counter should have been incremented 200 times (10 threads * 100 / 5) for i in 0..5 { assert_eq!(*counters.get(&i).unwrap(), 200); } println!("All counters: {:?}", counters); ``` -------------------------------- ### DashMap Bulk Operations: Retain, Alter, and Clear Entries Source: https://context7.com/xacrimon/dashmap/llms.txt Covers bulk operations in DashMap, including retaining elements based on a predicate, altering specific values, modifying all values, and clearing the map. It also shows how to view an entry's value without holding a lock. ```rust use dashmap::DashMap; let map = DashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Retain only matching elements map.retain(|key, value| *value > 1); assert_eq!(map.len(), 2); assert!(!map.contains_key("a")); // Alter specific value map.insert("x", 10); map.alter("x", |_key, value| value * 2); assert_eq!(*map.get("x").unwrap(), 20); // Alter all values map.alter_all(|_key, value| value + 100); assert_eq!(*map.get("b").unwrap(), 102); assert_eq!(*map.get("c").unwrap(), 103); // View without holding lock let is_even = map.view("x", |_key, value| value % 2 == 0); assert_eq!(is_even, Some(true)); // Clear all entries map.clear(); assert!(map.is_empty()); ``` -------------------------------- ### DashMap Read-Only View: Efficient Concurrent Read Access Source: https://context7.com/xacrimon/dashmap/llms.txt Explains how to convert a DashMap into a read-only view for efficient, lock-free read access. This is useful when sharing data across threads where mutations are infrequent or non-existent. ```rust use dashmap::DashMap; use std::sync::Arc; use std::thread; // Create and populate map let map = DashMap::new(); map.insert("config", "production"); map.insert("port", "8080"); // Convert to read-only view for efficient read-only access let readonly = map.into_read_only(); // Get raw references without locking overhead let config: &str = readonly.get("config").unwrap(); assert_eq!(config, "production"); // Share read-only view across threads let view = Arc::new(readonly); let handles: Vec<_> = (0..10) .map(|_| { let view = Arc::clone(&view); thread::spawn(move || { if let Some(port) = view.get("port") { println!("Port: {}", port); } }) }) .collect(); for handle in handles { handle.join().unwrap(); } // Iterate with raw references for (key, value) in view.iter() { println!("{}: {}", key, value); } // Convert back to mutable DashMap if needed let map_again = Arc::try_unwrap(view).unwrap().into_inner(); map_again.insert("new_key", "new_value"); ``` -------------------------------- ### Removing Entries from DashMap (Rust) Source: https://context7.com/xacrimon/dashmap/llms.txt Details the various methods for removing entries from a DashMap. Covers basic removal (`remove`), conditional removal based on key-value pairs (`remove_if`), and mutable conditional removal (`remove_if_mut`). ```rust use dashmap::DashMap; let map = DashMap::new(); map.insert("Alice", 30); map.insert("Bob", 25); // Basic removal - returns key-value pair if let Some((key, value)) = map.remove("Alice") { assert_eq!(key, "Alice"); assert_eq!(value, 30); } // Conditional removal map.insert("Charlie", 35); map.remove_if("Charlie", |_key, &value| value > 30); assert!(!map.contains_key("Charlie")); map.insert("Diana", 28); map.remove_if("Diana", |_key, &value| value > 50); assert!(map.contains_key("Diana")); // Not removed // Mutable conditional removal map.remove_if_mut("Diana", |_key, value| { if *value < 30 { *value += 10; // Can modify before deciding false // Don't remove } else { true } }); assert_eq!(*map.get("Diana").unwrap(), 38); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.