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
218
219
220
221
222
223
224
225
226
227
//! A reader-writer lock.
//!
//! See [`RwLock`] for more details.
//!
//! [`RwLock`]: struct.RwLock.html

use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering::*;

const WRITE_LOCK: usize = usize::max_value();
const NO_LOCK: usize = usize::min_value();

/// A reader-writer lock.
///
/// This lock supports only [`try_read`] and [`try_write`] method, and hence
/// never blocks.
///
/// [`try_read`]: #method.try_read
/// [`try_write`]: #method.try_write
pub struct RwLock<T> {
  lock: AtomicUsize,
  data: UnsafeCell<T>,
}

/// RAII structure used to release the shared read access of a lock when
/// dropped.
///
/// This structure is created by the [`try_read`] method on [`RwLock`].
///
/// [`RwLock`]: struct.RwLock.html
/// [`try_read`]: struct.RwLock.html#method.try_read
#[must_use]
pub struct RwLockReadGuard<'a, T: 'a> {
  lock: &'a RwLock<T>,
}

/// RAII structure used to release the exclusive write access of a lock when
/// dropped.
///
/// This structure is created by the [`try_write`] method on [`RwLock`].
///
/// [`RwLock`]: struct.RwLock.html
/// [`try_write`]: struct.RwLock.html#method.try_write
#[must_use]
pub struct RwLockWriteGuard<'a, T: 'a> {
  lock: &'a RwLock<T>,
}

unsafe impl<T: Send> Send for RwLock<T> {}
unsafe impl<T: Send + Sync> Sync for RwLock<T> {}

impl<'a, T> !Send for RwLockReadGuard<'a, T> {}
unsafe impl<'a, T: Sync> Sync for RwLockReadGuard<'a, T> {}

impl<'a, T> !Send for RwLockWriteGuard<'a, T> {}
unsafe impl<'a, T: Sync> Sync for RwLockWriteGuard<'a, T> {}

impl<T> RwLock<T> {
  /// Creates a new instance of an `RwLock<T>` which is unlocked.
  ///
  /// # Examples
  ///
  /// ```
  /// use drone_core::sync::RwLock;
  ///
  /// let lock = RwLock::new(5);
  /// ```
  #[inline(always)]
  pub const fn new(t: T) -> Self {
    Self {
      lock: AtomicUsize::new(NO_LOCK),
      data: UnsafeCell::new(t),
    }
  }

  /// Attempts to acquire this rwlock with shared read access.
  ///
  /// If the access could not be granted at this time, then `Err` is returned.
  /// Otherwise, an RAII guard is returned which will release the shared access
  /// when it is dropped.
  ///
  /// This function does not provide any guarantees with respect to the ordering
  /// of whether contentious readers or writers will acquire the lock first.
  ///
  /// # Examples
  ///
  /// ```
  /// use drone_core::sync::RwLock;
  ///
  /// let lock = RwLock::new(1);
  ///
  /// match lock.try_read() {
  ///   Some(n) => assert_eq!(*n, 1),
  ///   None => unreachable!(),
  /// };
  /// ```
  #[inline(always)]
  pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
    loop {
      let current = self.lock.load(Relaxed);
      if current >= WRITE_LOCK - 1 {
        break None;
      }
      if self.lock.compare_and_swap(current, current + 1, Acquire) == current {
        break Some(RwLockReadGuard { lock: self });
      }
    }
  }

  /// Attempts to lock this rwlock with exclusive write access.
  ///
  /// If the lock could not be acquired at this time, then `Err` is returned.
  /// Otherwise, an RAII guard is returned which will release the lock when it
  /// is dropped.
  ///
  /// This function does not provide any guarantees with respect to the ordering
  /// of whether contentious readers or writers will acquire the lock first.
  ///
  /// # Examples
  ///
  /// ```
  /// use drone_core::sync::RwLock;
  ///
  /// let lock = RwLock::new(1);
  ///
  /// let n = lock.try_read().unwrap();
  /// assert_eq!(*n, 1);
  ///
  /// assert!(lock.try_write().is_none());
  /// ```
  #[inline(always)]
  pub fn try_write(&self) -> Option<RwLockWriteGuard<T>> {
    if self.lock.compare_and_swap(NO_LOCK, WRITE_LOCK, Acquire) == NO_LOCK {
      Some(RwLockWriteGuard { lock: self })
    } else {
      None
    }
  }

  /// Consumes this `RwLock`, returning the underlying data.
  ///
  /// # Examples
  ///
  /// ```
  /// use drone_core::sync::RwLock;
  ///
  /// let lock = RwLock::new(String::new());
  /// {
  ///   let mut s = lock.try_write().unwrap();
  ///   *s = "modified".to_owned();
  /// }
  /// assert_eq!(lock.into_inner(), "modified");
  /// ```
  #[inline(always)]
  pub fn into_inner(self) -> T {
    let Self { data, .. } = self;
    unsafe { data.into_inner() }
  }

  /// Returns a mutable reference to the underlying data.
  ///
  /// Since this call borrows the `RwLock` mutably, no actual locking needs to
  /// take place --- the mutable borrow statically guarantees no locks exist.
  ///
  /// # Examples
  ///
  /// ```
  /// use drone_core::sync::RwLock;
  ///
  /// let mut lock = RwLock::new(0);
  /// *lock.get_mut() = 10;
  /// assert_eq!(*lock.try_read().unwrap(), 10);
  /// ```
  #[inline(always)]
  pub fn get_mut(&mut self) -> &mut T {
    unsafe { &mut *self.data.get() }
  }
}

impl<T: Default> Default for RwLock<T> {
  /// Creates a new `RwLock<T>`, with the `Default` value for T.
  #[inline(always)]
  fn default() -> RwLock<T> {
    RwLock::new(Default::default())
  }
}

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

  #[inline(always)]
  fn deref(&self) -> &T {
    unsafe { &*self.lock.data.get() }
  }
}

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

  #[inline(always)]
  fn deref(&self) -> &T {
    unsafe { &*self.lock.data.get() }
  }
}

impl<'a, T> DerefMut for RwLockWriteGuard<'a, T> {
  #[inline(always)]
  fn deref_mut(&mut self) -> &mut T {
    unsafe { &mut *self.lock.data.get() }
  }
}

impl<'a, T> Drop for RwLockReadGuard<'a, T> {
  #[inline(always)]
  fn drop(&mut self) {
    self.lock.lock.fetch_sub(1, Release);
  }
}

impl<'a, T> Drop for RwLockWriteGuard<'a, T> {
  #[inline(always)]
  fn drop(&mut self) {
    self.lock.lock.store(NO_LOCK, Release);
  }
}