### Struct Alignment and Padding Example (Rust) Source: https://doc.rust-lang.org/stable/nomicon/repr-rust Demonstrates how Rust inserts padding into structs to ensure proper alignment of fields and that the overall struct size is a multiple of its alignment. This example shows an initial struct and then its potential padded representation. ```Rust #![allow(unused)] fn main() { struct A { a: u8, b: u32, c: u16, } } ``` ```Rust #![allow(unused)] fn main() { struct A { a: u8, _pad1: [u8; 3], // to align `b` b: u32, c: u16, _pad2: [u8; 2], // to make overall size multiple of 4 } } ``` ```Rust #![allow(unused)] fn main() { struct A { b: u32, c: u16, a: u8, _pad: u8, } } ``` -------------------------------- ### Compiler Optimization Example in Rust/Pseudocode Source: https://doc.rust-lang.org/stable/nomicon/atomics Demonstrates how a compiler might optimize sequential assignments, potentially reordering or eliminating operations. This optimization is unobservable in single-threaded contexts but can cause issues in multi-threaded scenarios where order matters. The example shows a sequence of assignments and a possible optimized version. ```rust x = 1; y = 3; x = 2; ``` ```rust x = 2; y = 3; ``` -------------------------------- ### Call Rust Function from C Source: https://doc.rust-lang.org/stable/nomicon/print Provides an example C program that links against a Rust dynamic library and calls an exported Rust function. It shows the necessary C headers, linking flags (`-l` and `-L`), and runtime library path configuration (`LD_LIBRARY_PATH`). ```C extern void hello_from_rust(); int main(void) { hello_from_rust(); return 0; } ``` ```Shell gcc call_rust.c -o call_rust -lrust_from_c -L./target/debug LD_LIBRARY_PATH=./target/debug ./call_rust ``` -------------------------------- ### C Side of Nullable Function Pointer FFI Source: https://doc.rust-lang.org/stable/nomicon/ffi Illustrates the C-side counterpart to the Rust FFI example, showing how a nullable function pointer is declared and used in C. ```C __ void register(int (*f)(int (*)(int), int)) { ... } ``` -------------------------------- ### Rust Lifetimes: Basic Scope Example Source: https://doc.rust-lang.org/stable/nomicon/lifetimes Demonstrates a simple Rust code snippet and its desugared representation with explicit lifetimes, showcasing how Rust infers minimal lifetimes for references within nested scopes. ```rust #![allow(unused)] fn main() { let x = 0; let y = &x; let z = &y; } ``` ```rust // NOTE: `'a: {` and `&'b x` is not valid syntax! 'a: { let x: i32 = 0; 'b: { // lifetime used is 'b because that's good enough. let y: &'b i32 = &'b x; 'c: { // ditto on 'c let z: &'c &'b i32 = &'c y; // "a reference to a reference to an i32" (with lifetimes annotated) } } } ``` -------------------------------- ### Multi-threaded Memory Ordering Example in Rust/Pseudocode Source: https://doc.rust-lang.org/stable/nomicon/atomics Illustrates a common concurrency problem where hardware memory hierarchies can lead to unexpected program states. This example shows two threads interacting, with thread 2 checking a condition based on a variable modified by thread 1. The potential for race conditions and non-deterministic outcomes due to memory ordering is highlighted, showing ideal versus a problematic third state enabled by weak ordering. ```rust initial state: x = 0, y = 1 THREAD 1 THREAD 2 y = 3; if x == 1 { x = 1; y *= 2; } ``` -------------------------------- ### Struct Field Reordering for Space Optimization (Rust) Source: https://doc.rust-lang.org/stable/nomicon/print Demonstrates how Rust might reorder fields in generic monomorphizations to optimize space. This example shows `Foo` and `Foo` with different field orderings and padding to minimize wasted space. ```Rust struct Foo { count: u16, data1: u16, data2: u32, } struct Foo { count: u16, _pad1: u16, data1: u32, data2: u16, _pad2: u16, } ``` -------------------------------- ### Rust Nullable Function Pointer with C FFI Source: https://doc.rust-lang.org/stable/nomicon/print Demonstrates how to represent a nullable C function pointer in Rust using Option. This example shows registering a callback function that might be null, and how the Rust function handles the `None` case by providing a default behavior. ```rust use libc::c_int; #[cfg(hidden)] unsafe extern "C" { /// Registers the callback. fn register(cb: Option c_int>, c_int) -> c_int>); } unsafe fn register(_: Option c_int>, c_int) -> c_int>) {} /// This fairly useless function receives a function pointer and an integer /// from C, and returns the result of calling the function with the integer. /// In case no function is provided, it squares the integer by default. extern "C" fn apply(process: Option c_int>, int: c_int) -> c_int { match process { Some(f) => f(int), None => int * int } } fn main() { unsafe { register(Some(apply)); } } ``` ```c void register(int (*f)(int (*)(int), int)) { ... } ``` -------------------------------- ### Pointer Aliasing Example in Code Source: https://doc.rust-lang.org/stable/nomicon/print Illustrates a scenario where pointer aliasing can affect code execution and optimization. It shows two pointer dereferences and explains how aliasing analysis by the compiler is crucial for parallel execution. ```pseudocode *x *= 7; *y *= 3; ``` -------------------------------- ### Rust Callback to C Source: https://doc.rust-lang.org/stable/nomicon/print Illustrates how to pass a Rust function pointer to a C library to be used as a callback. The Rust function must be marked `extern` with a compatible calling convention. The example includes Rust code to register and trigger the callback, and corresponding C code to receive and invoke it. ```Rust extern fn callback(a: i32) { println!("I'm called from C with value {0}", a); } #[link(name = "extlib")] unsafe extern { fn register_callback(cb: extern fn(i32)) -> i32; fn trigger_callback(); } fn main() { unsafe { register_callback(callback); trigger_callback(); // Triggers the callback. } } ``` ```C typedef void (*rust_callback)(int32_t); rust_callback cb; int32_t register_callback(rust_callback callback) { cb = callback; return 1; } void trigger_callback() { cb(7); // Will call callback(7) in Rust. } ``` -------------------------------- ### Linking to Native Libraries in Rust Source: https://doc.rust-lang.org/stable/nomicon/ffi Demonstrates how to use the `#[link]` attribute to instruct the Rust compiler on linking to native libraries. It covers different link kinds like dynamic, static, and framework, and provides examples for build dependencies and common system libraries. ```rust #[link(name = "foo")] #[link(name = "foo", kind = "bar")] #[link(name = "readline")] #[link(name = "my_build_dependency", kind = "static")] #[link(name = "CoreFoundation", kind = "framework")] ``` -------------------------------- ### Struct Definition Example (Rust) Source: https://doc.rust-lang.org/stable/nomicon/print A basic Rust struct definition for `A` with fields `a` of type `u8`, `b` of type `u32`, and `c` of type `u16`. This is used to illustrate padding and alignment concepts. ```Rust #![allow(unused)] fn main() { struct A { a: u8, b: u32, c: u16, } } ``` -------------------------------- ### Declare Multiple Snappy Functions in Rust Source: https://doc.rust-lang.org/stable/nomicon/print This Rust code snippet shows how to declare multiple foreign functions from the `snappy` library using an `extern` block. It includes functions for compression, uncompression, getting max compressed length, getting uncompressed length, and validating compressed buffers. The `libc` crate is used for C types like `c_int` and `size_t`. ```rust use libc::{c_int, size_t}; #[link(name = "snappy")] unsafe extern "C" { fn snappy_compress(input: *const u8, input_length: size_t, compressed: *mut u8, compressed_length: *mut size_t) -> c_int; fn snappy_uncompress(compressed: *const u8, compressed_length: size_t, uncompressed: *mut u8, uncompressed_length: *mut size_t) -> c_int; fn snappy_max_compressed_length(source_length: size_t) -> size_t; fn snappy_uncompressed_length(compressed: *const u8, compressed_length: size_t, result: *mut size_t) -> c_int; fn snappy_validate_compressed_buffer(compressed: *const u8, compressed_length: size_t) -> c_int; } fn main() {} ``` -------------------------------- ### Rust: Static Drop Semantics with Branched Code Source: https://doc.rust-lang.org/stable/nomicon/drop-flags Shows an example of static drop semantics in branched Rust code. When all branches handle initialization and dropping consistently, the compiler can determine the drop state statically. ```rust #![allow(unused)] fn main() { let condition = true; let mut x = Box::new(0); // x was uninit; just overwrite. if condition { drop(x) // x gets moved out; make x uninit. } else { println!("{}", x); drop(x) // x gets moved out; make x uninit. } x = Box::new(0); // x was uninit; just overwrite. // x goes out of scope; x was init; Drop x! } ``` -------------------------------- ### Desugared Rust Code with Explicit Lifetimes Source: https://doc.rust-lang.org/stable/nomicon/print This example shows a desugared version of the previous Rust code, explicitly annotating lifetimes. This illustrates how Rust's borrow checker analyzes scopes and reference validity, though the syntax is not directly usable. ```rust // NOTE: `'a: {` and `&'b x` is not valid syntax! 'a: { let x: i32 = 0; 'b: { // lifetime used is 'b because that's good enough. let y: &'b i32 = &'b x; 'c: { // ditto on 'c let z: &'c &'b i32 = &'c y; // "a reference to a reference to an i32" (with lifetimes annotated) } } } ``` -------------------------------- ### Struct with Padding for Alignment (Rust) Source: https://doc.rust-lang.org/stable/nomicon/print Illustrates how Rust inserts padding into a struct to ensure fields are properly aligned and the overall struct size is a multiple of its alignment. This example shows a struct `A` with a `u8`, `u32`, and `u16`, and demonstrates how padding is added to align `b` and ensure the total size is a multiple of 4. ```Rust #![allow(unused)] fn main() { struct A { a: u8, _pad1: [u8; 3], // to align `b` b: u32, c: u16, _pad2: [u8; 2], // to make overall size multiple of 4 } } ``` -------------------------------- ### Elided vs. Expanded Lifetime Signatures in Rust Functions Source: https://doc.rust-lang.org/stable/nomicon/lifetime-elision Demonstrates how Rust's lifetime elision rules simplify function signatures. The examples show 'elided' signatures where lifetimes are omitted, and their 'expanded' counterparts where lifetimes are explicitly declared. ```rust fn print(s: &str); // elided fn print<'a>(s: &'a str); // expanded ``` ```rust fn debug(lvl: usize, s: &str); // elided fn debug<'a>(lvl: usize, s: &'a str); // expanded ``` ```rust fn substr(s: &str, until: usize) -> &str; // elided fn substr<'a>(s: &'a str, until: usize) -> &'a str; // expanded ``` ```rust fn get_str() -> &str; // ILLEGAL ``` ```rust fn frob(s: &str, t: &str) -> &str; // ILLEGAL ``` ```rust fn get_mut(&mut self) -> &mut T; // elided fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded ``` ```rust fn args(&mut self, args: &[T]) -> &mut Command // elided fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded ``` ```rust fn new(buf: &mut [u8]) -> BufWriter; // elided fn new(buf: &mut [u8]) -> BufWriter<'_>; // elided (with `rust_2018_idioms`) fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a> // expanded ``` -------------------------------- ### Rust Function Pointer Contravariance Example Source: https://doc.rust-lang.org/stable/nomicon/subtyping Explains and demonstrates why function types are contravariant over their arguments. It shows that a function expecting a `&'static str` cannot accept a `&'a str` (where `'a` is shorter than `'static`), but a function expecting `&'a str` can accept `&'static str`. ```Rust use std::cell::RefCell; thread_local! { pub static StaticVecs: RefCell> = RefCell::new(Vec::new()); } /// saves the input given into a thread local `Vec<&'static str>` fn store(input: &'static str) { StaticVecs.with_borrow_mut(|v| v.push(input)); } /// Calls the function with it's input (must have the same lifetime!) fn demo<'a>(input: &'a str, f: fn(&'a str)) { f(input); } fn main() { demo("hello", store); // "hello" is 'static. Can call `store` fine { let smuggle = String::from("smuggle"); // `&smuggle` is not static. If we were to call `store` with `&smuggle`, // we would have pushed an invalid lifetime into the `StaticVecs`. // Therefore, `fn(&'static str)` cannot be a subtype of `fn(&'a str)` demo(&smuggle, store); } // use after free 😿 StaticVecs.with_borrow(|v| println!("{v:?}")); } ``` -------------------------------- ### Rust: Delayed Initialization with Conditional Assignment Source: https://doc.rust-lang.org/stable/nomicon/checked-uninit Illustrates Rust's ability to handle delayed initialization when every possible code path assigns a value. This example shows a variable initialized within an if-else block, ensuring it's always assigned before use. ```rust fn main() { let x: i32; if true { x = 1; } else { x = 2; } println!("{}", x); } ``` -------------------------------- ### Implement Rust Callback Interface in C Source: https://doc.rust-lang.org/stable/nomicon/ffi This C code provides the `register_callback` and `trigger_callback` functions for the Rust example. It stores the Rust callback function pointer and invokes it when `trigger_callback` is called, demonstrating a C-to-Rust callback mechanism. ```c typedef void (*rust_callback)(int32_t); rust_callback cb; int32_t register_callback(rust_callback callback) { cb = callback; return 1; } void trigger_callback() { cb(7); // Will call callback(7) in Rust. } ``` -------------------------------- ### Rust: Desugared Example of Borrow Conflict Source: https://doc.rust-lang.org/stable/nomicon/print Shows the desugared version of the code that causes the mutable and immutable borrow conflict. This highlights how the lifetime system assigns explicit lifetimes (`'c`, `'d`) that lead to the alias analysis failure. ```rust struct Foo; impl Foo { fn mutate_and_share<'a>(&'a mut self) -> &'a Self { &'a *self } fn share<'a>(&'a self) {} } fn main() { 'b: { let mut foo: Foo = Foo; 'c: { let loan: &'c Foo = Foo::mutate_and_share::<'c>(&'c mut foo); 'd: { Foo::share::<'d>(&'d foo); } println!("{:?}", loan); } } } ``` -------------------------------- ### Rust Scoped Thread Usage Example Source: https://doc.rust-lang.org/stable/nomicon/leaking Demonstrates the typical usage of `thread::scoped` to modify data in a parent thread from a child thread. It shows how `JoinGuard` instances are collected and how their collective dropping ensures threads join before borrowed data is deallocated. ```rust let mut data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; { let mut guards = vec![]; for x in &mut data { // Move the mutable reference into the closure, and execute // it on a different thread. The closure has a lifetime bound // by the lifetime of the mutable reference `x` we store in it. // The guard that is returned is in turn assigned the lifetime // of the closure, so it also mutably borrows `data` as `x` did. // This means we cannot access `data` until the guard goes away. let guard = thread::scoped(move || { *x *= 2; }); // store the thread's guard for later guards.push(guard); } // All guards are dropped here, forcing the threads to join // (this thread blocks here until the others terminate). // Once the threads join, the borrow expires and the data becomes // accessible again in this thread. } // data is definitely mutated here. ``` -------------------------------- ### Rust Contravariant Function Example with `thread_local` Source: https://doc.rust-lang.org/stable/nomicon/print Demonstrates contravariance of function arguments using a `thread_local` static mutable vector. The `store` function expects `&'static str`, and the `demo` function correctly prevents passing a non-static reference that would lead to a use-after-free. ```rust use std::cell::RefCell; thread_local! { pub static StaticVecs: RefCell> = RefCell::new(Vec::new()); } /// saves the input given into a thread local `Vec<&'static str>` fn store(input: &'static str) { StaticVecs.with_borrow_mut(|v| v.push(input)); } /// Calls the function with it's input (must have the same lifetime!) fn demo<'a>(input: &'a str, f: fn(&'a str)) { f(input); } fn main() { demo("hello", store); // "hello" is 'static. Can call `store` fine { let smuggle = String::from("smuggle"); // `&smuggle` is not static. If we were to call `store` with `&smuggle`, // we would have pushed an invalid lifetime into the `StaticVecs`. // Therefore, `fn(&'static str)` cannot be a subtype of `fn(&'a str)` demo(&smuggle, store); } // use after free 😿 StaticVecs.with_borrow(|v| println!("{v:?}")); } ``` -------------------------------- ### Method Lookup Algorithm Example: Array Indexing Source: https://doc.rust-lang.org/stable/nomicon/dot-operator Demonstrates the method lookup algorithm when accessing an element of an array behind multiple indirections (Rc, Box). It shows how the compiler uses the Index trait and resolves through dereferencing and unsizing to find the correct `index` implementation. ```rust #![allow(unused)] fn main() { let array: Rc> = ...; let first_entry = array[0]; } ``` -------------------------------- ### Compile Rust as a Dynamic Library for C Source: https://doc.rust-lang.org/stable/nomicon/print Demonstrates how to configure a Rust project to compile into a dynamic library (`cdylib`) that can be linked and called from C code. This involves modifying `Cargo.toml` and exposing functions using `extern "C"` and `#[no_mangle]` attributes. ```Rust #[no_mangle] pub extern "C" fn hello_from_rust() { println!("Hello from Rust!"); } fn main() {} ``` ```TOML [lib] crate-type = ["cdylib"] ``` -------------------------------- ### Rust Type Variance Example: Mixed Variance Functions Source: https://doc.rust-lang.org/stable/nomicon/print Shows an example of mixed variance in a Rust function signature. The function `fn(Mixed) -> usize` would be contravariant over `Mixed` but invariance wins. ```Rust k1: fn(Mixed) -> usize ``` -------------------------------- ### Heap Bubble Up Pseudocode (Initial) Source: https://doc.rust-lang.org/stable/nomicon/print This pseudocode represents the initial, straightforward approach to bubbling an element up a heap. It uses repeated swaps, which can be inefficient. ```pseudocode __ bubble_up(heap, index): while index != 0 && heap[index] < heap[parent(index)]: heap.swap(index, parent(index)) index = parent(index) ``` -------------------------------- ### Rust Type Coercion Example and Error Source: https://doc.rust-lang.org/stable/nomicon/coercions Demonstrates Rust's type coercion rules, specifically how coercions do not apply when matching traits unless they are receivers. Shows a code example where a `&mut i32` cannot be coerced to satisfy a `Trait` bound implemented for `&i32`, leading to a compilation error. ```rust trait Trait {} fn foo(t: X) {} impl<'a> Trait for &'a i32 {} fn main() { let t: &mut i32 = &mut 0; foo(t); } ``` ```text error[E0277]: the trait bound `&mut i32: Trait` is not satisfied --> src/main.rs:9:9 | 3 | fn foo(t: X) {} | ----- required by this bound in `foo` ... 9 | foo(t); | ^ the trait `Trait` is not implemented for `&mut i32` | = help: the following implementations were found: <&'a i32 as Trait> = note: `Trait` is implemented for `&i32`, but not for `&mut i32` ``` -------------------------------- ### Rust Inspector with Static String - Sound Drop Example Source: https://doc.rust-lang.org/stable/nomicon/dropck An example demonstrating a variation of the `Inspector` struct that avoids the sound generic drop issue. By including a `&'static str` instead of relying solely on the borrowed `&'a u8` in its `Drop` implementation, the `Inspector` can safely execute its destructor. ```rust struct Inspector<'a>(&'a u8, &'static str); impl<'a> Drop for Inspector<'a> { fn drop(&mut self) { println!("Inspector(_, {}) knows when *not* to inspect.", self.1); } } struct World<'a> { inspector: Option>, days: Box, } fn main() { let mut world = World { inspector: None, days: Box::new(1), }; world.inspector = Some(Inspector(&world.days, "gadget")); } ``` -------------------------------- ### Implement compression with C API in Rust Source: https://doc.rust-lang.org/stable/nomicon/print This code wraps the `snappy_compress` C function to provide a safe Rust `compress` function. It calculates the maximum required buffer size using `snappy_max_compressed_length`, allocates a `Vec` with that capacity, and then calls the C function to perform the compression. The output vector's length is adjusted to the actual compressed size. ```rust __ use libc::{size_t, c_int}; unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8, d: *mut size_t) -> c_int { 0 } unsafe fn snappy_max_compressed_length(a: size_t) -> size_t { a } fn main() {} pub fn compress(src: &[u8]) -> Vec { unsafe { let srclen = src.len() as size_t; let psrc = src.as_ptr(); let mut dstlen = snappy_max_compressed_length(srclen); let mut dst = Vec::with_capacity(dstlen as usize); let pdst = dst.as_mut_ptr(); snappy_compress(psrc, srclen, pdst, &mut dstlen); dst.set_len(dstlen as usize); dst } } ``` -------------------------------- ### Rust Use-After-Free Bug Example Source: https://doc.rust-lang.org/stable/nomicon/subtyping Demonstrates a use-after-free bug in Rust due to incorrect lifetime assumptions when assigning a reference. The example highlights how a mutable reference to a string slice with a 'static lifetime is assigned a reference to a locally scoped String, leading to a compile-time error because the string goes out of scope before the static reference is used. ```rust #![allow(unused)] fn main() { fn assign(input: &mut T, val: T) { *input = val; } let mut hello: &'static str = "hello"; { let world = String::from("world"); assign(&mut hello, &world); } println!("{hello}"); // use after free 😿 } ``` -------------------------------- ### Simplified Rc Implementation in Rust Source: https://doc.rust-lang.org/stable/nomicon/print Presents a basic implementation of Rust's `Rc` (Reference Counting) smart pointer. It illustrates how `Rc` manages shared ownership of heap-allocated data and its `Drop` implementation for reference count decrementing and deallocation. ```rust struct Rc { ptr: *mut RcBox, } struct RcBox { data: T, ref_count: usize, } impl Rc { fn new(data: T) -> Self { unsafe { // Wouldn't it be nice if heap::allocate worked like this? let ptr = heap::allocate::>(); ptr::write(ptr, RcBox { data, ref_count: 1, }); Rc { ptr } } } fn clone(&self) -> Self { unsafe { (*self.ptr).ref_count += 1; } Rc { ptr: self.ptr } } } impl Drop for Rc { fn drop(&mut self) { unsafe { (*self.ptr).ref_count -= 1; if (*self.ptr).ref_count == 0 { // drop the data and then free it ptr::read(self.ptr); heap::deallocate(self.ptr); } } } } ``` -------------------------------- ### Rust Type Variance Example: Function Signatures Source: https://doc.rust-lang.org/stable/nomicon/print Illustrates type variance in Rust function signatures. A function type `fn(In) -> Out` is shown to be contravariant over `In` and covariant over `Out`. ```Rust i: fn(In) -> Out ``` -------------------------------- ### Simplified Rc Implementation in Rust Source: https://doc.rust-lang.org/stable/nomicon/leaking Presents a basic implementation of `Rc` in Rust, showing its structure and methods for creation, cloning, and dropping. It illustrates the management of a reference count for shared ownership of data on the heap. ```rust use std::ptr; struct Rc { ptr: *mut RcBox, } struct RcBox { data: T, ref_count: usize, } impl Rc { fn new(data: T) -> Self { unsafe { // Wouldn't it be nice if heap::allocate worked like this? let ptr = heap::allocate::>(); ptr::write(ptr, RcBox { data, ref_count: 1, }); Rc { ptr } } } fn clone(&self) -> Self { unsafe { (*self.ptr).ref_count += 1; } Rc { ptr: self.ptr } } } impl Drop for Rc { fn drop(&mut self) { unsafe { (*self.ptr).ref_count -= 1; if (*self.ptr).ref_count == 0 { // drop the data and then free it ptr::read(self.ptr); heap::deallocate(self.ptr); } } } } ``` -------------------------------- ### Rust Type Variance Example: Invariant Field Source: https://doc.rust-lang.org/stable/nomicon/print Demonstrates invariance in Rust for a field within a struct. The field `k2: Mixed` is invariant over `Mixed` because invariance is the default and highest precedence. ```Rust k2: Mixed ``` -------------------------------- ### Accessing ArcInner Data Source: https://doc.rust-lang.org/stable/nomicon/arc-mutex/arc-drop This snippet demonstrates how to safely get a reference to the inner data of an `Arc` using its pointer. It requires an unsafe block as it dereferences a raw pointer. ```rust let inner = unsafe { self.ptr.as_ref() }; ```