### Rust trim_start_matches Examples Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Demonstrates the usage of `trim_start_matches` in Rust to remove characters or patterns from the beginning of a string. It shows examples with single characters, numeric characters, and character slices. ```Rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Break Words Example Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap A simple example showing how the `wrap` function breaks a continuous string into smaller chunks based on a specified width. ```Rust assert_eq!(wrap("foobarbaz", 3), vec!["foo", "bar", "baz"]); ``` -------------------------------- ### Rust String starts_with Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Checks if a string slice begins with a specified pattern. The pattern can be a string slice, character, character slice, or a closure. Examples show usage with string slices and character slices. ```Rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```Rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` -------------------------------- ### Wrap Text with Basic Settings Source: https://docs.rs/textwrap/0.16.2/src/textwrap/lib Demonstrates basic text wrapping using the `wrap` function. It takes a string and a width, returning a vector of lines. This example requires the `smawk` feature. ```Rust # #[cfg(feature = "smawk")] { let text = "textwrap: a small library for wrapping text."; assert_eq!(textwrap::wrap(text, 18), vec!["textwrap: a", "small library for", "wrapping text."]); # } ``` -------------------------------- ### Custom Stair Wrap Algorithm Example Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/enum Demonstrates how to implement and use a custom text wrapping algorithm named 'stair'. This example shows how to define a custom function and pass it to the Options for text wrapping. ```Rust use textwrap::core::Word; use textwrap::{wrap, Options, WrapAlgorithm}; fn stair<'a, 'b>(words: &'b [Word<'a>], _: &'b [usize]) -> Vec<&'b [Word<'a>]> { let mut lines = Vec::new(); let mut step = 1; let mut start_idx = 0; while start_idx + step <= words.len() { lines.push(&words[start_idx .. start_idx+step]); start_idx += step; step += 1; } lines } let options = Options::new(10).wrap_algorithm(WrapAlgorithm::Custom(stair)); assert_eq!(wrap("First, second, third, fourth, fifth, sixth", options), vec!["First,", "second, third,", "fourth, fifth, sixth"]); ``` -------------------------------- ### Rust Optimal-Fit Algorithm Example (Greedy) Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/fn Illustrates the greedy algorithm's line breaking with penalties for the text 'To be, or not to be: that is the question' in a 10-character column. It shows the resulting lines and their squared gap penalties. ```Rust "To be, or" 1² = 1 "not to be:" "that is" "the" "question" ``` -------------------------------- ### Rust Optimal-Fit Algorithm Example (Optimal) Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/fn Demonstrates an improved line breaking using the optimal-fit algorithm for the same text and column width. It shows the resulting lines and their squared gap penalties, highlighting a lower total penalty. ```Rust "To be," "or not to" "be: that" "is the" "question" ``` -------------------------------- ### Rust: Example of FirstFit and OptimalFit wrapping Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap_algorithms Demonstrates the usage of `wrap_first_fit` and `wrap_optimal_fit` functions for text wrapping. It shows how `wrap_first_fit` can lead to short lines, while `wrap_optimal_fit` (when the 'smawk' feature is enabled) provides better line breaks by looking ahead. ```Rust use textwrap::core::Word; use textwrap::wrap_algorithms::wrap_first_fit; use textwrap::WordSeparator; // Helper to convert wrapped lines to a Vec. fn lines_to_strings(lines: Vec<&[Word<'_>]>) -> Vec { lines.iter().map(|line| { line.iter().map(|word| &**word).collect::>().join(" ") }).collect::>() } let text = "These few words will unfortunately not wrap nicely."; let words = WordSeparator::AsciiSpace.find_words(text).collect::>(); assert_eq!(lines_to_strings(wrap_first_fit(&words, &[15.0])), vec!["These few words", "will", // <-- short line "unfortunately", "not wrap", "nicely."]); // We can avoid the short line if we look ahead: #[cfg(feature = "smawk")] use textwrap::wrap_algorithms::{wrap_optimal_fit, Penalties}; #[cfg(feature = "smawk")] assert_eq!(lines_to_strings(wrap_optimal_fit(&words, &[15.0], &Penalties::new()).unwrap()), vec!["These few", "words will", "unfortunately", "not wrap", "nicely."]); ``` -------------------------------- ### Rust: Optimal-Fit Algorithm Explanation Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap_algorithms/optimal_fit Explains the core of the optimal-fit algorithm: minimizing line gaps by assigning penalties based on `gap * gap`. It illustrates this with an example of wrapping text in a narrow column and shows the resulting penalties for each line. ```Rust /// # Optimal-Fit Algorithm /// /// The algorithm considers all possible break points and picks the /// breaks which minimizes the gaps at the end of each line. More /// precisely, the algorithm assigns a cost or penalty to each break /// point, determined by `cost = gap * gap` where `gap = target_width - /// line_width`. Shorter lines are thus penalized more heavily since /// they leave behind a larger gap. /// /// We can illustrate this with the text “To be, or not to be: that is /// the question”. We will be wrapping it in a narrow column with room /// for only 10 characters. The [greedy /// algorithm](super::wrap_first_fit) will produce these lines, each /// annotated with the corresponding penalty: /// /// ```text /// "To be, or" 1² = 1 /// "not to be:" 0² = 0 /// "that is" 3² = 9 /// "the" 7² = 49 /// "question" 2² = 4 /// ``` /// /// We see that line four with “the” leaves a gap of 7 columns, which /// gives it a penalty of 49. The sum of the penalties is 63. ``` -------------------------------- ### Rust String trim_start() Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Illustrates the `trim_start()` method in Rust for removing leading whitespace from a string slice. It considers Unicode whitespace definitions and text directionality. ```Rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### Rust String find Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Finds the byte index of the first character matching a pattern within a string slice. Supports string slices, characters, character slices, and closures. Examples cover simple and complex patterns, including closures. ```Rust let s = "Löwe 老虎 Léopard Gepardi"; assert_eq!(s.find('L'), Some(0)); assert_eq!(s.find('é'), Some(14)); assert_eq!(s.find("pard"), Some(17)); ``` ```Rust let s = "Löwe 老虎 Léopard"; assert_eq!(s.find(char::is_whitespace), Some(5)); assert_eq!(s.find(char::is_lowercase), Some(1)); assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1)); assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4)); ``` ```Rust let s = "Löwe 老虎 Léopard"; let x: &[_] = &['1', '2']; assert_eq!(s.find(x), None); ``` -------------------------------- ### Rust Textwrap WordSplitter Examples Source: https://docs.rs/textwrap/0.16.2/textwrap/word_splitters/enum Demonstrates the usage of the WordSplitter trait from the textwrap crate in Rust. It shows examples for no hyphenation, standard hyphenation, and custom word splitting logic, illustrating how to obtain split points for different scenarios. ```Rust use textwrap::WordSplitter; assert_eq!(WordSplitter::NoHyphenation.split_points("cannot-be-split"), vec![]); assert_eq!(WordSplitter::HyphenSplitter.split_points("can-be-split"), vec![4, 7]); assert_eq!(WordSplitter::Custom(|word| vec![word.len()/2]).split_points("middle"), vec![3]); ``` -------------------------------- ### Rust Text Wrapping with fill() Source: https://docs.rs/textwrap/0.16.2/src/textwrap/fill Demonstrates the basic usage of the `fill` function for wrapping text to a specified width. It includes examples for simple cases, Unicode boundaries, and handling non-breaking spaces and hyphens. ```rust assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz"); // https://github.com/mgeisler/textwrap/issues/390 fill("\u{1b}!Ͽ", 10); let options = Options::new(5).break_words(false); assert_eq!(fill("foo bar baz", &options), "foo bar baz"); let options = Options::new(5).break_words(false); assert_eq!(fill("foo‑bar‑baz", &options), "foo‑bar‑baz"); assert_eq!(fill(" ", 80), ""); assert_eq!(fill(" \n ", 80), "\n"); assert_eq!(fill(" \n \n \n ", 80), "\n\n\n"); assert_eq!(fill("", 80), ""); assert_eq!(fill("\n", 80), "\n"); assert_eq!(fill("\n\n\n", 80), "\n\n\n"); assert_eq!(fill("test\n", 80), "test\n"); assert_eq!(fill("test\n\na\n\n", 80), "test\n\na\n\n"); assert_eq!( fill( "1 3 5 7\n1 3 5 7", Options::new(7).wrap_algorithm(WrapAlgorithm::FirstFit) ), "1 3 5 7\n1 3 5 7" ); assert_eq!( fill( "1 3 5 7\n1 3 5 7", Options::new(5).wrap_algorithm(WrapAlgorithm::FirstFit) ), "1 3 5\n7\n1 3 5\n7" ); assert_eq!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl"); assert_eq!(fill("abcdefgh\nijkl", 5), "abcde\nfgh\nijkl"); assert_eq!( fill("foo\nbar", &Options::new(2).break_words(false)), "foo\nbar" ); ``` -------------------------------- ### Short Last Line Penalty Examples Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/struct Illustrates the effect of the short_last_line_fraction and short_last_line_penalty on text wrapping using different algorithms. It shows how to adjust the threshold for considering a last line 'short' and how to disable the penalty. ```rust use textwrap::{wrap, wrap_algorithms, Options, WrapAlgorithm}; let text = "This is a demo of the short last line penalty."; // The first-fit algorithm leaves a single short word on the last line: assert_eq!(wrap(text, Options::new(37).wrap_algorithm(WrapAlgorithm::FirstFit)), vec!["This is a demo of the short last line", "penalty."]); #[cfg(feature = "smawk")] { let mut penalties = wrap_algorithms::Penalties::new(); // Since "penalty." is shorter than 25% of the line width, the // optimal-fit algorithm adds a penalty of 25. This is enough // to move "line " down: assert_eq!(wrap(text, Options::new(37).wrap_algorithm(WrapAlgorithm::OptimalFit(penalties))), vec!["This is a demo of the short last", "line penalty."]); // We can change the meaning of "short" lines. Here, only words // shorter than 1/10th of the line width will be considered short: penalties.short_last_line_fraction = 10; assert_eq!(wrap(text, Options::new(37).wrap_algorithm(WrapAlgorithm::OptimalFit(penalties))), vec!["This is a demo of the short last line", "penalty."]); // If desired, the penalty can also be disabled: penalties.short_last_line_fraction = 4; penalties.short_last_line_penalty = 0; assert_eq!(wrap(text, Options::new(37).wrap_algorithm(WrapAlgorithm::OptimalFit(penalties))), vec!["This is a demo of the short last line", "penalty."]); } ``` -------------------------------- ### Refill Text to Specific Width (Rust) Source: https://docs.rs/textwrap/0.16.2/src/textwrap/refill Demonstrates how to refill a given text string to a specified width using the `refill` function. This example shows basic text wrapping and how it handles different width constraints. ```Rust use textwrap::refill; let text = "Memory safety without garbage\ncollection."; assert_eq!(refill(text, 40), "\n> Memory safety without\n> garbage\n> collection."); assert_eq!(refill(text, 60), "\n> Memory safety without garbage collection."); ``` -------------------------------- ### Rust: Parse String to Type with Turbofish Syntax Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Demonstrates the `parse` method in Rust for converting a string slice to another type that implements `FromStr`. Includes examples of basic usage, error handling, and using the turbofish syntax (`::`) for explicit type inference. ```rust let four: u32 = "4".parse().unwrap();\n\nassert_eq!(4, four); ``` ```rust let four = "4".parse::();\n\nassert_eq!(Ok(4), four); ``` ```rust let nope = "j".parse::();\n\nassert!(nope.is_err()); ``` -------------------------------- ### Rust String trim_left() (Deprecated) Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Provides an example of the deprecated `trim_left()` method in Rust, which removes leading whitespace. It is superseded by `trim_start` and considers text directionality. ```Rust let s = " Hello\tworld\t"; assert_eq!("Hello\tworld\t", s.trim_left()); let s = " English"; assert!(Some('E') == s.trim_left().chars().next()); let s = " עברית"; assert!(Some('ע') == s.trim_left().chars().next()); ``` -------------------------------- ### Rust Release Profile Configuration Source: https://docs.rs/textwrap/0.16.2/index This snippet shows a typical Rust release profile configuration for optimizing binary size and performance. It enables link-time optimization (LTO) and sets the number of codegen units to 1, which are common practices for creating efficient release builds. ```Rust [profile.release] lto = true codegen-units = 1 ``` -------------------------------- ### Rust Release Profile Configuration Source: https://docs.rs/textwrap/0.16.2/textwrap This snippet shows a typical Rust release profile configuration for optimizing binary size and performance. It enables link-time optimization (LTO) and sets the number of codegen units to 1, which are common practices for creating efficient release builds. ```Rust [profile.release] lto = true codegen-units = 1 ``` -------------------------------- ### Rust String ends_with Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Checks if a string slice ends with a specified pattern. The pattern can be a string slice, character, character slice, or a closure. Examples demonstrate checking suffixes. ```Rust let bananas = "bananas"; assert!(bananas.ends_with("anas")); assert!(!bananas.ends_with("nana")); ``` -------------------------------- ### Rust Release Profile Configuration Source: https://docs.rs/textwrap/0.16.2/textwrap/index This snippet shows a typical Rust release profile configuration for optimizing binary size and performance. It enables link-time optimization (LTO) and sets the number of codegen units to 1, which are common practices for creating efficient release builds. ```Rust [profile.release] lto = true codegen-units = 1 ``` -------------------------------- ### Rust: Advanced Wrapping Options Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Illustrates text wrapping using advanced options, including custom wrap algorithms and handling of specific characters like em-dashes. It also shows how to set word separators. ```Rust assert_eq!( wrap( "To be, or not to be, that is the question.", Options::new(10).wrap_algorithm(WrapAlgorithm::FirstFit) ), vec!["To be, or", "not to be,", "that is", "the", "question."] ); let options = Options::new(1).word_separator(WordSeparator::AsciiSpace); assert_eq!(wrap("x – x", options), vec!["x", "–", "x"]); ``` -------------------------------- ### Rust String rfind Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Finds the byte index of the first character of the last match of a pattern within a string slice. Supports string slices, characters, character slices, and closures. Examples show finding last occurrences. ```Rust let s = "Löwe 老虎 Léopard Gepardi"; assert_eq!(s.rfind('L'), Some(13)); assert_eq!(s.rfind('é'), Some(14)); assert_eq!(s.rfind("pard"), Some(24)); ``` ```Rust let s = "Löwe 老虎 Léopard"; assert_eq!(s.rfind(char::is_whitespace), Some(12)); assert_eq!(s.rfind(char::is_lowercase), Some(20)); ``` ```Rust let s = "Löwe 老虎 Léopard"; let x: &[_] = &['1', '2']; assert_eq!(s.rfind(x), None); ``` -------------------------------- ### Rust Textwrap OverflowError Example Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/fn Demonstrates how an OverflowError is returned when text wrapping calculations exceed the limits of f64, specifically when fragment or line widths are extremely large. This example uses the `wrap_optimal_fit` function with large values to trigger the error. ```rust use textwrap::core::Fragment; use textwrap::wrap_algorithms::{wrap_optimal_fit, OverflowError, Penalties}; #[derive(Debug, PartialEq)] struct Word(f64); impl Fragment for Word { fn width(&self) -> f64 { self.0 } fn whitespace_width(&self) -> f64 { 1.0 } fn penalty_width(&self) -> f64 { 0.0 } } // Wrapping overflows because 1e155 * 1e155 = 1e310, which is // larger than f64::MAX: assert_eq!(wrap_optimal_fit(&[Word(0.0), Word(0.0)], &[1e155], &Penalties::default()), Err(OverflowError)); ``` -------------------------------- ### Rust: Implement From for Options Source: https://docs.rs/textwrap/0.16.2/textwrap/struct Provides a way to create `Options` from a `usize` value, likely representing a width or size parameter. This is a common pattern for initializing configuration structs. ```Rust impl From for Options<'_> fn from(width: usize) -> Self ``` -------------------------------- ### Wrap Text with Basic Options Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Demonstrates basic text wrapping using the `wrap` function with specified line width. It shows how text is split into lines that fit within the given width. ```Rust let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap(); let options = Options::new(10); assert_eq!( wrap("participation is the key to success", &options), vec!["participat", "ion is", "the key to", "success"] ); ``` -------------------------------- ### Check if byte index is a character boundary in Rust Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Determines if a given byte index in a string slice corresponds to the start or end of a UTF-8 character sequence. It considers the start and end of the string as boundaries and returns false for indices beyond the string length. ```Rust let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ``` -------------------------------- ### Rust textwrap Options::new Constructor Source: https://docs.rs/textwrap/0.16.2/textwrap/struct Demonstrates the creation of a new `Options` instance with a specified width. It shows the default values for other fields, which may vary based on Cargo features like `unicode-linebreak` and `smawk`. ```Rust pub const fn new(width: usize) -> Self { // ... implementation details showing default values ... // Example assertions: // assert_eq!(options.line_ending, LineEnding::LF); // assert_eq!(options.initial_indent, ""); // assert_eq!(options.subsequent_indent, ""); // assert_eq!(options.break_words, true); // ... assertions for word_separator, wrap_algorithm, word_splitter ... } ``` -------------------------------- ### Rust String rmatch_indices Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Demonstrates the usage of `rmatch_indices` to find all occurrences of a substring in reverse order within a Rust string. ```Rust let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect(); assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]); let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect(); assert_eq!(v, [(4, "abc"), (1, "abc")]); let v: Vec<_> = "ababa".rmatch_indices("aba").collect(); assert_eq!(v, [(2, "aba")]); // only the last `aba` ``` -------------------------------- ### Rustdoc Keyboard Shortcuts Source: https://docs.rs/textwrap/0.16.2/help This section details the keyboard shortcuts available for navigating and interacting with rustdoc documentation. These shortcuts enhance user experience by allowing quick access to help, search, and result navigation. ```text `?` Show this help dialog `S` / `/` Focus the search field `↑` Move up in search results `↓` Move down in search results `←` / `→` Switch result tab (when results focused) `⏎` Go to active search result `+` Expand all sections `-` Collapse all sections ``` -------------------------------- ### Rust: Get byte length of string Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Returns the length of the string in bytes. This may differ from the character or grapheme count for multi-byte characters. ```Rust pub fn len(&self) -> usize Returns the length of `self`. This length is in bytes, not `char`s or graphemes. In other words, it might not be what a human considers the length of the string. ##### §Examples ``` let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` ``` -------------------------------- ### Get Terminal Width Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/index Determines the current width of the terminal. This is often used to automatically adjust text wrapping to the user's display. ```Rust use textwrap::termwidth; // Example usage: // let width = termwidth(); ``` -------------------------------- ### Rust: Get TypeId of Self Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct This function, `type_id`, is part of the `Any` trait implementation. It returns the `TypeId` of the current instance, enabling runtime type checking. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Wrap Text with Default Settings Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Demonstrates basic text wrapping using the `wrap` function from the `textwrap` crate. It shows how trailing whitespace is removed and how text is split into lines based on the specified width. ```Rust use textwrap::wrap; assert_eq!(wrap("Foo bar baz", 10), vec!["Foo bar", "baz"]); assert_eq!(wrap("Foo bar baz", 8), vec!["Foo", "bar baz"]); ``` -------------------------------- ### Rust String trim_right() (Deprecated) Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Illustrates the deprecated `trim_right()` method in Rust for removing trailing whitespace. It is superseded by `trim_end` and considers text directionality. ```Rust let s = " Hello\tworld\t"; assert_eq!(" Hello\tworld", s.trim_right()); let s = "English "; assert!(Some('h') == s.trim_right().chars().rev().next()); let s = "עברית "; assert!(Some('ת') == s.trim_right().chars().rev().next()); ``` -------------------------------- ### Rust String trim_end() Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Demonstrates the `trim_end()` method in Rust, which removes trailing whitespace from a string slice. It accounts for Unicode whitespace and text directionality. ```Rust let s = "\n Hello\tworld\t\n"; assert_eq!("\n Hello\tworld", s.trim_end()); let s = " English "; assert!(Some('h') == s.trim_end().chars().rev().next()); let s = " עברית "; assert!(Some('ת') == s.trim_end().chars().rev().next()); ``` -------------------------------- ### Implement From<&Options> for Options Source: https://docs.rs/textwrap/0.16.2/src/textwrap/options Implements the `From` trait to create a new `Options` struct from a reference to an existing `Options` struct, effectively cloning the configuration. ```rust impl<'a> From<&'a Options<'a>> for Options<'a> { fn from(options: &'a Options<'a>) -> Self { Self { width: options.width, line_ending: options.line_ending, initial_indent: options.initial_indent, subsequent_indent: options.subsequent_indent, break_words: options.break_words, word_separator: options.word_separator, wrap_algorithm: options.wrap_algorithm, word_splitter: options.word_splitter.clone(), } } } ``` -------------------------------- ### Rust String trim_matches() Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Demonstrates the `trim_matches()` method in Rust for removing prefixes and suffixes that match a given pattern. The pattern can be a character, a slice of characters, or a closure. ```Rust assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar"); assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_matches(x), "foo1bar"); assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); ``` -------------------------------- ### Rust Release Profile for Binary Size Optimization Source: https://docs.rs/textwrap/0.16.2/src/textwrap/lib This TOML snippet defines a release profile for Rust projects, focusing on optimizing binary size. It enables Link Time Optimization (LTO) and sets the number of codegen units to 1, which are common practices for reducing executable size. ```toml [profile.release] lto = true codegen-units = 1 ``` -------------------------------- ### Word Separator Initialization Source: https://docs.rs/textwrap/0.16.2/src/textwrap/word_separators Demonstrates the creation of a `WordSeparator` instance, selecting between ASCII and Unicode-based separators depending on the `unicode-linebreak` feature. ```rust #[cfg(feature = "unicode-linebreak")] assert!(matches!(WordSeparator::new(), UnicodeBreakProperties)); #[cfg(not(feature = "unicode-linebreak"))] assert!(matches!(WordSeparator::new(), AsciiSpace)); ``` -------------------------------- ### Word splitting indices with textwrap Source: https://docs.rs/textwrap/0.16.2/src/textwrap/word_splitters Provides examples of how the `split_points` method on `WordSplitter` returns all possible indices where a word can be split. The indices point to the position *after* the split point. ```Rust use textwrap::WordSplitter; assert_eq!(WordSplitter::NoHyphenation.split_points("cannot-be-split"), vec![]); assert_eq!(WordSplitter::HyphenSplitter.split_points("can-be-split"), vec![4, 7]); assert_eq!(WordSplitter::Custom(|word| vec![word.len()/2]).split_points("middle"), vec![3]); ``` -------------------------------- ### Preventing hyphenation with textwrap Source: https://docs.rs/textwrap/0.16.2/src/textwrap/word_splitters Shows how to configure `textwrap` to avoid any hyphenation by using `WordSplitter::NoHyphenation`. This example demonstrates wrapping text where hyphens should not be used as split points. ```Rust use textwrap::{wrap, Options, WordSplitter}; let options = Options::new(8).word_splitter(WordSplitter::NoHyphenation); assert_eq!(wrap("foo bar-baz", &options), vec!["foo", "bar-baz"]); ``` -------------------------------- ### WrapAlgorithm Enum Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap_algorithms Defines different strategies for wrapping words into lines. Includes FirstFit, OptimalFit (requires 'smawk' feature), and a Custom option for user-defined algorithms. ```Rust pub enum WrapAlgorithm { /// Wrap words using a fast and simple algorithm. /// /// This algorithm uses no look-ahead when finding line breaks. /// Implemented by [`wrap_first_fit()`], please see that function /// for details and examples. FirstFit, /// Wrap words using an advanced algorithm with look-ahead. /// /// This wrapping algorithm considers the entire paragraph to find /// optimal line breaks. When wrapping text, "penalties" are /// assigned to line breaks based on the gaps left at the end of /// lines. See [`Penalties`] for details. /// /// The underlying wrapping algorithm is implemented by /// [`wrap_optimal_fit()`], please see that function for examples. /// /// **Note:** Only available when the `smawk` Cargo feature is /// enabled. #[cfg(feature = "smawk")] OptimalFit(Penalties), /// Custom wrapping function. /// /// Use this if you want to implement your own wrapping algorithm. /// The function can freely decide how to turn a slice of /// [`Word`]s into lines. /// /// # Example /// /// ``` /// use textwrap::core::Word; /// use textwrap::{wrap, Options, WrapAlgorithm}; /// /// fn stair<'a, 'b>(words: &'b [Word<'a>], _: &'b [usize]) -> Vec<&'b [Word<'a>]> { /// let mut lines = Vec::new(); /// let mut step = 1; /// let mut start_idx = 0; /// while start_idx + step <= words.len() { /// lines.push(&words[start_idx .. start_idx+step]); /// start_idx += step; /// step += 1; /// } /// lines /// } /// /// let options = Options::new(10).wrap_algorithm(WrapAlgorithm::Custom(stair)); /// assert_eq!(wrap("First, second, third, fourth, fifth, sixth", options), /// vec!["First,", /// "second, third,", /// "fourth, fifth, sixth"]); /// ``` Custom(for<'a, 'b> fn(words: &'b [Word<'a>], line_widths: &'b [usize]) -> Vec<&'b [Word<'a>]>), } ``` -------------------------------- ### Rust String trim_start_matches() Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Shows the `trim_start_matches()` method in Rust, which removes all prefixes matching a specified pattern. The pattern can be a string slice, character, character slice, or a closure. ```Rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); assert_eq!("1foo1barXX".trim_start_matches(|c| c == '1' || c == 'X'), "foo1barXX"); ``` -------------------------------- ### Configure Rustdoc Settings Source: https://docs.rs/textwrap/0.16.2/settings This section outlines various settings available for customizing the Rustdoc documentation. These settings control the appearance and behavior of the generated documentation, such as theme selection, auto-hiding content, and display of code elements. ```HTML ``` -------------------------------- ### Rust String trim() Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Shows how to use the `trim()` method in Rust to remove leading and trailing whitespace from a string slice. Whitespace is defined by the Unicode `White_Space` property. ```Rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld", s.trim()); ``` -------------------------------- ### Create Textwrap Options with Terminal Width Source: https://docs.rs/textwrap/0.16.2/textwrap/struct Initializes `Options` with the current terminal width. Falls back to 80 characters if the terminal size cannot be determined. Requires the `terminal_size` feature. ```Rust use textwrap::{termwidth, Options}; let options = Options::new(termwidth()); ``` -------------------------------- ### Set line ending for Options Source: https://docs.rs/textwrap/0.16.2/src/textwrap/options A method to modify the `line_ending` field of the `Options` struct, allowing customization of line breaks. Includes an example demonstrating its usage with the `refill` function. ```rust pub fn line_ending(self, line_ending: LineEnding) -> Self { Options { line_ending, ..self } } ``` -------------------------------- ### Rust: Indentation Options Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Shows how to apply initial indentation to wrapped text, including cases for empty lines and single-line text, ensuring consistent formatting. ```Rust let options = Options::new(10).initial_indent("!!!"); assert_eq!(wrap("", &options), vec!["!!!"]); let options = Options::new(10).initial_indent(">>>"); assert_eq!(wrap("foo", &options), vec![ ">>>foo"]); ``` -------------------------------- ### Get Terminal Width - Rust Source: https://docs.rs/textwrap/0.16.2/src/textwrap/termwidth Retrieves the current terminal width. If the terminal width cannot be determined, it defaults to 80 characters. This function requires the `terminal_size` Cargo feature to be enabled. ```Rust use crate::Options; /// Return the current terminal width. /// /// If the terminal width cannot be determined (typically because the /// standard output is not connected to a terminal), a default width /// of 80 characters will be used. /// /// # Examples /// /// Create an [`Options`] for wrapping at the current terminal width /// with a two column margin to the left and the right: /// /// ```no_run /// use textwrap::{termwidth, Options}; /// /// let width = termwidth() - 4; // Two columns on each side. /// let options = Options::new(width) /// .initial_indent(" ") /// .subsequent_indent(" "); /// ``` /// /// **Note:** Only available when the `terminal_size` Cargo feature is /// enabled. pub fn termwidth() -> usize { terminal_size::terminal_size().map_or(80, |(terminal_size::Width(w), _)| w.into()) } ``` -------------------------------- ### Copy Textwrap Options from Source Source: https://docs.rs/textwrap/0.16.2/textwrap/struct Performs copy-assignment from a source `Options` struct to the current one. This is an efficient way to update configurations. ```Rust const fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Reshape Bullet Points with Textwrap (Rust) Source: https://docs.rs/textwrap/0.16.2/src/textwrap/refill Illustrates reshaping bullet points in a text string using the `refill` function. This example shows how to maintain list formatting while adjusting the text width. ```Rust use textwrap::refill; let text = "\n- This is my\n list item.\n"; assert_eq!(refill(text, 20), "\n- This is my list\n item.\n"); ``` -------------------------------- ### Rust String split Example Source: https://docs.rs/textwrap/0.16.2/textwrap/core/struct Splits a string slice into an iterator of substrings based on a pattern. The pattern can be a string slice, character, character slice, or a closure. Discusses iterator behavior and the use of `rsplit`. -------------------------------- ### Rust: Basic Text Wrapping Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Demonstrates basic text wrapping functionality with a specified width. It covers scenarios like no wrapping, simple wrapping, and wrapping with multiple words on the first line. ```Rust assert_eq!(wrap("foo", 10), vec!["foo"]); assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]); assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]); ``` -------------------------------- ### Wrap text using OptimalFit algorithm in Rust Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Demonstrates text wrapping with the `OptimalFit` algorithm, which aims for more evenly distributed line lengths by considering all possible breaks. This requires the `smawk` feature. ```Rust # #[cfg(feature = "smawk")] { # use textwrap::{Options, WrapAlgorithm, wrap}; # # let lines = wrap( # "To be, or not to be: that is the question", # Options::new(10).wrap_algorithm(WrapAlgorithm::new_optimal_fit()) # ); # assert_eq!(lines.join("\n") + "\n", "\ To be, or not to be: that is the question "); } ``` -------------------------------- ### Wrap Text with textwrap Source: https://docs.rs/textwrap/0.16.2/textwrap Demonstrates basic text wrapping using the `wrap` function from the textwrap library. It splits a given string into lines of a specified width. ```Rust let text = "textwrap: a small library for wrapping text."; assert_eq!(textwrap::wrap(text, 18), vec!["textwrap: a", "small library for", "wrapping text."]); ``` -------------------------------- ### Wrap text with hanging indent and borrowing in Rust Source: https://docs.rs/textwrap/0.16.2/src/textwrap/wrap Shows an example of text wrapping with a hanging indent, where the first line borrows from the input string, and subsequent lines are owned strings due to the indentation. ```Rust use std::borrow::Cow::{Borrowed, Owned}; use textwrap::{wrap, Options}; let options = Options::new(15).subsequent_indent("...."); let lines = wrap("Wrapping text all day long.", &options); let annotated = lines .iter() .map(|line| match line { Borrowed(text) => format!("[Borrowed] {}", text), Owned(text) => format!("[Owned] {}", text), }) .collect::>(); assert_eq!( annotated, &[ "[Borrowed] Wrapping text", "[Owned] ....all day", "[Owned] ....long.", ] ); ``` -------------------------------- ### Indent Text Source: https://docs.rs/textwrap/0.16.2/textwrap/wrap_algorithms/index Adds a specified prefix to the beginning of each line in a given text. This is useful for creating indented output or code blocks. ```Rust use textwrap::indent; // Example usage: // let text = "Line 1\nLine 2"; // let indented_text = indent(text, " "); ```