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
cfg_if! {
    if #[cfg(feature = "multithread")] {
        use std::{
            ops::Deref,
            sync::{Arc, Mutex, MutexGuard},
        };

        #[derive(Debug)]
        pub struct Guard<'a, T> {
            inner: MutexGuard<'a, T>,
        }

        impl<'a, T> Deref for Guard<'a, T> {
            type Target = T;

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

        /// A reference abstraction that can handle single-threaded and multi-threaded environments
        #[derive(Debug)]
        pub struct Ref<T> {
            inner: Arc<Mutex<T>>,
        }

        impl<T> Ref<T> {
            /// Creates a new 'Ref' containing 'value'
            pub fn new(value: T) -> Self {
                Ref {
                    inner: Arc::new(Mutex::new(value)),
                }
            }

            /// Immutably borrows the wrapped value
            pub fn borrow(&self) -> Guard<T> {
                Guard {
                    inner: self.inner.lock().unwrap(),
                }
            }
        }

        impl<T> Clone for Ref<T> {
            fn clone(&self) -> Self {
                Ref {
                    inner: self.inner.clone(),
                }
            }
        }

    } else {
        use std::{
            cell::{Ref as StdRef, RefCell},
            ops::Deref,
            rc::Rc,
        };

        #[derive(Debug)]
        pub struct Guard<'a, T> {
            inner: StdRef<'a, T>,
        }

        impl<'a, T> Deref for Guard<'a, T> {
            type Target = T;

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

        /// A reference abstraction that can handle single-threaded and multi-threaded
        /// environments
        #[derive(Debug)]
        pub struct Ref<T> {
            inner: Rc<RefCell<T>>,
        }

        impl<T> Ref<T> {
            /// Creates a new 'Ref' containing 'value'
            pub fn new(value: T) -> Self {
                Ref {
                    inner: Rc::new(RefCell::new(value)),
                }
            }

            /// Immutably borrows the wrapped value
            pub fn borrow(&self) -> Guard<T> {
                Guard {
                    inner: self.inner.borrow(),
                }
            }
        }

        impl<T> Clone for Ref<T> {
            fn clone(&self) -> Self {
                Ref {
                    inner: self.inner.clone(),
                }
            }
        }
    }
}