Skip to main content

Crate borrow_for

Crate borrow_for 

Source
Expand description

§borrow-for

Crates.io Docs.rs CI MSRV License: MIT OR Apache-2.0

Let generic functions accept owned values, references, and other useful forms of the same data.

Suppose you are writing an equality check. When the actual value is a String, you might want callers to pass another String, a reference to one, or just a string literal as the expected value. The function needs to borrow each of these in a form it can compare with the actual value.

BorrowFor<Context> chooses that borrowed type, called its View. The Context is a type your function already knows, such as the actual value’s type. Each input type and context together determine one view, and core::borrow::Borrow provides a reference to it.

Here is why that choice helps when writing a generic comparison:

  • Expected: Borrow<Actual> requires the expected value to borrow as Actual. This rules out a string literal when the actual value is a String: the literal cannot provide a &String.
  • Expected: Borrow<View> lets you borrow another type, but Rust must also infer View. If several views could work, the caller needs to provide a type annotation.
  • Expected: BorrowFor<Actual> chooses the view from the expected and actual types. The function can use that view without asking the caller to choose it.

AsRef<Actual> fixes the borrowed type in the same way as Borrow<Actual>. A separate generic AsRef<View> can leave Rust with the same choice between several possible views.

The following equal function uses the same bounds as assertr’s EqualTo. One function accepts all of these input forms:

use borrow_for::BorrowFor;
use core::borrow::Borrow;

fn equal<Actual, Expected>(actual: &Actual, expected: Expected) -> bool
where
    Actual: ?Sized + PartialEq<Expected::View>,
    Expected: BorrowFor<Actual>,
{
    let view: &Expected::View = expected.borrow();
    actual.eq(view)
}

assert!(equal(&42, 42)); // View = i32

// These string and vector examples need the alloc feature, which is enabled by default.
let actual = String::from("hello");
let expected = String::from("hello");
assert!(equal(&actual, &expected)); // View = String
assert!(equal(&actual, expected)); // View = String
assert!(equal(&actual, "hello")); // View = str
assert!(equal(&actual, Box::<str>::from("hello"))); // View = str

let actual = vec![String::from("hello")];
let expected = ["hello"];
assert!(equal(&actual, expected)); // Context = Vec<String>, View = [&str; 1]
assert!(equal(&actual[..], expected)); // Context = [String], View = [&str]
assert!(equal(&actual, &expected[..])); // Context = Vec<String>, View = [&str]

Notice the last three calls. The same expected array is borrowed as an array when the actual type is Vec<String>, and as a slice when the actual type is [String]. Passing a slice as the expected value works too. The view still contains &str elements, which can be compared directly with the actual String elements. No elements need to be cloned or converted.

The PartialEq<Expected::View> bound checks that the actual type can compare with the chosen view. In the string example, equal(&actual, expected) takes ownership of expected. Pass &expected if you want to keep using it after the call.

To borrow a view directly, use the borrow_for::<Context, _>(&value) helper.

§Installation

Add the crate to your Cargo.toml:

[dependencies]
borrow-for = "0.1.3"

§Features

The crate has no third-party runtime dependencies unless you enable serde_json. By default, it uses the standard library. You can disable the default features to use it in no_std environments.

  • std is enabled by default and includes alloc. It adds PathBuf/Path and OsString/OsStr support, including str in OS string contexts.
  • serde_json adds strings, numbers, and booleans in serde_json::Value contexts. It works with alloc alone.
  • For no_std with allocation, set default-features = false, features = ["alloc"]. This keeps support for Box, Rc, Cow, strings, C strings, and vectors. It also supports Arc on targets with pointer-sized atomic operations.
  • For only core, set default-features = false. Values and shared or mutable references are still supported, as are arrays borrowed as slices.

§Custom views

A custom type can choose its own view. First, implement Borrow<View> to return a reference. Then implement BorrowFor<Context> to tell generic code which view to use for that context. Here, Text provides a str view when used with a String context:

use borrow_for::{BorrowFor, borrow_for};
use core::borrow::Borrow;

struct Text<'a>(&'a str);

impl Borrow<str> for Text<'_> {
    fn borrow(&self) -> &str {
        self.0
    }
}

impl BorrowFor<String> for Text<'_> {
    type View = str;
}

let text = Text("hello");
assert_eq!(borrow_for::<String, _>(&text), "hello");

Borrow has a contract: if your type and its view implement Eq, Ord, or Hash, they must agree on the results. For example, a wrapper that compares text without regard to case cannot borrow as str, because str comparisons are case-sensitive. If borrowing a field would change how equality, ordering, or hashing behaves, use AsRef or an accessor instead. This requirement relates your type to its View. The Context only helps choose that view.

