Skip to content

Commit d3e76f6

Browse files
committed
Refactor how existence of ivars is stored
1 parent fef8b5b commit d3e76f6

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
@@ -452,8 +452,12 @@ macro_rules! declare_class {
452452
// before any access to the variables.
453453
unsafe {
454454
__OBJC2_CLASS.write(__objc2_cls);
455-
__OBJC2_IVAR_OFFSET.write(__objc2_ivar_offset);
456-
__OBJC2_DROP_FLAG_OFFSET.write(__objc2_drop_flag_offset);
455+
if <Self as $crate::__macro_helpers::DeclaredIvarsHelper>::HAS_IVARS {
456+
__OBJC2_IVAR_OFFSET.write(__objc2_ivar_offset);
457+
}
458+
if <Self as $crate::__macro_helpers::DeclaredIvarsHelper>::HAS_DROP_FLAG {
459+
__OBJC2_DROP_FLAG_OFFSET.write(__objc2_drop_flag_offset);
460+
}
457461
}
458462
});
459463

@@ -477,15 +481,35 @@ macro_rules! declare_class {
477481

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

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

491515
// SAFETY: The offsets are implemented correctly

0 commit comments

Comments
 (0)