Skip to main content

trillium_http/
mut_cow.rs

1use std::{
2    fmt::{self, Debug, Formatter},
3    ops::{Deref, DerefMut},
4};
5
6#[doc(hidden)]
7pub enum MutCow<'a, T> {
8    Owned(T),
9    Borrowed(&'a mut T),
10}
11
12impl<'a, T: Debug> Debug for MutCow<'a, T> {
13    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
14        Debug::fmt(&**self, f)
15    }
16}
17
18impl<'a, T> MutCow<'a, T> {
19    pub fn is_owned(&self) -> bool {
20        matches!(self, MutCow::Owned(_))
21    }
22
23    pub(crate) fn unwrap_owned(self) -> T {
24        match self {
25            MutCow::Owned(t) => t,
26            MutCow::Borrowed(_) => panic!("attempted to unwrap a borrow"),
27        }
28    }
29}
30
31impl<'a, T> Deref for MutCow<'a, T> {
32    type Target = T;
33
34    fn deref(&self) -> &Self::Target {
35        match self {
36            MutCow::Owned(t) => t,
37            MutCow::Borrowed(t) => t,
38        }
39    }
40}
41
42impl<'a, T> DerefMut for MutCow<'a, T> {
43    fn deref_mut(&mut self) -> &mut Self::Target {
44        match self {
45            MutCow::Owned(t) => t,
46            MutCow::Borrowed(t) => t,
47        }
48    }
49}
50
51impl<T> From<T> for MutCow<'static, T> {
52    fn from(t: T) -> Self {
53        Self::Owned(t)
54    }
55}
56
57impl<'a, T> From<&'a mut T> for MutCow<'a, T> {
58    fn from(t: &'a mut T) -> Self {
59        Self::Borrowed(t)
60    }
61}