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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
//! Like [`std::sync::Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) but backed by a
//! memory [`Pool`](trait.Pool.html) rather than `#[global_allocator]`
//!
//! Note that the same limitations that apply to ["Box" pool] also apply to the "Arc" pool.
//!
//! ["Box" pool]: ../../index.html
//!
//! # Examples
//!
//! ``` ignore
//! use heapless::{arc_pool, Arc};
//!
//! pub struct BigStruct { // <- does NOT implement Clone
//!     data: [u8; 128],
//!     // ..
//! }
//!
//! // declare a memory pool
//! arc_pool!(P: BigStruct);
//!
//!
//! #[cortex_m_rt::entry]
//! fn main() -> ! {
//!     static mut MEMORY: [u8; 1024] = [0; 1024];
//!
//!     // give some static memory to the pool
//!     P::grow(MEMORY);
//!
//!     let x: Arc<P> = P::alloc(BigStruct::new()).ok().expect("OOM");
//!     //         ^ NOTE: this is the Pool type, not the data type
//!
//!     // cloning is cheap; it increases the refcount
//!     let y = x.clone();
//!
//!     // same data address
//!     assert_eq!(&*x as *const _, &*y as *const _);
//!
//!     // auto-deref
//!     let data: &[u8] = &x.data;
//!
//!     // decrease refcount
//!     drop(x);
//!
//!     // refcount decreased to 0; memory is returned to the pool
//!     drop(y);
//!
//!     // ..
//! }
//! ```
//!
//! The `grow_exact` API is also available on the "Arc pool". It requires using
//! `Node<ArcInner<Type>>` as the array element type. Example below:
//!
//! ``` ignore
//! use heapless::pool::{singleton::arc::ArcInner, Node};
//!
//! pub struct BigStruct { /* .. */ }
//!
//! arc_pool!(P: BigStruct);
//!
//! #[cortex_m_rt::entry]
//! fn main() -> ! {
//!     static mut MEMORY: MaybeUninit<[Node<ArcInner<BigStruct>>; 2]> = MaybeUninit::uninit();
//!
//!     P::grow_exact(MEMORY);
//!
//!     // 2 allocations are guaranteed to work
//!     let x = P::alloc(BigStruct::new()).ok().expect("OOM");
//!     let y = P::alloc(BigStruct::new()).ok().expect("OOM");
//!
//!     // ..
//! }
//! ```

use core::{
    cmp, fmt,
    hash::{Hash, Hasher},
    marker::PhantomData,
    ops::Deref,
    ptr,
    sync::atomic,
};

#[cfg(cas_atomic_polyfill)]
use atomic_polyfill::{AtomicUsize, Ordering};

#[cfg(not(cas_atomic_polyfill))]
use core::sync::atomic::{AtomicUsize, Ordering};

use crate::pool::{self, stack::Ptr, Node};

