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

feat: support customized offset #2

Merged
merged 2 commits into from
Nov 11, 2024
Merged
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: 21 additions & 2 deletions src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ macro_rules! intrusive_adapter {
(@impl
$(#[$attr:meta])* $vis:vis $name:ident ($($args:tt),*)
= $pointer:ty: $value:path { $($fields:expr)+ => $link:ty } $($where_:tt)*
) => {
intrusive_adapter!(@impl
$(#[$attr])* $vis $name ($($args),*)
= $pointer: $value { ?offset = $crate::offset_of!($value, $($fields)*) => $link } $($where_)*
);
};
(@impl
$(#[$attr:meta])* $vis:vis $name:ident ($($args:tt),*)
= $pointer:ty: $value:path { ?offset = $offset:expr => $link:ty } $($where_:tt)*
) => {
#[allow(explicit_outlives_requirements)]
$(#[$attr])*
Expand Down Expand Up @@ -207,13 +216,13 @@ macro_rules! intrusive_adapter {

#[inline]
unsafe fn get_value(&self, link: <Self::LinkOps as $crate::LinkOps>::LinkPtr) -> *const <Self::PointerOps as $crate::PointerOps>::Value {
$crate::container_of!(link.as_ptr(), $value, $($fields)+)
(link.as_ptr() as *const _ as *const u8).sub($offset) as *const $value
}
#[inline]
unsafe fn get_link(&self, value: *const <Self::PointerOps as $crate::PointerOps>::Value) -> <Self::LinkOps as $crate::LinkOps>::LinkPtr {
// We need to do this instead of just accessing the field directly
// to strictly follow the stack borrow rules.
let ptr = (value as *const u8).add($crate::offset_of!($value, $($fields)+));
let ptr = (value as *const u8).add($offset);
core::ptr::NonNull::new_unchecked(ptr as *mut _)
}
#[inline]
Expand Down Expand Up @@ -268,6 +277,7 @@ macro_rules! intrusive_adapter {
#[cfg(test)]
mod tests {
use crate::LinkedListLink;
use core::cell::UnsafeCell;
use std::rc::Rc;

struct Obj {
Expand All @@ -278,6 +288,10 @@ mod tests {
obj: Obj,
}

struct IndirectWrapper {
cell: UnsafeCell<Obj>,
}

intrusive_adapter! {
/// Test doc comment
ObjAdapter1 = Rc<Obj>: Obj { link => LinkedListLink }
Expand All @@ -287,4 +301,9 @@ mod tests {
/// Test doc comment
WrapperAdapter1 = Rc<Wrapper>: Wrapper { obj.link => LinkedListLink }
}

intrusive_adapter! {
/// Test doc comment
IndirectWrapperAdapter1 = Rc<Wrapper>: Wrapper { ?offset = crate::offset_of!(IndirectWrapper, cell) + crate::offset_of!(Obj, link) => LinkedListLink }
}
}
Loading