### Rust Public API Example Program Structure Source: https://www.lurklurk.org/effective-rust/print Illustrates the structure for providing example programs that exercise a Rust crate's public API. These examples are run using `cargo run --example ` or `cargo test --example ` and have access only to the public API. ```rust #![allow(unused)] fn main() { // Example of a typical main function in an example file // demonstrating public API usage. // Assume 'my_crate' is the crate being documented // use my_crate::some_public_function; pub fn main() -> Result<(), Box> { // Code demonstrating the use of the public API // For example: // let data = vec![1, 2, 3]; // let result = my_crate::process_data(data)?; // println!("Processed data: {:?}", result); Ok(()) } } ``` -------------------------------- ### Rust Benchmark for Factorial Function Source: https://www.lurklurk.org/effective-rust/print Demonstrates how to benchmark a Rust function, specifically a factorial calculation. Initially shows a naive benchmark setup, followed by an improved version using `std::hint::black_box` to get more realistic performance measurements. ```rust #![allow(unused)] fn main() { pub fn factorial(n: u128) -> u128 { match n { 0 => 1, n => n * factorial(n - 1), } } } ``` ```rust #![allow(unused)] #![feature(test)] extern crate test; // Assuming factorial function is accessible // fn factorial(n: u128) -> u128 { ... } #[bench] fn bench_factorial(b: &mut test::Bencher) { b.iter(|| { let result = factorial(15); assert_eq!(result, 1_307_674_368_000); }); } ``` ```rust #![allow(unused)] extern crate test; // Assuming factorial function is accessible // fn factorial(n: u128) -> u128 { ... } #[bench] fn bench_factorial_with_black_box(b: &mut test::Bencher) { b.iter(|| { let result = factorial(std::hint::black_box(15)); assert_eq!(result, 1_307_674_368_000); }); } ``` -------------------------------- ### Rust Vec Allocation Example Source: https://www.lurklurk.org/effective-rust/print Demonstrates how standard `Vec::push` operations in Rust might allocate memory. This example highlights the lack of explicit error handling for these allocations, which can lead to program termination (panic) if memory runs out. ```rust #![allow(unused)] fn main() { let mut v = Vec::new(); v.push(1); // might allocate v.push(2); // might allocate v.push(3); // might allocate v.push(4); // might allocate } ``` -------------------------------- ### Rust Derive Macro Example with Serde Source: https://www.lurklurk.org/effective-rust/macros Demonstrates a Rust derive macro using Serde for deserialization. It shows how to use a default value generated by a function when a field is missing during deserialization. This example requires the `serde` crate. ```Rust fn generate_value() -> String { "unknown".to_string() } #[derive(Debug, Deserialize)] struct MyData { // If `value` is missing when deserializing, invoke // `generate_value()` to populate the field instead. #[serde(default = "generate_value")] value: String, } ``` -------------------------------- ### Rust Macro Example: Logging Formatted Output Source: https://www.lurklurk.org/effective-rust/print An example demonstrating the usage of the `my_log!` macro to log a formatted string. It shows how to pass variables and format specifiers to the macro, which then formats and prints the message along with the source code location. This illustrates the practical application of custom formatting macros. ```rust let x = 10u8; // Format specifiers: // - `x` says print as hex // - `#` says prefix with '0x' // - `04` says add leading zeroes so width is at least 4 // (this includes the '0x' prefix). my_log!("x = {:#04x}", x); ``` -------------------------------- ### Rust Unit Test Example Source: https://www.lurklurk.org/effective-rust/testing Demonstrates a typical Rust unit test setup. It includes test functions marked with `#[test]`, a test module annotated with `#[cfg(test)]`, and assertions using `assert_eq!` and `#[should_panic]` to verify function behavior, including expected panics. ```rust #![allow(unused)] fn main() { // ... (code defining `nat_subtract*` functions for natural // number subtraction) #[cfg(test)] mod tests { use super::*; #[test] fn test_nat_subtract() { assert_eq!(nat_subtract(4, 3).unwrap(), 1); assert_eq!(nat_subtract(4, 5), None); } #[should_panic] #[test] fn test_something_that_panics() { nat_subtract_unchecked(4, 5); } } } ``` -------------------------------- ### Rust Doc Comment Formatting: Example Code Section Source: https://www.lurklurk.org/effective-rust/documentation Shows how to include an `# Examples` section in Rust documentation comments to provide sample code. This section's code is compiled and tested with `cargo test`, ensuring it remains synchronized with the actual code. ```rust /// Consider including example code : If it's not trivially obvious how to use an entrypoint, adding an `# Examples` section with sample code can be helpful. Note that sample code in doc comments gets compiled and executed when you run `cargo test` (see Item 30), which helps it stay in sync with the code it's demonstrating. ``` -------------------------------- ### Run All Test Types in CI Source: https://www.lurklurk.org/effective-rust/print CI should execute all types of tests, including unit, integration, doc tests, and example programs. While `cargo test` covers the former, example programs may require explicit invocation. ```bash cargo test --all-features cargo test --doc cargo run --examples ``` -------------------------------- ### Rust Heterogeneous Collection Rendering Example Source: https://www.lurklurk.org/effective-rust/print Shows how trait objects enable collections of different types that implement a common trait, allowing for uniform method invocation. ```rust let shapes: Vec<&dyn Shape> = vec![&square, &circle]; for shape in shapes { shape.render() } ``` -------------------------------- ### Rust cfg Example: Target Architecture Source: https://www.lurklurk.org/effective-rust/print Illustrates conditional compilation based on target environment variables like OS, CPU architecture, and pointer width. This enables writing portable code that adapts to different platforms by including specific implementations only when building for a particular target. For example, `#[cfg(target_os = "linux")]` would only compile code intended for Linux systems. ```rust // Example of conditional compilation based on target OS #[cfg(target_os = "windows")] fn run_on_windows() { println!("Running on Windows"); } #[cfg(target_os = "linux")] fn run_on_linux() { println!("Running on Linux"); } fn main() { // This function would only be compiled if the target OS is Windows #[cfg(target_os = "windows")] run_on_windows(); // This function would only be compiled if the target OS is Linux #[cfg(target_os = "linux")] run_on_linux(); } ``` -------------------------------- ### C++ Bank Account Multithreaded Usage Example Source: https://www.lurklurk.org/effective-rust/print Demonstrates the usage of the BankAccount class in a multithreaded C++ scenario. It sets up multiple threads for depositing and withdrawing funds, illustrating the potential for race conditions and errors. ```cpp BankAccount account; account.deposit(1000); // Start a thread that watches for a low balance and tops up the account. std::thread payer(pay_in, &account); // Start 3 threads that each try to repeatedly withdraw money. std::thread taker(take_out, &account); std::thread taker2(take_out, &account); std::thread taker3(take_out, &account); ``` -------------------------------- ### Rust Fallible Vec Construction Example Source: https://www.lurklurk.org/effective-rust/print Illustrates a safer approach to building a `Vec` in Rust by using `try_reserve` to pre-allocate memory. This method allows for explicit error handling if the allocation fails, returning a `Result` that can be managed by the program. ```rust #![allow(unused)] fn main() { fn try_build_a_vec() -> Result, String> { let mut v = Vec::new(); // Perform a careful calculation to figure out how much space is needed, // here simplified to... let required_size = 4; v.try_reserve(required_size) .map_err(|_e| format!("Failed to allocate {} items!", required_size))?; // We now know that it's safe to do: v.push(1); v.push(2); v.push(3); v.push(4); Ok(v) } } ``` -------------------------------- ### Rust Tuple Struct Example Source: https://www.lurklurk.org/effective-rust/use-types Demonstrates the creation and usage of a tuple struct in Rust. Tuple structs are similar to tuples but are given a name, and their fields are unnamed and accessed by number. ```rust #![allow(unused)] fn main() { /// Struct with two unnamed fields. struct TextMatch(usize, String); // Construct by providing the contents in order. let m = TextMatch(12, "needle".to_owned()); // Access by field number. assert_eq!(m.0, 12); } ``` -------------------------------- ### Get Unique Type ID in Rust using `std::any::TypeId` Source: https://www.lurklurk.org/effective-rust/print Shows how to get a unique identifier for a type at compile time using `std::any::TypeId`. Unlike `type_name`, `TypeId` provides a guarantee of uniqueness, making it suitable for use in code for type comparisons or as keys in collections. The example illustrates obtaining and printing the `TypeId` for different variables. ```rust #![allow(unused)] fn main() { use std::any::TypeId; fn type_id(_v: &T) -> TypeId { TypeId::of::() } let x = 42u32; let y = vec![3, 4, 2]; println!("x has {:?}", type_id(&x)); println!("y has {:?}", type_id(&y)); } ``` -------------------------------- ### Rust Function Documentation Example Source: https://www.lurklurk.org/effective-rust/documentation Demonstrates how to document a public Rust function using documentation comments (`///`). It shows how to include cross-references to types like `BoundingBox` and provides a placeholder for the function's implementation. This helps users understand the function's purpose and usage. ```rust /// Calculate the [`BoundingBox`] that exactly encompasses a pair /// of [`BoundingBox`] objects. pub fn union(a: &BoundingBox, b: &BoundingBox) -> BoundingBox { // ... } ``` -------------------------------- ### C Header File Example Source: https://www.lurklurk.org/effective-rust/bindgen This is an example of C declarations for a struct and functions that will be used for FFI bindings. It includes standard integer types and a custom struct definition. ```c #include typedef struct { uint8_t byte; uint32_t integer; } FfiStruct; int add(int x, int y); uint32_t add32(uint32_t x, uint32_t y); ``` -------------------------------- ### Rust: Manual Conversion from u32 to u64 using .into() Source: https://www.lurklurk.org/effective-rust/print Demonstrates how to manually convert a `u32` to a `u64` in Rust using the `.into()` method, as Rust does not perform automatic numeric type conversions. This is the recommended approach for safe and explicit type transformations. ```rust let x: u32 = 2; let y: u64 = x.into(); ``` -------------------------------- ### Rust Guest Structure and Basic Register Source: https://www.lurklurk.org/effective-rust/borrows Defines a `Guest` struct and a `GuestRegister` that stores guests in order of arrival using a `Vec`. Provides methods for registering new guests and retrieving them by index. This is a foundational example before introducing more complex indexing strategies. ```rust #![allow(unused)] fn main() { #[derive(Clone, Debug)] pub struct Guest { name: String, address: String, // ... many other fields } /// Local error type, used later. #[derive(Clone, Debug)] pub struct Error(String); /// Register of guests recorded in order of arrival. #[derive(Default, Debug)] pub struct GuestRegister(Vec); impl GuestRegister { pub fn register(&mut self, guest: Guest) { self.0.push(guest) } pub fn nth(&self, idx: usize) -> Option<&Guest> { self.0.get(idx) } } } ``` -------------------------------- ### Rust Intra-Doc Link Validation Error Example Source: https://www.lurklurk.org/effective-rust/documentation An example of the compiler output when the `broken_intra_doc_links` attribute detects an unresolved link in Rust documentation. The error message clearly indicates the problematic link and the missing item. ```text error: unresolved link to `Polygone` --> docs/src/main.rs:4:30 | 4 | /// The bounding box for a [`Polygone`]. | ^^^^^^^^ no item named `Polygone` in scope ``` -------------------------------- ### Rust Factorial Function for Benchmarking Source: https://www.lurklurk.org/effective-rust/testing This Rust code defines a recursive factorial function. It's a common example used to demonstrate benchmarking, illustrating how code can be optimized by the compiler. This function serves as the target for the benchmark examples. ```rust #![allow(unused)] fn main() { pub fn factorial(n: u128) -> u128 { match n { 0 => 1, n => n * factorial(n - 1), } } } ``` -------------------------------- ### Rust: Documenting Bounding Box Intersection with Usage Context Source: https://www.lurklurk.org/effective-rust/documentation Shows an example of Rust documentation for a BoundingBox intersection function that includes usage context from other modules. This approach is prone to becoming outdated as the using code evolves. ```rust /// Return the intersection of two [`BoundingBox`] objects, returning `None` /// if there is no intersection. The collision detection code in `hits.rs` /// uses this to do an initial check to see whether two objects might overlap, /// before performing the more expensive pixel-by-pixel check in /// `objects_overlap`. pub fn intersection( a: &BoundingBox, b: &BoundingBox, ) -> Option { ``` -------------------------------- ### Get Unique Type ID in Rust using std::any::TypeId Source: https://www.lurklurk.org/effective-rust/reflection Shows how to get a unique runtime identifier for a type using a generic function that wraps `std::any::TypeId::of`. This is suitable for unique identification in code but is not human-readable. ```rust #![allow(unused)] fn main() { use std::any::TypeId; fn type_id(_v: &T) -> TypeId { TypeId::of::() } let x = 42u32; let y = vec![3, 4, 2]; println!("x has {:?}", type_id(&x)); println!("y has {:?}", type_id(&y)); } ``` -------------------------------- ### Rust Guest Register with Indexing Source: https://www.lurklurk.org/effective-rust/borrows Implements a `GuestRegister` using a `Vec` for arrival order and a `BTreeMap` to map guest names to their index in the vector. This avoids cloning data and allows for efficient mutable access to guest details, but requires careful management of indices during operations like deregistration. ```rust mod indexed { use super::Guest; #[derive(Default)] pub struct GuestRegister { by_arrival: Vec, // Map from guest name to index into `by_arrival`. by_name: std::collections::BTreeMap, } impl GuestRegister { pub fn register(&mut self, guest: Guest) { // Not checking for duplicate names to keep this // example shorter. self.by_name .insert(guest.name.clone(), self.by_arrival.len()); self.by_arrival.push(guest); } pub fn named(&self, name: &str) -> Option<&Guest> { let idx = *self.by_name.get(name)?; self.nth(idx) } pub fn named_mut(&mut self, name: &str) -> Option<&mut Guest> { let idx = *self.by_name.get(name)?; self.nth_mut(idx) } pub fn nth(&self, idx: usize) -> Option<&Guest> { self.by_arrival.get(idx) } pub fn nth_mut(&mut self, idx: usize) -> Option<&mut Guest> { self.by_arrival.get_mut(idx) } } } ``` -------------------------------- ### Rust Lifetime Scope Disassociation Example Source: https://www.lurklurk.org/effective-rust/print This example demonstrates a scenario where the output reference's lifetime is not directly tied to one of the input references' lifetimes. The `find` function's output is used after the `needle`'s scope ends, but still within the `haystack`'s scope. ```rust { let haystack = b"123456789"; // start of lifetime 'a let found = { let needle = b"234"; // start of lifetime 'b find(haystack, needle) }; // end of lifetime 'b println!("found={:?}", found); // `found` used within 'a, outside of 'b } // end of lifetime 'a ``` -------------------------------- ### Run Benchmarks in CI Source: https://www.lurklurk.org/effective-rust/print Execute benchmarks using `cargo bench` in CI to measure performance on key scenarios. Note that CI environments may introduce variability, and dedicated environments are better for reliable benchmark data. ```bash cargo bench ``` -------------------------------- ### Rust Example: Newtype and Function with IanaAllocated Source: https://www.lurklurk.org/effective-rust/casts This snippet demonstrates a simple newtype struct `IanaAllocated` wrapping a `u64` and a function `is_iana_reserved` that operates on this newtype. It serves as a basic example for demonstrating type usage in Rust, potentially in conjunction with conversion traits. ```rust #![allow(unused)] fn main() { /// Integer value from an IANA-controlled range. #[derive(Clone, Copy, Debug)] pub struct IanaAllocated(pub u64); /// Indicate whether value is reserved. pub fn is_iana_reserved(s: IanaAllocated) -> bool { s.0 == 0 || s.0 == 65535 } } ``` -------------------------------- ### Rust Example of Heterogeneous Collections with Trait Objects Source: https://www.lurklurk.org/effective-rust/generics Illustrates a practical use case for trait objects: creating collections of heterogeneous types that share a common trait. This example shows a `Vec` containing different shapes that can all be rendered using their `render` method. ```rust let shapes: Vec<&dyn Shape> = vec![&square, &circle]; for shape in shapes { shape.render() } ``` -------------------------------- ### Rust Guest Register with Data Cloning Source: https://www.lurklurk.org/effective-rust/borrows Implements a `GuestRegister` that maintains separate collections for arrival order (`Vec`) and alphabetical name lookup (`BTreeMap`). This approach requires `Guest` to be `Clone` and can be inefficient for frequent modifications due to data duplication. ```rust mod cloned { use super::Guest; #[derive(Default, Debug)] pub struct GuestRegister { by_arrival: Vec, by_name: std::collections::BTreeMap, } impl GuestRegister { pub fn register(&mut self, guest: Guest) { // Requires `Guest` to be `Clone` self.by_arrival.push(guest.clone()); // Not checking for duplicate names to keep this // example shorter. self.by_name.insert(guest.name.clone(), guest); } pub fn named(&self, name: &str) -> Option<&Guest> { self.by_name.get(name) } pub fn nth(&self, idx: usize) -> Option<&Guest> { self.by_arrival.get(idx) } } } ``` -------------------------------- ### Rust Example Usage of Generic Functions Source: https://www.lurklurk.org/effective-rust/generics Provides an example of calling generic Rust functions `area` and `show` with different types (`Square` and `Circle`). It illustrates compile-time checks for trait bounds, showing that `show` will not compile for `Square` as it lacks the `Debug` trait. ```rust struct Square { top_left: Point, size: i64, } impl Draw for Square { fn bounds(&self) -> Bounds { Bounds { top_left: self.top_left, bottom_right: Point { x: self.top_left.x + self.size, y: self.top_left.y + self.size } } } } struct Circle { center: Point, radius: i64, } impl Draw for Circle { fn bounds(&self) -> Bounds { Bounds { top_left: Point { x: self.center.x - self.radius, y: self.center.y - self.radius }, bottom_right: Point { x: self.center.x + self.radius, y: self.center.y + self.radius } } } } impl Debug for Circle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Circle") .field("center", &self.center) .field("radius", &self.radius) .finish() } } let square = Square { top_left: Point { x: 1, y: 2 }, size: 2, }; let circle = Circle { center: Point { x: 3, y: 4 }, radius: 1, }; // Both `Square` and `Circle` implement `Draw`. println!("area(square) = {}", area(&square)); println!("area(circle) = {}", area(&circle)); // `Circle` implements `Debug`. show(&circle); // `Square` does not implement `Debug`, so this wouldn't compile: // show(&square); ``` -------------------------------- ### Rust Function to Find Substring and Example Usage Source: https://www.lurklurk.org/effective-rust/borrows This Rust function `find` searches for a `needle` within a `haystack` string slice and returns an `Option` containing a slice of the `haystack` if found. It uses the `str::find` method and `Option::map` for concise implementation. The example shows how to call this function with formatted strings and handle the result. ```rust /// If `needle` is present in `haystack`, return a slice containing it. pub fn find<'a, 'b>(haystack: &'a str, needle: &'b str) -> Option<&'a str> { haystack .find(needle) .map(|i| &haystack[i..i + needle.len()]) } // ... let found = find(&format!("{} to search", "Text"), "ex"); if let Some(text) = found { println!("Found '{text}'!"); } ``` -------------------------------- ### Rust GameServer add_and_join Method (Initial) Source: https://www.lurklurk.org/effective-rust/deadlock Implements the add_and_join method for the Rust GameServer. This function adds a new player and attempts to join them into an existing game. It acquires locks for both players and games sequentially. ```rust impl GameServer { /// Add a new player and join them into a current game. fn add_and_join(&self, username: &str, info: Player) -> Option { // Add the new player. let mut players = self.players.lock().unwrap(); players.insert(username.to_owned(), info); // Find a game with available space for them to join. let mut games = self.games.lock().unwrap(); for (id, game) in games.iter_mut() { if game.add_player(username) { return Some(id.clone()); } } None } } ``` -------------------------------- ### Run Clippy Linter with Warnings as Errors in CI Source: https://www.lurklurk.org/effective-rust/print Integrate Clippy into the CI pipeline with the `-Dwarnings` option to treat linter warnings as build failures. This enforces code quality and style consistency. ```bash cargo clippy --all-targets -- -D warnings ``` -------------------------------- ### Rust: Explicit conversion from i32 to i64 using into() Source: https://www.lurklurk.org/effective-rust/print Demonstrates the compiler-suggested explicit conversion from an i32 to an i64 in Rust using the `into()` method. This is a common way to handle safe type conversions between numeric types. ```rust let x = 42i32; let y: i64 = x.into(); ``` -------------------------------- ### Rust Attribute Macro Invocation (Logging) Source: https://www.lurklurk.org/effective-rust/macros An example of using an attribute macro `#[log_invocation]` before a function definition. This macro is intended to log function calls. ```rust #[log_invocation] fn add_three(x: u32) -> u32 { x + 3 } ``` -------------------------------- ### Rust Trait Object Initialization with Any Source: https://www.lurklurk.org/effective-rust/print Shows how to create trait objects of type `dyn Any` using `Box`. This allows storing different concrete types (like `u64` and a custom `Square` struct) behind a common interface, enabling runtime type examination. ```rust let x_any: Box = Box::new(42u64); let y_any: Box = Box::new(Square::new(3, 4, 3)); ``` -------------------------------- ### Rust Function-like Macro Invocation Source: https://www.lurklurk.org/effective-rust/macros An example of invoking a function-like procedural macro with multiple arguments. The macro itself receives a single token stream representing all arguments. ```rust my_func_macro!(15, x + y, f32::consts::PI); ``` -------------------------------- ### Rust Example: Update Guest Address Source: https://www.lurklurk.org/effective-rust/borrows Demonstrates how to modify a guest's address using the `named_mut` method provided by the indexed `GuestRegister`. This showcases the benefit of the indirection approach, allowing direct mutable access to the single owner of guest data. ```rust let new_address = "123 Bigger House St"; // Real code wouldn't assume that "Bob" exists... ledger.named_mut("Bob").unwrap().address = new_address.to_string(); assert_eq!(ledger.named("Bob").unwrap().address, new_address); ``` -------------------------------- ### C++ Bank Account Helper Functions for Multithreading Source: https://www.lurklurk.org/effective-rust/print Provides the C++ functions `pay_in` and `take_out` used in the multithreaded BankAccount example. `pay_in` monitors and tops up the balance, while `take_out` repeatedly attempts to withdraw funds, showcasing potential concurrency issues. ```cpp // Constantly monitor the `account` balance and top it up if low. void pay_in(BankAccount* account) { while (true) { if (account->balance() < 200) { log("[A] Balance running low, deposit 400"); account->deposit(400); } // (The infinite loop with sleeps is just for demonstration/simulation // purposes.) std::this_thread::sleep_for(std::chrono::milliseconds(5)); } } // Repeatedly try to perform withdrawals from the `account`. void take_out(BankAccount* account) { while (true) { if (account->withdraw(100)) { log("[B] Withdrew 100, balance now " + std::to_string(account->balance())); } else { log("[B] Failed to withdraw 100"); } std::this_thread::sleep_for(std::chrono::milliseconds(20)); } } ``` -------------------------------- ### C Function Definition Source: https://www.lurklurk.org/effective-rust/print Defines a simple C function named 'add' that takes two integers and returns their sum. This serves as an example of C code that can be called from Rust. ```c #include "lib.h" /* C function definition. */ int add(int x, int y) { return x + y; } ``` -------------------------------- ### Rust Usage of Generic Function with Circle Source: https://www.lurklurk.org/effective-rust/print Shows the usage of the generic `on_screen` function with a `Circle` instance. Similar to the `Square` example, this results in a monomorphized version of the function specific to the `Circle` type. ```Rust let circle = Circle { center: Point { x: 3, y: 4 }, radius: 1, }; // Calls `on_screen::(&Circle) -> bool` let visible = on_screen(&circle); ```