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
/* arc.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Very simple thread-safe Atomic Reference Counted pointer type
//! implementation.

use core::ops::Deref;
// Imports ===================================================================
use core::ptr::NonNull;
use avr_oxide::alloc::boxed::Box;
use avr_oxide::concurrency::interrupt;
use avr_oxide::util::datatypes::Volatile;

// Declarations ==============================================================
pub struct Arc<T: ?Sized> {
  ptr: NonNull<ArcInner<T>>
}

#[repr(C)]
struct ArcInner<T: ?Sized> {
  strong: Volatile<usize>,
  data: T,
}


// Code ======================================================================
unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}

impl<T: ?Sized> Arc<T> {
  #[allow(dead_code)]
  unsafe fn from_inner(ptr: NonNull<ArcInner<T>>) -> Self {
    Self { ptr  }
  }
  #[allow(dead_code)]
  unsafe fn from_ptr(ptr: *mut ArcInner<T>) -> Self {
    Self::from_inner(NonNull::new_unchecked(ptr))
  }
}

impl <T> Arc<T>{
  pub fn new(data: T) -> Arc<T> {
    let inner = Box::new(ArcInner {
      strong: Volatile::<usize>::zero(),
      data
    });

    Arc {
      ptr: Box::leak(inner).into()
    }
  }
}

impl<T: ?Sized> Clone for Arc<T> {
  fn clone(&self) -> Self {
    unsafe {
      (*self.ptr.as_ptr()).strong += 1;

      Arc {
        ptr: self.ptr
      }
    }
  }
}

impl<T: ?Sized> Drop for Arc<T> {
  fn drop(&mut self) {
    interrupt::isolated(|_isotoken|{
      unsafe {
        if (*self.ptr.as_ptr()).strong == 0 {
          // Dropping the final reference, so also drop the storage
          core::ptr::drop_in_place(self.ptr.as_ptr());
        } else {
          // Otherwise just decrement the counter
          (*self.ptr.as_ptr()).strong -= 1;
        }
      }
    });
  }
}

impl<T: ?Sized> Deref for Arc<T> {
  type Target = T;

  fn deref(&self) -> &Self::Target {
    unsafe {
      &(*self.ptr.as_ptr()).data
    }
  }
}


// Tests =====================================================================