### Example Searches for Rs Slotmap Source: https://docs.rs/slotmap/latest/src/slotmap/secondary.rs_search= Provides example search queries for common Rust patterns within the Rs Slotmap project. These examples demonstrate how to search for standard library types, type conversions, and generic function signatures. ```text Example searches: * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### SlotMap and SecondaryMap Initialization and Entry Operations (Rust) Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.OccupiedEntry Demonstrates the initialization of SlotMap and SecondaryMap, and showcases various operations on an occupied entry using the slotmap crate. This includes getting the key, removing the entry, getting a reference to the value, getting a mutable reference, converting to a mutable reference, inserting a new value, and removing the value. ```Rust let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let k = sm.insert(1); sec.insert(k, 10); assert_eq!(sec.entry(k).unwrap().key(), k); if let Some(Entry::Occupied(o)) = sec.entry(k) { assert_eq!(o.remove_entry(), (k, 10)); } assert_eq!(sec.contains_key(k), false); let k = sm.insert(1); sec.insert(k, 10); if let Entry::Occupied(o) = sec.entry(k).unwrap() { assert_eq!(*o.get(), 10); } let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let k = sm.insert(1); sec.insert(k, 10); if let Entry::Occupied(mut o) = sec.entry(k).unwrap() { *o.get_mut() = 20; } assert_eq!(sec[k], 20); let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let k = sm.insert(0); sec.insert(k, 0); let r; if let Entry::Occupied(o) = sec.entry(k).unwrap() { r = o.into_mut(); // v outlives the entry. } else { r = sm.get_mut(k).unwrap(); } *r = 1; assert_eq!((sm[k], sec[k]), (0, 1)); let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let k = sm.insert(1); sec.insert(k, 10); if let Entry::Occupied(mut o) = sec.entry(k).unwrap() { let v = o.insert(20); assert_eq!(v, 10); assert_eq!(*o.get(), 20); } let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let k = sm.insert(1); sec.insert(k, 10); if let Entry::Occupied(mut o) = sec.entry(k).unwrap() { assert_eq!(o.remove(), 10); assert_eq!(sec.contains_key(k), false); } ``` -------------------------------- ### Utility Functions Source: https://docs.rs/slotmap/latest/src/slotmap/util.rs_search=u32+-%3E+bool Utility functions provided by the slotmap crate. ```APIDOC ## Utility Functions ### `is_older_version(a: u32, b: u32) -> bool` #### Description Returns if `a` is an older version than `b`, taking into account wrapping of versions. #### Method GET #### Endpoint `/slotmap/util/is_older_version` #### Query Parameters - **a** (u32) - Required - The first version to compare. - **b** (u32) - Required - The second version to compare. #### Request Example ```json { "example": "No request body needed for this GET request." } ``` #### Response ##### Success Response (200) - **bool** (boolean) - `true` if `a` is older than `b`, `false` otherwise. #### Response Example ```json { "example": true } ``` ### `Never` Enum #### Description Internal stable replacement for `!`. Used to indicate a value that can never occur. #### Methods - `unwrap_never(self) -> T` - Description: Unwraps the `Result` into `T`. This method will panic if the `Err` variant is encountered, as `Never` cannot be constructed. - Method: GET - Endpoint: `/slotmap/util/Never/unwrap_never` - Request Example: `"example": "No request body needed for this GET request."` - Response Example: `"example": "The unwrapped value T."` ### `PanicOnDrop` Struct #### Description A struct that panics when dropped, used for debugging purposes. #### Fields - **0** (&'static str) - The panic message to be displayed when the struct is dropped. #### Method DROP (Implicit) #### Example Usage (Conceptual) ```rust let _panic_on_drop = PanicOnDrop("This should not be dropped!"); // When the scope ends, the struct is dropped and panics. ``` ``` -------------------------------- ### Construct SparseSecondaryMap with Custom Hasher Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap_search= Illustrates how to initialize a SparseSecondaryMap using a specific hash builder. This allows for control over the hashing algorithm used for keys. ```rust let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10); let mut sec: SparseSecondaryMap = SparseSecondaryMap::with_hasher(RandomState::new()); ``` -------------------------------- ### Get Mutable Values from SlotMap Source: https://docs.rs/slotmap/latest/slotmap/dense/struct.DenseSlotMap_search= Demonstrates how to get an iterator over mutable references to all values in a SlotMap using `values_mut`. This allows modifying all values, for example, by applying a transformation. ```rust use std::collections::HashSet; let mut sm = DenseSlotMap::new(); sm.insert(1); sm.insert(2); sm.insert(3); sm.values_mut().for_each(|n| { *n *= 3 }); let values: HashSet<_> = sm.into_iter().map(|(_k, v)| v).collect(); let check: HashSet<_> = vec![3, 6, 9].into_iter().collect(); assert_eq!(values, check); ``` -------------------------------- ### Get Immutable Reference to Value - Rust Example Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.OccupiedEntry_search= Illustrates how to obtain an immutable reference to the value within an `OccupiedEntry` using the `get()` method. This allows inspecting the value without modifying it. ```rust let mut sm = SlotMap::new(); let mut sec = SparseSecondaryMap::new(); let k = sm.insert(1); sec.insert(k, 10); if let Entry::Occupied(o) = sec.entry(k).unwrap() { assert_eq!(*o.get(), 10); } ``` -------------------------------- ### SlotMap Basic Usage Example Source: https://docs.rs/slotmap/latest/src/slotmap/lib.rs Demonstrates the basic usage of SlotMap, including inserting elements, accessing them by key, removing elements, and reusing space. It also shows the creation and usage of a SecondaryMap. ```rust #![doc(html_root_url = "https://docs.rs/slotmap/1.1.1")] #![crate_name = "slotmap"] #![cfg_attr(all(not(test), not(feature = "std")), no_std)] #![cfg_attr(all(nightly, doc), feature(doc_cfg))] #![warn( missing_debug_implementations, trivial_casts, trivial_numeric_casts, unused_lifetimes, unused_import_braces )] #![deny(missing_docs)] #![deny(clippy::all)] #![allow( clippy::while_let_on_iterator, // Style differences. clippy::unnecessary_map_or // Too high MSRV. )] //! # slotmap //! //! This library provides a container with persistent unique keys to access //! stored values, [`SlotMap`]. Upon insertion a key is returned that can be //! used to later access or remove the values. Insertion, removal and access all //! take O(1) time with low overhead. Great for storing collections of objects //! that need stable, safe references but have no clear ownership otherwise, //! such as game entities or graph nodes. //! //! The difference between a [`BTreeMap`] or [`HashMap`] and a slot map is //! that the slot map generates and returns the key when inserting a value. A //! key is always unique and will only refer to the value that was inserted. //! A slot map's main purpose is to simply own things in a safe and efficient //! manner. //! //! You can also create (multiple) secondary maps that can map the keys returned //! by [`SlotMap`] to other values, to associate arbitrary data with objects //! stored in slot maps, without hashing required - it's direct indexing under //! the hood. //! //! The minimum required stable Rust version for this crate is 1.58. //! //! # Examples //! //! ``` //! # use slotmap::*; //! let mut sm = SlotMap::new(); //! let foo = sm.insert("foo"); // Key generated on insert. //! let bar = sm.insert("bar"); //! assert_eq!(sm[foo], "foo"); //! assert_eq!(sm[bar], "bar"); //! //! sm.remove(bar); //! let reuse = sm.insert("reuse"); // Space from bar reused. //! assert_eq!(sm.contains_key(bar), false); // After deletion a key stays invalid. //! //! let mut sec = SecondaryMap::new(); //! sec.insert(foo, "noun"); // We provide the key for secondary maps. //! sec.insert(reuse, "verb"); //! //! for (key, val) in sm { //! println!("{} is a {}", val, sec[key]); //! } //! ``` //! //! # Serialization through [`serde`], [`no_std`] support and unstable features //! //! Both keys and the slot maps have full (de)seralization support through //! the [`serde`] library. A key remains valid for a slot map even after one or //! both have been serialized and deserialized! This makes storing or //! transferring complicated referential structures and graphs a breeze. Care has //! been taken such that deserializing keys and slot maps from untrusted sources //! is safe. If you wish to use these features you must enable the `serde` //! feature flag for `slotmap` in your `Cargo.toml`. //! //! ```text //! slotmap = { version = "1.0", features = ["serde"] } //! ``` //! //! This crate also supports [`no_std`] environments, but does require the //! [`alloc`] crate to be available. To enable this you have to disable the //! `std` feature that is enabled by default: //! //! ```text //! slotmap = { version = "1.0", default-features = false } //! ``` //! //! Unfortunately [`SparseSecondaryMap`] is not available in [`no_std`], because //! it relies on [`HashMap`]. Finally the `unstable` feature can be defined to //! enable the parts of `slotmap` that only work on nightly Rust. //! //! # Why not index a [`Vec`], or use [`slab`], [`stable-vec`], etc? //! //! Those solutions either can not reclaim memory from deleted elements or //! suffer from the ABA problem. The keys returned by `slotmap` are versioned. //! This means that once a key is removed, it stays removed, even if the //! physical storage inside the slotmap is reused for new elements. The key is a //! permanently unique* reference to the inserted value. Despite //! supporting versioning, a [`SlotMap`] is often not (much) slower than the //! alternative, by internally using carefully checked unsafe code. Finally, //! `slotmap` simply has a lot of features that make your life easy. //! //! # Performance characteristics and implementation details //! //! Insertion, access and deletion is all O(1) with low overhead by storing the //! elements inside a [`Vec`]. Unlike references or indices into a vector, //! unless you remove a key it is never invalidated. Behind the scenes each //! slot in the vector is a `(value, version)` tuple. After insertion the //! returned key also contains a version. Only when the stored version and //! version in a key match is a key valid. ``` -------------------------------- ### Get Value by Key in HopSlotMap Source: https://docs.rs/slotmap/latest/slotmap/hop/struct.HopSlotMap Shows how to retrieve a reference to a value associated with a key in a HopSlotMap using the `get` method. It returns `Some(&V)` if the key exists and `None` otherwise. The example also demonstrates that accessing a removed key results in `None`. ```rust let mut sm = HopSlotMap::new(); let key = sm.insert("bar"); assert_eq!(sm.get(key), Some(&"bar")); sm.remove(key); assert_eq!(sm.get(key), None); ``` -------------------------------- ### Get Key from VacantEntry - Rust Example Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.VacantEntry_search= Demonstrates how to retrieve the key associated with a VacantEntry. This is useful when you need to know the key before inserting a value into the SecondaryMap. ```rust let mut sm = SlotMap::new(); let mut sec: SecondaryMap<_, ()> = SecondaryMap::new(); let k = sm.insert(1); if let Entry::Vacant(v) = sec.entry(k).unwrap() { assert_eq!(v.key(), k); } ``` -------------------------------- ### SlotMap Initialization with Capacity and Custom Key Type Source: https://docs.rs/slotmap/latest/slotmap/basic/struct.SlotMap Demonstrates initializing a SlotMap with both a specified capacity and a custom key type. This combines pre-allocation benefits with custom key management. ```rust new_key_type! { struct MessageKey; } let mut messages = SlotMap::with_capacity_and_key(3); let welcome: MessageKey = messages.insert("Welcome"); let good_day = messages.insert("Good day"); let hello = messages.insert("Hello"); ``` -------------------------------- ### Get Key from VacantEntry in Rust Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.VacantEntry_search=std%3A%3Avec Retrieves the key that would be used for inserting a value into a SparseSecondaryMap via a VacantEntry. This is demonstrated with an example showing its usage with SlotMap. ```rust pub fn key(&self) -> K ``` ```rust let mut sm = SlotMap::new(); let mut sec: SparseSecondaryMap<_, ()> = SparseSecondaryMap::new(); let k = sm.insert(1); if let Entry::Vacant(v) = sec.entry(k).unwrap() { assert_eq!(v.key(), k); } ``` -------------------------------- ### SecondaryMap Initialization and Usage Example (Rust) Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.SecondaryMap Demonstrates how to initialize a SecondaryMap and associate data with keys from a SlotMap. It shows inserting elements into both maps, populating the SecondaryMap, and accessing/modifying associated data. ```rust let mut players = SlotMap::new(); let mut health = SecondaryMap::new(); let mut ammo = SecondaryMap::new(); let alice = players.insert("alice"); let bob = players.insert("bob"); for p in players.keys() { health.insert(p, 100); ammo.insert(p, 30); } // Alice attacks Bob with all her ammo! health[bob] -= ammo[alice] * 3; ammo[alice] = 0; ``` -------------------------------- ### Get Mutable Reference to Value - Rust Example Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.OccupiedEntry_search= Demonstrates obtaining a mutable reference to the value within an `OccupiedEntry` using `get_mut()`. This allows in-place modification of the entry's value. ```rust let mut sm = SlotMap::new(); let mut sec = SparseSecondaryMap::new(); let k = sm.insert(1); sec.insert(k, 10); if let Entry::Occupied(mut o) = sec.entry(k).unwrap() { *o.get_mut() = 20; } assert_eq!(sec[k], 20); ``` -------------------------------- ### Construct SparseSecondaryMap with Default Hasher Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap_search= Shows how to create a new, empty SparseSecondaryMap using the default RandomState hasher. This is the simplest way to initialize the map. ```rust let mut sec: SparseSecondaryMap = SparseSecondaryMap::new(); ``` -------------------------------- ### Getting KeyData from a Key (Rust) Source: https://docs.rs/slotmap/latest/slotmap/trait.Key Demonstrates how to retrieve the underlying `KeyData` from a key type that implements the `Key` trait. This example uses a custom key type `MyKey` and compares its `KeyData` with that of `DefaultKey`. ```rust new_key_type! { struct MyKey; } let dk = DefaultKey::null(); let mk = MyKey::null(); assert_eq!(dk.data(), mk.data()); ``` -------------------------------- ### Partitioning and Folding Source: https://docs.rs/slotmap/latest/slotmap/dense/struct.Values Adapters for partitioning elements and accumulating results. ```APIDOC ## partition(self, f: F) ### Description Consumes an iterator, creating two collections from it based on a predicate. ### Method `partition` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) let data = vec![1, 2, 3, 4, 5]; let (even, odd): (Vec<_>, Vec<_>) = data.into_iter().partition(|&x| x % 2 == 0); ``` ### Response #### Success Response (200) A tuple containing two collections, partitioned according to the predicate. #### Response Example ```rust // Conceptual output // (vec![2, 4], vec![1, 3, 5]) ``` ## is_partitioned

