### HashMap From implementation example Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Shows how to construct a HashMap from an array of key-value pairs. ```rust use std::collections::HashMap; let map1 = HashMap::from([(1, 2), (3, 4)]); let map2: HashMap<_, _> = [(1, 2), (3, 4)].into(); assert_eq!(map1, map2); ``` -------------------------------- ### BTreeMap::new Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Creates a new empty BTreeMap and inserts an entry. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); // entries can now be inserted into the empty map map.insert(1, "a"); ``` -------------------------------- ### split_off example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Splits a BTreeMap at a given key, returning a new map with all entries from that key onward. The original map retains entries before the key. The example shows the resulting lengths and values for both maps. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "a"); a.insert(2, "b"); a.insert(3, "c"); a.insert(17, "d"); a.insert(41, "e"); let b = a.split_off(&3); assert_eq!(a.len(), 2); assert_eq!(b.len(), 3); assert_eq!(a[&1], "a"); assert_eq!(a[&2], "b"); assert_eq!(b[&3], "c"); assert_eq!(b[&17], "d"); assert_eq!(b[&41], "e"); ``` -------------------------------- ### get(&self, k: &Q) -> Option<&V> Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Returns a reference to the value corresponding to the key. ```APIDOC ## `get(&self, k: &Q) -> Option<&V>` ### 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` ### Parameters - **k** (`&Q`) - Required - The key to look up. Can be any borrowed form of the map's key type. ### Return Value - **Option<&V>** - A reference to the value corresponding to the key, or `None` if the key is not present. ### 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 Returns `Some(&V)` if the key is present, otherwise `None`. ### Notes - **Version**: 1.40.0 ``` -------------------------------- ### BTreeMap::iter Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Iterates over entries sorted by key, printing key-value pairs and asserting the first entry. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(3, "c"); map.insert(2, "b"); map.insert(1, "a"); for (key, value) in map.iter() { println!("{key}: {value}"); } let (first_key, first_value) = map.iter().next().unwrap(); assert_eq!((*first_key, *first_value), (1, "a")); ``` -------------------------------- ### BTreeMap::entry example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Gets the given key’s corresponding entry in the map for in-place manipulation. The example counts occurrences of letters in a vector by using `entry` with `and_modify` and `or_insert`. ```rust use std::collections::BTreeMap; let mut count: BTreeMap<&str, usize> = BTreeMap::new(); // count the number of occurrences of letters in the vec for x in ["a", "b", "a", "c", "a", "b"] { count.entry(x).and_modify(|curr| *curr += 1).or_insert(1); } assert_eq!(count["a"], 3); assert_eq!(count["b"], 2); assert_eq!(count["c"], 1); ``` -------------------------------- ### BTreeMap::last_key_value example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Shows how to get the last key-value pair (the maximum key) using BTreeMap::last_key_value. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "b"); map.insert(2, "a"); assert_eq!(map.last_key_value(), Some((&2, &"a"))); ``` -------------------------------- ### Retrieve values with get Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Returns a reference to the value corresponding to the provided key. ```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); ``` -------------------------------- ### BTreeMap::keys Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Collects keys in sorted order into a vector and asserts the result. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(2, "b"); a.insert(1, "a"); let keys: Vec<_> = a.keys().cloned().collect(); assert_eq!(keys, [1, 2]); ``` -------------------------------- ### BTreeMap::range example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Constructs a double-ended iterator over a sub-range of elements. The example uses `range((Included(&4), Included(&8)))` to yield a left-inclusive, right-inclusive range from 4 to 8, and also shows `range(4..)` to get a range starting at 4. Panics if `start > end` or if `start == end` with both bounds `Excluded`. ```rust use std::collections::BTreeMap; use std::ops::Bound::Included; let mut map = BTreeMap::new(); map.insert(3, "a"); map.insert(5, "b"); map.insert(8, "c"); for (&key, &value) in map.range((Included(&4), Included(&8))) { println!("{key}: {value}"); } assert_eq!(Some((&5, &"b")), map.range(4..).next()); ``` -------------------------------- ### BTreeMap::pop_first example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Shows how to drain elements in ascending order using BTreeMap::pop_first while keeping a usable map each iteration. The map becomes empty after all elements are popped. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); map.insert(2, "b"); while let Some((key, _val)) = map.pop_first() { assert!(map.iter().all(|(k, _v)| *k > key)); } assert!(map.is_empty()); ``` -------------------------------- ### BTreeMap::get example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Shows how to retrieve a value by key using BTreeMap::get. The key may be any borrowed form of the map's key type, but the ordering on the borrowed form must match the ordering on the key type. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### BTreeMap::is_empty Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Checks if a BTreeMap is empty before and after insertion. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); ``` -------------------------------- ### into_keys example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Consumes the BTreeMap and collects all keys into a vector in sorted order. The map cannot be used after calling into_keys. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(2, "b"); a.insert(1, "a"); let keys: Vec = a.into_keys().collect(); assert_eq!(keys, [1, 2]); ``` -------------------------------- ### BTreeMap::len Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Checks the length of a BTreeMap before and after insertion. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### BTreeMap::values Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Collects values in order by key into a vector and asserts the result. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "hello"); a.insert(2, "goodbye"); let values: Vec<&str> = a.values().cloned().collect(); assert_eq!(values, ["hello", "goodbye"]); ``` -------------------------------- ### BTreeMap::first_entry example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Demonstrates BTreeMap::first_entry for in-place manipulation of the first entry (minimum key). The entry is an OccupiedEntry that allows modifying the value. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); map.insert(2, "b"); if let Some(mut entry) = map.first_entry() { if *entry.key() > 0 { entry.insert("first"); } } assert_eq!(*map.get(&1).unwrap(), "first"); assert_eq!(*map.get(&2).unwrap(), "b"); ``` -------------------------------- ### BTreeMap::try_insert example (nightly-only) Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Tries to insert a key-value pair into a BTreeMap without updating an existing key. Requires the nightly-only experimental API `map_try_insert`. Returns a mutable reference to the value on success, or an `OccupiedError` containing the existing entry, key, and value on failure. ```rust #![feature(map_try_insert)] use std::collections::BTreeMap; let mut map = BTreeMap::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.key, 37); assert_eq!(err.value, "b"); ``` -------------------------------- ### Convert Markdown to HTML with convert Source: https://docs.rs/ferrodoc/latest/index.html Use the convert function with a byte slice in Markdown format to produce HTML output. The example expects a specific HTML string with proper escaping. ```Rust let html = convert(b"# Title\n\nHello *world*.\n", Format::Markdown, Format::Html)?; assert_eq!( String::from_utf8(html)?, "

