borrow_for/lib.rs
1#![no_std]
2#![doc = include_str!("../README.md")]
3#![doc = include_str!("../COVERAGE.md")]
4
5#[cfg(feature = "alloc")]
6extern crate alloc;
7
8#[cfg(feature = "std")]
9extern crate std;
10
11use core::borrow::Borrow;
12
13/// Chooses the type to borrow when a value is used with a particular context.
14///
15/// The context is a type your generic code already knows. Each implementation chooses a
16/// [`View`](Self::View) for that context. Use [`borrow_for`] or [`Borrow::borrow`] to get a
17/// reference to the chosen view.
18///
19/// `Context` and `View` can be different types. For example, with the `alloc` feature, a string
20/// literal in a `String` context has a `str` view. You only need the context's type, so you do
21/// not have to create a value of that type.
22///
23/// Both `Context` and `View` can be unsized, such as `str` or `[T]`. This trait does not require
24/// cloning, comparison, or formatting support. Your code adds any bounds it needs to use the
25/// borrowed view.
26///
27/// The crate provides implementations for values, references, and arrays. The `alloc`
28/// feature adds strings, C strings, vectors, `Box`, `Rc`, and `Cow`. It also adds `Arc` on targets
29/// with pointer-sized atomic operations. The default `std` feature enables `alloc` and adds
30/// paths and OS strings. The `serde_json` feature adds strings, numbers, and booleans in JSON value
31/// contexts. See the [crate documentation](crate) for the view each implementation chooses.
32///
33/// # Implementing `BorrowFor`
34///
35/// First, implement [`Borrow<View>`](Borrow) to return a reference to your view. Then implement
36/// `BorrowFor<Context>` to choose that view for the context:
37///
38/// ```
39/// use borrow_for::{BorrowFor, borrow_for};
40/// use core::borrow::Borrow;
41///
42/// struct Text<'a>(&'a str);
43///
44/// impl Borrow<str> for Text<'_> {
45/// fn borrow(&self) -> &str {
46/// self.0
47/// }
48/// }
49///
50/// impl BorrowFor<String> for Text<'_> {
51/// type View = str;
52/// }
53///
54/// let text = Text("hello");
55/// assert_eq!(borrow_for::<String, _>(&text), "hello");
56/// ```
57///
58/// [`Borrow`] requires your type and its view to agree on equality, ordering, and hashing
59/// whenever they implement those operations. If the borrowed data would behave differently,
60/// use [`AsRef`] or an accessor instead.
61///
62/// # References
63///
64/// Implementing `BorrowFor<Context>` for `T` does not automatically implement it for `&T` or
65/// `&mut T`. Add those implementations explicitly if your API needs them. `BorrowFor` does not
66/// strip reference layers to find an implementation.
67///
68/// A reference can also choose a different view from an owned value. In a `str` context, a
69/// `String` is borrowed as `str`, but `&String` and `&mut String` are borrowed as `String`.
70/// Pass `.as_str()` if you want a `str` view from a borrowed `String`.
71pub trait BorrowFor<Context: ?Sized>: Borrow<Self::View> {
72 /// The type to borrow when this value is used in this context.
73 type View: ?Sized;
74}
75
76/// Borrows a value using the view chosen for `Context`.
77///
78/// [`BorrowFor<Context>`](BorrowFor) chooses the view, and this function calls [`Borrow::borrow`]
79/// once to get a reference to it. Both the input and the view can be unsized, such as `str` or
80/// `[T]`.
81///
82/// ```
83/// use borrow_for::borrow_for;
84///
85/// let array = [1, 2, 3];
86/// let slice: &[i32] = borrow_for::<[i32], _>(&array);
87/// assert_eq!(slice, &[1, 2, 3]);
88/// assert_eq!(borrow_for::<[i32], _>(slice), slice);
89/// ```
90#[must_use]
91pub fn borrow_for<Context: ?Sized, V: BorrowFor<Context> + ?Sized>(value: &V) -> &V::View {
92 Borrow::<V::View>::borrow(value)
93}
94
95mod impls;