(self, predicate: P) ### Description Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. ### Method `is_partitioned` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) // Note: This is a nightly-only experimental API. // let data = vec![2, 4, 1, 3, 5]; // let is_part = data.into_iter().is_partitioned(|&x| x % 2 == 0); ``` ### Response #### Success Response (200) A boolean indicating whether the iterator is partitioned. #### Response Example ```rust // Conceptual output // true (if partitioned correctly) ``` ## try_fold(&mut self, init: B, f: F) ### Description An iterator method that applies a function as long as it returns successfully, producing a single, final value. ### Method `try_fold` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) let mut data = vec![1, 2, 3]; let result = data.iter().try_fold(0, |acc, &x| { if x < 5 { Ok(acc + x) } else { Err("Too large") } }); ``` ### Response #### Success Response (200) The final accumulated value if the operation succeeds for all elements, or the first error encountered. #### Response Example ```rust // Conceptual output // Result containing Ok(6) or Err("Too large") ``` ## try_for_each(&mut self, f: F) ### Description An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. ### Method `try_for_each` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) let mut data = vec![1, 2, 3]; let result = data.iter().try_for_each(|&x| { if x < 5 { println!("Processing: {}", x); Ok(()) } else { Err("Too large") } }); ``` ### Response #### Success Response (200) `Ok(())` if the function succeeds for all elements, or the first error encountered. #### Response Example ```rust // Conceptual output // Result<(), &str> containing Ok(()) or Err("Too large") ``` ## fold(self, init: B, f: F) ### Description Folds every element into an accumulator by applying an operation, returning the final result. ### Method `fold` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) let data = vec![1, 2, 3]; let sum: i32 = data.iter().fold(0, |acc, &x| acc + x); ``` ### Response #### Success Response (200) The final accumulated value. #### Response Example ```rust // Conceptual output // 6 ``` ## reduce(self, f: F) ### Description Reduces the elements to a single one by repeatedly applying a reducing operation. ### Method `reduce` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (conceptual) let data = vec![1, 2, 3, 4, 5]; let product = data.iter().cloned().reduce(|acc, x| acc * x); ``` ### Response #### Success Response (200) An `Option` containing the single reduced value, or `None` if the iterator was empty. #### Response Example ```rust // Conceptual output // Some(120) ``` ``` -------------------------------- ### Construct SparseSecondaryMap with Capacity Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap_search= Demonstrates creating an empty SparseSecondaryMap with a specified initial capacity. This can help optimize performance by pre-allocating memory. ```rust let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10); let mut sec: SparseSecondaryMap = SparseSecondaryMap::with_capacity(sm.capacity()); ``` -------------------------------- ### Get Mutable Value by Key in HopSlotMap Source: https://docs.rs/slotmap/latest/slotmap/hop/struct.HopSlotMap Illustrates how to obtain a mutable reference to a value in a HopSlotMap using the `get_mut` method. This allows in-place modification of the value. The example shows incrementing a floating-point value. ```rust let mut sm = HopSlotMap::new(); let key = sm.insert(3.5); if let Some(x) = sm.get_mut(key) { *x += 3.0; } assert_eq!(sm[key], 6.5); ``` -------------------------------- ### Construct SparseSecondaryMap with Capacity and Custom Hasher Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap_search= Shows the creation of a SparseSecondaryMap with both a specified capacity and a custom hash builder. This provides fine-grained control over initialization. ```rust let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10); let mut sec: SparseSecondaryMap = SparseSecondaryMap::with_capacity_and_hasher(10, RandomState::new()); ``` -------------------------------- ### Get Key from OccupiedEntry in SlotMap (Rust) Source: https://docs.rs/slotmap/latest/src/slotmap/sparse_secondary.rs_search= The `key` method for `OccupiedEntry` in `SlotMap` returns the key associated with the occupied entry. This is useful when you have an `OccupiedEntry` and need to retrieve its corresponding key, for example, for further lookups or operations. ```rust impl<'a, K: Key, V> OccupiedEntry<'a, K, V> { /// Returns this entry's key. pub fn key(&self) -> K { self.kd.into() } } ``` -------------------------------- ### DenseSlotMap Initialization (Rust) Source: https://docs.rs/slotmap/latest/slotmap/dense/struct.DenseSlotMap Demonstrates how to create a new, empty DenseSlotMap using default keys or with a specified capacity. These methods are fundamental for starting to use the DenseSlotMap. ```Rust use slotmap::DenseSlotMap; // Create a new, empty DenseSlotMap with default keys let mut sm: DenseSlotMap<_, i32> = DenseSlotMap::new(); // Create an empty DenseSlotMap with a specific capacity let mut sm_with_capacity: DenseSlotMap<_, i32> = DenseSlotMap::with_capacity(10); ``` -------------------------------- ### SlotMap Entry Manipulation with SecondaryMap (Rust) Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.SecondaryMap Shows how to use the `entry` method on a SecondaryMap to get an entry associated with a key from a SlotMap. If the entry doesn't exist, it inserts a default value. This example verifies that the inserted value is correct. ```rust let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let k = sm.insert(1); let v = sec.entry(k).unwrap().or_insert(10); assert_eq!(*v, 10); ``` -------------------------------- ### SparseSecondaryMap Constructors Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap_search= Documentation for the constructor methods of SparseSecondaryMap. ```APIDOC ## Constructors ### `SparseSecondaryMap::new()` Constructs a new, empty `SparseSecondaryMap`. #### Method `pub fn new() -> Self` #### Example ```rust use slotmap::SparseSecondaryMap; let mut sec: SparseSecondaryMap = SparseSecondaryMap::new(); ``` ### `SparseSecondaryMap::with_capacity(capacity: usize)` Creates an empty `SparseSecondaryMap` with the given capacity of slots. #### Method `pub fn with_capacity(capacity: usize) -> Self` #### Parameters - **capacity** (`usize`) - The initial capacity of the secondary map. #### Example ```rust use slotmap::{SlotMap, SparseSecondaryMap}; let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10); let mut sec: SparseSecondaryMap = SparseSecondaryMap::with_capacity(sm.capacity()); ``` ### `SparseSecondaryMap::with_hasher(hash_builder: S)` Creates an empty `SparseSecondaryMap` which will use the given hash builder to hash keys. #### Method `pub fn with_hasher(hash_builder: S) -> Self` #### Parameters - **hash_builder** (`S`) - The `BuildHasher` to use for hashing keys. #### Example ```rust use slotmap::{SlotMap, SparseSecondaryMap}; use std::collections::hash_map::RandomState; let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10); let mut sec: SparseSecondaryMap = SparseSecondaryMap::with_hasher(RandomState::new()); ``` ### `SparseSecondaryMap::with_capacity_and_hasher(capacity: usize, hash_builder: S)` Creates an empty `SparseSecondaryMap` with the given capacity of slots, using `hash_builder` to hash the keys. #### Method `pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self` #### Parameters - **capacity** (`usize`) - The initial capacity of the secondary map. - **hash_builder** (`S`) - The `BuildHasher` to use for hashing keys. #### Example ```rust use slotmap::{SlotMap, SparseSecondaryMap}; use std::collections::hash_map::RandomState; let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10); let mut sec: SparseSecondaryMap = SparseSecondaryMap::with_capacity_and_hasher(10, RandomState::new()); ``` ``` -------------------------------- ### Get Disjoint Mutable References (Unchecked) in Rust Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.SecondaryMap This function retrieves mutable references to values corresponding to given keys, assuming they are valid and disjoint. It is unsafe and should only be used if the keys are valid and unique. The example demonstrates how to use the function to swap values. ```Rust let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let ka = sm.insert(()); sec.insert(ka, "butter"); let kb = sm.insert(()); sec.insert(kb, "apples"); let [a, b] = unsafe { sec.get_disjoint_unchecked_mut([ka, kb]) }; std::mem::swap(a, b); assert_eq!(sec[ka], "apples"); assert_eq!(sec[kb], "butter"); ``` -------------------------------- ### Get Mutable Reference (Unchecked) in Rust Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.SecondaryMap This function retrieves a mutable reference to a value in the secondary map, without bounds or version checking. It is unsafe and should only be used when the key is known to exist. The example demonstrates how to use the function and the potential dangers if used incorrectly. ```Rust let mut sm = SlotMap::new(); let key = sm.insert("foo"); let mut sec = SecondaryMap::new(); sec.insert(key, "bar"); unsafe { *sec.get_unchecked_mut(key) = "baz" }; assert_eq!(sec[key], "baz"); sec.remove(key); // sec.get_unchecked_mut(key) is now dangerous! ``` -------------------------------- ### Implement CloneToUninit for generic types Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap_search= Provides an experimental, nightly-only method `clone_to_uninit` for types that implement `Clone`. This allows for efficient copying of data into uninitialized memory. ```rust impl CloneToUninit for T where T: Clone, { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // Implementation details omitted for brevity unimplemented!(); } } ``` -------------------------------- ### Get Disjoint Mutable References in HopSlotMap Source: https://docs.rs/slotmap/latest/slotmap/hop/struct.HopSlotMap Demonstrates the `get_disjoint_mut` method for safely obtaining mutable references to multiple values corresponding to given keys. It returns `None` if any key is invalid or if the keys are not disjoint. The example shows swapping values after successful retrieval. ```rust let mut sm = HopSlotMap::new(); let ka = sm.insert("butter"); let kb = sm.insert("apples"); let kc = sm.insert("charlie"); sm.remove(kc); // Make key c invalid. assert_eq!(sm.get_disjoint_mut([ka, kb, kc]), None); // Has invalid key. assert_eq!(sm.get_disjoint_mut([ka, ka]), None); // Not disjoint. let [a, b] = sm.get_disjoint_mut([ka, kb]).unwrap(); std::mem::swap(a, b); assert_eq!(sm[ka], "apples"); assert_eq!(sm[kb], "butter"); ``` -------------------------------- ### Experimental and Nightly Features Source: https://docs.rs/slotmap/latest/slotmap/dense/struct.IntoIter_search=std%3A%3Avec Documentation for iterator adapters that are currently experimental or only available on the nightly Rust toolchain. ```APIDOC ## Iterator Adapters: Experimental and Nightly Features ### Description This section covers iterator adapters that are considered experimental or are gated behind the nightly Rust toolchain. Use these with caution as they may change or be removed in future versions. ### Methods #### `map_windows(f: F)` - **Description**: Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. Like `slice::windows()`, the windows during mapping overlap as well. This is a nightly-only experimental API. - **Method**: `map_windows` - **Endpoint**: N/A (Iterator method) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: - **Success Response (200)**: An iterator over the results of applying `f` to each window. - **Response Example**: None #### `try_collect()` - **Description**: Fallibly transforms an iterator into a collection, short-circuiting if a failure is encountered. The item type must implement `Try`, and the residual type must implement `Residual`. This is a nightly-only experimental API. - **Method**: `try_collect` - **Endpoint**: N/A (Iterator method) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: - **Success Response (200)**: A collection of type `B` or a residual type indicating failure. - **Response Example**: None #### `collect_into(collection: &mut E)` - **Description**: Collects all the items from an iterator into a mutable collection. The collection type `E` must implement `Extend`. This is a nightly-only experimental API. - **Method**: `collect_into` - **Endpoint**: N/A (Iterator method) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: - **Success Response (200)**: A mutable reference to the collection `E` after items have been added. - **Response Example**: None #### `is_partitioned

