Implementing a linked list in Rust for an embedded no_std project without heap allocation is quite a challenge because traditional linked lists rely heavily on dynamic memory allocation for node creation. However, there are approaches to achieve similar functionality without dynamic allocation. Here's a strategy and example implementation for a static, stack-based "linked list" (more accurately, a list with linked list-like functionality) suitable for no_std embedded Rust projects:
Approach Overview
Preallocate Nodes: Since you can't dynamically allocate, you'll need to preallocate all possible nodes at compile time. This limits the list's maximum size but ensures safety.
Use a Stack for Node Allocation: Implement a simple stack to manage the preallocated nodes. This allows for efficient "allocation" and "deallocation" of nodes from your pool.
Implement List Logic: With node management in place, implement the actual list logic (insert, remove, traverse, etc.).
Example Implementation
This example demonstrates a basic singly linked list with preallocated nodes managed by a stack. Note that error handling is minimal for brevity.
Cargo.toml (Ensure no_std is specified)
toml
[package]
name = "static_linked_list"
version = "0.1.0"
edition = "2018"
[dependencies]
# For embedded systems, ensure you're targeting appropriately
# and possibly include specific embedded system crates if needed
]
[profile.dev]
panic = "unwind"
[profile.release]
panic = "unwind"
src/lib.rs
rust
#![no_std]
extern crate core;
// Node structure
struct Node<T> {
data: T,
next: Option<*const Node<T>>,
}
// Stack to manage nodes
struct NodeStack<T, const N: usize> {
nodes: [Node<T>; N],
top: usize,
}
impl<T, const N: usize> NodeStack<T, N> {
const fn new() -> Self {
NodeStack {
nodes: [Node {
data: core::marker::PhantomData,
next: None,
}; N],
top: 0,
}
}
// "Allocate" a node
fn alloc(&mut self, data: T) -> Result<*mut Node<T>, &'static str> {
if self.top < N {
let node = &mut self.nodes[self.top];
node.data = data;
node.next = None;
self.top += 1;
return Ok(node as *mut _);
}
Err("Node allocation failed: stack is full.")
}
// "Deallocate" a node (simple, no actual deallocation, just decrement counter)
fn free(&mut self) -> Result<(), &'static str> {
if self.top > 0 {
self.top -= 1;
Ok(())
} else {
Err("Cannot deallocate: stack is empty.")
}
}
}
// The List itself
struct LinkedList<T, const N: usize> {
head: Option<*const Node<T>>,
node_stack: NodeStack<T, N>,
}
impl<T: Copy, const N: usize> LinkedList<T, N> {
const fn new() -> Self {
LinkedList {
head: None,
node_stack: NodeStack::new(),
}
}
// Insert at head
fn insert(&mut self, data: T) -> Result<(), &'static str> {
unsafe {
if let Some(new_node) = self.node_stack.alloc(data).transpose()? {
(*new_node).next = self.head;
self.head = Some(new_node as *const _);
Ok(())
} else {
Err("Insertion failed: unable to allocate node.")
}
}
}
// Remove head
fn remove(&mut self) -> Result<Option<T>, &'static str> {
if let Some(head_ptr) = self.head {
unsafe {
let head_node = &mut *head_ptr;
self.head = (*head_ptr).next;
self.node_stack.free()?;
return Ok(Some(head_node.data));
}
}
Ok(None)
}
}
// Example usage (in a `main.rs` for a quick test, or adapt for your embedded setup)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_linked_list() {
let mut list: LinkedList<i32, 5> = LinkedList::new(); // List of up to 5 elements
assert!(list.insert(10).is_ok());
assert!(list.insert(20).is_ok());
assert_eq!(list.remove().unwrap(), Some(20));
assert_eq!(list.remove().unwrap(), Some(10));
assert_eq!(list.remove().unwrap(), None);
}
#[test]
fn test_overflow() {
let mut list: LinkedList<i32, 2> = LinkedList::new();
assert!(list.insert(10).is_ok());
assert!(list.insert(20).is_ok());
assert!(list.insert(30).is_err()); // Should fail due to overflow
}
}
Notes
Safety: The use of raw pointers (*const T, *mut T) requires careful handling to prevent common errors like dereferencing null or dangling pointers. This implementation uses unsafe blocks to manage these pointers, assuming the user will not misuse the API. Always ensure that the unsafe code is properly validated.
Const Generics: This example utilizes const generics (Rust 1.51+) for specifying the list's maximum size at compile time. If you're using an earlier Rust version, you might need to fall back to less flexible solutions or upgrade your compiler.
Testing: Embedded projects often have unique testing challenges. The provided test is a simple demonstration; adapt it according to your project's testing requirements and environment.
Error Handling: For better reliability, error handling has been enhanced with Result types. This ensures that allocation failures or deallocation issues are explicitly reported, which is crucial in embedded systems where resource management is critical.
Edge Cases: Additional tests cover edge cases, such as stack overflow when inserting more elements than the predefined capacity. This helps ensure the implementation behaves predictably under various scenarios.