Title

\n

Hello world.

\n" ); ``` -------------------------------- ### BTreeMap::iter_mut Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Mutably iterates over entries, adding 10 to values unless the key is "a". ```rust use std::collections::BTreeMap; let mut map = BTreeMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); // add 10 to the value if the key isn't "a" for (key, value) in map.iter_mut() { if key != &"a" { *value += 10; } } ``` -------------------------------- ### get_key_value(&self, k: &Q) -> Option<(&K, &V)> Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Returns the key-value pair corresponding to the supplied key. 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. ```APIDOC ## get_key_value(&self, k: &Q) -> Option<(&K, &V)> ### Description Returns the key-value pair corresponding to the supplied key. 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. ### Method Rust method ### Signature ```rust pub fn get_key_value(&self, k: &Q) -> Option<(&K, &V)> where K: Borrow, Q: Hash + Eq + ?Sized, ``` ### Parameters - **k** (`&Q`) - Required - The key to look up. 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. ### Return Value - `Option<(&K, &V)>` - `Some` containing a reference to the key and value if the key is present, otherwise `None`. ### 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); ``` ``` -------------------------------- ### entry(&mut self, key: K) -> Entry<'_, K, V, A> Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Gets the given key’s corresponding entry in the map for in-place manipulation. ```APIDOC ## `entry(&mut self, key: K) -> Entry<'_, K, V, A>` ### Description Gets the given key’s corresponding entry in the map for in-place manipulation. ### Method `entry` ### Parameters - **key** (`K`) - Required - The key whose entry is to be retrieved. ### Return Value - **Entry<'_, K, V, A>** - An entry for the given key, which can be used for in-place manipulation. ### Request Example ```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); ``` ### Response #### Success Response Returns an `Entry` for the given key. ### Notes - **Version**: 1.0.0 ``` -------------------------------- ### Get hasher with hasher Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Returns a reference to the map's BuildHasher. ```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(); ``` -------------------------------- ### into_values example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Consumes the BTreeMap and collects all values into a vector in order by key. The map cannot be used after calling into_values. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "hello"); a.insert(2, "goodbye"); let values: Vec<&str> = a.into_values().collect(); assert_eq!(values, ["hello", "goodbye"]); ``` -------------------------------- ### Transform document AST with ferrodoc::parse and render Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Shows how to parse a document, modify its AST by removing headers, and render it to HTML. The example asserts the output is just the paragraph. ```rust use ferrodoc::{Format, ast::Block, parse, render}; let mut doc = parse(b"# Title\n\ntext\n", Format::Markdown)?; doc.blocks.retain(|block| !matches!(block, Block::Header(..))); let html = render(&doc, Format::Html)?; assert_eq!(String::from_utf8(html)?, "

