Function textwrap::fill_inplace

source ·
pub fn fill_inplace(text: &mut String, width: usize)
Expand description

Fill text in-place without reallocating the input string.

This function works by modifying the input string: some ' ' characters will be replaced by '\n' characters. The rest of the text remains untouched.

Since we can only replace existing whitespace in the input with '\n' (there is no space for "\r\n"), we cannot do hyphenation nor can we split words longer than the line width. We also need to use AsciiSpace as the word separator since we need ' ' characters between words in order to replace some of them with a '\n'. Indentation is also ruled out. In other words, fill_inplace(width) behaves as if you had called fill() with these options:

Options::new(width)
    .break_words(false)
    .line_ending(LineEnding::LF)
    .word_separator(WordSeparator::AsciiSpace)
    .wrap_algorithm(WrapAlgorithm::FirstFit)
    .word_splitter(WordSplitter::NoHyphenation);

The wrap algorithm is WrapAlgorithm::FirstFit since this is the fastest algorithm — and the main reason to use fill_inplace is to get the string broken into newlines as fast as possible.

A last difference is that (unlike fill()) fill_inplace can leave trailing whitespace on lines. This is because we wrap by inserting a '\n' at the final whitespace in the input string:

let mut text = String::from("Hello   World!");
textwrap::fill_inplace(&mut text, 10);
assert_eq!(text, "Hello  \nWorld!");

If we didn’t do this, the word World! would end up being indented. You can avoid this if you make sure that your input text has no double spaces.

§Performance

In benchmarks, fill_inplace is about twice as fast as fill(). Please see the linear benchmark for details.