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
//! A variant of RwLock with sublocks that can be opened at no cost by providing a proof that the
//! main lock is opened.

use std::cell::{ RefCell, Ref, RefMut };
use std::marker::PhantomData;
use std::sync::{ LockResult, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockResult };

/// A trait specifying that a structure supports immutable borrowing if some proof is provided.
pub trait ProofBorrow<P, T> {
    fn borrow<'a>(&'a self, proof: &P) -> Ref<'a, T>;
}


/// A trait specifying that a structure supports mutable borrowing if some proof is provided.
pub trait ProofBorrowMut<P, T> {
    fn borrow_mut<'a>(&'a self, proof: &P) -> RefMut<'a, T>;
}

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

    // The owner has type BigLock<_> and has a unique key equal to `owner_key`.
    owner_key: usize,
}

impl<T> SubCell<T> {
    pub fn new<'a>(proof: &ProofMut<'a>, value: T) -> Self {
        SubCell {
            cell: RefCell::new(value),
            owner_key: proof.0,
        }
    }
}

impl<'b, T> ProofBorrow<Proof<'b>, T> for SubCell<T> {
    fn borrow<'a>(&'a self, proof: &Proof<'b>) -> Ref<'a, T> {
        assert_eq!(self.owner_key, proof.0);
        self.cell.borrow()
    }
}

impl<'b, T> ProofBorrow<ProofMut<'b>, T> for SubCell<T> {
    fn borrow<'a>(&'a self, proof: &ProofMut<'b>) -> Ref<'a, T> {
        assert_eq!(self.owner_key, proof.0);
        self.cell.borrow()
    }
}

impl<'b, T> ProofBorrowMut<ProofMut<'b>, T> for SubCell<T> {
    fn borrow_mut<'a>(&'a self, proof: &ProofMut<'b>) -> RefMut<'a, T> {
        assert_eq!(self.owner_key, proof.0);
        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 proof that the MainLock is currently opened.
/// Its lifetime is limited by that of the ReadGuard that provided it.
pub struct Proof<'a>(usize, PhantomData<&'a()>);

/// A proof that the MainLock is currently opened mutably.
/// Its lifetime is limited by that of the WriteGuard that provided it.
pub struct ProofMut<'a>(usize, PhantomData<&'a()>);

pub type ReadGuard<'a, T> = (Proof<'a>, RwLockReadGuard<'a, T>);
pub type WriteGuard<'a, T> = (ProofMut<'a>, RwLockWriteGuard<'a, T>);

/// A variant of `RwLock` with sublocks that can be opened at no cost by providing a proof
/// that the main lock is opened.
///
/// ```
/// use sublock::prooflock::*;
/// use std::collections::HashMap;
///
/// type State = HashMap<usize, SubCell<usize>>;
/// let data : MainLock<State> = MainLock::new(HashMap::new());
///
/// {
///     println!("* Attempt to read in the MainLock.");
///     let (_, guard) = data.read().unwrap();
///     assert_eq!(guard.len(), 0);
/// }
///
/// {
///     println!("* Attempt to write in the MainLock.");
///     let (proof, mut guard) = data.write().unwrap();
///     guard.insert(0, SubCell::new(&proof, 42));
///     assert_eq!(guard.len(), 1);
/// }
///
/// {
///     println!("* Attempt to read in a SubCell.");
///     let (proof, guard) = data.read().unwrap();
///     assert_eq!(guard.len(), 1);
///     let cell = guard.get(&0).unwrap();
///     assert_eq!(*cell.borrow(&proof), 42);
/// }
///
/// {
///     println!("* Attempt to read and write in a SubCell.");
///     let (proof, guard) = data.write().unwrap();
///     assert_eq!(guard.len(), 1);
///     let cell = guard.get(&0).unwrap();
///     assert_eq!(*cell.borrow(&proof), 42);
///
///     *cell.borrow_mut(&proof) = 99;
///     assert_eq!(*cell.borrow(&proof), 99);
/// }
///
/// {
///     println!("* Check that the SubCell changes are kept.");
///     let (proof, guard) = data.read().unwrap();
///     assert_eq!(guard.len(), 1);
///     let cell = guard.get(&0).unwrap();
///     assert_eq!(*cell.borrow(&proof), 99);
/// }
/// ```
pub struct MainLock<T> {
    lock: RwLock<T>,
    ownership: usize,
}
impl<T> MainLock<T> {
    pub fn new(value: T) -> Self {
        use std::mem;
        let ownership : usize = unsafe { mem::transmute(&value as *const T) };
        MainLock {
            lock: RwLock::new(value),
            ownership: ownership
        }
    }

    // As `RwLock.read`.
    pub fn read(&self) -> LockResult<ReadGuard<T>> {
        let proof = Proof(self.ownership, PhantomData);
        match self.lock.read() {
            Ok(ok) => Ok((proof, ok)),
            Err(err) => Err(PoisonError::new((proof, err.into_inner())))
        }
    }

    // As `RwLock.try_read`.
    pub fn try_read(&self) ->  TryLockResult<ReadGuard<T>> {
        use std::sync::TryLockError::*;
        let proof = Proof(self.ownership, PhantomData);
        match self.lock.try_read() {
            Ok(ok) => Ok((proof, ok)),
            Err(WouldBlock) => Err(WouldBlock),
            Err(Poisoned(err)) => Err(Poisoned(PoisonError::new((proof, err.into_inner()))))
        }
    }

    // As `RwLock.write`.
    pub fn write(&self) -> LockResult<WriteGuard<T>> {
        let proof = ProofMut(self.ownership, PhantomData);
        match self.lock.write() {
            Ok(ok) => Ok((proof, ok)),
            Err(err) => Err(PoisonError::new((proof, err.into_inner())))
        }
    }

    // As `RwLock.try_write`.
    pub fn try_write(&self) ->  TryLockResult<WriteGuard<T>> {
        use std::sync::TryLockError::*;
        let proof = ProofMut(self.ownership, PhantomData);
        match self.lock.try_write() {
            Ok(ok) => Ok((proof, ok)),
            Err(WouldBlock) => Err(WouldBlock),
            Err(Poisoned(err)) => Err(Poisoned(PoisonError::new((proof, err.into_inner()))))
        }
    }
}