Sub topic 14
Cow<str>: borrow when you can, own when you must
This chapter assumes you know the difference between &str and String, understand ownership and borrowing, and can work with Option and Result. It builds on the chapters about function signatures and about growing and changing a String.
The problem: sometimes you must allocate, sometimes you don't
Consider a function that cleans up text. Most inputs are already clean, and a few need editing. You have two obvious signatures, and both have a cost.
fn normalize(input: &str) -> Stringalways allocates, even when the output equals the input.fn normalize(input: &str) -> &strcan never return an edited result, because the edited text would have to live somewhere that outlives the function.
Cow<str> solves this. Cow stands for "clone on write". It is an enum in std::borrow that holds either a borrowed value or an owned value:
// Simplified from the standard library
pub enum Cow<'a, B: ?Sized + ToOwned> {
Borrowed(&'a B),
Owned(<B as ToOwned>::Owned),
}For Cow<'a, str>, Borrowed holds a &'a str and Owned holds a String. The type says "this is text, and I may or may not own it". The caller does not need to care which case it is, because Cow<str> can be used like a &str.
A first example
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
fn main() {
println!("{}", normalize("no_spaces"));
println!("{}", normalize("has some spaces"));
}The first call returns Cow::Borrowed and allocates nothing. The second builds a new String with replace and wraps it in Cow::Owned. The '_ in the return type ties the borrowed case to the lifetime of input. The owned case does not borrow from anything, but the type must cover both cases.
The output is:
no_spaces
has_some_spacesUsing a Cow
A Cow<str> implements Deref<Target = str>. Every &str method works on it directly, and &cow coerces to &str where a function expects one (see the chapter on deref coercion).
use std::borrow::Cow;
fn describe(text: &str) -> usize {
text.len()
}
fn main() {
let a: Cow<str> = Cow::Borrowed("borrowed text");
let b: Cow<str> = Cow::Owned(String::from("owned text"));
println!("{} {}", a.len(), b.to_uppercase());
println!("{} {}", describe(&a), describe(&b));
}Cow<str> also implements Display, so it works with println! and format!, as the first example showed.
Checking which variant you have
You can match on the enum when you need to know:
use std::borrow::Cow;
fn kind(c: &Cow<str>) -> &'static str {
match c {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
}
}
fn main() {
let a: Cow<str> = Cow::Borrowed("x");
let b: Cow<str> = Cow::Owned(String::from("x"));
println!("{} {}", kind(&a), kind(&b));
}This prints borrowed owned. In normal code you rarely need this. It is mostly useful in tests that confirm a function avoided an allocation.
Converting in and out
Several conversions are common.
| You have | You want | Use |
|---|---|---|
| `&str` | `Cow<str>` | `Cow::Borrowed(s)` or `s.into()` |
| `String` | `Cow<str>` | `Cow::Owned(s)` or `s.into()` |
| `Cow<str>` | `String` | `cow.into_owned()` |
| `Cow<str>` | `&str` | `&*cow` or `cow.as_ref()` |
into_owned is cheap when the value is already Owned, because it just hands back the String. When the value is Borrowed, it allocates and copies. The From implementations let you write .into() in return position:
use std::borrow::Cow;
fn label(n: u32) -> Cow<'static, str> {
match n {
0 => "zero".into(),
1 => "one".into(),
_ => format!("many({n})").into(),
}
}
fn main() {
for n in [0, 1, 7] {
println!("{}", label(n));
}
}Here the fixed cases are string literals, so they borrow with the 'static lifetime and cost nothing. Only the _ arm allocates. This pattern is common for error messages and labels, where most values are constants and a few are computed.
Mutating a Cow: the "write" in clone on write
to_mut gives you a &mut String. If the Cow is borrowed, it first clones the data into an owned String. If it is already owned, it does nothing extra. After the call the value is always Owned.
use std::borrow::Cow;
fn ensure_trailing_slash(path: &str) -> Cow<'_, str> {
let mut result = Cow::Borrowed(path);
if !path.ends_with('/') {
result.to_mut().push('/');
}
result
}
fn main() {
let a = ensure_trailing_slash("/usr/");
let b = ensure_trailing_slash("/usr");
println!("{a} {b}");
println!("{}", matches!(a, std::borrow::Cow::Borrowed(_)));
println!("{}", matches!(b, std::borrow::Cow::Borrowed(_)));
}The output is:
/usr/ /usr/
true
falseThe first call never allocates. The second allocates exactly once, inside to_mut. Calling to_mut again on an owned value does not allocate again, so it is safe to call it several times in a loop.
Making a function that edits only when needed
A common shape is to scan the input for a problem and only build a new string when you find one. The scan is cheap, and the allocation happens at most once.
use std::borrow::Cow;
fn strip_carriage_returns(input: &str) -> Cow<'_, str> {
if input.contains('\r') {
Cow::Owned(input.replace('\r', ""))
} else {
Cow::Borrowed(input)
}
}
fn main() {
let unix = "line one\nline two\n";
let windows = "line one\r\nline two\r\n";
let a = strip_carriage_returns(unix);
let b = strip_carriage_returns(windows);
println!("{}", a.len());
println!("{}", b.len());
}Both calls give 18 for the length, because the cleaned Windows text equals the Unix text. Only the second allocated.
The standard library uses the same idea. String::from_utf8_lossy returns a Cow<str>. If the bytes are valid UTF-8 it borrows them, and if not it builds a new String with replacement characters (see the chapter on invalid UTF-8):
fn main() {
let good = String::from_utf8_lossy(b"fine");
let bad = String::from_utf8_lossy(&[b'a', 0xff, b'b']);
println!("{good} {bad}");
}This prints fine a�b.
Cow in structs and lifetimes
You can store a Cow<'a, str> in a struct to accept either borrowed or owned text without making the struct generic:
use std::borrow::Cow;
struct Greeting<'a> {
name: Cow<'a, str>,
}
impl<'a> Greeting<'a> {
fn new(name: impl Into<Cow<'a, str>>) -> Self {
Greeting { name: name.into() }
}
fn render(&self) -> String {
format!("Hello, {}!", self.name)
}
}
fn main() {
let a = Greeting::new("Ferris");
let b = Greeting::new(String::from("Corro"));
println!("{}", a.render());
println!("{}", b.render());
}Both &str and String convert into Cow<str>, so the constructor accepts either. If you need a value that carries no lifetime, call into_owned and use Cow<'static, str> or plain String.
Common errors
- Returning a Cow that borrows a local.
Cow::Borrowed(&local_string)fails to compile with "cannot return value referencing local variable". ReturnCow::Owned(local_string)instead. - Forgetting the lifetime.
fn f(s: &str) -> Cow<str>compiles because lifetime elision fills in the lifetime. WritingCow<'_, str>makes the borrow visible, and many style guides prefer it. - Calling
to_muton a non-mutbinding.to_muttakes&mut self, so the variable must be declaredlet mut. - Assuming Cow is always faster. A
Cowadds a discriminant and may be larger than a&str. If the function allocates on nearly every call, returnStringand keep the code simple. - Comparing with the wrong type.
Cow<str>implementsPartialEqwithstr,&str, andString, socow == "text"works. It does not coerce to&strin generic contexts, so use&*cowthere.
When to use Cow<str>
Use it when all of these hold:
- The function takes text and returns text, or produces a label that is usually a constant.
- A large share of calls need no change, or can use a literal.
- Callers read the result and often do not need to own it.
Skip it when the result is nearly always modified, when callers always need a String, or when the string is short and called rarely. Measure before you add the complexity.
Summary of behavior
Exercises
Exercise
Write a function fn trim_and_lower(input: &str) -> Cow<'_, str> that returns the input borrowed when it has no uppercase letters and no leading or trailing whitespace, and an owned, trimmed, lowercase String otherwise. Which check decides the variant?
Show answer
use std::borrow::Cow; fn trimandlower(input: &str) -> Cow<', str> { let trimmed = input.trim(); if trimmed.len() == input.len() && !input.chars().any(|c| c.isuppercase()) { Cow::Borrowed(input) } else { Cow::Owned(trimmed.to_lowercase()) } } The check compares the trimmed length to the original length (so nothing was trimmed) and tests for any uppercase character. Only when both pass does the function borrow.
Exercise
In let mut c = Cow::Borrowed("abc"); c.to_mut().push('d');, how many allocations happen, and what variant is c afterwards? What if to_mut is called a second time?
Show answer
One allocation happens, inside the first to_mut, which clones "abc" into a String. Afterwards c is Cow::Owned. A second to_mut call allocates nothing for cloning, because the value is already owned, though push may reallocate if the String's capacity is exceeded.
Exercise
Why does this fail to compile, and how do you fix it? fn f() -> Cow<'static, str> { let s = String::from("x"); Cow::Borrowed(&s) }
Show answer
It borrows s, a local variable that is dropped when the function returns, so the reference would dangle. Return Cow::Owned(s) (or s.into()) to move ownership into the Cow.