hello, I am trying to understand intrusive data structure with this linked list example. I understand that for T to be an element of a single linked list it must store a pointer to next inside of T, and thus containing a list embedded inside T itself. But how does this help? How is this better as compared to a normal singly linked list and how does this reduce the overall allocation?
use std::cell::Cell;
use std::marker::PhantomData;
use std::ptr::NonNull;
struct Foo {
value: i32,
next: Cell<Option<NonNull<Foo>>>,
}
struct SingleLinkedIntrusiveList<'b, T>
where
T: SingleLinkedIntrusiveListItem,
{
first: Cell<Option<NonNull<T>>>,
last: Cell<Option<NonNull<T>>>,
_marker: core::marker::PhantomData<&'b ()>,
}
trait SingleLinkedIntrusiveListItem {
fn next(&self) -> Option<NonNull<Self>>;
fn set_next(&self, new_next: Option<NonNull<Self>>);
}
impl SingleLinkedIntrusiveListItem for Foo {
fn next(&self) -> Option<NonNull<Self>> {
self.next.get()
}
fn set_next(&self, new_next: Option<NonNull<Self>>) {
self.next.set(new_next)
}
}