Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Papaya
https://docs.rs/papaya/
Admin
Papaya is a fast and ergonomic concurrent hash-table for read-heavy workloads.
Tokens:
88,486
Snippets:
625
Trust Score:
9.1
Update:
4 weeks ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### get() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Returns a reference to the value corresponding to the key. The example inserts a value and retrieves it, also checking for a missing key. ```rust use papaya::HashSet; let set = HashSet::new(); set.pin().insert(1); assert_eq!(set.pin().get(&1), Some(&1)); assert_eq!(set.pin().get(&2), None); ``` -------------------------------- ### get example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type. ```rust use papaya::HashMap; let map = HashMap::new(); map.pin().insert(1, "a"); assert_eq!(map.pin().get(&1), Some(&"a")); assert_eq!(map.pin().get(&2), None); ``` -------------------------------- ### reserve() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Tries to reserve capacity for additional elements. The example reserves capacity for 10 more elements in a new set. ```rust use papaya::HashSet; let set: HashSet<&str> = HashSet::new(); set.pin().reserve(10); ``` -------------------------------- ### len() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Returns the number of entries in the set. The example creates a new HashSet, inserts two values, and asserts the length is 2. ```rust use papaya::HashSet; let set = HashSet::new(); set.pin().insert(1); set.pin().insert(2); assert!(set.len() == 2); ``` -------------------------------- ### Example: building a HashSet with builder options Source: https://docs.rs/papaya/latest/papaya/struct.HashSetBuilder.html Shows how to use HashSet::builder() to configure a HashSet with capacity, hasher, resize mode, and a custom collector, then build it. ```rust use papaya::{HashSet, ResizeMode}; use seize::Collector; use std::collections::hash_map::RandomState; let set: HashSet<i32> = HashSet::builder() // Set the initial capacity. .capacity(2048) // Set the hasher. .hasher(RandomState::new()) // Set the resize mode. .resize_mode(ResizeMode::Blocking) // Set a custom garbage collector. .collector(Collector::new().batch_size(128)) // Construct the hash set. .build(); ``` -------------------------------- ### iter() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html An iterator visiting all values in arbitrary order. The example creates a set from an array and iterates over its values, printing each one. ```rust use papaya::HashSet; let set = HashSet::from([ "a", "b", "c" ]); for val in set.pin().iter() { println!("val: {val}"); } ``` -------------------------------- ### clear() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Clears the set, removing all values. The example inserts a value, clears the set, and asserts it is empty. ```rust use papaya::HashSet; let set = HashSet::new(); set.pin().insert(1); set.pin().clear(); assert!(set.pin().is_empty()); ``` -------------------------------- ### insert() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Inserts a value into the set. Returns true if the key was not present, false if it was (and the old value is not updated). The example shows both cases. ```rust use papaya::HashSet; let set = HashSet::new(); assert_eq!(set.pin().insert(37), true); assert_eq!(set.pin().is_empty(), false); set.pin().insert(37); assert_eq!(set.pin().insert(37), false); assert_eq!(set.pin().get(&37), Some(&37)); ``` -------------------------------- ### is_empty() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Returns true if the set is empty, otherwise false. The example checks that a new set is empty, inserts a value, and checks that it is not empty. ```rust use papaya::HashSet; let set = HashSet::new(); assert!(set.is_empty()); set.pin().insert("a"); assert!(!set.is_empty()); ``` -------------------------------- ### Example: building a HashMap with HashMap::builder() Source: https://docs.rs/papaya/latest/papaya/struct.HashMapBuilder.html Shows how to construct a `HashMap` using the builder pattern, setting capacity, hasher, resize mode, and a custom collector. Requires the `papaya`, `seize`, and `std` crates. ```rust use papaya::{HashMap, ResizeMode}; use seize::Collector; use std::collections::hash_map::RandomState; let map: HashMap<i32, i32> = HashMap::builder() // Set the initial capacity. .capacity(2048) // Set the hasher. .hasher(RandomState::new()) // Set the resize mode. .resize_mode(ResizeMode::Blocking) // Set a custom garbage collector. .collector(Collector::new().batch_size(128)) // Construct the hash map. .build(); ``` -------------------------------- ### remove() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Removes a key from the set, returning true if the key was previously in the set. The example removes a key and then attempts to remove it again. ```rust use papaya::HashSet; let set = HashSet::new(); set.pin().insert(1); assert_eq!(set.pin().remove(&1), true); assert_eq!(set.pin().remove(&1), false); ``` -------------------------------- ### HashMap::compute example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Performs a compare-and-swap operation using a compute closure. The closure receives the current entry state and returns an Operation. The example shows removing even values, incrementing odd values, and aborting when the key is absent. ```rust use papaya::{HashMap, Operation, Compute}; let map = HashMap::new(); let map = map.pin(); let compute = |entry| match entry { // Remove the value if it is even. Some((_key, value)) if value % 2 == 0 => { Operation::Remove } // Increment the value if it is odd. Some((_key, value)) => { Operation::Insert(value + 1) } // Do nothing if the key does not exist None => Operation::Abort(()), }; assert_eq!(map.compute('A', compute), Compute::Aborted(())); map.insert('A', 1); assert_eq!(map.compute('A', compute), Compute::Updated { old: (&'A', &1), new: (&'A', &2), }); assert_eq!(map.compute('A', compute), Compute::Removed(&'A', &2)); ``` -------------------------------- ### Basic usage of papaya::HashMap with pinning Source: https://docs.rs/papaya/latest/papaya/index.html Shows how to create a papaya HashMap, pin it, and perform basic operations like insert, get, and len. Pinning is similar to a lock guard but cheap and deadlock-free. ```rust use papaya::HashMap; // Create a map. let map = HashMap::new(); // Pin the map. let map = map.pin(); // Use the map as normal. map.insert('A', 1); assert_eq!(map.get(&'A'), Some(&1)); assert_eq!(map.len(), 1); ``` -------------------------------- ### retain() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Retains only the elements specified by the predicate. The example retains even numbers from a set of 0..8 and checks the results. ```rust use papaya::HashSet; let set: HashSet<i32> = (0..8).collect(); set.pin().retain(|&v| v % 2 == 0); assert_eq!(set.len(), 4); assert_eq!(set.pin().contains(&1), false); assert_eq!(set.pin().contains(&2), true); ``` -------------------------------- ### insert example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Inserts a key-value pair into the map. If the key was not present, None is returned. If the key was present, the value is updated and the old value is returned. The key is not updated. ```rust use papaya::HashMap; let map = HashMap::new(); assert_eq!(map.pin().insert(37, "a"), None); assert_eq!(map.pin().is_empty(), false); map.pin().insert(37, "b"); assert_eq!(map.pin().insert(37, "c"), Some(&"b")); assert_eq!(map.pin().get(&37), Some(&"c")); ``` -------------------------------- ### get_or_insert example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Returns a reference to the value corresponding to the key, or inserts a default value. If the given key is present, the corresponding value is returned. If it is not present, the provided value is inserted, and a reference to the newly inserted value is returned. ```rust use papaya::HashMap; let map = HashMap::new(); assert_eq!(map.pin().get_or_insert("a", 3), &3); assert_eq!(map.pin().get_or_insert("a", 6), &3); ``` -------------------------------- ### Keys::step_by Source: https://docs.rs/papaya/latest/papaya/struct.Keys.html Creates an iterator starting at the same point, but stepping by the given amount at each iteration. ```APIDOC ## step_by ### Description Creates an iterator starting at the same point, but stepping by the given amount at each iteration. ### Method step_by ### Signature ```rust fn step_by(self, step: usize) -> StepBy<Self> ⓘ ``` ### Parameters - `step` (usize) - The step amount. ### Returns - `StepBy<Self>` - A new iterator that steps by the given amount. ``` -------------------------------- ### Iterate over keys with keys Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Iterates over all keys in arbitrary order. The example creates a map from an array and prints each key. Note that this method blocks until any in-progress resizes complete. ```rust use papaya::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for key in map.pin().keys() { println!("{key}"); } ``` -------------------------------- ### is_empty example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Checks if the map is empty. Returns true if empty, false otherwise. ```rust use papaya::HashMap; let map = HashMap::new(); assert!(map.is_empty()); map.pin().insert("a", 1); assert!(!map.is_empty()); ``` -------------------------------- ### Iterate over entries with iter Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Iterates over all key-value pairs in arbitrary order. The example creates a map from an array and prints each key-value pair. Note that this method blocks until any in-progress resizes complete. ```rust use papaya::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for (key, val) in map.pin().iter() { println!("key: {key} val: {val}"); } ``` -------------------------------- ### HashMap::update_or_insert example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Updates an existing entry or inserts a default value. If the key is present, the update closure is applied; otherwise the provided value is inserted. Returns a reference to the resulting value. ```rust use papaya::HashMap; let map = HashMap::new(); assert_eq!(*map.pin().update_or_insert("a", |i| i + 1, 0), 0); assert_eq!(*map.pin().update_or_insert("a", |i| i + 1, 0), 1); ``` -------------------------------- ### HashMap::update_or_insert_with example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Updates an existing entry or inserts a value computed from a closure. If the key is absent, the closure f is called to produce the default value. Returns a reference to the resulting value. ```rust use papaya::HashMap; let map = HashMap::new(); assert_eq!(*map.pin().update_or_insert_with("a", |i| i + 1, || 0), 0); assert_eq!(*map.pin().update_or_insert_with("a", |i| i + 1, || 0), 1); ``` -------------------------------- ### try_insert_with example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Tries to insert a key and value computed from a closure into the map, and returns a reference to the value that was inserted. If the map already had this key present, nothing is updated, and the existing value is returned. ```rust use papaya::HashMap; let map = HashMap::new(); let map = map.pin(); assert_eq!(map.try_insert_with(37, || "a").unwrap(), &"a"); let current = map.try_insert_with(37, || "b").unwrap_err(); assert_eq!(current, &"a"); ``` -------------------------------- ### get_or_insert_with example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Returns a reference to the value corresponding to the key, or inserts a default value computed from a closure. If the given key is present, the corresponding value is returned. If it is not present, the value computed from f is inserted, and a reference to the newly inserted value is returned. ```rust use papaya::HashMap; let map = HashMap::new(); assert_eq!(map.pin().get_or_insert_with("a", || 3), &3); assert_eq!(map.pin().get_or_insert_with("a", || 6), &3); ``` -------------------------------- ### get_key_value example Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Returns the key-value pair corresponding to the supplied key. The supplied key may be any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match those for the key type. ```rust use papaya::HashMap; let map = HashMap::new(); map.pin().insert(1, "a"); assert_eq!(map.pin().get_key_value(&1), Some((&1, &"a"))); assert_eq!(map.pin().get_key_value(&2), None); ``` -------------------------------- ### Iterate over values with map.pin().values() Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Example from the documentation for the values method. It creates a HashMap from an array of key-value pairs and iterates over its values using pin().values(), printing each value. The iterator yields references to the values in arbitrary order. ```rust use papaya::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for value in map.pin().values() { println!("{value}"); } ``` -------------------------------- ### Get or allocate next table with spin and lock Source: https://docs.rs/papaya/latest/src/papaya/raw/mod.rs.html Returns the next table, allocating it if not already created. Uses a spin loop and then a lock to handle concurrent allocation, with logic to grow, shrink, or keep capacity based on load. ```rust fn get_or_alloc_next( &self, capacity: Option<usize>, table: Table<Entry<K, V>>, ) -> Table<Entry<K, V>> { // Avoid spinning in tests, which can hide race conditions. const SPIN_ALLOC: usize = if cfg!(any(test, debug_assertions)) { 1 } else { 7 }; // The next table is already allocated. if let Some(next) = table.next_table() { return next; } let state = table.state(); // Otherwise, try to acquire the allocation lock. // // Unlike in `init`, we do not race here to prevent unnecessary allocator pressure. let _allocating = match state.allocating.try_lock() { Ok(lock) => lock, // Someone else is currently allocating. Err(_) => { let mut spun = 0; // Spin for a bit, waiting for the table to be initialized. while spun <= SPIN_ALLOC { for _ in 0..(spun * spun) { hint::spin_loop(); } // The table was initialized. if let Some(next) = table.next_table() { return next; } spun += 1; } // Otherwise, we have to block. state.allocating.lock().unwrap() } }; // The table was allocated while we were waiting for the lock. if let Some(next) = table.next_table() { return next; } let current_capacity = table.len(); // Loading the length here is quite expensive, we may want to consider // a probabilistic counter to detect high-deletion workloads. let active_entries = self.len(); let next_capacity = match cfg!(papaya_stress) { // Never grow the table to stress the incremental resizing algorithm. true => current_capacity, // Double the table capacity if we are at least 50% full. false if active_entries >= (current_capacity >> 1) => current_capacity << 1, // Halve the table if we are at most 12.5% full. // // This heuristic is intentionally pessimistic as unnecessarily shrinking // is an expensive operation, but it may change in the future. We also respect // the initial capacity to give the user a way to retain a strict minimum table // size. false if active_entries <= (current_capacity >> 3) => { self.initial_capacity.max(current_capacity >> 1) } // Otherwise keep the capacity the same. // // This can occur due to poor hash distribution or frequent cycling of // insertions and deletions, in which case we want to avoid continuously // growing the table. false => current_capacity, }; let next_capacity = capacity.unwrap_or(next_capacity); assert!( next_capacity <= isize::MAX as usize, "`HashMap` exceeded maximum capacity" ); // Allocate the new table while holding the lock. let next = Table::alloc(next_capacity); state.next.store(next.raw, Ordering::Release); drop(_allocating); next } ``` -------------------------------- ### Get number of entries with len() Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Returns the number of entries in the map. The example inserts two entries and asserts the length is 2. ```rust use papaya::HashMap; let map = HashMap::new(); map.pin().insert(1, "a"); map.pin().insert(2, "b"); assert!(map.len() == 2); ``` -------------------------------- ### Custom HashMap wrapper with Guard-based get method Source: https://docs.rs/papaya/latest/src/papaya/lib.rs.html Defines a custom map type that wraps papaya's HashMap and provides a get method that returns a reference to a slice of u64 values, tied to the guard's lifetime. The example demonstrates the use of the Guard trait and the 'guard lifetime, showing that no wrapper types or guard mapping are necessary. ```rust //! pub fn get<'guard>(&self, name: &str, guard: &'guard impl Guard) -> Option<&'guard [u64]> { //! Some(self.map.get(name, guard)?.as_slice()) //! } //! } ``` -------------------------------- ### Create HashMap with capacity and hasher using with_capacity_and_hasher() Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Creates an empty `HashMap` with at least the specified capacity and a custom hasher. Warning: setting a manual hasher can expose a DoS attack vector. ```rust use papaya::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map = HashMap::with_capacity_and_hasher(10, s); map.pin().insert(1, 2); ``` -------------------------------- ### HashMapBuilder::new Source: https://docs.rs/papaya/latest/src/papaya/map.rs.html Creates a new HashMapBuilder with default configuration. ```APIDOC ## HashMapBuilder::new ### Description Creates a new `HashMapBuilder` with default configuration. ### Method `pub fn new() -> HashMapBuilder<K, V, S>` ### Parameters None. ### Returns - `HashMapBuilder<K, V, S>` - A new builder instance. ### Example ```rust use papaya::HashMapBuilder; let builder = HashMapBuilder::new(); ``` ``` -------------------------------- ### Initialize table with compare_exchange Source: https://docs.rs/papaya/latest/src/papaya/raw/mod.rs.html Initializes the table by allocating a new table and racing to write it using compare_exchange. If another thread wins, the allocated table is deallocated and the winning table is used. ```rust let mut new = Table::alloc(capacity.unwrap_or(CAPACITY)); *new.state_mut().status.get_mut() = State::PROMOTED; // Race to write the initial table. match self.table.compare_exchange( ptr::null_mut(), new.raw, Ordering::Release, Ordering::Acquire, ) { // Successfully initialized the table. Ok(_) => new, // Someone beat us, deallocate our table and use the table that was written. Err(found) => { // Safety: We allocated the table above and never shared it. unsafe { Table::dealloc(new) } // Safety: The table was just initialized. unsafe { Table::from_raw(found) } } } ``` -------------------------------- ### contains() example Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Returns true if the set contains a value for the specified key. The example inserts a value and checks for its presence and absence. ```rust use papaya::HashSet; let set = HashSet::new(); set.pin().insert(1); assert_eq!(set.pin().contains(&1), true); assert_eq!(set.pin().contains(&2), false); ``` -------------------------------- ### Creating a HashSet with capacity and hasher Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Creates an empty HashSet with at least the specified capacity and a custom hash builder. Capacity is an estimate; early resizing may occur with poor hash distribution. Setting the hasher manually can expose a DoS attack vector. ```rust use papaya::HashSet; use std::hash::RandomState; let s = RandomState::new(); let set = HashSet::with_capacity_and_hasher(10, s); set.pin().insert(1); ``` -------------------------------- ### prepare_retry_insert: handle resize and copy assistance Source: https://docs.rs/papaya/latest/src/papaya/raw/mod.rs.html Prepares to retry an insert in the next table. In blocking mode, completes the resize; in incremental mode, helps with copying and waits for the entry to be copied if needed. Limits incremental copying to once per operation. ```rust /// Prepare to retry an insert operation in the next table. #[cold] #[inline(never)] fn prepare_retry_insert( &self, copying: Option<usize>, help_copy: &mut bool, table: Table<Entry<K, V>>, guard: &impl VerifiedGuard, ) -> Table<Entry<K, V>> { // If went over the probe limit or found a copied entry, trigger a resize. let mut next_table = self.get_or_alloc_next(None, table); let next_table = match self.resize { // In blocking mode we must complete the resize before proceeding. ResizeMode::Blocking => self.help_copy(true, &table, guard), // In incremental mode we can perform more granular blocking. ResizeMode::Incremental(_) => { // Help out with the copy. if *help_copy { next_table = self.help_copy(false, &table, guard); } // The entry we want to update is being copied. if let Some(i) = copying { // Wait for the entry to be copied. // // We could race with the copy to insert into the table. However, // this entire code path is very rare and likely to complete quickly, // so blocking allows us to make copies faster. self.wait_copied(i, &table); } next_table } }; // Limit incremental copying to once per operation, for more consistent latency. *help_copy = false; // Continue in the new table. next_table } ``` -------------------------------- ### Create HashMap with custom hasher using with_hasher() Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Creates an empty `HashMap` with a custom hasher. Warning: setting a manual hasher can expose a DoS attack vector. The hasher must implement `BuildHasher`. ```rust use papaya::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map = HashMap::with_hasher(s); map.pin().insert(1, 2); ``` -------------------------------- ### Advanced lifetimes: returning reference from method (error example) Source: https://docs.rs/papaya/latest/papaya/index.html This example shows a common error when trying to return a reference to a map contained in an outer type. The code fails with error[E0515] because the guard is temporary and the reference would outlive it. ```rust pub struct Metrics { map: papaya::HashMap<String, Vec<u64>> } impl Metrics { pub fn get(&self, name: &str) -> Option<&[u64]> { // error[E0515]: cannot return value referencing temporary value Some(self.map.pin().get(name)?.as_slice()) } } ``` -------------------------------- ### get Source: https://docs.rs/papaya/latest/papaya/struct.HashSetRef.html Returns a reference to the value corresponding to the key. ```APIDOC ## get ### Description Returns a reference to the value corresponding to the key. See `HashSet::get` for details. ### Method `pub fn get<Q>(&self, key: &Q) -> Option<&K> where Q: Equivalent<K> + Hash + ?Sized` ### Parameters - `&self` - The reference to the `HashSetRef`. - `key: &Q` - The key to look up. ### Returns - `Option<&K>` - A reference to the value if found, `None` otherwise. ``` -------------------------------- ### HashSetBuilder::build Source: https://docs.rs/papaya/latest/papaya/struct.HashSetBuilder.html Constructs a HashSet from the builder using the configured options. ```APIDOC ## HashSetBuilder::build ### Description Constructs a `HashSet` from the builder, using the configured options. ### Method pub fn build(self) -> HashSet<K, S> ### Parameters None. ### Returns - **HashSet<K, S>** - The constructed hash set. ``` -------------------------------- ### Get a guard for the set Source: https://docs.rs/papaya/latest/src/papaya/set.rs.html Returns a LocalGuard for use with the set. Holding the guard prevents garbage collection. ```rust pub fn guard(&self) -> LocalGuard<'_> { self.raw.collector().enter() } ``` -------------------------------- ### prepare_retry method implementation Source: https://docs.rs/papaya/latest/src/papaya/raw/mod.rs.html Prepares to retry an operation on an existing key in the next table. Handles blocking and incremental resize modes, helps with copying, and waits for entries to be copied. Returns None if the search is exhausted. ```rust fn prepare_retry( &self, copying: Option<usize>, help_copy: &mut bool, table: Table<Entry<K, V>>, guard: &impl VerifiedGuard, ) -> Option<Table<Entry<K, V>>> { let next_table = match self.resize { ResizeMode::Blocking => match copying { // The entry we want to perform the operation on is being copied. // // In blocking mode we must complete the resize before proceeding. Some(_) => self.help_copy(true, &table, guard), // If we went over the probe limit, the key is not in the map. None => return None, }, ResizeMode::Incremental(_) => { // In incremental resize mode, we always have to check the next table. let next_table = table.next_table()?; // Help out with the copy. if *help_copy { self.help_copy(false, &table, guard); } if let Some(i) = copying { // Wait for the entry to be copied. // // We could race with the copy to insert into the table. However, // this entire code path is very rare and likely to complete quickly, // so blocking allows us to make copies faster. self.wait_copied(i, &table); } next_table } }; // Limit incremental copying to once per operation, for more consistent latency. *help_copy = false; // Continue in the new table. Some(next_table) } ``` -------------------------------- ### HashSet::with_capacity_and_hasher Source: https://docs.rs/papaya/latest/papaya/struct.HashSet.html Creates an empty HashSet with a specified capacity and custom hash builder. Warning: manual hash builder can expose a DoS attack vector. ```APIDOC ## HashSet::with_capacity_and_hasher ### Description Creates an empty `HashSet` with at least the specified capacity, using `hash_builder` to hash the keys. The set should be able to hold at least `capacity` elements before resizing. However, the capacity is an estimate, and the set may prematurely resize due to poor hash distribution. If `capacity` is 0, the hash set will not allocate. Warning: `hash_builder` is normally randomly generated, and is designed to allow HashSets to be resistant to attacks that cause many collisions and very poor performance. Setting it manually using this function can expose a DoS attack vector. The `hasher` passed should implement the `BuildHasher` trait for the HashSet to be useful. ### Method `pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashSet<K, S>` ### Parameters - `capacity` (usize) - Required - The desired capacity of the hash set. - `hash_builder` (S) - Required - The hash builder to use for hashing keys. ### Returns - `HashSet<K, S>` - A new hash set with the specified capacity and hash builder. ### Example ```rust use papaya::HashSet; use std::hash::RandomState; let s = RandomState::new(); let set = HashSet::with_capacity_and_hasher(10, s); set.pin().insert(1); ``` ``` -------------------------------- ### Values::step_by Source: https://docs.rs/papaya/latest/papaya/struct.Values.html Creates an iterator starting at the same point, but stepping by the given amount at each iteration. This is part of the Iterator trait implementation for the Values struct. ```APIDOC ## Iterator Implementation for Values ### Description Creates an iterator starting at the same point, but stepping by the given amount at each iteration. ### Method `fn step_by(self, step: usize) -> StepBy<Self>` ### Parameters - `self` - The iterator to adapt. - `step` (usize) - The step size. ### Returns - `StepBy<Self>` - The new iterator that steps by the given amount. ### Notes - This method is part of the `Iterator` trait implementation. ``` -------------------------------- ### Clear all entries with clear Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Removes all key-value pairs from the map. Blocks until any in-progress resizes complete. The example inserts a pair, clears the map, and asserts it is empty. ```rust use papaya::HashMap; let map = HashMap::new(); map.pin().insert(1, "a"); map.pin().clear(); assert!(map.pin().is_empty()); ``` -------------------------------- ### Create HashMap with capacity using with_capacity() Source: https://docs.rs/papaya/latest/papaya/struct.HashMap.html Creates an empty `HashMap` with the specified capacity. The table may resize prematurely due to poor hash distribution, but will never shrink below the initial capacity. ```rust use papaya::HashMap; let map: HashMap<&str, i32> = HashMap::with_capacity(10); ``` -------------------------------- ### Get a pinned reference to the set Source: https://docs.rs/papaya/latest/src/papaya/set.rs.html Returns a pinned reference that manages a guard internally, preventing garbage collection while held. Useful for safe concurrent access. ```rust pub fn pin(&self) -> HashSetRef<'_, K, S, LocalGuard<'_>> { HashSetRef { guard: self.raw.guard(), set: self, } } ``` -------------------------------- ### Incremental Copy and Promotion Loop Source: https://docs.rs/papaya/latest/src/papaya/raw/mod.rs.html This snippet shows the core loop that copies entries from the old table to the new table during a resize. It handles spinning and parking when the copy is blocked, and promotes the table once all entries are copied. The code uses unsafe operations and requires careful safety reasoning. ```rust unsafe { self.copy_at_incremental(i, &table, &next, guard) }; copied += 1; } // Update the copy state, and try to promote the table. // // Only copy a single chunk if promotion fails, unless we are forced // to complete the resize. if self.try_promote(&table, &next, copied, guard) || !block { return next; } } // There are no entries that we can copy, block if necessary. if !block { return next; } let state = next.state(); for spun in 0.. { // Avoid spinning in tests, which can hide race conditions. const SPIN_WAIT: usize = if cfg!(any(test, debug_assertions)) { 1 } else { 7 }; // The copy has completed. // // Note that `Acquire` is necessary here to ensure we see the // relevant modifications to the root table if see the updated // state before parking. // // Otherwise, `Parker::park` will ensure the necessary synchronization // when we are unparked. let status = state.status.load(Ordering::Acquire); if status == State::PROMOTED { return next; } // Copy chunks are relatively small and we expect to finish quickly, // so spin for a bit before resorting to parking. if spun <= SPIN_WAIT { for _ in 0..(spun * spun) { hint::spin_loop(); } continue; } // Park until the table is promoted. state .parker .park(&state.status, |status| status == State::PENDING); } } } ``` -------------------------------- ### Promote table with compare_exchange and retire old table Source: https://docs.rs/papaya/latest/src/papaya/raw/mod.rs.html Promotes a new table by atomically comparing and exchanging the root pointer. On success, stores the PROMOTED state with SeqCst ordering, retires the old table using a deferred closure that drops entries without dropping them (since they were copied), and unparks waiting writers. ```rust .compare_exchange(table.raw, next.raw, Ordering::Release, Ordering::Acquire) .is_ok() { // Successfully promoted the table. // // Note that the `SeqCst` is necessary to make the store visible to threads // that are unparked. state.status.store(State::PROMOTED, Ordering::SeqCst); // Retire the old table. // // Safety: `table.raw` is a valid pointer to the table we just copied from. // Additionally, the CAS above made the previous table unreachable from the // root pointer, allowing it to be safely retired. unsafe { guard.defer_retire(table.raw, |table, collector| { // Note that we do not drop entries because they have been copied to // the new root. drop_table(Table::from_raw(table), collector); }); } } // Wake up any writers waiting for the resize to complete. state.parker.unpark(&state.status); return true; } } // Not ready to promote yet. false } ``` -------------------------------- ### with_capacity_and_hasher Source: https://docs.rs/papaya/latest/src/papaya/set.rs.html Creates an empty HashSet with the specified capacity and hasher. ```APIDOC ## with_capacity_and_hasher ### Description Creates an empty `HashSet` with the specified capacity and hasher. ### Method `pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashSet<K, S>` ### Parameters - **capacity** (`usize`) - Required - The initial capacity of the set. - **hash_builder** (`S`) - Required - The hasher to use for hashing keys. ### Returns - `HashSet<K, S>` - A new empty `HashSet`. ```