text

\n"); # Ok::<(), Box>(()) ``` -------------------------------- ### BTreeMap::get_key_value example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Demonstrates BTreeMap::get_key_value with a custom key type where non-identical keys can be considered equal. The supplied key may be any borrowed form of the map's key type, but the ordering on the borrowed form must match the ordering on the key type. ```rust use std::cmp::Ordering; use std::collections::BTreeMap; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and ordering operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl PartialOrd for S { fn partial_cmp(&self, other: &S) -> Option { self.id.partial_cmp(&other.id) } } impl Ord for S { fn cmp(&self, other: &S) -> Ordering { self.id.cmp(&other.id) } } 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 = BTreeMap::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); ``` -------------------------------- ### Get multiple mutable references with get_disjoint_mut Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Retrieves mutable references to multiple values at once. Panics if keys overlap. ```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 ] ); ``` -------------------------------- ### Get disjoint mutable references Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Demonstrates retrieving multiple mutable references from a collection using unsafe disjoint access. Missing keys result in None. ```rust // 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_disjoint_mut(&mut self, ks: [&Q; N]) -> [Option<&mut V>; N] Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html 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. ```APIDOC ## get_disjoint_mut(&mut self, ks: [&Q; N]) -> [Option<&mut V>; N] ### 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 Rust method ### Signature ```rust pub fn get_disjoint_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] where K: Borrow, Q: Hash + Eq + ?Sized, ``` ### Parameters - **ks** (`[&Q; N]`) - Required - An array of keys to look up. Each 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. ### Return Value - `[Option<&mut V>; N]` - An array of length `N` with the results of each query. `Some(&mut V)` if the key is present, otherwise `None`. ### Panics Panics if any keys are overlapping. ### 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 ] ); ``` ``` -------------------------------- ### get_disjoint_unchecked_mut(&mut self, ks: [&Q; N]) -> [Option<&mut V>; N] Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html 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`. ```APIDOC ## get_disjoint_unchecked_mut(&mut self, ks: [&Q; N]) -> [Option<&mut V>; N] ### 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 Rust method ### Signature ```rust pub unsafe fn get_disjoint_unchecked_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] where K: Borrow, Q: Hash + Eq + ?Sized, ``` ### Parameters - **ks** (`[&Q; N]`) - Required - An array of keys to look up. Each 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. ### Return Value - `[Option<&mut V>; N]` - An array of length `N` with the results of each query. `Some(&mut V)` if the key is present, otherwise `None`. ### Safety Calling this method with overlapping keys is _undefined behavior_ even if the resulting references are not used. ### 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); // 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), ], ); ``` ``` -------------------------------- ### Format Wrapping Configurations Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Demonstrates how different output formats (Plain, Latex, Rst, AsciiDoc) handle various wrapping configurations, including None, Preserve, and Auto. ```rust #[cfg(feature = "text")] assert_eq!(out(Format::Plain, Wrap::None).unwrap(), "one two\n"); #[cfg(feature = "text")] assert_eq!(out(Format::Plain, Wrap::Auto(5)).unwrap(), "one\ntwo\n"); #[cfg(feature = "text")] assert_eq!(out(Format::Plain, Wrap::Auto(72)).unwrap(), "one two\n"); // LaTeX does all three too. `preserve` is what it always did. #[cfg(feature = "latex")] assert_eq!(out(Format::Latex, Wrap::None).unwrap(), "one two\n"); #[cfg(feature = "latex")] assert_eq!(out(Format::Latex, Wrap::Preserve).unwrap(), "one\ntwo\n"); #[cfg(feature = "latex")] assert_eq!(out(Format::Latex, Wrap::Auto(5)).unwrap(), "one\ntwo\n"); #[cfg(feature = "latex")] assert_eq!(out(Format::Latex, Wrap::Auto(72)).unwrap(), "one two\n"); // RST too, since 2026-08-24. #[cfg(feature = "rst")] assert_eq!(out(Format::Rst, Wrap::None).unwrap(), "one two\n"); #[cfg(feature = "rst")] assert_eq!(out(Format::Rst, Wrap::Preserve).unwrap(), "one\ntwo\n"); #[cfg(feature = "rst")] assert_eq!(out(Format::Rst, Wrap::Auto(5)).unwrap(), "one\ntwo\n"); #[cfg(feature = "rst")] assert_eq!(out(Format::Rst, Wrap::Auto(72)).unwrap(), "one two\n"); // AsciiDoc completes the five. #[cfg(feature = "asciidoc")] assert_eq!(out(Format::Asciidoc, Wrap::None).unwrap(), "one two\n"); #[cfg(feature = "asciidoc")] assert_eq!(out(Format::Asciidoc, Wrap::Preserve).unwrap(), "one\ntwo\n"); #[cfg(feature = "asciidoc")] assert_eq!(out(Format::Asciidoc, Wrap::Auto(5)).unwrap(), "one\ntwo\n"); #[cfg(feature = "asciidoc")] assert_eq!(out(Format::Asciidoc, Wrap::Auto(72)).unwrap(), "one two\n"); // `pandoc --wrap=auto -t json` is accepted and does nothing; // refusing it would break a command line pandoc runs. assert!(out(Format::Json, Wrap::Auto(72)).is_ok()); ``` -------------------------------- ### Parse and guess document formats Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Demonstrates how to parse format names from strings and guess formats from file paths. ```rust #[test] fn formats_are_named_and_guessed() { assert_eq!(Format::parse("CommonMark"), Some(Format::Markdown)); assert_eq!(Format::from_path(std::path::Path::new("a/b.docx")), Some(Format::Docx)); assert_eq!(Format::parse("pdf"), None); // The spellings a real Makefile uses. `dropin/` found `html5` // being refused for its name alone; `pandoc -t html5` and // `pandoc -t html` write the same bytes. assert_eq!(Format::parse("html5"), Some(Format::Html)); assert_eq!(Format::parse("markdown_github"), Some(Format::PandocMarkdown)); // Not aliases: pandoc's html4 writer differs on real constructs // and `markdown_strict` is a different dialect, so both are // refused by name rather than answered wrongly. assert_eq!(Format::parse("html4"), None); assert_eq!(Format::parse("markdown_strict"), None); } ``` -------------------------------- ### BTreeMap::first_key_value example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Shows how to get the first key-value pair (the minimum key) using BTreeMap::first_key_value. Returns None when the map is empty. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); assert_eq!(map.first_key_value(), None); map.insert(1, "b"); map.insert(2, "a"); assert_eq!(map.first_key_value(), Some((&1, &"b"))); ``` -------------------------------- ### Docx to Markdown Round-trip Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Demonstrates converting Markdown to Docx and back to Markdown, verifying content preservation. ```rust let docx = convert(b"# Title\n\nBody *text*.\n", Format::Markdown, Format::Docx) .expect("writable"); let md = convert(&docx, Format::Docx, Format::Markdown).expect("convertible"); let md = String::from_utf8(md).expect("utf8"); assert!(md.contains("# Title"), "{md}"); assert!(md.contains("*text*"), "{md}"); ``` -------------------------------- ### BTreeMap::get_mut example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Gets a mutable reference to the value for a key and modifies it in place. The key may be a borrowed form, but its ordering must match the key type's ordering. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); ``` -------------------------------- ### tex_inlines usage example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/fn.tex_inlines.html Example usage of tex_inlines. It shows that "x^2" renders as emphasis and superscript, while "\frac{1}{2}" returns None. ```rust let inlines = tex_inlines("x^2").expect("a superscript renders"); assert!(matches!(inlines.as_slice(), [Inline::Emph(_), Inline::Superscript(_)])); assert!(tex_inlines(r"\frac{1}{2}").is_none()); ``` -------------------------------- ### BTreeMap::append example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Moves all elements from `other` into `self`, leaving `other` empty. If a key from `other` is already present in `self`, the value from `self` is overwritten with the value from `other`, but the key is not overwritten. The example shows the resulting lengths and values after the append. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "a"); a.insert(2, "b"); a.insert(3, "c"); // Note: Key (3) also present in b. let mut b = BTreeMap::new(); b.insert(3, "d"); // Note: Key (3) also present in a. b.insert(4, "e"); b.insert(5, "f"); a.append(&mut b); assert_eq!(a.len(), 5); assert_eq!(b.len(), 0); assert_eq!(a[&1], "a"); assert_eq!(a[&2], "b"); assert_eq!(a[&3], "d"); // Note: "c" has been overwritten. assert_eq!(a[&4], "e"); assert_eq!(a[&5], "f"); ``` -------------------------------- ### Round-trip conversion through Docx Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Shows how to convert Markdown to Docx and then back to HTML, verifying the content is preserved. ```rust #[test] #[cfg(all(feature = "markdown", feature = "docx", feature = "html"))] fn docx_round_trips_through_the_facade() { let docx = convert(b"# Title\n\nBody.\n", Format::Markdown, Format::Docx).unwrap(); let html = convert(&docx, Format::Docx, Format::Html).unwrap(); let html = String::from_utf8(html).unwrap(); assert!(html.contains(" = (0..8).map(|x| (x, x)).collect(); let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect(); let odds = map; assert_eq!(evens.keys().copied().collect::>(), [0, 2, 4, 6]); assert_eq!(odds.keys().copied().collect::>(), [1, 3, 5, 7]); // Splitting a map into low and high halves, reusing the original map: let mut map: BTreeMap = (0..8).map(|x| (x, x)).collect(); let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect(); let high = map; assert_eq!(low.keys().copied().collect::>(), [0, 1, 2, 3]); assert_eq!(high.keys().copied().collect::>(), [4, 5, 6, 7]); ``` -------------------------------- ### Image Handling in Docx Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Initializes a PNG byte array and parses Markdown to demonstrate Docx image handling capabilities. ```rust let png: &[u8] = &[ 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, b'I', b'H', b'D', b'R', 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 0, b'I', b'E', b'N', b'D', 0xae, 0x42, 0x60, 0x82, ]; let doc = parse(b"![alt](pic.png)\n", Format::Markdown).unwrap(); ``` -------------------------------- ### Pandoc::new Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/struct.Pandoc.html Creates a new Pandoc document with the given blocks, empty metadata, and the current API version. This is the primary constructor for building a Pandoc document. ```APIDOC ## Pandoc::new ### Description Creates a new Pandoc document with the given blocks, empty metadata, and the current API version. ### Method new ### Signature pub fn new(blocks: Vec) -> Pandoc ### Parameters - **blocks** (Vec) - Required - The document body blocks. ### Returns - **Pandoc** - A new Pandoc document with the provided blocks, empty metadata, and the current API version. ### Example ```rust let doc = Pandoc::new(vec![/* blocks */]); ``` ``` -------------------------------- ### pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> HashMap Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Creates an empty HashMap with at least the specified capacity, using a custom hash builder and allocator. This is a nightly-only experimental API. ```APIDOC ## `pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> HashMap` ### Description Creates an empty `HashMap` with at least the specified capacity, using `hasher` to hash the keys and `alloc` to allocate memory. The hash map will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is zero, the hash map will not allocate. Warning: `hasher` is normally randomly generated, and is designed to allow HashMaps 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 `HashMap` to be useful, see its documentation for details. ### Method `pub fn with_capacity_and_hasher_in` ### Parameters - **capacity** (`usize`) - Required - The minimum capacity for the map. - **hash_builder** (`S`) - Required - The hash builder to use for hashing keys. - **alloc** (`A`) - Required - The allocator to use for memory allocation. ### Returns - `HashMap` - An empty `HashMap` with the given capacity, hash builder, and allocator. ### Examples ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_capacity_and_hasher_in(10, s, Global); ``` ``` -------------------------------- ### Transform document AST using parse and render Source: https://docs.rs/ferrodoc Shows how to parse a document into an AST, filter out specific blocks, and render the result back to a format. ```rust use ferrodoc::{Format, ast::Block, parse, render}; let mut doc = parse(b"# Title\n\ntext\n", Format::Markdown)?; doc.blocks.retain(|block| !matches!(block, Block::Header(..))); let html = render(&doc, Format::Html)?; assert_eq!(String::from_utf8(html)?, "

