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
//! Shareable resources.

#[cfg(feature = "arc")] use std::sync::{Arc, Mutex, MutexGuard};
#[cfg(not(feature = "arc"))] use std::{
  cell::{Ref, RefCell, RefMut},
  rc::Rc
};

/// Shareable resource type.
///
/// Resources are wrapped in this type. You cannot do much with an object of this type, despite
/// borrowing immutable or mutably its content.
#[derive(Debug)]
pub struct Res<T>(ResInner<T>);

#[cfg(feature = "arc")]
type ResInner<T> = Arc<Mutex<T>>;

#[cfg(not(feature = "arc"))]
type ResInner<T> = Rc<RefCell<T>>;

impl<T> Clone for Res<T> {
  fn clone(&self) -> Self {
    Res(self.0.clone())
  }
}

#[cfg(feature = "arc")]
impl<T> Res<T> {
  /// Wrap a value in a shareable resource.
  pub fn new(t: T) -> Self {
    Res(Arc::new(Mutex::new(t)))
  }

  /// Borrow a resource for as long as the return value lives.
  pub fn borrow(&self) -> MutexGuard<T> {
    self.0.lock().unwrap()
  }

  /// Mutably borrow a resource for as long as the return value lives.
  pub fn borrow_mut(&self) -> MutexGuard<T> {
    self.0.lock().unwrap()
  }
}

#[cfg(not(feature = "arc"))]
impl<T> Res<T> {
  /// Wrap a value in a shareable resource.
  pub fn new(t: T) -> Self {
    Res(Rc::new(RefCell::new(t)))
  }

  /// Borrow a resource for as long as the return value lives.
  pub fn borrow(&self) -> Ref<T> {
    self.0.borrow()
  }

  /// Mutably borrow a resource for as long as the return value lives.
  pub fn borrow_mut(&self) -> RefMut<T> {
    self.0.borrow_mut()
  }
}