Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zero cost ivars #296

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions crates/objc2/src/__macro_helpers/declare_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,29 @@ impl<T: Message> MaybeOptionId for Option<Id<T>> {
}
}

pub struct IvarStaticHelper {
offset: Cell<isize>,
}

impl IvarStaticHelper {
#[inline]
pub const fn new() -> Self {
Self {
offset: Cell::new(0),
}
}

pub fn set<T: IvarType>(&self, cls: &Class) {
let offset = ivar_offset(cls, T::NAME, &T::Type::__ENCODING);
self.offset.set(offset);
}

#[inline]
pub fn get(&self) -> isize {
self.offset.get()
}
}

/// Helper for ensuring that `ClassType::Mutability` is implemented correctly
/// for subclasses.
pub trait ValidSubclassMutability<T: mutability::Mutability> {}
Expand Down
18 changes: 18 additions & 0 deletions crates/objc2/src/macros/__field_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,31 @@ macro_rules! __parse_fields {
__priv: (),
}

impl $field_name {
#[inline]
unsafe fn __offset_ptr() -> &'static $crate::__macro_helpers::IvarStaticHelper {
static mut OFFSET: $crate::__macro_helpers::IvarStaticHelper
= $crate::__macro_helpers::IvarStaticHelper::new();
#[allow(unused_unsafe)]
unsafe { &OFFSET }
}
}

// SAFETY:
// - The ivars are in a type used as an Objective-C object.
// - The ivar is added to the class in `__objc2_declare_ivars`.
// - Caller upholds that the ivars are properly initialized.
unsafe impl $crate::declare::IvarType for $field_name {
type Type = IvarDrop<$ty>;
const NAME: &'static $crate::__macro_helpers::str = $ivar_name;

#[inline]
unsafe fn __offset(
_ptr: $crate::__macro_helpers::NonNull<$crate::runtime::AnyObject>,
) -> $crate::__macro_helpers::isize {
#[allow(unused_unsafe)]
unsafe { Self::__offset_ptr().get() }
}
}
) ($($ivar_type_name)* $field_name)
(
Expand Down
6 changes: 6 additions & 0 deletions crates/objc2/src/macros/declare_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,12 @@ macro_rules! __inner_declare_class {
}

let _cls = __objc2_builder.register();

$(
unsafe {
$ivar::__offset_ptr().set::<$ivar>(_cls);
}
)*
});

// We just registered the class, so it should be available
Expand Down
Loading