basic_oop/
lib.rs

1#![no_std]
2
3extern crate alloc;
4
5use alloc::rc::Rc;
6use alloc::sync::Arc;
7use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
8use macro_magic::export_tokens_no_emit;
9
10#[doc(hidden)]
11pub use macro_magic;
12
13pub use basic_oop_macro::class_unsafe;
14
15pub use basic_oop_macro::class_sync_unsafe;
16
17#[doc(hidden)]
18pub use alloc::rc::Rc as alloc_rc_Rc;
19#[doc(hidden)]
20pub use alloc::sync::Arc as alloc_sync_Arc;
21#[doc(hidden)]
22pub use core::mem::transmute as core_mem_transmute;
23#[doc(hidden)]
24pub use dynamic_cast::SupportsInterfaces as dynamic_cast_SupportsInterfaces;
25#[doc(hidden)]
26pub use dynamic_cast::impl_supports_interfaces as dynamic_cast_impl_supports_interfaces;
27#[doc(hidden)]
28pub use dynamic_cast::dyn_cast_rc as dynamic_cast_dyn_cast_rc;
29#[doc(hidden)]
30pub use dynamic_cast::dyn_cast_arc as dynamic_cast_dyn_cast_arc;
31
32#[export_tokens_no_emit]
33struct inherited_from_Obj { __class__: ::basic_oop::Obj }
34
35pub type Vtable = *const *const ();
36
37#[derive(Debug, Clone)]
38pub struct Obj {
39    vtable: Vtable,
40}
41
42unsafe impl Send for Obj { }
43
44unsafe impl Sync for Obj { }
45
46impl Obj {
47    pub fn new() -> Rc<dyn TObj> {
48        Rc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
49    }
50
51    pub fn new_sync() -> Arc<dyn TObj> {
52        Arc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
53    }
54
55    pub unsafe fn new_raw(vtable: Vtable) -> Self {
56        Obj { vtable }
57    }
58
59    pub fn vtable(&self) -> Vtable { self.vtable }
60}
61
62pub trait TObj: SupportsInterfaces {
63    fn obj(&self) -> &Obj;
64}
65
66impl_supports_interfaces!(Obj: TObj);
67
68impl TObj for Obj {
69    fn obj(&self) -> &Obj { self }
70}
71
72#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
73#[repr(usize)]
74pub enum ObjVirtMethods {
75    VirtMethodsCount = 0usize,
76}
77
78pub struct ObjVtable(pub [*const (); ObjVirtMethods::VirtMethodsCount as usize]);
79
80impl ObjVtable {
81    pub const fn new() -> Self {
82        ObjVtable([])
83    }
84}
85
86const OBJ_VTABLE: [*const (); ObjVirtMethods::VirtMethodsCount as usize] = ObjVtable::new().0;
87
88#[repr(C)]
89pub struct VtableJoin<const A: usize, const B: usize> {
90    pub a: [*const (); A],
91    pub b: [*const (); B],
92}