/// Instantiates a pool of Arc pointers as a global singleton
// NOTE(any(test)) makes testing easier (no need to enable Cargo features for testing)
#[cfg(any(
    armv6m,
    armv7a,
    armv7r,
    armv7m,
    armv8m_main,
    all(
        any(target_arch = "x86_64", target_arch = "x86"),
        feature = "x86-sync-pool"
    ),
    test
))]
#[macro_export]
macro_rules! arc_pool {
    ($(#[$($attr:tt)*])* $ident:ident: $ty:ty) => {
        pub struct $ident;

        impl $crate::pool::singleton::arc::Pool for $ident {
            type Data = $ty;

            fn ptr() -> &'static $crate::pool::Pool<$crate::pool::singleton::arc::ArcInner<$ty>> {
                $(#[$($attr)*])*
                static POOL: $crate::pool::Pool<$crate::pool::singleton::arc::ArcInner<$ty>> =
                    $crate::pool::Pool::new();

                &POOL
            }
        }

        impl $ident {
            /// Allocates a new `Arc` and writes `data` to it
            ///
            /// Returns an `Err`or if the backing memory pool is empty
            pub fn alloc(data: $ty) -> Result<$crate::Arc<Self>, $ty>
            where
                Self: Sized,
            {
                $crate::Arc::new(data)
            }

            /// Increases the capacity of the pool
            ///
            /// This method might *not* fully utilize the given memory block due to alignment requirements
            ///
            /// This method returns the number of *new* blocks that can be allocated.
            pub fn grow(memory: &'static mut [u8]) -> usize {
                <Self as $crate::pool::singleton::arc::Pool>::ptr().grow(memory)
            }

            /// Increases the capacity of the pool
            ///
            /// Unlike `grow`, this method fully utilizes the given memory block
            pub fn grow_exact<A>(memory: &'static mut MaybeUninit<A>) -> usize
            where
                A: AsMut<[$crate::pool::Node<$crate::pool::singleton::arc::ArcInner<$ty>>]>,
            {
                <Self as $crate::pool::singleton::arc::Pool>::ptr().grow_exact(memory)
            }
        }
    };
}

/// Pool of Arc pointers
pub trait Pool {
    /// The data behind the Arc pointer
    type Data: 'static;

    #[doc(hidden)]
    fn ptr() -> &'static pool::Pool<ArcInner<Self::Data>>;
}

// mostly a verbatim copy of liballoc(/src/sync.rs) as of v1.54.0 minus the `Weak` API
// anything that diverges has been marked with `XXX`

/// `std::sync::Arc` but backed by a memory [`Pool`] rather than `#[global_allocator]`
///
/// [`Pool`]: trait.Pool.html
///
/// An example and more details can be found in the [module level documentation](index.html).
// XXX `Pool::Data` is not `?Sized` -- `Unsize` coercions cannot be implemented on stable
pub struct Arc<P>
where
    P: Pool,
{
    phantom: PhantomData<ArcInner<P::Data>>,
    ptr: Ptr<Node<ArcInner<P::Data>>>,
    pool: PhantomData<P>,
}

impl<P> Arc<P>
where
    P: Pool,
{
    /// Constructs a new `Arc`
    ///
    /// Returns an `Err`or if the backing memory pool is empty
    // XXX original API is "infallible"
    pub fn new(data: P::Data) -> Result<Self, P::Data> {
        if let Some(node) = P::ptr().stack.try_pop() {
            unsafe {
                ptr::write(
                    node.as_ref().data.get(),
                    ArcInner {
                        strong: AtomicUsize::new(1),
                        data,
                    },
                )
            }

            Ok(Self {
                phantom: PhantomData,
                pool: PhantomData,
                ptr: node,
            })
        } else {
            Err(data)
        }
    }

    fn inner(&self) -> &ArcInner<P::Data> {
        unsafe { &*self.ptr.as_ref().data.get() }
    }

    fn from_inner(ptr: Ptr<Node<ArcInner<P::Data>>>) -> Self {
        Self {
            phantom: PhantomData,
            pool: PhantomData,
            ptr,
        }
    }

    unsafe fn get_mut_unchecked(this: &mut Self) -> &mut P::Data {
        &mut (*this.ptr.as_ref().data.get()).data
        // &mut (*this.ptr.as_ptr()).data
    }

    #[inline(never)]
    unsafe fn drop_slow(&mut self) {
        // run `P::Data`'s destructor
        ptr::drop_in_place(Self::get_mut_unchecked(self));

        // XXX memory pool instead of `#[global_allocator]`
        // return memory to pool
        P::ptr().stack.push(self.ptr);
    }
}

const MAX_REFCOUNT: usize = (isize::MAX) as usize;

impl<P> AsRef<P::Data> for Arc<P>
where
    P: Pool,
{
    fn as_ref(&self) -> &P::Data {
        &**self
    }
}

// XXX no `Borrow` implementation due to 'conflicting implementations of trait' error

impl<P> Clone for Arc<P>
where
    P: Pool,
{
    fn clone(&self) -> Self {
        let old_size = self.inner().strong.fetch_add(1, Ordering::Relaxed);

        if old_size > MAX_REFCOUNT {
            // XXX original code calls `intrinsics::abort` which is unstable API
            panic!();
        }

        Self::from_inner(self.ptr)
    }
}

impl<P> fmt::Debug for Arc<P>
where
    P: Pool,
    P::Data: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<P> Deref for Arc<P>
where
    P: Pool,
{
    type Target = P::Data;

    fn deref(&self) -> &P::Data {
        &self.inner().data
    }
}

impl<P> fmt::Display for Arc<P>
where
    P: Pool,
    P::Data: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

// XXX original uses `#[may_dangle]` which is an unstable language feature
impl<P> Drop for Arc<P>
where
    P: Pool,
{
    fn drop(&mut self) {
        if self.inner().strong.fetch_sub(1, Ordering::Release) != 1 {
            return;
        }

        atomic::fence(Ordering::Acquire);

        unsafe {
            self.drop_slow();
        }
    }
}

impl<P> Eq for Arc<P>
where
    P: Pool,
    P::Data: Eq,
{
}

impl<P> Hash for Arc<P>
where
    P: Pool,
    P::Data: Hash,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        (**self).hash(state)
    }
}

impl<P> Ord for Arc<P>
where
    P: Pool,
    P::Data: Ord,
{
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        (**self).cmp(&**other)
    }
}

impl<P> PartialEq for Arc<P>
where
    P: Pool,
    P::Data: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        // XXX missing pointer equality specialization, which uses an unstable language feature
        (**self).eq(&**other)
    }
}

impl<P> PartialOrd for Arc<P>
where
    P: Pool,
    P::Data: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        (**self).partial_cmp(&**other)
    }
}

unsafe impl<P> Send for Arc<P>
where
    P: Pool,
    P::Data: Sync + Send,
{
}

unsafe impl<P> Sync for Arc<P>
where
    P: Pool,
    P::Data: Sync + Send,
{
}

impl<P> Unpin for Arc<P> where P: Pool {}

/// Unfortunate implementation detail required to use the `grow_exact` API
pub struct ArcInner<T> {
    data: T,
    strong: AtomicUsize,
    // XXX `Weak` API not implemented
    // weak: AtomicUsize,
}