Skip to content

Commit 434b8d7

Browse files
committed
examples: kernel_ptr: add container_of function
1 parent c6a4a01 commit 434b8d7

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

examples/kernel_ptr.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,25 @@ where
5050
}
5151
}
5252

53+
impl<'a, T: 'a> Ptr<'a, T> {
54+
/// Turn this pointer-to-a-field into a pointer to the entire container.
55+
///
56+
/// # Safety
57+
///
58+
/// * `self` points at a `T` that is contained as the field `F` inside of a `U`.
59+
/// * `self` is derived from a pointer that originally pointed at the entire `U` that contains
60+
/// this `T` as the field `F`.
61+
pub unsafe fn container_of<U, F>(self) -> Ptr<'a, U>
62+
where
63+
U: 'a,
64+
F: Field<Base = U, Type = T>,
65+
{
66+
let inner = unsafe { self.inner.byte_sub(F::OFFSET) };
67+
Ptr {
68+
inner: inner.cast(),
69+
_phantom: PhantomData,
70+
}
71+
}
72+
}
73+
5374
fn main() {}

0 commit comments

Comments
 (0)