1#![no_std]
15#![cfg_attr(test, no_main)]
16
17use core::cell::UnsafeCell;
18use core::marker::PhantomData;
19use core::mem::{ManuallyDrop, offset_of};
20use core::ops::{Deref, DerefMut};
21use core::ptr::NonNull;
22use core::sync::atomic::Ordering;
23
24use pw_atomic::AtomicUsize;
25
26pub struct ForeignBox<T: ?Sized> {
27 inner: NonNull<T>,
28
29 consumed: bool,
34
35 _phantom: PhantomData<T>,
38}
39
40unsafe impl<T: Send + ?Sized> Send for ForeignBox<T> {}
42unsafe impl<T: Sync + ?Sized> Sync for ForeignBox<T> {}
43
44impl<T: ?Sized> ForeignBox<T> {
45 #[allow(dead_code)]
46 #[must_use]
52 pub const unsafe fn new(ptr: NonNull<T>) -> Self {
53 Self {
54 inner: ptr,
55 consumed: false,
56 _phantom: PhantomData,
57 }
58 }
59
60 #[must_use]
68 pub unsafe fn new_from_ptr(ptr: *mut T) -> Self {
69 let Some(ptr) = NonNull::new(ptr) else {
70 pw_assert::panic!("Null pointer");
71 };
72 unsafe { Self::new(ptr) }
73 }
74
75 #[allow(clippy::must_use_candidate)]
76 pub fn consume(mut self) -> NonNull<T> {
77 self.consumed = true;
78 self.inner
79 }
80
81 #[must_use]
86 pub unsafe fn as_ptr(&self) -> *const T {
87 self.inner.as_ptr()
88 }
89
90 #[must_use]
95 pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
96 unsafe { self.inner.as_mut() }
97 }
98}
99
100impl<T: ?Sized> Drop for ForeignBox<T> {
101 fn drop(&mut self) {
102 if !self.consumed {
103 pw_assert::panic!(
104 "ForeignBox@{:08x} dropped before being consumed!",
105 self.inner.as_ptr().cast::<()>() as usize
106 );
107 }
108 }
109}
110
111impl<T: ?Sized> From<&'static mut T> for ForeignBox<T> {
112 fn from(t: &'static mut T) -> ForeignBox<T> {
113 unsafe { ForeignBox::new(NonNull::from(t)) }
116 }
117}
118
119impl<T: ?Sized> AsRef<T> for ForeignBox<T> {
120 fn as_ref(&self) -> &T {
121 unsafe { self.inner.as_ref() }
122 }
123}
124
125impl<T: ?Sized> AsMut<T> for ForeignBox<T> {
126 fn as_mut(&mut self) -> &mut T {
127 unsafe { self.inner.as_mut() }
128 }
129}
130
131impl<T: ?Sized> Deref for ForeignBox<T> {
132 type Target = T;
133
134 fn deref(&self) -> &Self::Target {
135 self.as_ref()
136 }
137}
138
139impl<T: ?Sized> DerefMut for ForeignBox<T> {
140 fn deref_mut(&mut self) -> &mut Self::Target {
141 self.as_mut()
142 }
143}
144
145#[doc(hidden)]
146pub struct ForeignRcState<A: AtomicUsize, T: ?Sized> {
147 _not_send_sync: PhantomData<NonNull<()>>,
150
151 ref_count: A,
168 inner: UnsafeCell<ManuallyDrop<T>>,
170}
171
172unsafe impl<A: Send + AtomicUsize, T: Send + ?Sized> Send for ForeignRcState<A, T> {}
175unsafe impl<A: Sync + AtomicUsize, T: Sync + ?Sized> Sync for ForeignRcState<A, T> {}
180
181impl<A: AtomicUsize, T> ForeignRcState<A, T> {
182 pub fn new(val: T) -> Self {
183 Self {
184 ref_count: A::new(1),
185 inner: UnsafeCell::new(ManuallyDrop::new(val)),
186 _not_send_sync: PhantomData,
187 }
188 }
189}
190
191impl<A: AtomicUsize, T: ?Sized> ForeignRcState<A, T> {
192 pub unsafe fn create_first_ref(&'static mut self) -> ForeignRc<A, T> {
199 ForeignRc { state: self }
203 }
204
205 pub fn ref_count(&self) -> &A {
206 &self.ref_count
207 }
208}
209
210impl<A: AtomicUsize, T: Sized> ForeignRcState<A, T> {
211 pub unsafe fn create_ref_from_inner(inner: &T) -> ForeignRc<A, T> {
218 let inner = NonNull::from_ref(inner);
219 let state: &Self = unsafe { inner.byte_sub(offset_of!(Self, inner)).cast().as_ref() };
220 state.ref_count.fetch_add(1, Ordering::SeqCst);
221 ForeignRc { state }
222 }
223}
224
225pub struct ForeignRc<A: AtomicUsize + 'static, T: ?Sized + 'static> {
226 state: &'static ForeignRcState<A, T>,
227}
228
229impl<A: AtomicUsize, T: ?Sized> ForeignRc<A, T> {
230 #[must_use]
231 pub fn state(&self) -> &ForeignRcState<A, T> {
232 self.state
233 }
234
235 #[doc(hidden)]
236 pub unsafe fn map<U: ?Sized>(
242 self,
243 map: impl Fn(&ForeignRcState<A, T>) -> &ForeignRcState<A, U>,
244 ) -> ForeignRc<A, U> {
245 let this = core::mem::ManuallyDrop::new(self);
247 ForeignRc {
248 state: map(this.state),
249 }
250 }
251}
252
253impl<A: AtomicUsize, T: ?Sized> Deref for ForeignRc<A, T> {
254 type Target = T;
255
256 fn deref(&self) -> &T {
257 let ptr = self.state.inner.get();
258 unsafe { &*ptr }
262 }
263}
264
265impl<A: AtomicUsize, T: ?Sized> Clone for ForeignRc<A, T> {
266 fn clone(&self) -> Self {
267 self.state.ref_count.fetch_add(1, Ordering::SeqCst);
268 Self { state: self.state }
273 }
274}
275
276impl<A: AtomicUsize, T: ?Sized> Drop for ForeignRc<A, T> {
277 fn drop(&mut self) {
278 let old = self.state.ref_count.fetch_sub(1, Ordering::SeqCst);
279 if old == 1 {
280 let ptr = self.state.inner.get();
281 let md = unsafe { &mut *ptr };
291 unsafe { ManuallyDrop::drop(md) };
296 }
297 }
298}
299
300#[macro_export]
303macro_rules! upcast_foreign_rc {
304 ($rc:expr => dyn $trait:ident $(<$($trait_tyvar:ident),*>)? ) => {{
305 use $crate::ForeignRcState;
306 let rc = $rc;
307 unsafe {
310 rc.map(|inner: &ForeignRcState<_, _>|
311 -> &ForeignRcState<_, dyn $trait $(<$($trait_tyvar),*>)?> { inner })
312 }
313 }};
314}
315
316#[doc(hidden)]
321pub struct StaticStorage<T> {
322 inner: UnsafeCell<core::mem::MaybeUninit<T>>,
323}
324
325impl<T> StaticStorage<T> {
326 #[must_use]
328 pub const fn new() -> Self {
329 Self {
330 inner: UnsafeCell::new(core::mem::MaybeUninit::uninit()),
331 }
332 }
333
334 #[allow(clippy::mut_from_ref)]
340 pub unsafe fn init(&self, val: T) -> &mut T {
341 unsafe { (*self.inner.get()).write(val) }
342 }
343
344 pub const unsafe fn address(&self) -> *const () {
355 self.inner.get() as *const ()
356 }
357}
358
359unsafe impl<T> Sync for StaticStorage<T> {}
362
363#[macro_export]
368macro_rules! static_foreign_box {
369 ($ty:ty, $init:expr) => {{
370 unsafe fn declare_static(val: $ty) -> &'static mut $ty {
371 use $crate::StaticStorage;
372
373 static STORAGE: StaticStorage<$ty> = StaticStorage::new();
374 unsafe { STORAGE.init(val) }
375 }
376 let r = declare_static($init);
377
378 $crate::ForeignBox::new(NonNull::from_ref(r))
380 }};
381}
382
383#[macro_export]
388macro_rules! static_foreign_rc {
389 ($atomic_usize:ty, $ty:ty, $init:expr) => {{
390 unsafe fn declare_static(val: $ty) -> $crate::ForeignRc<$atomic_usize, $ty> {
391 use $crate::{ForeignRcState, StaticStorage};
392
393 static STORAGE: StaticStorage<ForeignRcState<$atomic_usize, $ty>> =
394 StaticStorage::new();
395 unsafe {
396 let r = STORAGE.init(ForeignRcState::new(val));
397 r.create_first_ref()
398 }
399 }
400
401 declare_static($init)
402 }};
403}
404
405#[cfg(test)]
406mod tests {
407 use core::cell::Cell;
408
409 use pw_atomic::AtomicLoad;
410 use unittest::test;
411
412 use super::*;
413
414 #[test]
415 fn consume_returns_the_same_pointer() -> unittest::Result<()> {
416 let mut value = 0xdecafbad_u32;
417 let ptr = &raw mut value;
418 let foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
419 let consumed_ptr = foreign_box.consume();
420
421 unittest::assert_eq!(ptr, consumed_ptr.as_ptr());
422 Ok(())
423 }
424
425 #[test]
426 fn value_can_be_read_through_as_ref() -> unittest::Result<()> {
427 let mut value = 0xdecafbad_u32;
428 let ptr = &raw mut value;
429 let foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
430 unittest::assert_eq!(value, *(foreign_box.as_ref()));
431
432 let _ = foreign_box.consume();
434 Ok(())
435 }
436
437 #[test]
438 fn value_can_be_modified_through_as_mut() -> unittest::Result<()> {
439 let mut value = 0xdecafbad_u32;
440 let ptr = &raw mut value;
441 let mut foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
442 *(foreign_box.as_mut()) = 0xcafecafe;
443
444 unittest::assert_eq!(unsafe { ptr.read_volatile() }, 0xcafecafe);
445
446 let _ = foreign_box.consume();
448 Ok(())
449 }
450
451 #[test]
452 fn value_can_be_read_through_deref() -> unittest::Result<()> {
453 let mut value = 0xdecafbad_u32;
454 let ptr = &raw mut value;
455 let foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
456 unittest::assert_eq!(value, *foreign_box);
457
458 let _ = foreign_box.consume();
460 Ok(())
461 }
462
463 #[test]
464 fn value_can_be_modified_through_deref_mut() -> unittest::Result<()> {
465 let mut value = 0xdecafbad_u32;
466 let ptr = &raw mut value;
467 let mut foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
468 *foreign_box = 0xcafecafe;
469
470 unittest::assert_eq!(unsafe { ptr.read_volatile() }, 0xcafecafe);
471
472 let _ = foreign_box.consume();
474 Ok(())
475 }
476
477 trait TestDynTrait {
478 fn number(&self) -> u32;
479 }
480
481 struct TimesOne {
482 val: u32,
483 }
484
485 impl TestDynTrait for TimesOne {
486 fn number(&self) -> u32 {
487 self.val
488 }
489 }
490
491 #[allow(dead_code)]
492 struct TimesTwo {
493 val: u32,
494 }
495
496 #[allow(dead_code)]
497 impl TestDynTrait for TimesTwo {
498 fn number(&self) -> u32 {
499 self.val * 2
500 }
501 }
502
503 fn get_number(val: &ForeignBox<dyn TestDynTrait>) -> u32 {
504 val.as_ref().number()
505 }
506
507 #[test]
508 fn supports_dynamic_dispatch() -> unittest::Result<()> {
509 let mut times_one_val = TimesOne { val: 10 };
510 let ptr = &raw mut times_one_val;
511 let times_one_box = unsafe { ForeignBox::<dyn TestDynTrait>::new_from_ptr(ptr) };
512
513 let mut times_two_val = TimesTwo { val: 10 };
514 let ptr = &raw mut times_two_val;
515 let times_two_box = unsafe { ForeignBox::<dyn TestDynTrait>::new_from_ptr(ptr) };
516
517 unittest::assert_eq!(get_number(×_one_box), 10);
518 unittest::assert_eq!(get_number(×_two_box), 20);
519
520 times_one_box.consume();
521 times_two_box.consume();
522 Ok(())
523 }
524
525 #[test]
526 fn static_foreign_box_can_be_created_and_consumed() -> unittest::Result<()> {
527 let b = unsafe { static_foreign_box!(u32, 42) };
528 unittest::assert_eq!(*b, 42);
529 let ptr = b.consume();
530 unittest::assert_eq!(unsafe { ptr.read() }, 42);
531 Ok(())
532 }
533
534 struct TestAtomicUsize(Cell<usize>);
544
545 unsafe impl Sync for TestAtomicUsize {}
548
549 impl pw_atomic::AtomicNew<usize> for TestAtomicUsize {
550 fn new(val: usize) -> Self {
551 Self(Cell::new(val))
552 }
553 }
554
555 impl pw_atomic::AtomicLoad<usize> for TestAtomicUsize {
556 fn load(&self, _order: Ordering) -> usize {
557 self.0.get()
558 }
559 }
560
561 impl pw_atomic::AtomicStore<usize> for TestAtomicUsize {
562 fn store(&self, val: usize, _order: Ordering) {
563 self.0.set(val);
564 }
565 }
566
567 impl pw_atomic::AtomicCompareExchange<usize> for TestAtomicUsize {
568 fn compare_exchange(
569 &self,
570 current: usize,
571 new: usize,
572 _success: Ordering,
573 _failure: Ordering,
574 ) -> Result<usize, usize> {
575 let prev = self.0.get();
576 if prev == current {
577 self.0.set(new);
578 Ok(prev)
579 } else {
580 Err(prev)
581 }
582 }
583 }
584
585 impl pw_atomic::AtomicAdd<usize> for TestAtomicUsize {
586 fn fetch_add(&self, val: usize, _order: Ordering) -> usize {
587 self.0.replace(self.0.get().wrapping_add(val))
588 }
589 }
590
591 impl pw_atomic::AtomicSub<usize> for TestAtomicUsize {
592 fn fetch_sub(&self, val: usize, _order: Ordering) -> usize {
593 self.0.replace(self.0.get().wrapping_sub(val))
594 }
595 }
596
597 impl pw_atomic::AtomicZero for TestAtomicUsize {
598 const ZERO: Self = Self(Cell::new(0));
599 }
600
601 impl pw_atomic::AtomicOne for TestAtomicUsize {
602 const ONE: Self = Self(Cell::new(1));
603 }
604
605 impl pw_atomic::Atomic<usize> for TestAtomicUsize {}
606 impl AtomicUsize for TestAtomicUsize {}
607
608 #[test]
609 fn static_foreign_rc_ref_count_is_correct() -> unittest::Result<()> {
610 let rc = unsafe { static_foreign_rc!(TestAtomicUsize, u32, 42) };
611 unittest::assert_eq!(*rc, 42);
612 unittest::assert_eq!(rc.state.ref_count.load(Ordering::SeqCst), 1);
613 let rc2 = rc.clone();
614 unittest::assert_eq!(rc.state.ref_count.load(Ordering::SeqCst), 2);
615 drop(rc2);
616 unittest::assert_eq!(rc.state.ref_count.load(Ordering::SeqCst), 1);
617 Ok(())
618 }
619}