### HashMap get_mut Example Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Shows how to get a mutable reference to a value associated with a key using `get_mut`. This allows in-place modification of the value if the key exists. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### Get Disjoint Unchecked Mut Example Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Demonstrates the use of `get_disjoint_unchecked_mut` for safely obtaining mutable references to multiple disjoint entries in a HashMap. It shows scenarios with overlapping and non-existent keys. ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // SAFETY: The keys do not overlap. let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Bodleian Library", ]) }) else { panic!() }; // SAFETY: The keys do not overlap. let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Library of Congress", ]) }; assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // SAFETY: The keys do not overlap. let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "New York Public Library", ]) }; // Missing keys result in None assert_eq!(got, [Some(&mut 1807), None]); ``` -------------------------------- ### get Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Returns a shared reference to the output at this location, if in bounds. This is a nightly-only experimental API. ```APIDOC ## fn get ### Description Returns a shared reference to the output at this location, if in bounds. ### Method `get` ### Parameters #### Path Parameters - **slice** (`&str`) - Required - The string slice to get the reference from. ### Response #### Success Response - **Output** (`Option<& as SliceIndex>::Output>`) - A shared reference to the output if the range is within bounds, otherwise None. ``` -------------------------------- ### HashMap with Capacity Example Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Demonstrates how to create a HashMap with a specified initial capacity. The capacity returned is a lower bound. ```rust use std::collections::HashMap; let map: HashMap = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### HashMap insert Example Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Demonstrates inserting key-value pairs into a HashMap using the `insert` method. It shows how `insert` returns `None` for new keys and the old value for updated keys. ```rust use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.insert(37, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[&37], "c"); ``` -------------------------------- ### HashMap remove_entry Example Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Demonstrates removing a key-value pair and retrieving both the key and value using `remove_entry`. This is useful when the key itself is needed after removal. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove_entry(&1), Some((1, "a"))); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### Handling Start of HTML Entity in Rust Source: https://docs.rs/htmlentity/latest/src/htmlentity/entity.rs.html This snippet manages the beginning of an HTML entity. It appends the preceding data and resets the start index for the new entity. ```rust data.extend_from_slice(&content[start_index - 1..idx]); start_index = idx + 1; ``` -------------------------------- ### HashMap try_insert Example (Nightly) Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Illustrates the experimental `try_insert` method for inserting a key-value pair. It returns a mutable reference on success or an error containing the occupied entry and the new value if the key already exists. ```rust #![feature(map_try_insert)] use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.try_insert(37, "a").unwrap(), &"a"); let err = map.try_insert(37, "b").unwrap_err(); assert_eq!(err.entry.key(), &37); assert_eq!(err.entry.get(), &"a"); assert_eq!(err.value, "b"); ``` -------------------------------- ### Get the Start of a RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Retrieves the lower bound of an inclusive range. ```rust assert_eq!((3..=5).start(), &3); ``` -------------------------------- ### entry Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Gets the given key’s corresponding entry in the map for in-place manipulation. ```APIDOC ## pub fn entry(&mut self, key: K) -> Entry<'_, K, V> ### Description Gets the given key’s corresponding entry in the map for in-place manipulation. ### Parameters - **key** (K) - The key to get the entry for. ### Returns - `Entry<'_, K, V>`: An enum that allows in-place modification of the map based on the key's presence. ### Examples ```rust use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1); } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None); ``` ``` -------------------------------- ### HashMap remove Example Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Shows how to remove a key-value pair from a HashMap using the `remove` method. It returns the value associated with the key if it was present, otherwise `None`. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### get Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Retrieves a reference to the value corresponding to the key. The key can be any borrowed form of the map's key type. ```APIDOC ## get ### Description 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. ### Method `get(&self, k: &Q) -> Option<&V>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` ### Response #### Success Response (200) - **V** (Option<&V>) - A reference to the value if the key exists, otherwise None. #### Response Example ```json { "example": "Some(\"a\")" } ``` ``` -------------------------------- ### get Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.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. ```APIDOC ## get ### Description Returns a reference to the value corresponding to the key. ### Method `pub fn get(&self, k: &Q) -> Option<&V>` ### Parameters #### Path Parameters None #### Query Parameters - **k** (Q) - The key to look up. ### Response #### Success Response (Option<&V>) - `Some(&V)` if the key exists, `None` otherwise. ### Examples ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` ``` -------------------------------- ### Convert CharEntity to Byte List Source: https://docs.rs/htmlentity/latest/src/htmlentity/entity.rs.html The `to_bytes` method provides a convenient way to get the byte representation of a `CharEntity` by calling `write_bytes` internally. ```rust pub fn to_bytes(&self) -> ByteList { let mut bytes: ByteList = Vec::with_capacity(self.entity_data.len() + 2); self.write_bytes(&mut bytes); bytes } ``` -------------------------------- ### First Letter Position Data Initialization Source: https://docs.rs/htmlentity/latest/src/htmlentity/data.rs.html Initializes a static hash map containing the byte range for the first letter of HTML entities. This is used for efficient lookup of entities starting with a specific letter. ```rust lazy_static! { pub static ref FIRST_LETTER_POSITION: FirstLetterRange = { let mut data: FirstLetterRange = HashMap::with_capacity(52); data.insert(b'Y', (558, 568)); ``` -------------------------------- ### Getting HashMap Length Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Shows how to get the number of elements currently stored in a HashMap. The length is updated after insertions and removals. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### Get multiple mutable references unchecked Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Attempts to get mutable references to multiple values simultaneously without validating uniqueness. Calling with overlapping keys results in undefined behavior. ```rust pub unsafe fn get_disjoint_unchecked_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] where K: Borrow, Q: Hash + Eq + ?Sized, Attempts to get mutable references to `N` values in the map at once, without validating that the values are unique. Returns an array of length `N` with the results of each query. `None` will be used if the key is missing. For a safe alternative see `get_disjoint_mut`. ``` -------------------------------- ### Iterating Over HashMap Keys Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Shows how to iterate over all keys in a HashMap. Note that iteration performance is O(capacity) in the current implementation. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for key in map.keys() { println!("{key}"); } ``` -------------------------------- ### Get multiple mutable references safely Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Attempts to get mutable references to multiple values simultaneously. Ensures that no two mutable references point to the same value. Panics if duplicate keys are provided. ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // Get Athenæum and Bodleian Library let [Some(a), Some(b)] = libraries.get_disjoint_mut([ "Athenæum", "Bodleian Library", ]) else { panic!() }; // Assert values of Athenæum and Library of Congress let got = libraries.get_disjoint_mut([ "Athenæum", "Library of Congress", ]); assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // Missing keys result in None let got = libraries.get_disjoint_mut([ "Athenæum", "New York Public Library", ]); assert_eq!( got, [ Some(&mut 1807), None ] ); ``` ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Athenæum".to_string(), 1807); // Duplicate keys panic! let got = libraries.get_disjoint_mut([ "Athenæum", "Athenæum", ]); ``` -------------------------------- ### get_key_value Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.BytesCharEntity.html Retrieves the key-value pair corresponding to the supplied key. This is useful for key types where non-identical keys can be considered equal, for getting the stored key value from a borrowed lookup key, or for getting a reference to a key with the same lifetime as the collection. ```APIDOC ## get_key_value ### Description Returns the key-value pair corresponding to the supplied key. This is potentially useful: * for key types where non-identical keys can be considered equal; * for getting the `&K` stored key value from a borrowed `&Q` lookup key; or * for getting a reference to a key with the same lifetime as the collection. 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. ### Method `get_key_value` ### Parameters #### Path Parameters - **k** (Q) - Description: The key to look up. #### Query Parameters None #### Request Body None ### Response #### Success Response (Option<(&K, &V)>) - **Some((&K, &V))**: A tuple containing references to the key and value if the key is found. - **None**: If the key is not found. ### Request Example ```rust use std::collections::HashMap; use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and hashing operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl Hash for S { fn hash(&self, state: &mut H) { self.id.hash(state); } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = HashMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` ``` -------------------------------- ### Create a HashMap with capacity and custom hasher Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html This creates an empty HashMap with a specified capacity and a custom hash builder. Be cautious about using custom hashers due to potential DoS vulnerabilities. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` -------------------------------- ### HashMap::new Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.BytesCharEntity.html Creates an empty HashMap with no initial capacity. It will allocate memory on the first insertion. ```APIDOC ## HashMap::new() ### Description Creates an empty `HashMap`. The hash map is initially created with a capacity of 0, so it will not allocate until it is first inserted into. ### Method `new()` ### Parameters None ### Returns An empty `HashMap`. ### Examples ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::new(); ``` ``` -------------------------------- ### Get multiple mutable references unchecked in HashMap Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.BytesCharEntity.html Use `get_disjoint_unchecked_mut` to attempt to get mutable references to multiple values without validating that the values are unique. This method is unsafe and calling it with overlapping keys results in undefined behavior. ```rust pub unsafe fn get_disjoint_unchecked_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] where K: Borrow, Q: Hash + Eq + ?Sized, Attempts to get mutable references to `N` values in the map at once, without validating that the values are unique. Returns an array of length `N` with the results of each query. `None` will be used if the key is missing. For a safe alternative see `get_disjoint_mut`. ##### §Safety Calling this method with overlapping keys is _undefined behavior_ even if the resulting references are not used. ``` -------------------------------- ### Initialize Normal Name Entity Map Source: https://docs.rs/htmlentity/latest/src/htmlentity/entity.rs.html Sets up a static HashMap to map common entity names (like 'lt', 'gt', 'amp', 'quot', 'apos', 'nbsp') back to their corresponding characters. This is crucial for decoding named HTML entities. ```rust lazy_static! { // normal name entity static ref NORMAL_NAME_ENTITY_BYTE: BytesCharEntity = { let mut map: BytesCharEntity = HashMap::with_capacity(10); map.insert(b"lt", '<'); map.insert(b"LT", '<'); map.insert(b"gt", '>'); map.insert(b"GT", '>'); map.insert(b"amp", '&'); map.insert(b"AMP", '&'); map.insert(b"quot", '"'); map.insert(b"QUOT", '"'); map.insert(b"apos", '\''); map.insert(b"nbsp", 0xa0 as char); map }; } ``` -------------------------------- ### Get the End of a RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Retrieves the upper bound of an inclusive range. ```rust assert_eq!((3..=5).end(), &5); ``` -------------------------------- ### Destructure a RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Converts an inclusive range into a tuple of its start and end bounds. ```rust assert_eq!((3..=5).into_inner(), (3, 5)); ``` -------------------------------- ### IBytesTrait Implementation for CharEntity Source: https://docs.rs/htmlentity/latest/htmlentity/entity/struct.CharEntity.html Implementation of the `IBytesTrait` for `CharEntity`. ```APIDOC ### impl IBytesTrait for CharEntity #### `fn byte(&self, index: usize) -> Option<&Byte>` Returns a reference to the byte at the specified index, if it exists. #### `fn bytes_len(&self) -> usize` Returns the total number of bytes in the character entity. ``` -------------------------------- ### Iterating Over HashMap Key-Value Pairs Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Illustrates how to iterate over all key-value pairs in a HashMap. Performance is O(capacity) due to internal implementation details. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for (key, val) in map.iter() { println!("key: {key} val: {val}"); } ``` -------------------------------- ### Reverse Fold on RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Reduces the iterator's elements to a single value, starting from the back. ```rust fn rfold(self, init: AAA, fold: FFF) -> AAA where FFF: FnMut(AAA, as Iterator>::Item) -> AAA, A: Step; ``` -------------------------------- ### IBytesTrait Methods Source: https://docs.rs/htmlentity/latest/htmlentity/entity/trait.IBytesTrait.html This snippet details the methods available on the IBytesTrait. These methods are intended to be implemented by types that represent byte sequences. ```APIDOC ## Trait IBytesTrait ### Summary Provides an interface for accessing bytes within a data structure. ### Methods #### fn byte(&self, index: usize) -> Option<&Byte> Retrieves a reference to a byte at the specified index. Returns `None` if the index is out of bounds. #### fn bytes_len(&self) -> usize Returns the total number of bytes in the data structure. ``` -------------------------------- ### take Source: https://docs.rs/htmlentity/latest/htmlentity/entity/struct.DataIter.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Signature `fn take(self, n: usize) -> Take` ### Type Parameters - `Self`: The type of the iterator, must implement `Sized`. ``` -------------------------------- ### Get the Nth Element from the End of a RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Returns the nth element from the end of the inclusive range iterator. ```rust fn nth_back(&mut self, n: usize) -> Option where A: Step; ``` -------------------------------- ### HashMap::with_capacity_and_hasher Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.BytesCharEntity.html Creates an empty HashMap with specified capacity and a custom hash builder. ```APIDOC ## HashMap::with_capacity_and_hasher(capacity: usize, hasher: S) ### Description Creates an empty `HashMap` with at least the specified capacity, using `hasher` to hash the keys. ### Method `with_capacity_and_hasher(capacity: usize, hasher: S)` ### Parameters * **capacity** (usize) - The minimum capacity for the HashMap. * **hasher** (S) - The hash builder to use for hashing keys. Must implement `BuildHasher`. ### Returns An empty `HashMap` with the specified capacity and hash builder. ### Warning Manually setting the `hasher` can expose a Denial-of-Service (DoS) attack vector. ### Examples ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` ``` -------------------------------- ### Try Reverse Fold on RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html A reverse version of `Iterator::try_fold()`, taking elements starting from the back. ```rust fn try_rfold(&mut self, init: B, f: F) -> R where RangeInclusive: Sized, F: FnMut(B, as Iterator>::Item) -> R, R: Try, A: Step; ``` -------------------------------- ### partition Source: https://docs.rs/htmlentity/latest/htmlentity/entity/struct.DataIter.html Consumes an iterator, creating two collections from it. ```APIDOC ## partition ### Description Consumes the iterator and partitions its elements into two collections based on a predicate. ### Signature `fn partition(self, f: F) -> (B, B)` ### Type Parameters - `B`: The type of the collections to create, must implement `Default` and `Extend`. - `F`: The type of the closure, which takes a reference to an item and returns a boolean indicating which partition it belongs to. - `Self`: The type of the iterator, must implement `Sized`. ``` -------------------------------- ### Getting HashMap Hasher Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Retrieves a reference to the `BuildHasher` used by the HashMap. This is useful for understanding or replicating the hashing strategy. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### Default HashMap Creation Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Creates an empty HashMap with the default hasher. ```APIDOC ## fn default() -> HashMap ### Description Creates an empty `HashMap`, with the `Default` value for the hasher. ### Method `default()` ### Returns A new, empty `HashMap`. ``` -------------------------------- ### Create a New RangeInclusive Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Demonstrates creating a new inclusive range using RangeInclusive::new(). ```rust use std::ops::RangeInclusive; assert_eq!(3..=5, RangeInclusive::new(3, 5)); ``` -------------------------------- ### get_disjoint_unchecked_mut Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Attempts to get mutable references to multiple values in the map at once, without validating that the values are unique. This is an unsafe operation. ```APIDOC ## get_disjoint_unchecked_mut ### Description Attempts to get mutable references to `N` values in the map at once, without validating that the values are unique. Returns an array of length `N` with the results of each query. `None` will be used if the key is missing. For a safe alternative see `get_disjoint_mut`. ### Method `get_disjoint_unchecked_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Safety Calling this method with overlapping keys is _undefined behavior_ even if the resulting references are not used. ### Response #### Success Response (200) - **[Option<&mut V>; N]** - An array of mutable references to the values, or None if the key was not found. #### Response Example ```json { "example": "[Some(&mut 1807), None]" } ``` ``` -------------------------------- ### Create a HashMap with a custom hasher Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html This creates an empty HashMap that uses a provided hash builder for hashing keys. Be cautious about using custom hashers due to potential DoS vulnerabilities. ```rust use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let mut map = HashMap::with_hasher(s); map.insert(1, 2); ``` -------------------------------- ### Initialize HTML Bytes Map Source: https://docs.rs/htmlentity/latest/src/htmlentity/entity.rs.html Initializes a static HashMap to store common HTML byte entities like '>', '<', and '&'. This map is used for quick lookups during encoding. ```rust lazy_static! { // html bytes static ref HTML_BYTES: EntityCharBytes = { let mut map: EntityCharBytes = HashMap::with_capacity(3); map.insert('>', b"gt"); map.insert('<', b"lt"); map.insert('&', b"amp"); map }; } ``` -------------------------------- ### Check if a RangeInclusive is Empty Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Determines if the range contains any items. An empty range occurs when start > end or when bounds are incomparable. ```rust assert!(!(3..=5).is_empty()); assert!(!(3..=3).is_empty()); assert!( (3..=2).is_empty()); ``` ```rust assert!(!(3.0..=5.0).is_empty()); assert!( (3.0..=f32::NAN).is_empty()); assert!( (f32::NAN..=5.0).is_empty()); ``` ```rust let mut r = 3..=5; for _ in r.by_ref() {} // Precise field values are unspecified here assert!(r.is_empty()); ``` -------------------------------- ### Getting Value by Key from HashMap Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Retrieves a reference to the value associated with a given key. Returns `None` if the key is not found in the map. ```rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Encode and Decode HTML Entities Source: https://docs.rs/htmlentity/latest/src/htmlentity/lib.rs.html Demonstrates encoding a string into HTML entities and then decoding it back. Shows how to convert the results to bytes, strings, and character vectors. Ensure the necessary types and functions are imported. ```rust use htmlentity::entity::{ encode, decode, EncodeType, CharacterSet, ICodedDataTrait }; use htmlentity::types::{ AnyhowResult, Byte }; # fn main() -> AnyhowResult<()> { let html = "
Hello!世界!
"; let html_after_encoded = "<div name='htmlentity'>Hello!世界!</div>"; // encode let encoded_data = encode( html.as_bytes(), &EncodeType::NamedOrHex, &CharacterSet::HtmlAndNonASCII ); // encoded data to bytes assert_eq!( encoded_data.to_bytes(), html_after_encoded.as_bytes() ); // encoded data to string assert_eq!( encoded_data.to_string()?, String::from(html_after_encoded) ); // encoded data to chars assert_eq!( encoded_data.to_chars()?, String::from(html_after_encoded).chars().collect::>() ); // decode let bytes = encoded_data .into_iter() .map(|(byte, _)| *byte) .collect::>(); let decoded_data = decode(&bytes); // decoded data to bytes assert_eq!( decoded_data.to_bytes(), html.as_bytes() ); // decoded data to string assert_eq!( decoded_data.to_string()?, String::from(html) ); // decoded data to chars assert_eq!( decoded_data.to_chars()?, String::from(html).chars().collect::>() ); # Ok(()) # } ``` -------------------------------- ### Get TypeId of CharacterSet Source: https://docs.rs/htmlentity/latest/htmlentity/entity/enum.CharacterSet.html Obtains the unique `TypeId` for the CharacterSet type. This is part of the `Any` trait implementation and is useful for runtime type introspection. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### partition_in_place Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Reorders elements in-place based on a predicate. This is a nightly-only experimental API. ```APIDOC ## fn partition_in_place<'a, T, P>(self, predicate: P) -> usize ### Description Reorders the elements of this iterator _in-place_ according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. ### Note This is a nightly-only experimental API. (`iter_partition_in_place`) ### Parameters - `predicate`: A closure that takes a reference to an element and returns a boolean. ### Returns The number of elements for which the predicate returned `true`. ### Type Parameters - `'a`: Lifetime parameter. - `T`: The type of the elements in the iterator. - `P`: The type of the closure. Must be `FnMut`. ### Constraints - `T` must have lifetime `'a`. - `Self` must be `Sized` and a `DoubleEndedIterator` yielding `&'a mut T`. ### Example ```rust // This is an example of how it might be used, but requires nightly Rust. // let mut data = vec![1, 2, 3, 4, 5]; // let count = data.iter_mut().partition_in_place(|&mut x| x % 2 == 0); // assert_eq!(count, 2); // assert_eq!(data, vec![2, 4, 1, 3, 5]); // Order of false elements is not guaranteed ``` ``` -------------------------------- ### Implement IBytesTrait for CharEntity Source: https://docs.rs/htmlentity/latest/src/htmlentity/entity.rs.html Provides byte-level access to a CharEntity, handling prefixes like '&', '#', and 'x', as well as the entity data and the trailing ';'. ```rust impl IBytesTrait for CharEntity { fn byte(&self, index: usize) -> Option<&Byte> { let prefix_len = self.prefix_len(); if index > prefix_len { // from entity data or let cur_index = index - prefix_len - 1; return match cur_index.cmp(&self.entity_data.len()) { Ordering::Less => self.entity_data.get(cur_index), Ordering::Equal => Some(&b';'), Ordering::Greater => None, }; } else if index == 0 { // the first byte return Some(&b'&'); } else { // the next prefix bytes match prefix_len { 1 => Some(&b'#'), 2 => { if index == 1 { return Some(&b'#'); } Some(&b'x') } _ => unreachable!(), } } } fn bytes_len(&self) -> usize { let prefix_len = self.prefix_len(); // '&;' => 2 '#'|'#x' => prefix_len 2 + prefix_len + self.entity_data.len() } } ``` -------------------------------- ### get_key_value Source: https://docs.rs/htmlentity/latest/htmlentity/data/struct.FIRST_LETTER_POSITION.html Returns the key-value pair corresponding to the supplied key. This is potentially useful for key types where non-identical keys can be considered equal, for getting the `&K` stored key value from a borrowed `&Q` lookup key, or for getting a reference to a key with the same lifetime as the collection. 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. ```APIDOC ## get_key_value ### Description Returns the key-value pair corresponding to the supplied key. ### Method `pub fn get_key_value(&self, k: &Q) -> Option<(&K, &V)>` ### Parameters #### Path Parameters None #### Query Parameters - **k** (Q) - The key to look up. ### Response #### Success Response (Option<(&K, &V)>) - `Some((&K, &V))` if the key exists, `None` otherwise. ### Examples ```rust use std::collections::HashMap; use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and hashing operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl Hash for S { fn hash(&self, state: &mut H) { self.id.hash(state); } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = HashMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` ``` -------------------------------- ### by_ref Source: https://docs.rs/htmlentity/latest/htmlentity/entity/struct.DataIter.html Creates a “by reference” adapter for this instance of `Iterator`. ```APIDOC ## by_ref ### Description Creates an adapter that allows borrowing the iterator by reference, enabling methods that consume `self` to be called without taking ownership. ### Signature `fn by_ref(&mut self) -> &mut Self` ### Type Parameters - `Self`: The type of the iterator, must implement `Sized`. ``` -------------------------------- ### Create an empty HashMap Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Use this function to create an empty HashMap. It will not allocate memory until the first element is inserted. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::new(); ``` -------------------------------- ### get_disjoint_mut Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Attempts to get mutable references to multiple values in the map at once. Returns an array of results, with `None` for missing keys. Panics if any keys are overlapping. ```APIDOC ## get_disjoint_mut ### Description Attempts to get mutable references to `N` values in the map at once. Returns an array of length `N` with the results of each query. For soundness, at most one mutable reference will be returned to any value. `None` will be used if the key is missing. This method performs a check to ensure there are no duplicate keys, which currently has a time-complexity of O(n^2), so be careful when passing many keys. ### Method `get_disjoint_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // Get Athenæum and Bodleian Library let [Some(a), Some(b)] = libraries.get_disjoint_mut([ "Athenæum", "Bodleian Library", ]) else { panic!() }; // Assert values of Athenæum and Library of Congress let got = libraries.get_disjoint_mut([ "Athenæum", "Library of Congress", ]); assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // Missing keys result in None let got = libraries.get_disjoint_mut([ "Athenæum", "New York Public Library", ]); assert_eq!( got, [ Some(&mut 1807), None ] ); ``` ### Panics Panics if any keys are overlapping. ### Response #### Success Response (200) - **[Option<&mut V>; N]** - An array of mutable references to the values, or None if the key was not found. #### Response Example ```json { "example": "[Some(&mut 1807), Some(&mut 1800)]" } ``` ``` -------------------------------- ### index Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRange.html Returns a shared reference to the output at this location, panicking if out of bounds. This is a nightly-only experimental API. ```APIDOC ## fn index ### Description Returns a shared reference to the output at this location, panicking if out of bounds. ### Method `index` ### Parameters #### Path Parameters - **slice** (`&str`) - Required - The string slice to index into. ### Response #### Success Response - **Output** (`& as SliceIndex>::Output`) - A shared reference to the output. ``` -------------------------------- ### Iterate and Mutate Values in HashMap Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Use `values_mut` to get a mutable iterator over the values. Modify values in place. The iterator element type is `&'a mut V`. ```rust use std::collections::HashMap; let mut map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for val in map.values_mut() { *val = *val + 10; } for val in map.values() { println!("{val}"); } ``` -------------------------------- ### partial_cmp_by Source: https://docs.rs/htmlentity/latest/htmlentity/entity/struct.DataIter.html A nightly-only experimental API that lexicographically compares elements using a custom partial comparison function. It returns `Option` and supports short-circuit evaluation. ```APIDOC ## fn partial_cmp_by(self, other: I, partial_cmp: F) -> Option where Self: Sized, I: IntoIterator, F: FnMut(Self::Item, ::Item) -> Option, 🔬This is a nightly-only experimental API. (`iter_order_by`) Lexicographically compares the elements of this `Iterator` with those of another with respect to the specified comparison function. Read more 1.5.0 · Source ``` -------------------------------- ### Iterate and Mutate Key-Value Pairs in HashMap Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Use `iter_mut` to get an iterator over key-value pairs with mutable references to values. The iterator element type is `(&'a K, &'a mut V)`. ```rust use std::collections::HashMap; let mut map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); // Update all values for (_, val) in map.iter_mut() { *val *= 2; } for (key, val) in &map { println!("key: {key} val: {val}"); } ``` -------------------------------- ### CodeRangeTuple Type Alias Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.CodeRangeTuple.html Defines a type alias `CodeRangeTuple` as a tuple of two `usize` values, commonly used to represent a range within code, such as start and end indices. ```APIDOC ## Type Alias CodeRangeTuple ### Summary ```rust pub type CodeRangeTuple = (usize, usize); ``` ### Description This type alias represents a tuple of two `usize` values. It is typically used to denote a range, where the first element is the start index and the second element is the end index (exclusive or inclusive, depending on usage context). This is a common pattern for representing character or byte ranges within a string or byte slice. ``` -------------------------------- ### Create a HashMap with capacity Source: https://docs.rs/htmlentity/latest/htmlentity/data/type.FirstLetterRange.html Use this function to create an empty HashMap with a specified initial capacity to avoid reallocations. ```rust use std::collections::HashMap; let mut map: HashMap<&str, i32> = HashMap::with_capacity(10); ``` -------------------------------- ### get_disjoint_mut Source: https://docs.rs/htmlentity/latest/htmlentity/types/type.BytesCharEntity.html Attempts to get mutable references to multiple values in the map at once. Returns an array of results, with `None` for missing keys. It includes a check for duplicate keys, which has a time complexity of O(n^2). ```APIDOC ## get_disjoint_mut ### Description Attempts to get mutable references to `N` values in the map at once. Returns an array of length `N` with the results of each query. For soundness, at most one mutable reference will be returned to any value. `None` will be used if the key is missing. This method performs a check to ensure there are no duplicate keys, which currently has a time-complexity of O(n^2), so be careful when passing many keys. ### Method `get_disjoint_mut` ### Parameters #### Path Parameters - **ks** ([&Q; N]) - Description: An array of keys to look up. #### Query Parameters None #### Request Body None ### Response #### Success Response ([Option<&mut V>; N]) - **[Option<&mut V>; N]**: An array of mutable references to the values, or `None` if the key is not found. ### Panics Panics if any keys are overlapping. ### Request Example ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // Get Athenæum and Bodleian Library let [Some(a), Some(b)] = libraries.get_disjoint_mut([ "Athenæum", "Bodleian Library", ]) else { panic!() }; // Assert values of Athenæum and Library of Congress let got = libraries.get_disjoint_mut([ "Athenæum", "Library of Congress", ]); assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // Missing keys result in None let got = libraries.get_disjoint_mut([ "Athenæum", "New York Public Library", ]); assert_eq!( got, [ Some(&mut 1807), None ] ); ``` ⓘ``` use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Athenæum".to_string(), 1807); // Duplicate keys panic! let got = libraries.get_disjoint_mut([ "Athenæum", "Athenæum", ]); ``` ``` -------------------------------- ### Initialize Special Bytes Map Source: https://docs.rs/htmlentity/latest/src/htmlentity/entity.rs.html Initializes a static HashMap for special byte entities, including quotes and apostrophes, and merges them with the common HTML entities. Useful for comprehensive entity encoding. ```rust lazy_static! { // special bytes static ref SPECIAL_BYTES: EntityCharBytes = { let mut map: EntityCharBytes = HashMap::with_capacity(5); map.insert('"', b"quot"); map.insert('"', b"apos"); for (k, v) in HTML_BYTES.iter(){ map.insert(*k, *v); } map }; } ```