Sub topic 5
Allocate only when needed with Cow
This chapter assumes you know ownership, borrowing and lifetimes, and the difference between &str and String. It also assumes you have seen allocation counting, as in the earlier chapter on measuring allocations.
The problem: sometimes you change the data, sometimes you don't
Suppose a function replaces tabs with spaces. Most inputs contain no tabs. Two obvious signatures both have a cost:
- Returning
Stringallocates on every call, even when nothing changed. - Returning
&strcannot work, because new text has nowhere to live.
Cow (clone-on-write) solves this. Cow<'a, str> is an enum with two variants. Borrowed(&'a str) points at existing data. Owned(String) holds a new heap string. The function returns whichever one fits.
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);
}The contains check is cheap and does not allocate. Only inputs with tabs pay for replace. The '_ lifetime ties the result to input, because the borrowed variant points into it.
Using a Cow
A Cow<str> dereferences to &str, so most callers use it like a string slice. println!, .len() and .trim() all work without extra steps.
Three methods cover most other needs:
| Method | What it does | Allocates when |
|---|---|---|
| `into_owned()` | Returns a `String` | The value is `Borrowed` |
| `to_mut()` | Returns `&mut String` | The value is `Borrowed` (clones once) |
| `is_borrowed()` / `matches!` | Tells you which variant you have | Never |
to_mut is useful when the decision to modify comes partway through the function:
use std::borrow::Cow;
fn ensure_trailing_newline(s: &str) -> Cow<'_, str> {
let mut text = Cow::Borrowed(s);
if !s.ends_with('\n') {
text.to_mut().push('\n');
}
text
}
fn main() {
let a = ensure_trailing_newline("done\n");
let b = ensure_trailing_newline("done");
println!("{:?} {:?}", a, b);
}The first call returns the borrowed input untouched. The second clones once inside to_mut and then appends.
Gotchas
- The result borrows from the input. You cannot keep a
Cow::Borrowedlonger than the original string. Callinto_owned()when you need to store it past that point. - Check before you build. If your "no change" test is as costly as the work itself, you save little. Calling
replaceand comparing the result to the input allocates every time, which defeats the purpose. - Not every function needs it. If nearly every call changes the data, plain
Stringis simpler.Cowadds a branch and a more complex type. - Constant text fits well.
Cow<'static, str>lets a type hold either a string literal or a runtime-built message, as in error types. Literals cost nothing, and only dynamic messages allocate. - It works for slices too.
Cow<'_, [T]>follows the same pattern, for example when deduplicating a list only if it has duplicates.
Verify the saving with the counting allocator. Calling expand_tabs on a tab-free string should leave the allocation count unchanged.
Exercise
A function normalize(name: &str) -> Cow<'_, str> lowercases a name only if it contains an uppercase letter. Why is Cow::Owned(name.to_lowercase()) on every call a mistake, and what check should come first?
Show answer
to_lowercase always allocates a new String, even when the name is already lowercase, so every call pays for an allocation it did not need. Check first with name.chars().any(|c| c.is_uppercase()). If it is true, return Cow::Owned(name.to_lowercase()). Otherwise return Cow::Borrowed(name), which does not allocate.