### Rust println! Macro Example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/macro Illustrates the usage of the built-in `println!` macro in Rust for formatted output to the console. ```Rust println!("Hello, {}!", "world"); ``` -------------------------------- ### Rust Match Statement Example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/flow-control Demonstrates the `match` statement in Rust, which allows for pattern matching against a value. This example matches an integer against several possible values. ```rust #![allow(unused)] fn main() { let number = 3; match number { 1 => println!("One"), 2 => println!("Two"), 3 => println!("Three"), _ => println!("Something else"), } } ``` -------------------------------- ### Rust Procedural Macro Setup (Cargo.toml) Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/macro Shows how to configure a Rust crate to support procedural macros by setting `proc-macro = true` in `Cargo.toml`. ```toml [lib] proc-macro = true ``` -------------------------------- ### Rust For Loop Example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/flow-control Shows how to use a `for` loop in Rust to iterate over a range of numbers. This example prints numbers from 1 up to (but not including) 5. ```rust #![allow(unused)] fn main() { for number in 1..5 { println!("The number is: {}", number); } } ``` -------------------------------- ### Example Usage of Bcrypt Hashing in Rust Source: https://idiomatic-rust-snippets.org/algorithms/cryptographic/bcrypt Demonstrates the usage of the `generate_salt` and `bcrypt_hash` functions in Rust. It shows how to generate a salt, hash a password using the simulated bcrypt function, and print the results. ```rust extern crate rand; use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; use base64; const BCRYPT_COST: u32 = 12; const BCRYPT_SALT_LEN: usize = 16; const BCRYPT_HASH_LEN: usize = 24; fn generate_salt() -> String { let salt: String = thread_rng() .sample_iter(&Alphanumeric) .take(BCRYPT_SALT_LEN) .map(char::from) .collect(); salt } fn bcrypt_hash(password: &str, salt: &str) -> String { let mut hash = vec![0u8; BCRYPT_HASH_LEN]; let cost = BCRYPT_COST; let password_bytes = password.as_bytes(); let salt_bytes = salt.as_bytes(); // Simulate bcrypt hashing (this is a simplified version) for i in 0..BCRYPT_HASH_LEN { hash[i] = password_bytes[i % password_bytes.len()] ^ salt_bytes[i % salt_bytes.len()] ^ (cost as u8); } base64::encode(&hash) } fn main() { let password = "my_secure_password"; let salt = generate_salt(); let hashed_password = bcrypt_hash(password, &salt); println!("Password: {}", password); println!("Salt: {}", salt); println!("Hashed Password: {}", hashed_password); } ``` -------------------------------- ### Rust Declarative Macro Example (macro_rules!) Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/macro Demonstrates a simple declarative macro using `macro_rules!` to print 'Hello, world!'. This macro is defined and then invoked within the `main` function. ```Rust macro_rules! say_hello { () => { println!("Hello, world!"); }; } fn main() { say_hello!(); } ``` -------------------------------- ### Rust library crate function example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/crate Provides an example of a public function within a Rust library crate's `lib.rs` file. This function can be called by other crates. ```rust pub fn hello() { println!("Hello, library!"); } ``` -------------------------------- ### A* Pathfinding Algorithm in Rust Source: https://idiomatic-rust-snippets.org/algorithms/graph/a-star Implements the A* pathfinding algorithm using Rust's standard library collections like BinaryHeap and HashMap. It calculates the shortest path between a start and goal point while avoiding specified obstacles. The implementation includes custom `Node` struct with `Ord` and `PartialOrd` traits for use in the priority queue. ```Rust use std::collections::{BinaryHeap, HashMap}; use std::cmp::Ordering; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Node { position: (i32, i32), g: i32, h: i32, } impl Node { fn f(&self) -> i32 { self.g + self.h } } impl Ord for Node { fn cmp(&self, other: &Self) -> Ordering { other.f().cmp(&self.f()) } } impl PartialOrd for Node { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } fn heuristic(a: (i32, i32), b: (i32, i32)) -> i32 { (a.0 - b.0).abs() + (a.1 - b.1).abs() } fn a_star(start: (i32, i32), goal: (i32, i32), obstacles: &[(i32, i32)]) -> Option> { let mut open_list = BinaryHeap::new(); let mut closed_list = HashMap::new(); let mut came_from = HashMap::new(); open_list.push(Node { position: start, g: 0, h: heuristic(start, goal), }); while let Some(current) = open_list.pop() { if current.position == goal { let mut path = vec![current.position]; let mut current_position = current.position; while let Some(&prev_position) = came_from.get(¤t_position) { path.push(prev_position); current_position = prev_position; } path.reverse(); return Some(path); } closed_list.insert(current.position, current.g); for &neighbor in &[ (current.position.0 - 1, current.position.1), (current.position.0 + 1, current.position.1), (current.position.0, current.position.1 - 1), (current.position.0, current.position.1 + 1), ] { if obstacles.contains(&neighbor) || closed_list.contains_key(&neighbor) { continue; } let tentative_g = current.g + 1; if let Some(&existing_g) = closed_list.get(&neighbor) { if tentative_g >= existing_g { continue; } } open_list.push(Node { position: neighbor, g: tentative_g, h: heuristic(neighbor, goal), }); came_from.insert(neighbor, current.position); } } None } fn main() { let start = (0, 0); let goal = (4, 4); let obstacles = [(1, 1), (2, 2), (3, 3)]; if let Some(path) = a_star(start, goal, &obstacles) { println!("Path found: {:?}", path); } else { println!("No path found."); } } ``` -------------------------------- ### Facade Pattern Implementation in Rust Source: https://idiomatic-rust-snippets.org/patterns/structural/facade Demonstrates the Facade design pattern in Rust. It simplifies a complex subsystem by providing a unified, higher-level interface. This example includes two subsystems (SubsystemA and SubsystemB) and a Facade struct that orchestrates their operations. ```rust struct SubsystemA; impl SubsystemA { fn operation_a1(&self) -> String { "Subsystem A, Operation A1".to_string() } fn operation_a2(&self) -> String { "Subsystem A, Operation A2".to_string() } } struct SubsystemB; impl SubsystemB { fn operation_b1(&self) -> String { "Subsystem B, Operation B1".to_string() } fn operation_b2(&self) -> String { "Subsystem B, Operation B2".to_string() } } struct Facade { subsystem_a: SubsystemA, subsystem_b: SubsystemB, } impl Facade { fn new() -> Self { Facade { subsystem_a: SubsystemA, subsystem_b: SubsystemB, } } fn operation(&self) -> String { let mut result = String::new(); result.push_str(&self.subsystem_a.operation_a1()); result.push_str("\n"); result.push_str(&self.subsystem_a.operation_a2()); result.push_str("\n"); result.push_str(&self.subsystem_b.operation_b1()); result.push_str("\n"); result.push_str(&self.subsystem_b.operation_b2()); result } } fn main() { let facade = Facade::new(); println!("{}", facade.operation()); } ``` -------------------------------- ### Rust If Statement Example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/flow-control Demonstrates the basic usage of an `if-else` statement in Rust to execute code conditionally. It checks if a number is less than 10. ```rust #![allow(unused)] fn main() { let number = 5; if number < 10 { println!("The number is less than 10"); } else { println!("The number is 10 or greater"); } } ``` -------------------------------- ### Rust While Loop Example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/flow-control Illustrates the use of a `while` loop in Rust for repeating a block of code as long as a specified condition remains true. It increments a counter until it reaches 5. ```rust #![allow(unused)] fn main() { let mut count = 0; while count < 5 { println!("Count is: {}", count); count += 1; } } ``` -------------------------------- ### Get Current Time Since UNIX EPOCH in Rust Source: https://idiomatic-rust-snippets.org/essentials/packaging/modules Demonstrates how to get the current system time and calculate the duration since the UNIX epoch in seconds. It handles potential errors if the system time is before the UNIX epoch. ```rust use std::time::{SystemTime, UNIX_EPOCH}; fn main() { // Get the current system time match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => println!("Current time since UNIX EPOCH: {} seconds", n.as_secs()), Err(_) => println!("SystemTime before UNIX EPOCH!"), } } ``` -------------------------------- ### Access Vector Elements in Rust Source: https://idiomatic-rust-snippets.org/essentials/types/vector Illustrates accessing elements by index (which panics if out of bounds) and using the `get` method (which returns an `Option` for safe access). ```Rust #![allow(unused)] fn main() { let v = vec![1, 2, 3, 4, 5]; println!("The third element is {}", v[2]); match v.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), } } ``` -------------------------------- ### Rust Bubble Sort Implementation and Usage Source: https://idiomatic-rust-snippets.org/algorithms/sorting/buble Demonstrates an idiomatic Rust implementation of the bubble sort algorithm. It includes the `bubble_sort` function and a `main` function to showcase its usage with an example array. The algorithm repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. ```rust fn bubble_sort(arr: &mut [i32]) { let mut n = arr.len(); while n > 0 { let mut new_n = 0; for i in 1..n { if arr[i - 1] > arr[i] { arr.swap(i - 1, i); new_n = i; } } println!("Iteration {:?} {}, arr, new_n); n = new_n; } } fn main() { let mut arr = [64, 34, 25, 12, 22, 12, 90, 33]; println!("Unsorted array: {:?}", arr); bubble_sort(&mut arr); println!("Sorted array: {:?}", arr); } ``` -------------------------------- ### Implement Prototype Pattern with Rust Clone Trait Source: https://idiomatic-rust-snippets.org/patterns/creational/prototype Demonstrates the prototype pattern in Rust by leveraging the `Clone` trait for object cloning. This pattern is useful for creating new objects by copying an existing one, especially when object creation is resource-intensive. The example defines a struct, derives `Clone`, and provides a method for cloning. ```rust #[derive(Clone)] struct Prototype { field1: String, field2: i32, } impl Prototype { fn new(field1: String, field2: i32) -> Self { Prototype { field1, field2 } } fn clone_prototype(&self) -> Self { self.clone() } } fn main() { let original = Prototype::new(String::from("Prototype"), 42); let cloned = original.clone_prototype(); println!("Original: {} - {}", original.field1, original.field2); println!("Cloned: {} - {}", cloned.field1, cloned.field2); } ``` -------------------------------- ### Define and Use a Tuple Struct in Rust Source: https://idiomatic-rust-snippets.org/essentials/types/struct Illustrates the creation of a tuple struct named Color with three unnamed fields of type u8. The example shows how to instantiate the tuple struct and access its elements using dot notation with index. ```rust struct Color(u8, u8, u8); fn main() { let black = Color(0, 0, 0); println!("Black color: ({}, {}, {})", black.0, black.1, black.2); } ``` -------------------------------- ### Rust binary crate entry point Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/crate Shows the basic structure of a `main.rs` file for a Rust binary crate, including the `main` function which is the entry point of the program. ```rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Create a new Rust library crate Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/crate Illustrates the command to create a new Rust library crate using Cargo with the `--lib` flag. Library crates are collections of code for reuse. ```bash cargo new my_library_crate --lib ``` -------------------------------- ### Rust: Function with Parameters Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/function Illustrates how to define a function that accepts parameters. The 'greet' function takes a string slice ('&str') as an argument and prints a personalized greeting. Multiple calls to the function show its reusability. ```rust fn greet(name: &str) { println!("Hello, {}!", name); } fn main() { greet("Alice"); greet("Bob"); } ``` -------------------------------- ### Rust Strategy Pattern Implementation Source: https://idiomatic-rust-snippets.org/patterns/behavioral/strategy Demonstrates the Strategy pattern in Rust, allowing algorithms to be defined, encapsulated, and made interchangeable. It includes a Strategy trait, concrete strategy implementations (A and B), and a Context struct to manage strategy execution. Dependencies include standard Rust features for traits and structs. The primary input is a string slice, and the output is printed to the console. This pattern is useful for runtime algorithm switching. ```rust // Strategy type pub trait Strategy { fn execute(&self, data: &str); } pub struct ConcreteStrategyA; // Concrete Strategy A impl Strategy for ConcreteStrategyA { fn execute(&self, data: &str) { println!("ConcreteStrategyA: {}", data); } } pub struct ConcreteStrategyB; // Concrete Strategy B impl Strategy for ConcreteStrategyB { fn execute(&self, data: &str) { println!("ConcreteStrategyB: {}", data); } } // Context type pub struct Context { strategy: Box, } // Concrete Context impl Context { pub fn new(strategy: Box) -> Self { Context { strategy } } pub fn set_strategy(&mut self, strategy: Box) { self.strategy = strategy; } pub fn execute_strategy(&self, data: &str) { self.strategy.execute(data); } } fn main() { let strategy_a = Box::new(ConcreteStrategyA); let strategy_b = Box::new(ConcreteStrategyB); let mut context = Context::new(strategy_a); context.execute_strategy("Hello, World!"); context.set_strategy(strategy_b); context.execute_strategy("Hello, Rust!"); } ``` -------------------------------- ### Unwrap Option with Default Value in Rust Source: https://idiomatic-rust-snippets.org/essentials/std-lib/option Shows how to use the `unwrap_or` method to safely get a value from an Option, providing a default if it's None. ```rust fn main() { let some_number = Some(10); let none_number: Option = None; println!("The number is: {}", some_number.unwrap_or(0)); println!("The number is: {}", none_number.unwrap_or(0)); } ``` -------------------------------- ### Organize Rust Modules in Separate Files Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/module Shows the idiomatic way to split Rust modules into separate files. It details the file structure and how to declare and use modules across files using `mod` declarations. ```rust // src/main.rs mod my_module; fn main() { my_module::say_hello(); } ``` ```rust // src/my_module.rs pub fn say_hello() { println!("Hello from my_module!"); } ``` -------------------------------- ### Create a new Rust binary crate Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/crate Demonstrates the command to create a new Rust binary crate using Cargo. A binary crate is a program that can be compiled into an executable. ```bash cargo new my_binary_crate ``` -------------------------------- ### Simulate Bcrypt Hashing in Rust Source: https://idiomatic-rust-snippets.org/algorithms/cryptographic/bcrypt Simulates the bcrypt password hashing process by combining a password, a salt, and a cost factor. This is a simplified implementation for educational purposes and not suitable for production use. It uses the `base64` crate for encoding the resulting hash. ```rust use base64; const BCRYPT_COST: u32 = 12; const BCRYPT_HASH_LEN: usize = 24; fn bcrypt_hash(password: &str, salt: &str) -> String { let mut hash = vec![0u8; BCRYPT_HASH_LEN]; let cost = BCRYPT_COST; let password_bytes = password.as_bytes(); let salt_bytes = salt.as_bytes(); // Simulate bcrypt hashing (this is a simplified version) for i in 0..BCRYPT_HASH_LEN { hash[i] = password_bytes[i % password_bytes.len()] ^ salt_bytes[i % salt_bytes.len()] ^ (cost as u8); } base64::encode(&hash) } ``` -------------------------------- ### Define and Use a Unit-like Struct in Rust Source: https://idiomatic-rust-snippets.org/essentials/types/struct Shows the definition of a unit-like struct in Rust, which has no fields. This type of struct is useful for implementing traits or generics where a type placeholder is needed. The example demonstrates its instantiation. ```rust struct Unit; fn main() { let unit = Unit; println!("Unit struct created!"); } ``` -------------------------------- ### Generic Enums in Rust Source: https://idiomatic-rust-snippets.org/essentials/types/generic Illustrates the use of generic enums in Rust, enabling variants to hold data of different types. The 'Option' enum is a common example, with 'Some' variant capable of holding any type T. ```rust enum Option { Some(T), None, } fn main() { let some_number = Option::Some(5); let some_string = Option::Some("a string"); println!("Some number: {:?}", some_number); println!("Some string: {:?}", some_string); } ``` -------------------------------- ### Enable Unstable Features with #![feature(...)] in Rust Source: https://idiomatic-rust-snippets.org/essentials/packaging/feature-attribute The #![feature(...)] attribute enables unstable features from the nightly Rust compiler. It must be placed at the top of the file. This example demonstrates enabling the 'test' crate for benchmarking. ```rust #![feature(test)] extern crate bcrypt; extern crate test; use bcrypt::{hash, DEFAULT_COST}; #[bench] fn bench_cost_4(b: &mut test::Bencher) { b.iter(|| hash("hunter2", 4)); } ``` -------------------------------- ### Rust: Custom Display for no_std Source: https://idiomatic-rust-snippets.org/essentials/packaging/no-std Demonstrates implementing the `fmt::Display` trait for a custom struct in a `no_std` environment. This allows for custom string formatting without relying on the standard library's `println!` macro. Requires the `core` crate. ```rust #![no_std] extern crate core; use core::fmt; struct MyStruct; impl fmt::Display for MyStruct { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Hello, no_std!") } } fn main() { let my_struct = MyStruct; // println! is from std and will not work here. // A custom logging or output mechanism would be needed. } ``` -------------------------------- ### Rust: Handling errors with Result enum for division Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/error-handling Demonstrates using the `Result` enum to handle potential errors in a division function. It shows how to return `Ok` for successful division and `Err` for division by zero, with examples of matching on the result. ```rust fn divide(a: f64, b: f64) -> Result { if b == 0.0 { Err(String::from("Division by zero")) } else { Ok(a / b) } } fn main() { match divide(4.0, 2.0) { Ok(result) => println!("Result: {}", result), Err(e) => println!("Error: {}", e), } match divide(5.0, 0.0) { Ok(result) => println!("Result: {}", result), Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Create Rc Instance in Rust Source: https://idiomatic-rust-snippets.org/essentials/std-lib/rc Demonstrates how to create a new Rc instance holding a value using `Rc::new`. This is the fundamental step for enabling shared ownership in single-threaded Rust programs. ```rust use std::rc::Rc; fn main() { let value = Rc::new(5); println!("Value: {}", value); } ``` -------------------------------- ### Rust: Basic Match Statement Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/pattern-matching Demonstrates a basic Rust match statement with simple integer comparison. It matches a variable against different literal values and a wildcard. ```rust #![allow(unused)] fn main() { let x = 1; match x { 1 => println!("One!"), 2 => println!("Two!"), _ => println!("Something else!"), } } ``` -------------------------------- ### Rust Ownership Move Example Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/ownership Demonstrates Rust's ownership transfer (move semantics) for String types. When a value is moved, the original variable is no longer valid, preventing double-free errors. This highlights Rust's compile-time memory safety. ```rust fn main() { let s1 = String::from("hello"); let s2 = s1; // s1 is moved to s2 // println!("{}", s1); // This line would cause a compile-time error because s1 is no longer valid println!("{}", s2); // s2 is now the owner of the string } ``` -------------------------------- ### Rust Diffie-Hellman Key Exchange Implementation Source: https://idiomatic-rust-snippets.org/algorithms/cryptographic/diffie-hellman Demonstrates the Diffie-Hellman key exchange algorithm in Rust without external libraries. It includes functions for generating private keys and computing modular exponentiation, showcasing the process of securely sharing a secret key. Uses small numbers for simplicity; larger primes are recommended for real-world applications. ```rust extern crate rand; use rand::Rng; fn main() { // Step 1: Agree on a prime number p and base g let p: u64 = 23; // A small prime number for simplicity let g: u64 = 5; // A primitive root modulo p // Step 2: Each party generates a private key let private_key_a = generate_private_key(); let private_key_b = generate_private_key(); // Step 3: Compute public keys let public_key_a = mod_exp(g, private_key_a, p); let public_key_b = mod_exp(g, private_key_b, p); // Step 4: Exchange public keys (simulated here) println!("Public Key A: {}", public_key_a); println!("Public Key B: {}", public_key_b); // Step 5: Compute shared secret let shared_secret_a = mod_exp(public_key_b, private_key_a, p); let shared_secret_b = mod_exp(public_key_a, private_key_b, p); // Both shared secrets should be the same println!("Shared Secret A: {}", shared_secret_a); println!("Shared Secret B: {}", shared_secret_b); } fn generate_private_key() -> u64 { rand::thread_rng().gen_range(1..100) } fn mod_exp(base: u64, exp: u64, modulus: u64) -> u64 { let mut result = 1; let mut base = base % modulus; let mut exp = exp; while exp > 0 { if exp % 2 == 1 { result = (result * base) % modulus; } exp = exp >> 1; base = (base * base) % modulus; } result } ``` -------------------------------- ### Rust Function-Like Procedural Macro Usage Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/macro Demonstrates how to use a custom function-like procedural macro. The macro is imported and then invoked using the `!` syntax with a code block as its argument. ```Rust use my_function_like_macro::my_function_like_macro; my_function_like_macro! { // Your code here } ``` -------------------------------- ### Rust AES Encryption Implementation Source: https://idiomatic-rust-snippets.org/algorithms/cryptographic/aes Demonstrates a basic, from-scratch implementation of the AES encryption algorithm in Rust. It includes core components like S-Box substitution, row shifting, column mixing, and round key addition. Note that `mix_columns` and `key_expansion` require full implementation for a complete algorithm. This snippet is for educational purposes and not recommended for production security. ```rust const S_BOX: [u8; 256] = [ // S-Box values here... ]; fn sub_bytes(state: &mut [u8; 16]) { for i in 0..16 { state[i] = S_BOX[state[i] as usize]; } } fn shift_rows(state: &mut [u8; 16]) { let mut temp = [0u8; 16]; for i in 0..16 { temp[i] = state[i]; } for i in 0..4 { for j in 0..4 { state[i + 4 * j] = temp[i + 4 * ((j + i) % 4)]; } } } fn mix_columns(state: &mut [u8; 16]) { // MixColumns implementation here... } fn add_round_key(state: &mut [u8; 16], round_key: &[u8; 16]) { for i in 0..16 { state[i] ^= round_key[i]; } } fn aes_encrypt_block(block: &mut [u8; 16], key: &[u8; 16]) { let mut round_keys = [0u8; 176]; key_expansion(key, &mut round_keys); add_round_key(block, &round_keys[0..16]); for round in 1..10 { sub_bytes(block); shift_rows(block); mix_columns(block); add_round_key(block, &round_keys[round * 16..(round + 1) * 16]); } sub_bytes(block); shift_rows(block); add_round_key(block, &round_keys[160..176]); } fn key_expansion(key: &[u8; 16], round_keys: &mut [u8; 176]) { // Key expansion implementation here... } fn main() { let mut block = [0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34]; let key = [0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x4d, 0x4a, 0x4e, 0xa6, 0x2b, 0x7e]; aes_encrypt_block(&mut block, &key); println!("Encrypted block: {:?}", block); } ``` -------------------------------- ### Rust Depth First Search (DFS) for Graph Traversal Source: https://idiomatic-rust-snippets.org/algorithms/searching/depth-first Implements Depth First Search (DFS) on a graph represented by a HashMap. The function recursively visits nodes, keeping track of visited nodes to avoid cycles. It requires a graph, a starting node, and a mutable vector to store visited nodes. ```rust use std::collections::HashMap; fn dfs(graph: &HashMap>, start: i32, visited: &mut Vec) { if visited.contains(&start) { return; } visited.push(start); if let Some(neighbors) = graph.get(&start) { for &neighbor in neighbors { dfs(graph, neighbor, visited); } } } fn main() { // Create a sample graph as an adjacency list let mut graph = HashMap::new(); graph.insert(0, vec![1, 2]); graph.insert(1, vec![2]); graph.insert(2, vec![0, 3]); graph.insert(3, vec![3]); // Vector to keep track of visited nodes let mut visited = Vec::new(); // Perform DFS starting from node 2 dfs(&graph, 2, &mut visited); // Print the visited nodes println!("Visited nodes: {:?}", visited); } ``` -------------------------------- ### Rust Trait Definition and Implementation Source: https://idiomatic-rust-snippets.org/essentials/types/trait Demonstrates defining a trait 'Greet' with a 'greet' method and implementing it for 'Person' and 'Dog' structs. This showcases Rust's trait system for shared behavior and polymorphism. ```rust pub trait Greet { fn greet(&self); } pub struct Person { name: String, } impl Greet for Person { fn greet(&self) { println!("Hello, my name is {}!", self.name); } } pub struct Dog { name: String, } impl Greet for Dog { fn greet(&self) { println!("Woof! My name is {}!", self.name); } } fn main() { let person = Person { name: String::from("Alice"), }; let dog = Dog { name: String::from("Buddy"), }; dog.greet(); person.greet(); } ``` -------------------------------- ### Rust Command Pattern Implementation for Light Control Source: https://idiomatic-rust-snippets.org/patterns/behavioral/command Implements the Command pattern in Rust to control a Light. Includes the Command trait, concrete commands (TurnOnCommand, TurnOffCommand), an invoker (RemoteControl), and the receiver (Light). Demonstrates decoupling of invoker and receiver. ```rust use std::cell::RefCell; use std::rc::Rc; // Command pub trait Command { fn execute(&self); } // ConcreteCommand for turning on the light pub struct TurnOnCommand { pub light: Rc>, } impl Command for TurnOnCommand { fn execute(&self) { self.light.borrow_mut().turn_on(); } } // ConcreteCommand for turning off the light pub struct TurnOffCommand { pub light: Rc>, } impl Command for TurnOffCommand { fn execute(&self) { self.light.borrow_mut().turn_off(); } } // Invoker pub struct RemoteControl{ command: Option>, } impl RemoteControl { pub fn new() -> Self { RemoteControl { command: None } } pub fn set_command(&mut self, command: Box) { self.command = Some(command); } pub fn press_button(&mut self) { if let Some(ref mut command) = self.command { command.execute(); } } } // Receiver pub struct Light { is_on: bool, } impl Light { pub fn new() -> Self { Light { is_on: false } } pub fn turn_on(&mut self) { self.is_on = true; println!("The light is on"); } pub fn turn_off(&mut self) { self.is_on = false; println!("The light is off"); } pub fn is_on(&self) -> bool { self.is_on } } // Client fn main() { let light = Rc::new(RefCell::new(Light::new())); let turn_on_command = TurnOnCommand { light: Rc::clone(&light) }; let turn_off_command = TurnOffCommand { light: Rc::clone(&light) }; let mut remote = RemoteControl::new(); remote.set_command(Box::new(turn_on_command)); remote.press_button(); println!("Light Status: {}", light.borrow().is_on()); remote.set_command(Box::new(turn_off_command)); remote.press_button(); println!("Light Status: {}", light.borrow().is_on()); } ``` -------------------------------- ### Rust Factory Method Pattern for Shape Creation Source: https://idiomatic-rust-snippets.org/patterns/creational/factory-method Demonstrates the Factory Method design pattern in Rust using traits and structs. It defines a `Shape` trait and concrete `Circle` and `Square` structs, along with corresponding `ShapeFactory` traits and implementations for creating these shapes. The `main` function shows how to use these factories to instantiate and draw different shapes. ```rust // Define the Shape trait trait Shape { fn draw(&self); } // Implement the Shape trait for Circle struct Circle; impl Shape for Circle { fn draw(&self) { println!("Drawing a Circle"); } } // Implement the Shape trait for Square struct Square; impl Shape for Square { fn draw(&self) { println!("Drawing a Square"); } } // Define the ShapeFactory trait trait ShapeFactory { fn create_shape(&self) -> Box; } // Implement the ShapeFactory trait for CircleFactory struct CircleFactory; impl ShapeFactory for CircleFactory { fn create_shape(&self) -> Box { Box::new(Circle) } } // Implement the ShapeFactory trait for SquareFactory struct SquareFactory; impl ShapeFactory for SquareFactory { fn create_shape(&self) -> Box { Box::new(Square) } } fn main() { // Create a Circle using CircleFactory let circle_factory = CircleFactory; let circle = circle_factory.create_shape(); circle.draw(); // Create a Square using SquareFactory let square_factory = SquareFactory; let square = square_factory.create_shape(); square.draw(); } ``` -------------------------------- ### Rust Struct Instance Creation with Associated `new` Function Source: https://idiomatic-rust-snippets.org/essentials/std-lib/new Illustrates the idiomatic Rust approach to creating struct instances using an associated function named `new`. This function acts as a constructor, taking necessary parameters to initialize and return a new instance of the struct. It does not rely on a `new` keyword, but rather on convention. ```rust struct MyStruct { value: i32, } impl MyStruct { // Associated function `new` to create an instance of `MyStruct` fn new(value: i32) -> MyStruct { MyStruct { value } } } fn main() { // Creating an instance of `MyStruct` using the `new` function let instance = MyStruct::new(10); println!("MyStruct value: {}", instance.value); } ``` -------------------------------- ### Enabling Features for a Crate Dependency Source: https://idiomatic-rust-snippets.org/essentials/packaging/features-compilation Illustrates how to specify which features to enable for a dependent crate in the Cargo.toml file. This controls the functionality included from the dependency. ```toml [dependencies] my_crate = { version = "1.0", features = ["feature1", "feature2"] } ``` -------------------------------- ### Generate Bcrypt Salt and Hash Password in Rust Source: https://idiomatic-rust-snippets.org/algorithms/cryptographic/bcrypt Demonstrates how to generate a random salt and simulate Bcrypt password hashing in Rust. It utilizes the `rand` crate for salt generation and a simplified hashing logic. For production use, a dedicated Bcrypt library is recommended. ```rust extern crate rand; use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; use std::time::{SystemTime, UNIX_EPOCH}; use std::convert::TryInto; const BCRYPT_COST: u32 = 12; const BCRYPT_SALT_LEN: usize = 16; const BCRYPT_HASH_LEN: usize = 24; fn generate_salt() -> String { let salt: String = thread_rng() .sample_iter(&Alphanumeric) .take(BCRYPT_SALT_LEN) .map(char::from) .collect(); salt } fn bcrypt_hash(password: &str, salt: &str) -> String { let mut hash = vec![0u8; BCRYPT_HASH_LEN]; let cost = BCRYPT_COST; let password_bytes = password.as_bytes(); let salt_bytes = salt.as_bytes(); // Simulate bcrypt hashing (this is a simplified version) for i in 0..BCRYPT_HASH_LEN { hash[i] = password_bytes[i % password_bytes.len()] ^ salt_bytes[i % salt_bytes.len()] ^ (cost as u8); } base64::encode(&hash) } fn main() { let password = "my_secure_password"; let salt = generate_salt(); let hashed_password = bcrypt_hash(password, &salt); println!("Password: {}", password); println!("Salt: {}", salt); println!("Hashed Password: {}", hashed_password); } ``` -------------------------------- ### Implement Quick Sort in Rust Source: https://idiomatic-rust-snippets.org/algorithms/sorting/quick Demonstrates the Quick Sort algorithm in Rust. It includes functions for sorting an array and partitioning it around a pivot. The implementation uses recursion for sub-array sorting. ```rust fn quick_sort(arr: &mut [i32]) { let len = arr.len(); if len < 2 { return; } let pivot_index = partition(arr); println!("Left array: {:?}", &arr[0..pivot_index]); println!("Right array: {:?}", &arr[pivot_index + 1..len]); quick_sort(&mut arr[0..pivot_index]); quick_sort(&mut arr[pivot_index + 1..len]); } fn partition(arr: &mut [i32]) -> usize { let len = arr.len(); // Pick the mid element as pivot let pivot_index = len / 2; arr.swap(pivot_index, len - 1); let mut store_index = 0; for i in 0..len - 1 { if arr[i] < arr[len - 1] { arr.swap(i, store_index); store_index += 1; } } arr.swap(store_index, len - 1); store_index } fn main() { let mut arr = [64, 34, 25, 12, 22, 12, 90, 33]; println!("Original array: {:?}", arr); quick_sort(&mut arr); println!("Sorted array: {:?}", arr); } ``` -------------------------------- ### Create a Vector in Rust Source: https://idiomatic-rust-snippets.org/essentials/types/vector Demonstrates how to create a new, empty vector or initialize a vector with values using the `Vec::new` method or the `vec!` macro. Vectors in Rust are dynamic arrays. ```Rust #![allow(unused)] fn main() { let mut v: Vec = Vec::new(); let v = vec![1, 2, 3, 4, 5]; } ``` -------------------------------- ### Disabling Default Features and Enabling Specific Ones Source: https://idiomatic-rust-snippets.org/essentials/packaging/features-compilation Shows how to explicitly disable a crate's default features and then enable only specific features. This provides fine-grained control over dependencies. ```toml [dependencies] my_crate = { version = "1.0", default-features = false, features = ["feature1"] } ``` -------------------------------- ### Define and Use Nested Rust Modules Source: https://idiomatic-rust-snippets.org/essentials/core-concepts/module Illustrates how to create nested modules in Rust, allowing for further organization of code. It shows how to access functions in deeply nested modules. ```rust mod outer_module { pub mod inner_module { pub fn say_hello() { println!("Hello from inner_module!"); } } } fn main() { outer_module::inner_module::say_hello(); } ```