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
37pub struct Obj {
38    vtable: Vtable,
39}
40
41unsafe impl Send for Obj { }
42
43unsafe impl Sync for Obj { }
44
45impl Obj {
46    pub fn new() -> Rc<dyn TObj> {
47        Rc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
48    }
49
50    pub fn new_sync() -> Arc<dyn TObj> {
51        Arc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
52    }
53
54    pub unsafe fn new_raw(vtable: Vtable) -> Self {
55        Obj { vtable }
56    }
57
58    pub fn vtable(&self) -> Vtable { self.vtable }
59}
60
61pub trait TObj: SupportsInterfaces {
62    fn obj(&self) -> &Obj;
63}
64
65impl_supports_interfaces!(Obj: TObj);
66
67impl TObj for Obj {
68    fn obj(&self) -> &Obj { self }
69}
70
71#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
72#[repr(usize)]
73pub enum ObjVirtMethods {
74    VirtMethodsCount = 0usize,
75}
76
77pub struct ObjVtable(pub [*const (); ObjVirtMethods::VirtMethodsCount as usize]);
78
79impl ObjVtable {
80    pub const fn new() -> Self {
81        ObjVtable([])
82    }
83}
84
85const OBJ_VTABLE: [*const (); ObjVirtMethods::VirtMethodsCount as usize] = ObjVtable::new().0;
86
87#[repr(C)]
88pub struct VtableJoin<const A: usize, const B: usize> {
89    pub a: [*const (); A],
90    pub b: [*const (); B],
91}