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
//! This microcrate provides a mutable memory wrapper that is thread-safe
//! and usable on `no_std` platforms by using [`std::sync::RwLock`]
//! when crate feature `std` is enabled (this is the default) and
//! falling back to [`core::cell::Cell`] when `std` disabled.
//!
//! the API of the core struct [`Stem`] was chosen to discourage long-lived
//! immutable references to the cell's contents, so that deadlocks are less likely.

// docs
#![doc(html_root_url = "https://docs.rs/toad-stem/0.0.0")]
#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
// -
// style
#![allow(clippy::unused_unit)]
// -
// deny
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(missing_copy_implementations)]
#![cfg_attr(not(test), deny(unsafe_code))]
// -
// warnings
#![cfg_attr(not(test), warn(unreachable_pub))]
// -
// features
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;

use core::ops::{Deref, DerefMut};

#[cfg(feature = "std")]
type Inner<T> = std::sync::RwLock<T>;

#[cfg(not(feature = "std"))]
type Inner<T> = core::cell::RefCell<T>;

/// A thread-safe mutable memory location that allows
/// for many concurrent readers or a single writer.
///
/// When feature `std` enabled, this uses [`std::sync::RwLock`].
/// When `std` disabled, uses [`core::cell::Cell`].
#[derive(Debug, Default)]
pub struct Stem<T>(Inner<T>);

impl<T> Stem<T> {
  /// Create a new Stem cell
  pub const fn new(t: T) -> Self {
    Self(Inner::new(t))
  }

  /// Map a reference to `T` to a new type
  ///
  /// This will block if called concurrently with `map_mut`.
  ///
  /// There can be any number of concurrent `map_ref`
  /// sections running at a given time.
  pub fn map_ref<F, R>(&self, f: F) -> R
    where F: for<'a> FnMut(&'a T) -> R
  {
    self.0.map_ref(f)
  }

  /// Map a mutable reference to `T` to a new type
  ///
  /// This will block if called concurrently with `map_ref` or `map_mut`.
  pub fn map_mut<F, R>(&self, f: F) -> R
    where F: for<'a> FnMut(&'a mut T) -> R
  {
    self.0.map_mut(f)
  }
}

// NOTE(orion): I chose to use a trait here to tie RwLock
// and Cell together in a testable way, to keep the actual
// code behind feature flags extremely thin.

/// A mutable memory location
///
/// This is used to back the behavior of [`Stem`],
/// which should be used instead of this trait.
pub trait StemCellInternal<T> {
  /// Create an instance of `Self`
  fn new(t: T) -> Self
    where Self: Sized;

  /// Map a reference to `T` to a new type
  ///
  /// Implementors may choose to panic or block
  /// if `map_mut` called concurrently.
  fn map_ref<F, R>(&self, f: F) -> R
    where F: for<'a> FnMut(&'a T) -> R;

  /// Map a mutable reference to `T` to a new type
  ///
  /// Implementors may choose to panic or block
  /// if `map_ref` or `map_mut` called concurrently.
  fn map_mut<F, R>(&self, f: F) -> R
    where F: for<'a> FnMut(&'a mut T) -> R;
}

#[cfg(feature = "std")]
impl<T> StemCellInternal<T> for std::sync::RwLock<T> {
  fn new(t: T) -> Self {
    Self::new(t)
  }

  fn map_ref<F, R>(&self, mut f: F) -> R
    where F: for<'a> FnMut(&'a T) -> R
  {
    f(self.read().unwrap().deref())
  }

  fn map_mut<F, R>(&self, mut f: F) -> R
    where F: for<'a> FnMut(&'a mut T) -> R
  {
    f(self.write().unwrap().deref_mut())
  }
}

impl<T> StemCellInternal<T> for core::cell::RefCell<T> {
  fn new(t: T) -> Self {
    Self::new(t)
  }

  fn map_ref<F, R>(&self, mut f: F) -> R
    where F: for<'a> FnMut(&'a T) -> R
  {
    f(self.borrow().deref())
  }

  fn map_mut<F, R>(&self, mut f: F) -> R
    where F: for<'a> FnMut(&'a mut T) -> R
  {
    f(self.borrow_mut().deref_mut())
  }
}

#[cfg(test)]
mod test {
  use core::cell::RefCell;
  use std::sync::{Arc, Barrier, RwLock};

  use super::*;

  #[test]
  fn refcell_mut() {
    let s = RefCell::new(Vec::<usize>::new());
    s.map_mut(|v| v.push(12));
    s.map_ref(|v| assert_eq!(v, &vec![12usize]));
  }

  #[test]
  fn refcell_concurrent_read_does_not_block_or_panic() {
    let s = RefCell::new(Vec::<usize>::new());
    s.map_ref(|_| s.map_ref(|_| ()));
  }

  #[test]
  fn rwlock_mut() {
    let s = RwLock::new(Vec::<usize>::new());
    s.map_mut(|v| v.push(12));
    s.map_ref(|v| assert_eq!(v, &vec![12usize]));
  }

  #[test]
  fn rwlock_concurrent_read_does_not_block_or_panic() {
    let s = RwLock::new(Vec::<usize>::new());
    s.map_ref(|_| s.map_ref(|_| ()));
  }

  #[test]
  fn stem_modify_blocks_until_refs_dropped() {
    unsafe {
      static VEC: Stem<Vec<usize>> = Stem::new(Vec::new());

      static mut START: Option<Arc<Barrier>> = None;
      static mut READING: Option<Arc<Barrier>> = None;
      static mut READING_DONE: Option<Arc<Barrier>> = None;
      static mut MODIFY_DONE: Option<Arc<Barrier>> = None;

      START = Some(Arc::new(Barrier::new(3)));
      READING = Some(Arc::new(Barrier::new(3)));
      READING_DONE = Some(Arc::new(Barrier::new(2)));
      MODIFY_DONE = Some(Arc::new(Barrier::new(3)));

      macro_rules! wait {
        ($b:ident) => {
          $b.as_ref().unwrap().clone().wait();
        };
      }

      std::thread::spawn(|| {
        wait!(START);
        VEC.map_ref(|v| {
             assert!(v.is_empty());
             wait!(READING);
             wait!(READING_DONE);
           });

        wait!(MODIFY_DONE);
      });

      std::thread::spawn(|| {
        wait!(START);
        wait!(READING);
        VEC.map_mut(|v| v.push(12)); // unblocked by READING_DONE
        wait!(MODIFY_DONE);
      });

      wait!(START);
      wait!(READING);
      wait!(READING_DONE);
      wait!(MODIFY_DONE);
      VEC.map_ref(|v| assert_eq!(v, &vec![12]));
    }
  }
}