Hi. From time to time I've heard term "intrusive linked list". I also remember that I've read claims that they are particularly (more than standard ones) difficult to implement in Rust. I've found a nice article Intrusive linked lists, to understand what they are, and maybe why their implementation would be difficult. This article is really put well, however after reading it I have more questions than before.
I think that the main point of this article is that in C you can define a linked list either like this:
struct list_node {
struct list_node *next;
struct list_node *prev;
char *data; // type erased linked list value
};
Where data
and node
are allocated separately, or:
struct list_node {
struct list_node *next;
struct list_node *prev;
struct Data data; // concrete Data type
};
Since C does not support generics the former definition is easier to use, since one can erase type of data using another layer of indirection. And the latter one does not result in memory fragmentation, but requires defining a unique node type for each "generic instance" of a list.
However an intrusive linked list is defined as:
struct list {
struct list *next;
struct list *prev;
};
Data stores it inline:
typedef struct item {
int val;
struct list items;
} item;
And later one can use pointer offsets to go from pointer to node, to pointer to data.
What I don't understand is what is the difference between intrusive linked list (as defined above) and a linked list, which defines node which stores data inline. It's as if node and data were two boxes, one containing the other. It doesn't matter witch one is the outer, and which one is the inner one. Outer box will always occupy the same amount of space, and getting from one to the other can always be defined as some pointer offset. Is the real usefulness of intrusive linked lists only that they allow C code to have a "generic" implementation of list algorithms?
Does any of this changes when implementation is written in Rust, and not in C? Is there anything more than standard headache when it comes to this variant of lists? I've found quite popular intrusive_collections crate, so there must be something that intrusive lists provide, that cannot be done using std::collections::LinkedList
, is there?