container_of 0.5.1

Porting C's `container_of` macro to Rust
Documentation
  • Coverage
  • 100%
    2 out of 2 items documented1 out of 1 items with examples
  • Size
  • Source code size: 4.17 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.08 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 10s Average build duration of successful builds.
  • all releases: 10s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • sampersand

A Rust port of the C macro container_of.

This macro is used to convert from a pointer to a struct's field to a pointer to the struct itself. Note that the struct should be sized.

Example

#[repr(C)]
struct ListNode<T> {
	prev: Option<Box<ListNode<T>>>,
	next: Option<Box<ListNode<T>>>,
	data: T
}

# fn main() {
let list = ListNode { prev: None, next: None, data: 123 };

// Get a pointer to the `data` from `list`.
let data_ptr = &list.data as *const i32;

// Get the container of `data_ptr`, ie the `ListNode` it was made within.
// SAFETY: `data_ptr` is a valid pointer to the `data` field of a
// `ListNode<i32>`. Additionally, `ListNode<i32>` is sized.
let list_ptr = unsafe {
	container_of::container_of!(data_ptr, ListNode<i32>, data)
};

// The resulting pointer is the same as if you just got it straight
// from the containing structure.
assert_eq!(list_ptr, &list as *const ListNode<i32>);
# }

Safety

The following are needed to ensure soundness:

  • The $type must be a sized struct that is #[repr(C)] (or #[repr(packed)]).
  • The $ptr must be a valid pointer to the $field field of a $type. More concretely, this means that the $ptr must have originated from a valid $type struct.