An implementation for a custom T does not automatically carry over to &T or &mut T. A reference can also choose a different view from an owned value. For example, in a str context, a String is borrowed as str, but an &String is borrowed as String.

§Implementation coverage

The coverage tables list all supported input types and contexts. They show which View each combination uses, which features you need, and why some combinations are not provided. The same tables appear in the crate documentation. These choices of view are part of the crate’s public API.

Sequences can have different element types, as the vector of String values and array of string literals do in the first example. A Vec context also accepts boxed, reference-counted, and Cow slices. A Cow<str> context accepts owned strings and borrowed forms, while a Cow<[T]> context accepts slices and vectors. These implementations borrow the existing elements. The function using the view supplies any comparison bounds it needs.

§Development

Run just --list to see the available development commands. just verify checks formatting, runs tests and Clippy, builds the documentation, and checks the minimum supported Rust version. It covers the core-only, alloc, and std configurations. The integration tests in tests/borrowing.rs have no third-party dependencies.

Rust 1.85.1 is the oldest supported version. just test-msrv runs the tests and documentation examples with that toolchain. just msrv runs cargo msrv find to find the minimum version that can build the crate.

§License

Licensed under either Apache License, Version 2.0 or MIT license, at your option.

§Implementation coverage

Use these tables to look up which borrowed view an input type provides for a context. Input is the type that implements BorrowFor<Context>. The borrow_for helper takes &Input and returns &View. For example, a row with &String as its input means you pass an &&String to the helper. These choices of view are part of the crate’s public API.

A pair in the table means you can borrow that view. The function using it may need other bounds, such as PartialEq for comparisons or Debug for formatting. Whether two different types can be compared also depends on the implementations available in your Rust version.

§Generic contexts

T can be any type, including an unsized type such as str or [u8]. It can also be a reference or a container, so these rules cover borrowing a container as its own type too.

ContextInputViewFeature
TT, &T, &mut TTCore only
TBox<T>, Rc<T>, Arc<T>Talloc
TCow<'_, T>Talloc; T: ToOwned

Arc is supported only on targets with pointer-sized atomic operations (target_has_atomic = "ptr").

§Owned and borrowed families

Each owned type below has a corresponding borrowed type, and all four pairs use the same rules. In the second table, replace O with the owned type, such as String, and B with its borrowed type, such as str. These implementations exist for the pairs listed here. Implementing ToOwned on another type does not automatically add it to this table.

Owned type OBorrowed type BFeature
Stringstralloc
CStringCStralloc
PathBufPathstd
OsStringOsStrstd
ContextInputView
BOB
B&O, &mut OO
&BO, &O, &mut OO
OB, &B, &mut BB
O&&'s B&'s B
OBox<B>, Rc<B>, Arc<B>, Cow<'_, B>B
O&Cow<'a, B>, &mut Cow<'a, B>Cow<'a, B>
&O&'s B&'s B
Cow<'_, B>B, &B, &mut B, OB
Cow<'_, B>&O, &mut OO
Cow<'_, B>Box<B>, Rc<B>, Arc<B>B

The generic implementations above also cover O in an O context and smart pointers in a B context. The input’s lifetime does not have to match a lifetime in the context type. For example, a short-lived &str can use a Cow<'static, str> context without having to live for 'static itself.

§Sequences

T is the context’s element type, and U is the input’s element type. They can be different, and the borrowed view keeps the input’s element type. These implementations do not require equality, cloning, or formatting support, apart from the ToOwned bounds shown for Cow. N is the array length and can be zero.

ContextInputViewFeature
[T][U; N][U]Core only
[T]&[U; N], &mut [U; N][U; N]Core only
[T]Vec<U>[U]alloc
[T]&Vec<U>, &mut Vec<U>Vec<U>alloc
&[T][U; N], &[U; N], &mut [U; N][U; N]Core only
&[T]Vec<U>, &Vec<U>, &mut Vec<U>Vec<U>alloc
[T; N][U], &[U], &mut [U][U]Core only
[T; N]Vec<U>[U]alloc
Vec<T>[U], &[U], &mut [U][U]alloc
Vec<T>[U; N], &[U; N], &mut [U; N][U; N]alloc
Vec<T>Box<[U]>, Rc<[U]>, Arc<[U]>[U]alloc
Vec<T>Cow<'_, [U]>[U]alloc; [U]: ToOwned
&Vec<T>&'s [U]&'s [U]alloc
Cow<'_, [T]>&'s [U]&'s [U]alloc; [T]: ToOwned
Cow<'_, [T]>&'s mut [U]&'s mut [U]alloc; [T]: ToOwned
Cow<'_, [T]>Vec<U>, &Vec<U>, &mut Vec<U>Vec<U>alloc; [T]: ToOwned