text

\n"); ``` -------------------------------- ### render_wrapped_with_media Source: https://docs.rs/ferrodoc Renders with a line layout and a media resolver. ```APIDOC ## render_wrapped_with_media ### Description Renders with a line layout and a media resolver. ### Signature `pub fn render_wrapped_with_media(doc: &Pandoc, format: Format, columns: usize, media: &Media) -> Result, Error>` ### Parameters - `doc` (&Pandoc) - Required - The document to render. - `format` (Format) - Required - The output format. - `columns` (usize) - Required - The column width for wrapping. - `media` (&Media) - Required - The media resolver. ### Returns - `Result, Error>` - The rendered document bytes, or an error if rendering fails. ``` -------------------------------- ### Handling Unsupported Conversion Directions Source: https://docs.rs/ferrodoc/latest/src/ferrodoc/lib.rs.html Verifies that attempting an unsupported conversion returns an Error rather than panicking. ```rust assert!(matches!( convert(b"x", Format::Plain, Format::Json), Err(Error::NotReadable(Format::Plain)) )); ``` -------------------------------- ### BTreeMap::values_mut Example Source: https://docs.rs/ferrodoc/latest/ferrodoc/ast/type.Meta.html Mutably iterates over values, appending '!' to each, and asserts the modified values. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### pub fn with_hasher_in(hash_builder: S, alloc: A) -> HashMap Source: https://docs.rs/ferrodoc/latest/ferrodoc/type.Media.html Creates an empty HashMap with a custom hash builder and allocator. This is a nightly-only experimental API. ```APIDOC ## `pub fn with_hasher_in(hash_builder: S, alloc: A) -> HashMap` ### Description Creates an empty `HashMap` which will use the given hash builder and allocator. The created map has the default initial capacity. Warning: `hash_builder` is normally randomly generated, and is designed to allow HashMaps 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 `hash_builder` passed should implement the `BuildHasher` trait for the `HashMap` to be useful, see its documentation for details. ### Method `pub fn with_hasher_in` ### Parameters - **hash_builder** (`S`) - Required - The hash builder to use for hashing keys. - **alloc** (`A`) - Required - The allocator to use for memory allocation. ### Returns - `HashMap` - An empty `HashMap` with the given hash builder and allocator. ### Examples ```rust #![feature(allocator_api)] use std::alloc::Global; use std::collections::HashMap; use std::hash::RandomState; let s = RandomState::new(); let map: HashMap = HashMap::with_hasher_in(s, Global); ``` ```