### Install Miri with Rustup Source: https://rust-unofficial.github.io/too-many-lists/print This command installs the Miri component for a specific nightly Rust toolchain. Miri requires nightly Rust because it interacts closely with the compiler's internals. The `+nightly-2022-01-21` flag specifies the exact toolchain date, ensuring compatibility, as Miri can sometimes lag behind the latest nightly builds. This is crucial for accurate undefined behavior detection. ```bash __ > rustup +nightly-2022-01-21 component add miri info: syncing channel updates for 'nightly-2022-01-21-x86_64-pc-windows-msvc' info: latest update on 2022-01-21, rust version 1.60.0-nightly (777bb86bc 2022-01-20) info: downloading component 'cargo' info: downloading component 'clippy' info: downloading component 'rust-docs' info: downloading component 'rust-std' info: downloading component 'rustc' info: downloading component 'rustfmt' info: installing component 'cargo' info: installing component 'clippy' info: installing component 'rust-docs' info: installing component 'rust-std' info: installing component 'rustc' info: installing component 'rustfmt' info: downloading component 'miri' info: installing component 'miri' ``` -------------------------------- ### Rust Lifetime Elision Examples Source: https://rust-unofficial.github.io/too-many-lists/second-iter Demonstrates Rust's lifetime elision rules for function signatures. These rules automatically infer lifetimes in common scenarios, reducing the need for explicit annotations. The examples show how single and multiple input references, as well as method signatures, are implicitly handled. ```rust // Only one reference in input, so the output must be derived from that input fn foo(&A) -> &B; // sugar for: fn foo<'a>(&'a A) -> &'a B; // Many inputs, assume they're all independent fn foo(&A, &B, &C); // sugar for: fn foo<'a, 'b, 'c>(&'a A, &'b B, &'c C); // Methods, assume all output lifetimes are derived from `self` fn foo(&self, &B, &C) -> &D; // sugar for: fn foo<'a, 'b, 'c>(&'a self, &'b B, &'c C) -> &'a D; ``` -------------------------------- ### Run Miri Tests with Cargo Source: https://rust-unofficial.github.io/too-many-lists/print This command executes Rust tests using Miri with a specified nightly toolchain. It first prompts to install `xargo`, a tool that helps with building Rust projects, especially those with custom configurations or when targeting specific environments. Subsequently, it prompts to install the `rust-src` component, which provides the source code for Rust's standard library, often needed by tools like Miri for deeper analysis. ```bash __ > cargo +nightly-2022-01-21 miri test I will run "cargo.exe" "install" "xargo" to install a recent enough xargo. Proceed? [Y/n] ``` ```bash __ > y Updating crates.io index Installing xargo v0.3.24 ... Finished release [optimized] target(s) in 10.65s Installing C:\Users\ninte\.cargo\bin\xargo-check.exe Installing C:\Users\ninte\.cargo\bin\xargo.exe Installed package `xargo v0.3.24` (executables `xargo-check.exe`, `xargo.exe`) I will run "rustup" "component" "add" "rust-src" to install the `rust-src` component for the selected toolchain. Proceed? [Y/n] ``` ```bash __ > y info: downloading component 'rust-src' info: installing component 'rust-src' ``` -------------------------------- ### Rust Test Module Setup Source: https://rust-unofficial.github.io/too-many-lists/first-test This snippet demonstrates how to set up a test module in Rust using `mod test` and the `#[test]` attribute for a test function. It's a basic structure for organizing tests within a Rust project. ```rust mod test { #[test] fn basics() { // TODO } } ``` -------------------------------- ### Rust Linked List Instantiation and Printing Source: https://rust-unofficial.github.io/too-many-lists/first-layout Example code demonstrating how to create an instance of the `List` enum using `Box` for heap allocation and then print its debug representation. ```rust fn main() { let list: List = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); println!("{:?}", list); } ``` -------------------------------- ### Basic Test Setup for Rust LinkedList Source: https://rust-unofficial.github.io/too-many-lists/sixth-final Provides helper functions `generate_test` and `list_from` for creating and populating `LinkedList` instances within tests. `generate_test` creates a predefined list, while `list_from` converts a slice into a `LinkedList`. ```rust @cfg(test) mod test { use super::LinkedList; fn generate_test() -> LinkedList { list_from(&[0, 1, 2, 3, 4, 5, 6]) } fn list_from(v: &[T]) -> LinkedList { v.iter().map(|x| (*x).clone()).collect() } #[test] fn test_basic_front() { ``` -------------------------------- ### Rust Mutable Reference Reborrowing Example Source: https://rust-unofficial.github.io/too-many-lists/fifth-stacked-borrows Demonstrates mutable reference reborrowing in Rust. It shows how a mutable reference can be reborrowed, modified through the new reference, and then the original reference can still be used. This code compiles and runs successfully. ```rust #![allow(unused)] fn main() { let mut data = 10; let ref1 = &mut data; let ref2 = &mut *ref1; *ref2 += 2; *ref1 += 1; println!("{}", data); } ``` -------------------------------- ### Rust: Understanding UnsafeCell for Interior Mutability Source: https://rust-unofficial.github.io/too-many-lists/fifth-testing-stacked-borrows Illustrates the fundamental primitive for interior mutability in Rust, `UnsafeCell`. This example shows how `UnsafeCell` opts out of Rust's immutability guarantees for shared references, allowing mutation. It demonstrates the use of `get_mut` to obtain a mutable reference and the potential for undefined behavior if not handled carefully, as shown by Miri's error output. ```rust use std::cell::UnsafeCell; fn opaque_read(val: &i32) { println!("{}", val); } unsafe { let mut data = UnsafeCell::new(10); let mref1 = data.get_mut(); // Get a mutable ref to the contents let ptr2 = mref1 as *mut i32; let sref3 = &*ptr2; *ptr2 += 2; opaque_read(sref3); *mref1 += 1; println!("{}", *data.get()); } ``` -------------------------------- ### Safe Box Pointer Aliasing with Corrected Order in Rust Source: https://rust-unofficial.github.io/too-many-lists/print Presents a corrected version of the Box pointer aliasing example in Rust. By ensuring the raw pointer is used after the mutable reference has been fully utilized and its modifications applied, Miri correctly executes the code, demonstrating the importance of order in stacked borrows. ```rust unsafe { let mut data = Box::new(10); let ptr1 = (&mut *data) as *mut i32; *ptr1 += 1; *data += 10; // Should be 21 println!("{}", data); } ``` -------------------------------- ### Declaring Functions in Rust Source: https://rust-unofficial.github.io/too-many-lists/first-new Illustrates the syntax for declaring a function in Rust. It shows how to define function name, parameters with their types, and the return type. ```rust fn foo(arg1: Type1, arg2: Type2) -> ReturnType { // body } ``` -------------------------------- ### Miri Food Test Case Setup in Rust Source: https://rust-unofficial.github.io/too-many-lists/fifth-extras Initializes a test function named `miri_food` to stress-test the list implementation with Miri. It starts by creating a new list and pushing an element. ```rust #[test] fn miri_food() { let mut list = List::new(); list.push(1); ``` -------------------------------- ### Rust: Unused Attribute Example Source: https://rust-unofficial.github.io/too-many-lists/sixth-panics A basic Rust function demonstrating the `#![allow(unused)]` attribute, which suppresses unused variable warnings. This is often used in examples or when code is conditionally compiled. ```rust #![allow(unused)] fn main() { // Note that we don't need to mess around with `take` anymore // because everything is Copy and there are no dtors that will // run if we mess up... right? :) Riiiight? :))) } ``` -------------------------------- ### Naive Queue Push Implementation (Inefficient) in Rust Source: https://rust-unofficial.github.io/too-many-lists/print Demonstrates a naive approach to implementing a queue's push operation by traversing the entire list to append a new element. This method is inefficient for large lists. ```Rust __ input list: [Some(ptr)] -> (A, Some(ptr)) -> (B, None) flipped push X: [Some(ptr)] -> (A, Some(ptr)) -> (B, Some(ptr)) -> (X, None) ``` -------------------------------- ### Rust Cargo Build Command Source: https://rust-unofficial.github.io/too-many-lists/print Demonstrates the basic command to compile a Rust project using Cargo. This command builds the executable and any associated libraries, preparing the project for testing or deployment. ```bash __ cargo build ``` -------------------------------- ### Rust Mutable Iterator Example Source: https://rust-unofficial.github.io/too-many-lists/sixth-cursors-intro Demonstrates the usage of `iter_mut()` on a mutable list in Rust. This example highlights how mutable references can be obtained and compared, illustrating a scenario where iterator flexibility is beneficial. ```rust let mut list = ...; let iter = list.iter_mut(); let elem1 = list.next(); let elem2 = list.next(); if elem1 == elem2 { ... } ``` -------------------------------- ### Rust Cargo Build Command Source: https://rust-unofficial.github.io/too-many-lists/fourth-breaking Demonstrates the command used to build a Rust project. This command compiles the source code and links it into an executable or library, preparing it for execution or distribution. ```bash __ cargo build ``` ``` -------------------------------- ### Rust Example Usage of Iter Source: https://rust-unofficial.github.io/too-many-lists/second-iter-mut Provides a practical example of using the 'Iter' iterator to traverse a list and access its elements via shared references. This showcases the typical usage pattern for immutable iteration. ```Rust let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut iter = list.iter(); let x = iter.next().unwrap(); let y = iter.next().unwrap(); let z = iter.next().unwrap(); ``` -------------------------------- ### Rust Doubly Linked List: Basic and Peek Tests Source: https://rust-unofficial.github.io/too-many-lists/print Contains comprehensive unit tests for a Rust doubly linked list implementation. The `basics` test covers `push_front`, `pop_front`, `push_back`, and `pop_back` operations, verifying correct behavior for empty lists, populated lists, and list exhaustion. The `peek` test validates the `peek_front`, `peek_back`, `peek_front_mut`, and `peek_back_mut` methods. ```rust #[test] fn basics() { let mut list = List::new(); // Check empty list behaves right assert_eq!(list.pop_front(), None); // Populate list list.push_front(1); list.push_front(2); list.push_front(3); // Check normal removal assert_eq!(list.pop_front(), Some(3)); assert_eq!(list.pop_front(), Some(2)); // Push some more just to make sure nothing's corrupted list.push_front(4); list.push_front(5); // Check normal removal assert_eq!(list.pop_front(), Some(5)); assert_eq!(list.pop_front(), Some(4)); // Check exhaustion assert_eq!(list.pop_front(), Some(1)); assert_eq!(list.pop_front(), None); // ---- back ----- // Check empty list behaves right assert_eq!(list.pop_back(), None); // Populate list list.push_back(1); list.push_back(2); list.push_back(3); // Check normal removal assert_eq!(list.pop_back(), Some(3)); assert_eq!(list.pop_back(), Some(2)); // Push some more just to make sure nothing's corrupted list.push_back(4); list.push_back(5); // Check normal removal assert_eq!(list.pop_back(), Some(5)); assert_eq!(list.pop_back(), Some(4)); // Check exhaustion assert_eq!(list.pop_back(), Some(1)); assert_eq!(list.pop_back(), None); } #[test] fn peek() { let mut list = List::new(); assert!(list.peek_front().is_none()); assert!(list.peek_back().is_none()); assert!(list.peek_front_mut().is_none()); assert!(list.peek_back_mut().is_none()); list.push_front(1); list.push_front(2); list.push_front(3); assert_eq!(&*list.peek_front().unwrap(), &3); assert_eq!(&mut *list.peek_front_mut().unwrap(), &mut 3); assert_eq!(&*list.peek_back().unwrap(), &1); assert_eq!(&mut *list.peek_back_mut().unwrap(), &mut 1); } ``` -------------------------------- ### Rust Cargo Test Output Source: https://rust-unofficial.github.io/too-many-lists/print Example output from running 'cargo test' in a Rust project, showing that tests, including the 'into_iter' test, have passed successfully. ```text > cargo test Running target/debug/lists-5c71138492ad4b4a running 4 tests test first::test::basics ... ok test second::test::basics ... ok test second::test::into_iter ... ok test second::test::peek ... ok test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured ``` -------------------------------- ### Rust List Manipulation and Testing Source: https://rust-unofficial.github.io/too-many-lists/print Demonstrates basic operations on a Rust list, including pushing elements to the front, popping elements from the front, and verifying the list's length after each operation. It covers cases for empty lists, single-item lists, and multiple-item lists. ```Rust // Try to break a one item list list.push_front(10); assert_eq!(list.len(), 1); assert_eq!(list.pop_front(), Some(10)); assert_eq!(list.len(), 0); assert_eq!(list.pop_front(), None); assert_eq!(list.len(), 0); // Mess around list.push_front(10); assert_eq!(list.len(), 1); list.push_front(20); assert_eq!(list.len(), 2); list.push_front(30); assert_eq!(list.len(), 3); assert_eq!(list.pop_front(), Some(30)); assert_eq!(list.len(), 2); list.push_front(40); assert_eq!(list.len(), 3); assert_eq!(list.pop_front(), Some(40)); assert_eq!(list.len(), 2); assert_eq!(list.pop_front(), Some(20)); assert_eq!(list.len(), 1); assert_eq!(list.pop_front(), Some(10)); assert_eq!(list.len(), 0); assert_eq!(list.pop_front(), None); assert_eq!(list.len(), 0); assert_eq!(list.pop_front(), None); assert_eq!(list.len(), 0); } } } ``` ``` -------------------------------- ### Initialize CursorMut for LinkedList in Rust Source: https://rust-unofficial.github.io/too-many-lists/print Implements the `cursor_mut` method for the `LinkedList` struct. This method creates and returns a new `CursorMut` instance, initializing it to point to the 'ghost' element (None) at the start of the list. ```rust impl LinkedList { pub fn cursor_mut(&mut self) -> CursorMut { CursorMut { list: self, cur: None, index: None, } } } ``` -------------------------------- ### Basic Linked List Tests (Rust) Source: https://rust-unofficial.github.io/too-many-lists/print A basic test suite for the linked list implementation, covering `pop_front` and `push_front` operations. This test verifies the core functionality after the `pop_front` method has been successfully implemented. ```rust #[cfg(test)] mod test { use super::List; #[test] fn basics() { let mut list = List::new(); // Check empty list behaves right assert_eq!(list.pop_front(), None); // Populate list list.push_front(1); list.push_front(2); list.push_front(3); // Check normal removal assert_eq!(list.pop_front(), Some(3)); assert_eq!(list.pop_front(), Some(2)); // Push some more just to make sure nothing's corrupted list.push_front(4); list.push_front(5); ``` -------------------------------- ### Rust Function to Accept Two Values of Same Type Source: https://rust-unofficial.github.io/too-many-lists/print A generic Rust function `take_two` that accepts two arguments of the same generic type `T`. This function serves as a basic example to illustrate type and lifetime interactions in Rust. ```rust #![allow(unused)] fn main() { fn take_two(_val1: T, _val2: T) { } } ``` -------------------------------- ### Rust Mutable Reference Reborrowing with Interleaved Uses Source: https://rust-unofficial.github.io/too-many-lists/fifth-stacked-borrows Illustrates a scenario where interleaved uses of mutable references after reborrowing lead to a Rust compiler error. This example highlights the importance of nested usage for mutable references. ```rust let mut data = 10; let ref1 = &mut data; let ref2 = &mut *ref1; // ORDER SWAPPED! *ref1 += 1; *ref2 += 2; println!("{}", data); ``` -------------------------------- ### Build Project with Cargo Source: https://rust-unofficial.github.io/too-many-lists/fourth-peek This command compiles the Rust project using Cargo, the Rust build system and package manager. It ensures all dependencies are met and produces an executable artifact in the target directory. ```bash cargo build ``` -------------------------------- ### Get Back Element Reference in Doubly Linked List (Rust) Source: https://rust-unofficial.github.io/too-many-lists/sixth-random-bits Returns an immutable reference to the element at the back of the list without removing it. Uses `unsafe` for pointer dereferencing. Returns `None` if the list is empty. ```Rust pub fn back(&self) -> Option<&T> { unsafe { self.back.map(|node| &(*node.as_ptr()).elem) } } ``` -------------------------------- ### Linked List Basic and Peek Tests in Rust Source: https://rust-unofficial.github.io/too-many-lists/fourth-symmetry Provides comprehensive unit tests for a Rust linked list implementation. It covers basic operations like `push_front`, `pop_front`, `push_back`, `pop_back`, and peeking operations (`peek_front`, `peek_back`, `peek_front_mut`, `peek_back_mut`) to ensure the list functions correctly under various scenarios, including empty lists and full exhaustion. ```rust #[test] fn basics() { let mut list = List::new(); // Check empty list behaves right assert_eq!(list.pop_front(), None); // Populate list list.push_front(1); list.push_front(2); list.push_front(3); // Check normal removal assert_eq!(list.pop_front(), Some(3)); assert_eq!(list.pop_front(), Some(2)); // Push some more just to make sure nothing's corrupted list.push_front(4); list.push_front(5); // Check normal removal assert_eq!(list.pop_front(), Some(5)); assert_eq!(list.pop_front(), Some(4)); // Check exhaustion assert_eq!(list.pop_front(), Some(1)); assert_eq!(list.pop_front(), None); // ---- back ----- // Check empty list behaves right assert_eq!(list.pop_back(), None); // Populate list list.push_back(1); list.push_back(2); list.push_back(3); // Check normal removal assert_eq!(list.pop_back(), Some(3)); assert_eq!(list.pop_back(), Some(2)); // Push some more just to make sure nothing's corrupted list.push_back(4); list.push_back(5); // Check normal removal assert_eq!(list.pop_back(), Some(5)); assert_eq!(list.pop_back(), Some(4)); // Check exhaustion assert_eq!(list.pop_back(), Some(1)); assert_eq!(list.pop_back(), None); } #[test] fn peek() { let mut list = List::new(); assert!(list.peek_front().is_none()); assert!(list.peek_back().is_none()); assert!(list.peek_front_mut().is_none()); assert!(list.peek_back_mut().is_none()); list.push_front(1); list.push_front(2); list.push_front(3); assert_eq!(&*list.peek_front().unwrap(), &3); assert_eq!(&mut *list.peek_front_mut().unwrap(), &mut 3); assert_eq!(&*list.peek_back().unwrap(), &1); assert_eq!(&mut *list.peek_back_mut().unwrap(), &mut 1); } ``` -------------------------------- ### Rust LinkedList Iterator Element Access Source: https://rust-unofficial.github.io/too-many-lists/print Provides methods to get a mutable reference to the current element, or peek at the next or previous elements without advancing the iterator. These methods use unsafe blocks to dereference raw pointers to list nodes. ```Rust pub fn current(&mut self) -> Option<&mut T> { unsafe { self.cur.map(|node| &mut (*node.as_ptr()).elem) } } pub fn peek_next(&mut self) -> Option<&mut T> { unsafe { self.cur .and_then(|node| (*node.as_ptr()).back) .map(|node| &mut (*node.as_ptr()).elem) } } pub fn peek_prev(&mut self) -> Option<&mut T> { unsafe { self.cur .and_then(|node| (*node.as_ptr()).front) .map(|node| &mut (*node.as_ptr()).elem) } } ``` -------------------------------- ### Alternative Memory Layout Visualization Source: https://rust-unofficial.github.io/too-many-lists/print An alternative memory layout visualization for a linked list, showing unconditional heap allocation of nodes and the absence of 'junk' data. ```text [ptr] -> (Elem A, ptr) -> (Elem B, *null*) ``` -------------------------------- ### CursorMut: Get Index (Rust) Source: https://rust-unofficial.github.io/too-many-lists/sixth-cursors-impl Provides a method to retrieve the current index of the cursor within the linked list. Returns `Some(usize)` if the cursor is on a valid element and has an associated index, otherwise returns `None`. ```rust impl<'a, T> CursorMut<'a, T> { pub fn index(&self) -> Option { self.index } ``` -------------------------------- ### Rust List Manipulation: Push, Pop, Peek, and Iteration Source: https://rust-unofficial.github.io/too-many-lists/print Demonstrates basic list operations in Rust, including adding elements with `push`, removing elements with `pop`, viewing the top element with `peek`, modifying elements with `peek_mut`, and iterating through the list with `iter` and `iter_mut`. This code assumes a custom list implementation. ```rust let mut list = TooManyLists::new(); list.push(1); list.push(2); list.push(3); assert!(list.pop() == Some(3)); list.push(4); assert!(list.pop() == Some(4)); list.push(5); assert!(list.peek() == Some(&3)); list.push(6); list.peek_mut().map(|x| *x *= 10); assert!(list.peek() == Some(&30)); assert!(list.pop() == Some(30)); for elem in list.iter_mut() { *elem *= 100; } let mut iter = list.iter(); assert_eq!(iter.next(), Some(&100)); assert_eq!(iter.next(), Some(&200)); assert_eq!(iter.next(), Some(&500)); assert_eq!(iter.next(), Some(&600)); assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); assert!(list.pop() == Some(100)); list.peek_mut().map(|x| *x *= 10); assert!(list.peek() == Some(&2000)); list.push(7); // Drop it on the ground and let the dtor exercise itself } ``` -------------------------------- ### Constructing a New List Instance in Rust Source: https://rust-unofficial.github.io/too-many-lists/first-new Shows how to create a constructor function for a `List` type in Rust using an `impl` block and a static method `new()`. It initializes the list with an `Empty` head. ```rust impl List { pub fn new() -> Self { List { head: Link::Empty } } } ``` -------------------------------- ### Get Mutable Back Element Reference in Doubly Linked List (Rust) Source: https://rust-unofficial.github.io/too-many-lists/sixth-random-bits Returns a mutable reference to the element at the back of the list without removing it. Uses `unsafe` for pointer dereferencing. Returns `None` if the list is empty. ```Rust pub fn back_mut(&mut self) -> Option<&mut T> { unsafe { self.back.map(|node| &mut (*node.as_ptr()).elem) } } ``` -------------------------------- ### Get Mutable Front Element Reference in Doubly Linked List (Rust) Source: https://rust-unofficial.github.io/too-many-lists/sixth-random-bits Returns a mutable reference to the element at the front of the list without removing it. Uses `unsafe` for pointer dereferencing. Returns `None` if the list is empty. ```Rust pub fn front_mut(&mut self) -> Option<&mut T> { unsafe { self.front.map(|node| &mut (*node.as_ptr()).elem) } } ``` -------------------------------- ### Get Length of LinkedList in Rust Source: https://rust-unofficial.github.io/too-many-lists/sixth-basics Returns the current number of elements in the linked list. This is a simple getter method that returns the value of the `len` field, providing an efficient way to check the list's size. ```rust pub fn len(&self) -> usize { self.len } ``` -------------------------------- ### Naive Queue Pop Implementation (Inefficient) in Rust Source: https://rust-unofficial.github.io/too-many-lists/print Illustrates a naive approach to implementing a queue's pop operation by traversing the list to find the second-to-last node. This method is also inefficient. ```Rust __ input list: [Some(ptr)] -> (A, Some(ptr)) -> (B, Some(ptr)) -> (X, None) flipped pop: [Some(ptr)] -> (A, Some(ptr)) -> (B, None) ``` -------------------------------- ### Naive Queue Push Operation (Moving Push to End) Source: https://rust-unofficial.github.io/too-many-lists/fifth-layout Demonstrates a naive approach to implementing a queue by moving the push operation to the end of the list. This involves traversing the entire list, leading to suboptimal performance. ```Rust input list: [Some(ptr)] -> (A, Some(ptr)) -> (B, None) flipped push X: [Some(ptr)] -> (A, Some(ptr)) -> (B, Some(ptr)) -> (X, None) ``` -------------------------------- ### Rust Pop Function Logic Initialization Source: https://rust-unofficial.github.io/too-many-lists/first-pop Initializes the `pop` function's logic by declaring a `result` variable and starting a `match` statement to handle the `Link::Empty` case by assigning `None` to `result`. ```rust pub fn pop(&mut self) -> Option { let result; match &self.head { Link::Empty => { result = None; } Link::More(node) => { ``` -------------------------------- ### Rust Enum with Null Pointer Optimization Example Source: https://rust-unofficial.github.io/too-many-lists/first-layout Demonstrates the null pointer optimization in Rust enums. If one variant contains a non-null pointer, the tag for that variant can be omitted, as the presence of the pointer itself signifies the variant. This saves space. ```rust __ enum Foo { A, B(ContainsANonNullPtr), } ``` -------------------------------- ### Rust: Basic doubly linked list test suite Source: https://rust-unofficial.github.io/too-many-lists/fourth-breaking A basic test suite for the doubly linked list implementation in Rust. It verifies the functionality of `pop_front` and `push_front` by creating a list, adding elements, and removing them, checking for correct behavior on both populated and empty lists. ```rust #[cfg(test)] mod test { use super::List; #[test] fn basics() { let mut list = List::new(); // Check empty list behaves right assert_eq!(list.pop_front(), None); // Populate list list.push_front(1); list.push_front(2); list.push_front(3); // Check normal removal assert_eq!(list.pop_front(), Some(3)); assert_eq!(list.pop_front(), Some(2)); // Push some more just to make sure nothing's corrupted list.push_front(4); list.push_front(5); } } ``` -------------------------------- ### Rust Linked List Basic Test Cases Source: https://rust-unofficial.github.io/too-many-lists/fifth-layout Provides basic unit tests for a Rust linked list implementation. It verifies the behavior of `pop` on an empty list and the sequence of `push` and `pop` operations for a populated list. ```rust #[cfg(test)] mod test { use super::List; #[test] fn basics() { let mut list = List::new(); // Check empty list behaves right assert_eq!(list.pop(), None); // Populate list list.push(1); list.push(2); list.push(3); // Check normal removal ``` -------------------------------- ### Initialize Mutable Cursor for Rust LinkedList Source: https://rust-unofficial.github.io/too-many-lists/sixth-cursors-impl Provides the `cursor_mut` method for the LinkedList, which creates and returns a new mutable cursor. The cursor is initialized to point to the 'ghost' element (None) and has no index, representing the start or end of the list. ```rust impl LinkedList { pub fn cursor_mut(&mut self) -> CursorMut { CursorMut { list: self, cur: None, index: None, } } } ``` -------------------------------- ### Final peek_front Implementation using Ref::map (Rust) Source: https://rust-unofficial.github.io/too-many-lists/print The refined peek_front implementation that successfully returns an Option> by using the map function on the Ref returned by node.borrow(). This correctly handles the lifetime and borrowing requirements. ```rust pub fn peek_front(&self) -> Option> { self.head.as_ref().map(|node| { ``` -------------------------------- ### Rust Test Failure Due to Incorrect Lifetime Handling Source: https://rust-unofficial.github.io/too-many-lists/print Demonstrates a scenario where a `compile_fail` test fails because the code, despite compiling successfully, does not exhibit the expected compilation failure. This indicates an issue with the test setup or the code's actual behavior regarding lifetimes. ```rust cargo test ... Doc-tests linked-list running 1 test test src\\lib.rs - assert_properties::iter_mut_invariant (line 458) - compile fail ... FAILED failures: ---- src\\lib.rs - assert_properties::iter_mut_invariant (line 458) stdout ---- Test compiled successfully, but it's marked `compile_fail`. failures: src\\lib.rs - assert_properties::iter_mut_invariant (line 458) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.15s ``` -------------------------------- ### Rust Cargo Test Execution and Results Source: https://rust-unofficial.github.io/too-many-lists/fourth-breaking Shows the command to run tests for the Rust project and the typical output indicating the number of tests passed, failed, ignored, and measured. This is a standard part of the Rust development workflow. ```bash __ cargo test Running target/debug/lists-5c71138492ad4b4a running 9 tests test first::test::basics ... ok test fourth::test::basics ... ok test second::test::iter_mut ... ok test second::test::basics ... ok test fifth::test::iter_mut ... ok test third::test::basics ... ok test second::test::iter ... ok test third::test::iter ... ok test second::test::into_iter ... ok test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured ``` ``` -------------------------------- ### Box Pointer Aliasing Undefined Behavior in Rust Source: https://rust-unofficial.github.io/too-many-lists/print Illustrates a scenario with Box where aliasing mutable references and raw pointers leads to undefined behavior according to Miri. The example attempts to modify the Box through both a mutable reference and a raw pointer derived from it, causing Miri to report an error. ```rust unsafe { let mut data = Box::new(10); let ptr1 = (&mut *data) as *mut i32; *data += 10; *ptr1 += 1; // Should be 21 println!("{}", data); } ```