(predicate: P)` - **Description**: Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. This is a nightly-only experimental API. - **Method**: `is_partitioned` - **Endpoint**: N/A (Iterator method) - **Parameters**: - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: None - **Request Example**: None - **Response**: - **Success Response (200)**: A boolean value indicating whether the iterator is partitioned. - **Response Example**: None ``` -------------------------------- ### Get Disjoint Mutable References in Rust Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.SecondaryMap This function retrieves mutable references to values corresponding to given keys, ensuring they are valid and disjoint. It returns `None` if any key is invalid or if keys are not disjoint. The example shows how to use the function to swap values and handle potential errors. ```Rust let mut sm = SlotMap::new(); let mut sec = SecondaryMap::new(); let ka = sm.insert(()); sec.insert(ka, "butter"); let kb = sm.insert(()); sec.insert(kb, "apples"); let kc = sm.insert(()); sec.insert(kc, "charlie"); sec.remove(kc); // Make key c invalid. assert_eq!(sec.get_disjoint_mut([ka, kb, kc]), None); // Has invalid key. assert_eq!(sec.get_disjoint_mut([ka, ka]), None); // Not disjoint. let [a, b] = sec.get_disjoint_mut([ka, kb]).unwrap(); std::mem::swap(a, b); assert_eq!(sec[ka], "apples"); assert_eq!(sec[kb], "butter"); ``` -------------------------------- ### SlotMap Initialization with Custom Key Type Source: https://docs.rs/slotmap/latest/slotmap/basic/struct.SlotMap Illustrates creating a SlotMap with a custom key type, allowing for more specific key management. Requires defining a new key type using `new_key_type!` macro. ```rust new_key_type! { struct PositionKey; } let mut positions: SlotMap = SlotMap::with_key(); ``` -------------------------------- ### Unsafe Get Disjoint Mutable References in HopSlotMap Source: https://docs.rs/slotmap/latest/slotmap/hop/struct.HopSlotMap Illustrates the `get_disjoint_unchecked_mut` method, which provides unchecked mutable access to multiple values by key. This unsafe method requires the caller to ensure all keys are valid and distinct. The example swaps values using the obtained mutable references. ```rust let mut sm = HopSlotMap::new(); let ka = sm.insert("butter"); let kb = sm.insert("apples"); let [a, b] = unsafe { sm.get_disjoint_unchecked_mut([ka, kb]) }; std::mem::swap(a, b); assert_eq!(sm[ka], "apples"); assert_eq!(sm[kb], "butter"); ``` -------------------------------- ### Any Implementation Source: https://docs.rs/slotmap/latest/slotmap/struct.HopSlotMap_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides runtime type information for the HopSlotMap. ```APIDOC ## GET /websites/rs_slotmap/type_id ### Description Gets the `TypeId` of `self`, providing runtime type information. ### Method GET ### Endpoint /websites/rs_slotmap/type_id ### Parameters #### Query Parameters - `self` (T) - Required - The instance for which to get the `TypeId`. ### Request Example ```json { "self": "" } ``` ### Response #### Success Response (200) - `TypeId` - The unique identifier for the type of `self`. #### Response Example ```json { "type_id": "" } ``` ``` -------------------------------- ### Unsafe Get Mutable Value Without Bounds Checking in HopSlotMap Source: https://docs.rs/slotmap/latest/slotmap/hop/struct.HopSlotMap Shows the `get_unchecked_mut` method, which provides unchecked mutable access to a value by key. Similar to `get_unchecked`, this method is unsafe and requires the caller to ensure the key's validity to prevent undefined behavior. The example modifies a string value. ```rust let mut sm = HopSlotMap::new(); let key = sm.insert("foo"); unsafe { *sm.get_unchecked_mut(key) = "bar" }; assert_eq!(sm[key], "bar"); sm.remove(key); // sm.get_unchecked_mut(key) is now dangerous! ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/slotmap/latest/slotmap/struct.SecondaryMap Details the nightly-only experimental `clone_to_uninit` method for types implementing the `Clone` trait. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method `unsafe fn` ### Endpoint N/A (Standard Library Implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### SlotMap and SparseSecondaryMap Initialization and Basic Operations (Rust) Source: https://docs.rs/slotmap/latest/src/slotmap/sparse_secondary.rs Demonstrates how to initialize a SlotMap and a SparseSecondaryMap, insert key-value pairs, and retrieve or remove values using keys. This example highlights the basic usage pattern for these data structures. ```Rust # use slotmap::* let mut sm = SlotMap::new(); let key = sm.insert("foo"); let mut sec = SparseSecondaryMap::new(); sec.insert(key, "bar"); assert_eq!(sec.get(key), Some(&"bar")); sec.remove(key); assert_eq!(sec.get(key), None); ``` -------------------------------- ### SparseSecondaryMap Blanket Implementations Source: https://docs.rs/slotmap/latest/slotmap/sparse_secondary/struct.SparseSecondaryMap Details blanket implementations applicable to SparseSecondaryMap, such as Any, Borrow, CloneToUninit, From, Into, ToOwned, TryFrom, and TryInto. ```APIDOC ## Blanket Implementations for SparseSecondaryMap ### Description This section outlines blanket implementations that apply to `SparseSecondaryMap` due to its generic nature and adherence to other traits. These include traits for runtime type information, borrowing, cloning, conversions, and ownership management. ### Implemented Traits and Methods - **Any**: Provides `type_id()` for runtime type identification. - **Borrow**: Provides `borrow()` for immutable borrowing. - **BorrowMut**: Provides `borrow_mut()` for mutable borrowing. - **CloneToUninit**: (Nightly-only experimental) Provides `clone_to_uninit()` for copying to uninitialized memory. - **From**: Provides `from()` for creating a type from another. - **Into**: Provides `into()` for converting a type into another (requires `U: From`). - **ToOwned**: Provides `to_owned()` and `clone_into()` for creating owned versions. - **TryFrom**: Provides `try_from()` for fallible conversions from another type. - **TryInto**: Provides `try_into()` for fallible conversions into another type. ### Endpoint N/A (These are trait implementations, not REST endpoints) ### Parameters None ### Request Body None ### Response #### Success Response (N/A) - **Method Availability**: The specified methods are available for `SparseSecondaryMap` instances if the generic constraints are met. ### Request Example ```rust // Example demonstrating TryInto let map: SparseSecondaryMap<_, _> = /* ... */; // Assuming a compatible target type exists // let converted_map: TargetType = map.try_into().expect("Conversion failed"); ``` ### Response Example ```json // No direct JSON response, indicates availability of blanket implementations ``` ``` -------------------------------- ### Occupied Entry Get Value Source: https://docs.rs/slotmap/latest/src/slotmap/secondary.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets an immutable reference to the value within an occupied entry. ```APIDOC ## GET /websites/rs_slotmap/entry/get ### Description Gets an immutable reference to the value in an occupied entry. ### Method GET ### Endpoint `/websites/rs_slotmap/entry/get` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "Not applicable for this operation" } ``` ### Response #### Success Response (200) - **value** (&V) - A reference to the value within the occupied entry. #### Response Example ```json { "value": "example_value" } ``` ``` -------------------------------- ### DenseSlotMap Initialization with Custom Key (Rust) Source: https://docs.rs/slotmap/latest/slotmap/dense/struct.DenseSlotMap Shows how to initialize a DenseSlotMap with a custom key type, allowing for more specific key management. It also demonstrates initializing with both a custom key and a specified capacity. ```Rust use slotmap::{DenseSlotMap, Key}; // Define a custom key type slotmap::new_key_type! { struct PositionKey; } // Construct a new, empty DenseSlotMap with a custom key type let mut positions: DenseSlotMap = DenseSlotMap::with_key(); // Define another custom key type slotmap::new_key_type! { struct MessageKey; } // Create an empty DenseSlotMap with capacity and a custom key type let mut messages: DenseSlotMap = DenseSlotMap::with_capacity_and_key(3); let welcome_key: MessageKey = messages.insert("Welcome"); let good_day_key = messages.insert("Good day"); let hello_key = messages.insert("Hello"); ``` -------------------------------- ### Occupied Entry Get Mutable Value Source: https://docs.rs/slotmap/latest/src/slotmap/secondary.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a mutable reference to the value within an occupied entry. ```APIDOC ## PUT /websites/rs_slotmap/entry/get_mut ### Description Gets a mutable reference to the value in an occupied entry. ### Method PUT ### Endpoint `/websites/rs_slotmap/entry/get_mut` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "Not applicable for this operation" } ``` ### Response #### Success Response (200) - **value** (&mut V) - A mutable reference to the value within the occupied entry. #### Response Example ```json { "value": "modified_value" } ``` ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/slotmap/latest/slotmap/struct.SecondaryMap Explains the `TryFrom` and `TryInto` traits for fallible type conversions. ```APIDOC #### type Error = Infallible ### Description The type returned in the event of a conversion error for `TryFrom`. #### fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. Returns a `Result` which is `Ok` on success and `Err` on failure. ### Method `fn` ### Endpoint N/A (Standard Library Implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None #### Success Response (200) None #### Response Example None #### type Error = >::Error ### Description The type returned in the event of a conversion error for `TryInto`. #### fn try_into(self) -> Result>::Error> ### Description Performs the conversion. Returns a `Result` which is `Ok` on success and `Err` on failure. ### Method `fn` ### Endpoint N/A (Standard Library Implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### SlotMap Detach, Reattach, and Get Source: https://docs.rs/slotmap/latest/slotmap/struct.SlotMap_search= Illustrates how to temporarily remove a key using `detach`, reattach it with `reattach`, and check its presence with `get`. ```APIDOC ## SlotMap Detach and Reattach ### Description Demonstrates the temporary removal of a key using `detach` and its subsequent reattachment using `reattach`. Also shows how to retrieve values using `get`. ### Method POST /slotmap/detach, POST /slotmap/reattach, GET /slotmap/get ### Endpoint `/slotmap` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `key` (KeyType) - Required - The key to detach or reattach. * `value` (any) - Required - The new value to associate with the key upon reattachment. ### Request Example ```json { "action": "detach", "key": "some_key" } ``` ```json { "action": "reattach", "key": "some_key", "value": 100 } ``` ```json { "action": "get", "key": "some_key" } ``` ### Response #### Success Response (200) * `value` (any) - The value associated with the detached key, if found. * `exists` (boolean) - Indicates if the key exists after reattachment or get operation. #### Response Example ```json { "value": 42 } ``` ```json { "exists": true } ``` ``` -------------------------------- ### Getting the Length of a SecondaryMap (Rust) Source: https://docs.rs/slotmap/latest/slotmap/secondary/struct.SecondaryMap Illustrates how to get the number of elements currently stored in a SecondaryMap. This is useful for checking the size of the map. ```rust let mut sm = SlotMap::new(); let k = sm.insert(4); let mut squared = SecondaryMap::new(); assert_eq!(squared.len(), 0); squared.insert(k, 16); assert_eq!(squared.len(), 1); ```