Skip to content

Commit 56b3b62

Browse files
committed
Refactor how existence of ivars is stored
1 parent 7b361f6 commit 56b3b62

File tree

3 files changed

+345
-337
lines changed

3 files changed

+345
-337
lines changed

crates/objc2/src/macros/declare_class.rs

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -450,8 +450,12 @@ macro_rules! declare_class {
450450
// before any access to the variables.
451451
unsafe {
452452
__OBJC2_CLASS.write(__objc2_cls);
453-
__OBJC2_IVAR_OFFSET.write(__objc2_ivar_offset);
454-
__OBJC2_DROP_FLAG_OFFSET.write(__objc2_drop_flag_offset);
453+
if <Self as $crate::__macro_helpers::DeclaredIvarsHelper>::HAS_IVARS {
454+
__OBJC2_IVAR_OFFSET.write(__objc2_ivar_offset);
455+
}
456+
if <Self as $crate::__macro_helpers::DeclaredIvarsHelper>::HAS_DROP_FLAG {
457+
__OBJC2_DROP_FLAG_OFFSET.write(__objc2_drop_flag_offset);
458+
}
455459
}
456460
});
457461

@@ -475,15 +479,35 @@ macro_rules! declare_class {
475479

476480
#[inline]
477481
fn __ivars_offset() -> $crate::__macro_helpers::isize {
478-
// SAFETY: Accessing the offset is guaranteed to only be
479-
// done after the class has been initialized.
480-
unsafe { __OBJC2_IVAR_OFFSET.assume_init() }
482+
// Only access ivar offset if we have an ivar.
483+
//
484+
// This makes the offset not be included in the final
485+
// executable if it's not needed.
486+
if <Self as $crate::__macro_helpers::DeclaredIvarsHelper>::HAS_IVARS {
487+
// SAFETY: Accessing the offset is guaranteed to only be
488+
// done after the class has been initialized.
489+
unsafe { __OBJC2_IVAR_OFFSET.assume_init() }
490+
} else {
491+
// Fall back to an offset of zero.
492+
//
493+
// This is fine, since any reads here will only be via. zero-sized
494+
// ivars, where the actual pointer doesn't matter.
495+
0
496+
}
481497
}
482498

483499
#[inline]
484500
fn __drop_flag_offset() -> $crate::__macro_helpers::isize {
485-
// SAFETY: Same as above.
486-
unsafe { __OBJC2_DROP_FLAG_OFFSET.assume_init() }
501+
if <Self as $crate::__macro_helpers::DeclaredIvarsHelper>::HAS_DROP_FLAG {
502+
// SAFETY: Same as above.
503+
unsafe { __OBJC2_DROP_FLAG_OFFSET.assume_init() }
504+
} else {
505+
// Fall back to an offset of zero.
506+
//
507+
// This is fine, since the drop flag is never actually used in the
508+
// cases where it was not added.
509+
0
510+
}
487511
}
488512

489513
// SAFETY: The offsets are implemented correctly

0 commit comments

Comments
 (0)