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
/// A reference to a value that is _maybe_ mutable.
pub enum MaybeMutRef<'a, T> {
    Ref(&'a T),
    MutRef(&'a mut T),
}

impl<'a, T> MaybeMutRef<'a, T> {
    /// Returns the mutable reference, if possible.
    #[inline]
    pub fn as_mut(&mut self) -> Option<&mut T> {
        match self {
            Self::Ref(_) => None,
            Self::MutRef(r) => Some(r),
        }
    }
}

impl<'a, T> std::ops::Deref for MaybeMutRef<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        match self {
            Self::Ref(r) => r,
            Self::MutRef(r) => r,
        }
    }
}

impl<'a, T> AsRef<T> for MaybeMutRef<'a, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        match self {
            Self::Ref(r) => r,
            Self::MutRef(r) => r,
        }
    }
}

#[test]
fn test_maybe_mut_ref() {
    {
        let x = 42;
        let mut x_ref = MaybeMutRef::Ref(&x);
        assert_eq!(x_ref.as_mut(), None);
        assert_eq!(*x_ref, 42);
    }
    {
        let mut x = 42;
        let mut x_ref = MaybeMutRef::MutRef(&mut x);
        assert_eq!(*x_ref, 42);
        *x_ref.as_mut().unwrap() = 1337;
        assert_eq!(*x_ref, 1337);
    }
}