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
//! A variant of RwLock with sublocks that can be opened for reading iff the main lock is currently
//! opened for reading, opened for writing iff the main lock is currently opened for writing.

use std::cell::{ RefCell, Ref, RefMut };
use std::ops::{ Deref, DerefMut };
use std::sync::atomic::{ AtomicBool, Ordering };
use std::sync::{ Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockResult };
pub use std::sync::LockResult;

pub struct Liveness {
    is_alive: AtomicBool,
    is_mut: AtomicBool
}

pub struct SubCell<T> {
    cell: RefCell<T>,

    liveness: Arc<Liveness>,
}

impl<T> SubCell<T> {
    pub fn new<'a>(liveness: &Arc<Liveness>, value: T) -> Self {
        SubCell {
            cell: RefCell::new(value),
            liveness: liveness.clone(),
        }
    }
    pub fn borrow(&self) -> Ref<T> {
        assert!(self.liveness.is_alive.load(Ordering::Relaxed));
        self.cell.borrow()
    }

    pub fn borrow_mut(&self) -> RefMut<T> {
        assert!(self.liveness.is_mut.load(Ordering::Relaxed));
        self.cell.borrow_mut()
    }

}

/// With respect to Send and Sync, SubCell behaves as a RwLock.
unsafe impl<T> Send for SubCell<T> where T: Send + Sync {
}

/// With respect to Send and Sync, SubCell behaves as a RwLock.
unsafe impl<T> Sync for SubCell<T> where T: Send + Sync {
}

/// A variant of RwLock with sublocks that can be opened for reading iff the main lock is currently
/// opened for reading, opened for writing iff the main lock is currently opened for writing.
///
/// ```
/// use sublock::atomlock::*;
///
/// use std::collections::HashMap;
/// use std::sync::Arc;
///
/// struct State {
///   live: Arc<Liveness>,
///   data: HashMap<usize, SubCell<usize>>
/// }
/// impl State {
///   fn insert(&mut self, key: usize, value: usize) {
///     self.data.insert(key, SubCell::new(&self.live, value));
///   }
/// }
///
/// let lock = MainLock::new(|liveness| State {
///   live: liveness.clone(),
///   data: HashMap::new()
/// });
///
/// {
///     println!("* Attempt to read in the MainLock.");
///     let guard = lock.read().unwrap();
///     assert_eq!(guard.data.len(), 0);
/// }
///
/// {
///     println!("* Attempt to write in the MainLock.");
///     let mut guard = lock.write().unwrap();
///     guard.insert(0, 42);
///     assert_eq!(guard.data.len(), 1);
/// }
///
/// {
///     println!("* Attempt to read in a SubCell in `read()`.");
///     let guard = lock.read().unwrap();
///     assert_eq!(guard.data.len(), 1);
///     let cell = guard.data.get(&0).unwrap();
///     assert_eq!(*cell.borrow(), 42);
/// }
///
/// {
///     println!("* Attempt to read and write in a SubCell in `write()`.");
///     let guard = lock.write().unwrap();
///     assert_eq!(guard.data.len(), 1);
///     let cell = guard.data.get(&0).unwrap();
///     assert_eq!(*cell.borrow(), 42);
///
///     *cell.borrow_mut() = 99;
///     assert_eq!(*cell.borrow(), 99);
/// }
///
/// {
///     println!("* Check that the SubCell changes are kept.");
///     let guard = lock.read().unwrap();
///     assert_eq!(guard.data.len(), 1);
///     let cell = guard.data.get(&0).unwrap();
///     assert_eq!(*cell.borrow(), 99);
/// }
/// ```
pub struct MainLock<T> {
    lock: RwLock<T>,
    liveness: Arc<Liveness>,
}

impl<T> Drop for MainLock<T> {
    fn drop(&mut self) {
        self.liveness.is_alive.store(false, Ordering::Relaxed);
        self.liveness.is_mut.store(false, Ordering::Relaxed);
    }
}

pub type ReadGuard<'a, T> = RwLockReadGuard<'a, T>;

pub struct WriteGuard<'a, T> where T: 'a {
    guard: RwLockWriteGuard<'a, T>,
    liveness: Arc<Liveness>
}
impl<'a, T> WriteGuard<'a, T> where T: 'a {
    fn new(guard: RwLockWriteGuard<'a, T>, liveness: &Arc<Liveness>) -> Self {
        liveness.is_mut.store(true, Ordering::Relaxed);
        WriteGuard {
            guard: guard,
            liveness: liveness.clone(),
        }
    }
}

impl<'a, T> Deref for WriteGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.guard.deref()
    }
}

impl<'a, T> DerefMut for WriteGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.guard.deref_mut()
    }
}

impl<'a, T> Drop for WriteGuard<'a, T> {
    fn drop(&mut self) {
        self.liveness.is_mut.store(false, Ordering::Relaxed)
    }
}

impl<T> MainLock<T> {
    pub fn new<F>(cb: F) -> Self
        where F: FnOnce(&Arc<Liveness>) -> T
    {
        let liveness = Arc::new(Liveness {
             is_alive: AtomicBool::new(true),
             is_mut: AtomicBool::new(false)
        });
        let value = cb(&liveness);
        MainLock {
            lock: RwLock::new(value),
            liveness: liveness
        }
    }

    pub fn read(&self) -> LockResult<ReadGuard<T>> {
        self.lock.read()
    }

    pub fn try_read(&self) ->  TryLockResult<ReadGuard<T>> {
        self.lock.try_read()
    }

    pub fn write(&self) -> LockResult<WriteGuard<T>> {
        match self.lock.write() {
            Ok(guard) => Ok(WriteGuard::new(guard, &self.liveness)),
            Err(poison) => Err(PoisonError::new(
                WriteGuard::new(poison.into_inner(), &self.liveness)
            ))
        }
    }

    pub fn try_write(&self) ->  TryLockResult<WriteGuard<T>> {
        use std::sync::TryLockError::*;
        match self.lock.try_write() {
            Ok(guard) => Ok(WriteGuard::new(guard, &self.liveness)),
            Err(WouldBlock) => Err(WouldBlock),
            Err(Poisoned(poison)) => Err(Poisoned(PoisonError::new(
                WriteGuard::new(poison.into_inner(), &self.liveness)
            )))
        }
    }

    pub fn liveness(&self) -> &Arc<Liveness> {
        &self.liveness
    }
}