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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use std::borrow::{Borrow, BorrowMut};
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};

/// A smart pointer that either owns or mutably borrows a value.
///
/// # Example
///
/// ```
/// use borrowned::BorrownedBox;
///
/// fn print_text(text: &BorrownedBox<'_, String>) {
///     println!("{}", text);
/// }
///
/// let owned = BorrownedBox::Owned(Box::new("hello".to_string()));
/// let mut owned2 = Box::new("world".to_string());
/// let borrowed = BorrownedBox::Borrowed(&mut *owned2);
///
/// print_text(&owned);
/// print_text(&borrowed);
/// print_text(&owned2.into());
///
/// ```
#[derive(Debug)]
pub enum BorrownedBox<'b, T: ?Sized> {
    /// Contains the owned value
    Owned(Box<T>),
    /// Contains the borrowed value
    Borrowed(&'b mut T),
}

impl<'b, T: ?Sized> BorrownedBox<'b, T> {
    /// Extracts the owned data.
    ///
    /// Returns `self` in `Err` if it's not owned.
    pub fn try_into_box(self) -> Result<Box<T>, Self> {
        match self {
            BorrownedBox::Owned(owned) => Ok(owned),
            _ => Err(self),
        }
    }

    /// Extracts the borrowed data.
    ///
    /// Returns `self` in `Err` if it's not borrowed.
    pub fn try_into_borrowed(self) -> Result<&'b mut T, Self> {
        match self {
            BorrownedBox::Borrowed(borrowed) => Ok(borrowed),
            _ => Err(self),
        }
    }

    fn inner_ref(&self) -> &T {
        match self {
            BorrownedBox::Owned(owned) => owned,
            BorrownedBox::Borrowed(borrowed) => *borrowed,
        }
    }

    fn inner_mut(&mut self) -> &mut T {
        match self {
            BorrownedBox::Owned(owned) => owned,
            BorrownedBox::Borrowed(borrowed) => *borrowed,
        }
    }
}

impl<'b, T: ?Sized> Deref for BorrownedBox<'b, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.inner_ref()
    }
}

impl<'b, T: ?Sized> DerefMut for BorrownedBox<'b, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner_mut()
    }
}

impl<'b, T: ?Sized> Borrow<T> for BorrownedBox<'b, T> {
    fn borrow(&self) -> &T {
        self.inner_ref()
    }
}

impl<'b, T: ?Sized> BorrowMut<T> for BorrownedBox<'b, T> {
    fn borrow_mut(&mut self) -> &mut T {
        self.inner_mut()
    }
}

impl<'b, T: ?Sized> AsRef<T> for BorrownedBox<'b, T> {
    fn as_ref(&self) -> &T {
        self.inner_ref()
    }
}

impl<'b, T: ?Sized> AsMut<T> for BorrownedBox<'b, T> {
    fn as_mut(&mut self) -> &mut T {
        self.inner_mut()
    }
}

impl<'b, T: Clone + ?Sized> Clone for BorrownedBox<'b, T> {
    fn clone(&self) -> Self {
        match self {
            BorrownedBox::Owned(owned) => BorrownedBox::Owned(owned.clone()),
            BorrownedBox::Borrowed(borrowed) => BorrownedBox::Owned(Box::new((*borrowed).clone())),
        }
    }
}

impl<'b, T: PartialEq + ?Sized> PartialEq for BorrownedBox<'b, T> {
    fn eq(&self, other: &Self) -> bool {
        let b_self = self.inner_ref();
        let b_other = other.inner_ref();

        b_self.eq(b_other)
    }
}

impl<'b, T: Eq + ?Sized> Eq for BorrownedBox<'b, T> {}

impl<'b, T: PartialOrd + ?Sized> PartialOrd for BorrownedBox<'b, T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let b_self = self.inner_ref();
        let b_other = other.inner_ref();

        b_self.partial_cmp(b_other)
    }
}

impl<'b, T: Ord> Ord for BorrownedBox<'b, T> {
    fn cmp(&self, other: &Self) -> Ordering {
        let b_self = self.inner_ref();
        let b_other = other.inner_ref();

        b_self.cmp(&b_other)
    }
}

impl<'b, T: Hash + ?Sized> Hash for BorrownedBox<'b, T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let b_self = self.inner_ref();
        b_self.hash(state);
    }
}

impl<'b, T: Default + ?Sized> Default for BorrownedBox<'b, T> {
    fn default() -> Self {
        Self::Owned(Box::default())
    }
}

impl<'b, T: fmt::Display + ?Sized> fmt::Display for BorrownedBox<'b, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.inner_ref(), f)
    }
}

impl<'b, T: ?Sized> From<Box<T>> for BorrownedBox<'b, T> {
    fn from(owned: Box<T>) -> Self {
        Self::Owned(owned)
    }
}

impl<'b, T: ?Sized> From<&'b mut T> for BorrownedBox<'b, T> {
    fn from(borrowed: &'b mut T) -> Self {
        Self::Borrowed(borrowed)
    }
}

#[cfg(test)]
mod tests {
    use crate::BorrownedBox;

    #[test]
    fn into_owned_gives_owned_when_owned() {
        let hw = "Hello World".to_string();
        let ob = BorrownedBox::Owned(Box::new(hw.clone()));
        let hw2 = ob.try_into_box();

        assert_eq!(hw2, Ok(Box::new(hw)));
    }

    #[test]
    fn into_owned_gives_self_when_not_owned() {
        let mut hw = "Hello World".to_string();
        let ob = BorrownedBox::Borrowed(&mut hw);
        let hw2 = ob.try_into_box();

        assert!(hw2.is_err());
    }

    #[test]
    fn into_borrowed_gives_borrowed_when_borrowed() {
        let mut hw = "Hello World".to_string();
        let ob = BorrownedBox::Borrowed(&mut hw);
        let hw2 = ob.try_into_borrowed();

        assert!(hw2.is_ok());
    }

    #[test]
    fn into_borrowed_gives_self_when_not_borrowed() {
        let hw = "Hello World".to_string();
        let ob = BorrownedBox::Owned(Box::new(hw));
        let hw2 = ob.try_into_borrowed();

        assert!(hw2.is_err());
    }
}