§Sequences of one owned and borrowed family

Sequences whose elements are one family’s owned values in the context and references to its borrowed type in the input, or the other way around, also cover vectors, slices, and arrays of the same length. O and B are the pairs from the family table above, such as String and str.

ContextInputViewFeature
Vec<O>Vec<&B>[&B]Family’s (alloc, std)
Vec<O>&Vec<&B>, &mut Vec<&B>Vec<&B>Family’s
Vec<&B>Vec<O>[O]Family’s
Vec<&B>&Vec<O>, &mut Vec<O>Vec<O>Family’s
[O][&B], &[&B], &mut [&B][&B]Family’s
[&B][O], &[O], &mut [O][O]Family’s
[O; N][&B; N], &[&B; N], &mut [&B; N][&B; N]Family’s
[&B; N][O; N], &[O; N], &mut [O; N][O; N]Family’s
&[O]&'s [&B]&'s [&B]Family’s
&[&B]&'s [O]&'s [O]Family’s

The views keep the input’s element type, so comparing them needs PartialEq between O and &B. String, PathBuf, and OsString sequences compare with their borrowed counterparts in both directions. CString and &CStr elements cannot be compared on Rust 1.85.1. Rust 1.90 and later compare a context of CString elements with &CStr elements, but not a context of &CStr elements with CString elements.

For a Cow<[T]> context, the views are slice references or vectors. These match the forms supported by its PartialEq implementations on Rust 1.85.1. For example, an &[U] input keeps &[U] as its view in a Cow<[T]> context, but uses [U] in a Vec<T> context.

§UTF-8 strings in OS string contexts

With the std feature, a str can be borrowed where an OS string is expected, because the standard library compares OsStr and OsString with str. The view stays a string slice, so a string literal can be compared with an OS string without converting it.

ContextInputViewFeature
OsStrstr, &str, &mut strstrstd
OsStringstr, &str, &mut strstrstd
OsString&&'s str&'s strstd
&OsStr&'s str&'s strstd

Paths are not covered: the standard library compares Path with str only since Rust 1.91.

§JSON values

With the serde_json feature, strings, numbers, and booleans can be borrowed where a serde_json::Value is expected, matching the PartialEq implementations of Value. Each view is the input’s type without its outer reference, so "name" compares with a JSON string and 3 with a JSON number.

ContextInputViewFeature
Valuestr, &str, &mut strstrserde_json
Value&&'s str&'s strserde_json
ValueString, &String, &mut StringStringserde_json
ValueS, &S, &mut S for every integer, float, and boolSserde_json
use borrow_for::BorrowFor;
use core::borrow::Borrow;
use serde_json::{Value, json};

fn equal<L: ?Sized + PartialEq<R::View>, R: BorrowFor<L>>(left: &L, right: R) -> bool {
    left.eq(right.borrow())
}

assert!(equal(&json!("hello"), "hello"));
assert!(equal(&json!(3), 3));
assert!(!equal(&json!("3"), 3));

§Coverage policy and limits

  • The tables and generic rules list the supported combinations. Adding another reference layer does not automatically preserve an implementation. Borrow itself does not follow arbitrary chains of references: for example, &String borrows String.
  • Each input type and context together choose exactly one view. Automatically carrying all implementations over to references would conflict with the generic implementations above. Rust rejects overlapping implementations, so reference support must be added explicitly.
  • Two vectors with different element types need an explicit slice input, as shown below, unless their elements are one family’s owned and borrowed types (Vec<&str> in a Vec<String> context, see above). A generic implementation for Vec<U> in a Vec<T> context would also apply when T = U, where the generic implementation already borrows the vector as its own type. Rust rejects that overlap. The same limitation applies to [U] inputs in [T] contexts.
  • Custom views must preserve Borrow’s equality, ordering, and hashing behavior. Use AsRef or an accessor when the borrowed data behaves differently. You can extend the table with your own input or context types. Rust’s orphan rules prevent you from adding an implementation when the trait and all types involved come from other crates.

To compare two vectors with other different element types, borrow the expected vector as a slice:

use borrow_for::borrow_for;

let actual = vec![String::from("hello")];
let expected = vec!["hello"];
let view: &[&str] = borrow_for::<Vec<String>, _>(expected.as_slice());
assert!(actual.eq(view));

Traits§

BorrowFor
Chooses the type to borrow when a value is used with a particular context.

Functions§

borrow_for
Borrows a value using the view chosen for Context.