Skip to content

Borrow Until Text Needs to Change

The Course
•
28 min study

The ledger stores item names in one format: trimmed, ASCII lowercase. Most names arrive already in that format, a few do not. A normalizer that returns String must allocate a fresh copy for every name, even the ones it did not change. A normalizer that returns &str cannot return a changed name at all, because the lowercase bytes do not exist anywhere yet. Neither signature fits a function that only sometimes needs new bytes.

Cow<'a, str>, short for clone on write, is an enum with two variants: Cow::Borrowed(&'a str) and Cow::Owned(String). The function decides at run time which one to return, and callers use either through the same Deref to str. The lifetime 'a still applies: a Cow that might be borrowed cannot outlive the text it might borrow from. When you need text that survives its input, into_owned() gives you a String in both cases. It moves an owned String out without copying, and copies a borrowed slice.

Predict and run

Which input produces a borrow? Which needs an owned result?

Predict, then run Rust
use std::borrow::Cow;

fn normalize(text: &str) -> Cow<'_, str> {
    let text = text.trim();
    if text.bytes().any(|byte| byte.is_ascii_uppercase()) {
        Cow::Owned(text.to_ascii_lowercase())
    } else {
        Cow::Borrowed(text)
    }
}
fn main() {
    for input in [" bolt ", "BOLT"] {
        let value = normalize(input);
        println!("{value}: borrowed={}", matches!(value, Cow::Borrowed(_)));
    }
}
Check your prediction
Text
bolt: borrowed=true
bolt: borrowed=false

Trimming never needs new bytes: trim returns a slice of the same string, so " bolt " is borrowed. Changing case does, so "BOLT" is owned. Now add " Écrou " to the inputs and predict its line. It prints Écrou: borrowed=true, because É is not an ASCII uppercase letter and the check never fires. That is correct for a ledger whose names are ASCII by rule, but a normalizer for arbitrary text would need to_lowercase, which handles Unicode and can even change the length of the string.

Clone only on the first write

Cow gets its name from to_mut(). Called on a borrowed value, it copies the text into a new String, switches the Cow to Owned and hands you &mut String. Called on an owned value, it just returns the existing String. So you can start borrowed and pay for a copy only if, and when, you change something.

Copy on the first write with to_mut Rust
use std::borrow::Cow;

fn label(name: &str, count: u32) -> Cow<'_, str> {
    let mut label = Cow::Borrowed(name);
    if count != 1 {
        label.to_mut().push('s');
    }
    label
}

fn main() {
    for count in [1, 3] {
        let text = label("bolt", count);
        println!("{count} {text}: borrowed={}", matches!(text, Cow::Borrowed(_)));
    }
}
Text
1 bolt: borrowed=true
3 bolts: borrowed=false

The single bolt never allocated. This is the pattern for functions that make zero or more edits: each edit calls to_mut(), and only the first one copies.

The borrowed case still has a lifetime

Because a Cow might hold a borrow, the compiler checks it as if it always does. Keeping the result after the input is dropped fails:

Rust
let saved;
{
    let input = String::from(" bolt ");
    saved = normalize(&input);
}
println!("{saved}");

The compiler reports error[E0597] and says that input does not live long enough, pointing at the end of the inner block where the String is dropped while saved may still borrow it. Writing saved = normalize(&input).into_owned(); fixes it: saved becomes a String with its own bytes, at the cost of one copy in the borrowed case.

Some functions only ever borrow from string literals, which live for the whole program. Their return type can be Cow<'static, str>, with no tie to any input:

Static text or a formatted message Rust
use std::borrow::Cow;

fn status(stock: u32) -> Cow<'static, str> {
    match stock {
        0 => "out of stock".into(),
        1..=5 => format!("low: {stock} left").into(),
        _ => "in stock".into(),
    }
}

fn main() {
    for stock in [0, 3, 40] {
        let text = status(stock);
        println!("{stock}: {text} (borrowed={})", matches!(text, Cow::Borrowed(_)));
    }
}
Text
0: out of stock (borrowed=true)
3: low: 3 left (borrowed=false)
40: in stock (borrowed=true)

.into() builds the right variant from the type: a &'static str becomes Borrowed, a String becomes Owned. The fixed messages cost nothing; only the one that contains a number allocates.

When Cow is worth its complexity

Cow pays off when the unchanged case is common and the function sits on a hot path, such as normalizing every name in a large import. If nearly every call allocates anyway, or the caller immediately needs a String, return String: the signature is simpler and nothing is gained by the extra variant.

Practice

Exercise

Your turn

Write normalize(text: &str) -> Cow<'_, str> that removes a leading prefix: if there is one, then lowercases the rest only if it contains an ASCII uppercase letter. Text that needs no lowercasing must not be copied. Check three inputs:

  • Inside an inner block, create String::from("prefix:bolt"), call normalize, assert that the result is Cow::Borrowed, and keep it as an owned String after the block ends.
  • normalize("prefix:Bolt") is Cow::Owned and equals "bolt".
  • normalize("nut") is Cow::Borrowed("nut").

Print the saved text and the lowered one, separated by a space: bolt bolt.

Your working space Rust
fn main() {
    // Borrow a suffix inside a scope, then keep the owned result.
}
Hint 1: the idea

Removing a prefix never needs new bytes: what is left is a slice of the input. Lowercasing does, but only when there is an uppercase letter to change. So the decision between the variants is made at run time, from the text itself, and ownership of the borrowed result only matters at the end of the block.

Hint 2: a first step

Do the borrowed step first and name its result: a slice with the prefix gone, or the whole text when there was none. Then ask one question of that slice, whether any character is uppercase, and let the answer choose the variant. For the block, think about which method turns any Cow into a String that no longer borrows input.

Worked solution
Run the solution Rust
use std::borrow::Cow;

fn normalize(text: &str) -> Cow<'_, str> {
    let rest = text.strip_prefix("prefix:").unwrap_or(text);
    if rest.chars().any(|c| c.is_ascii_uppercase()) {
        Cow::Owned(rest.to_ascii_lowercase())
    } else {
        Cow::Borrowed(rest)
    }
}

fn main() {
    let saved = {
        let input = String::from("prefix:bolt");
        let result = normalize(&input);
        assert!(matches!(result, Cow::Borrowed(_)));
        result.into_owned()
    };
    let lowered = normalize("prefix:Bolt");
    assert!(matches!(lowered, Cow::Owned(_)));
    assert_eq!(lowered, "bolt");
    assert!(matches!(normalize("nut"), Cow::Borrowed("nut")));
    println!("{saved} {lowered}");
}
Text
bolt bolt

The two bolts look the same but got there differently. saved was borrowed from input and into_owned() copied its four bytes before input was dropped, which is why it can outlive the block. lowered was owned from the start, because lowercasing needed new bytes; into_owned() on it would hand over that String without copying again. A plain &str return type could not express the second case, and a String return type would copy in all three. The comparison lowered == "bolt" works because Cow<str> implements PartialEq<&str>. The same function can also be written with to_mut: start with Cow::Borrowed(rest) and call result.to_mut().make_ascii_lowercase() only when needed, which switches it to Owned on that first write. The next lesson stores interchangeable rules of a different kind: behavior chosen at run time.

Was this article helpful?

Your response is saved on this device.