1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::{
fmt::{self, Debug, Formatter},
ops::{Deref, DerefMut},
};
#[doc(hidden)]
pub enum MutCow<'a, T> {
Owned(T),
Borrowed(&'a mut T),
}
impl<T: Debug> Debug for MutCow<'_, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Debug::fmt(&**self, f)
}
}
impl<T> MutCow<'_, T> {
pub fn is_owned(&self) -> bool {
matches!(self, MutCow::Owned(_))
}
/// Extract the owned value, panicking on `Borrowed`.
///
/// Caller asserts ownership — typically because they've just checked with
/// [`is_owned`](Self::is_owned), or because the impl block constrains the
/// lifetime to `'static`. Panic semantics are deliberate: returning `Option`
/// would force every call site to handle a case that the surrounding logic
/// has already ruled out.
pub(crate) fn unwrap_owned(self) -> T {
match self {
MutCow::Owned(t) => t,
MutCow::Borrowed(_) => panic!("attempted to unwrap a borrow"),
}
}
/// Retype as `MutCow<'static, T>` if this is an `Owned` variant.
///
/// Returns `None` for `Borrowed` (in which case the borrow is dropped).
/// `Owned(T)` carries no reference, so the lifetime parameter is unused for that
/// variant — re-wrapping it as `'static` is purely a type-level rename.
#[doc(hidden)]
#[cfg(feature = "unstable")]
pub fn try_into_owned(self) -> Option<MutCow<'static, T>> {
match self {
MutCow::Owned(t) => Some(MutCow::Owned(t)),
MutCow::Borrowed(_) => None,
}
}
}
impl<T> Deref for MutCow<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match self {
MutCow::Owned(t) => t,
MutCow::Borrowed(t) => t,
}
}
}
impl<T> DerefMut for MutCow<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
match self {
MutCow::Owned(t) => t,
MutCow::Borrowed(t) => t,
}
}
}
impl<T> From<T> for MutCow<'static, T> {
fn from(t: T) -> Self {
Self::Owned(t)
}
}
impl<'a, T> From<&'a mut T> for MutCow<'a, T> {
fn from(t: &'a mut T) -> Self {
Self::Borrowed(t)
}
}