Sub topic 5
Allocate only when needed with Cow
This chapter assumes you know Rust ownership, borrowing and lifetimes, and that you are comfortable with String, &str and Vec. It also assumes you have seen the earlier chapters on hidden allocations and on borrowing in APIs.
Borrowing works when a function never needs to change its input. Cloning works when it always does. Many functions sit between the two. They change the input only sometimes, for example when they escape a character that is usually absent. Cow handles this case. It lets you return the borrowed input in the common case and allocate only in the rare one.
What Cow is
Cow stands for "clone on write". It lives in std::borrow and is an enum with two variants.
pub enum Cow<'a, B: ?Sized + ToOwned + 'a> {
Borrowed(&'a B),
Owned(<B as ToOwned>::Owned),
}For Cow<'a, str>, the Borrowed variant holds a &'a str and the Owned variant holds a String. For Cow<'a, [T]>, the variants hold a &'a [T] and a Vec<T>.
Cow implements Deref to the borrowed type. A Cow<str> can therefore be used wherever a &str is expected, with no match needed. Callers can read the result without knowing which variant they received.
Creating a Cow::Borrowed costs nothing. It stores a pointer and a length, and no heap allocation happens. Only the Owned variant owns heap memory.
A worked example: expand_tabs
The function below replaces tab characters with four spaces. Most inputs have no tabs, so most calls should not allocate.
use std::borrow::Cow;
fn expand_tabs(input: &str) -> Cow<'_, str> {
if input.contains('\t') {
Cow::Owned(input.replace('\t', " "))
} else {
Cow::Borrowed(input)
}
}
fn main() {
let a = expand_tabs("no tabs here");
let b = expand_tabs("one\ttab");
println!("{} / {}", a, b);
println!("a borrowed: {}", matches!(a, Cow::Borrowed(_)));
println!("b borrowed: {}", matches!(b, Cow::Borrowed(_)));
}The contains check scans the input but does not allocate. Only when a tab is found does the code call replace, which builds a new String. The output of main is:
no tabs here / one tab
a borrowed: true
b borrowed: falseThe lifetime '_ ties the returned Cow to input. That tie is what makes the borrowed case possible, because the result may point into the caller's data.
Check first, then allocate
The saving depends on testing before you build the new value. The version below looks similar but never avoids the allocation.
use std::borrow::Cow;
fn expand_tabs_wasteful(input: &str) -> Cow<'_, str> {
let replaced = input.replace('\t', " ");
if replaced == input {
Cow::Borrowed(input)
} else {
Cow::Owned(replaced)
}
}
fn main() {
println!("{}", expand_tabs_wasteful("plain"));
}str::replace returns a new String on every call, so this function allocates even when it returns Borrowed. It also pays for a comparison. The cheap check must come first, and the expensive work must sit behind it.
Changing a Cow lazily with to_mut
Sometimes a function makes several optional edits. Branching to Owned at each one gets clumsy. Cow::to_mut handles this. It returns a &mut to the owned value. If the Cow is still borrowed, it clones the data into an owned value first.
use std::borrow::Cow;
fn ensure_trailing_newline(text: &str) -> Cow<'_, str> {
let mut cow = Cow::Borrowed(text);
if !text.ends_with('\n') {
cow.to_mut().push('\n');
}
cow
}
fn main() {
let a = ensure_trailing_newline("done\n");
let b = ensure_trailing_newline("done");
println!("{:?} {:?}", a, b);
}The first call stays borrowed. The second clones "done" into a new String, then appends. The clone allocates exactly the input length, so the push may then reallocate. If you know the final size, build the String with String::with_capacity and return Cow::Owned directly.
Getting an owned value out
Sometimes the caller needs a String after all, for example to store it in a struct that outlives the input. Call into_owned.
use std::borrow::Cow;
fn into_owned_demo(c: Cow<'_, str>) -> String {
c.into_owned()
}
fn main() {
let owned: String = into_owned_demo(Cow::Borrowed("hello"));
let reused: String = into_owned_demo(Cow::Owned(String::from("world")));
println!("{} {}", owned, reused);
}For a Borrowed value, into_owned allocates and copies. For an Owned value, it moves the existing String out with no copy. Call it as late as possible, and only when ownership is needed.
Cow in return types for static and dynamic text
A common use is a function that returns mostly fixed strings and occasionally a computed one. Error messages are a typical case. Cow<'static, str> covers both without forcing an allocation for the fixed ones.
use std::borrow::Cow;
fn describe(code: u32) -> Cow<'static, str> {
match code {
404 => Cow::Borrowed("not found"),
500 => Cow::Borrowed("server error"),
other => Cow::Owned(format!("unknown status {other}")),
}
}
fn main() {
for code in [404, 500, 418] {
println!("{code}: {}", describe(code));
}
}The 'static lifetime is valid because string literals live for the whole program. No lifetime parameter reaches the caller, which makes this form easy to use in structs and error types.
Cow in parameters and struct fields
A struct can hold either borrowed or owned text by using a Cow field. A constructor that takes impl Into<Cow<'a, str>> accepts both &str and String callers.
use std::borrow::Cow;
struct Label<'a> {
text: Cow<'a, str>,
}
impl<'a> Label<'a> {
fn new(text: impl Into<Cow<'a, str>>) -> Self {
Label { text: text.into() }
}
}
fn main() {
let fixed = Label::new("static text");
let built = Label::new(format!("item-{}", 7));
println!("{} / {}", fixed.text, built.text);
}The standard library provides From<&str> and From<String> for Cow<str>. A literal stays borrowed. A String is moved in without a copy. Neither call site clones.
Cow for slices
Cow is not limited to strings. Any type with a ToOwned implementation works. For slices the owned type is Vec<T>.
use std::borrow::Cow;
fn clamp_all(values: &[i32], max: i32) -> Cow<'_, [i32]> {
if values.iter().any(|&v| v > max) {
Cow::Owned(values.iter().map(|&v| v.min(max)).collect())
} else {
Cow::Borrowed(values)
}
}
fn main() {
let small = [1, 2, 3];
let big = [1, 50, 3];
println!("{:?} {:?}", clamp_all(&small, 10), clamp_all(&big, 10));
}The pattern is the same as before. A read-only scan decides whether any work is needed, and only then is a new Vec built.
Common errors and limits
| Problem | Cause | Fix |
|---|---|---|
| The function allocates even when nothing changed | The new value is built before the check | Test with a non-allocating check, then build |
| "borrowed value does not live long enough" | The returned `Cow` borrows from a local variable | Return `Cow::Owned`, or borrow only from the input parameter |
| A `Cow` field spreads a lifetime parameter through your types | `Cow<'a, str>` carries `'a` | Use `Cow<'static, str>`, or store `String` if the lifetime is too costly |
| No speedup in a benchmark | The change path is the common path | Measure the share of calls that allocate before adopting `Cow` |
| `into_owned` called early | The value is converted before it is needed | Pass the `Cow` along and convert at the last point |
When Cow is worth it
Cow adds an enum tag and a branch on every access, and it adds a lifetime to your signatures. It pays off when two conditions hold. First, the change path must be rare, so most calls return Borrowed. Second, the call must be hot enough that the avoided allocation shows up in a measurement.
If the function always changes its input, return a String and skip Cow. If the function never changes it, return &str. If the function runs a few times at startup, the clearer signature is usually the better choice.
Measure before and after. The counting allocator from the measurement chapter works well here. Count allocations for a realistic input mix, where most inputs need no change, and compare the Cow version with the version that returns String.
Exercise
Write a function strip_carriage_returns(input: &str) -> Cow<'_, str> that removes every '\r' character. It must not allocate when the input contains no '\r'. Which check decides the branch, and which variant does each branch return?
Show answer
Use input.contains('\r') as the check, since it scans without allocating. If it is false, return Cow::Borrowed(input). If it is true, return Cow::Owned(input.replace('\r', "")). A complete version is:
use std::borrow::Cow;
fn stripcarriagereturns(input: &str) -> Cow<'_, str> {
if input.contains('\r') {
Cow::Owned(input.replace('\r', ""))
} else {
Cow::Borrowed(input)
}
}
Exercise
A function calls let s = input.replace('a', "b"); and then returns Cow::Borrowed(input) if s == input. Why does this fail to save an allocation, and how do you fix it?
Show answer
replace always builds a new String, so the allocation happens before the comparison. Fix it by checking input.contains('a') first, and call replace only when that is true.