### Start evcxr_repl Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch02-getting-started.md Command to start the interactive Rust REPL after installation. ```bash evcxr ``` -------------------------------- ### Install and Run cargo-careful Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch05-miri-valgrind-and-sanitizers-verifying-u.md Instructions for installing `cargo-careful` and running tests or binaries with its extra undefined behavior checks. ```bash # Install (requires nightly, but runs your code at near-native speed) cargo install cargo-careful # Run tests with extra UB checks (catches uninitialized memory, invalid values) cargo +nightly careful test # Run a binary with extra checks cargo +nightly careful run -- --run-diagnostics ``` -------------------------------- ### Rust Cross-Compilation Setup Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch08-crates-and-modules.md Install a cross-compilation target using 'rustup target add' and then build for that target using 'cargo build --target'. ```bash # Install a cross-compilation target rustup target add aarch64-unknown-linux-gnu # Cross-compile cargo build --target aarch64-unknown-linux-gnu --release ``` -------------------------------- ### Rust Module-Level Documentation Source: https://github.com/microsoft/rusttraining/blob/main/rust-patterns-book/src/ch15-crate-architecture-and-api-design.md Illustrates using `//!` for documentation at the module or crate level, providing an overview and quick start guide for a diagnostic framework. ```rust //! # Diagnostic Framework //! //! This crate provides the core diagnostic execution engine. //! It supports running diagnostic tests, collecting results, //! and reporting to the BMC via IPMI. //! //! ## Quick Start //! //! ```no_run //! use diag_framework::Framework; //! //! let mut fw = Framework::new("config.json")?; //! fw.run_all_tests()?; //! ``` ``` -------------------------------- ### Install Zig and `cargo-zigbuild` Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch02-cross-compilation-one-source-many-target.md Installs the Zig programming language, which provides a convenient cross-compilation linker, and the `cargo-zigbuild` helper tool. Zig is distributed as a single binary, simplifying installation. ```bash # Install Zig (single binary, no package manager needed) # Download from https://ziglang.org/download/ # Or via package manager: sudo snap install zig --classic --beta # Ubuntu brew install zig # macOS # Install cargo-zigbuild cargo install cargo-zigbuild ``` -------------------------------- ### Python Package Installation with pip Source: https://github.com/microsoft/rusttraining/blob/main/python-book/src/ch08-crates-and-modules.md Demonstrates common pip commands for installing packages from PyPI, specifying version constraints, and managing environments with `requirements.txt`. ```bash # Python pip install requests # Install from PyPI pip install "requests>=2.28" # Version constraint pip freeze > requirements.txt # Lock versions pip install -r requirements.txt # Reproduce environment ``` -------------------------------- ### Usage Example for Diagnostic Session Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch12-exercises.md Demonstrates how to instantiate, start, run tests, and finish a diagnostic session. It highlights the compile-time errors that occur if a test token is reused or if reporting is attempted before completion. ```rust // Usage: // let session = DiagSession::new("GPU stress"); // let (mut session, tokens) = session.start(&["vram", "compute", "thermal"]); // for token in tokens { // session = session.run_test(token); // } // let session = session.finish(); // println!("{}", session.report()); // "GPU stress: 3/3 passed" // // // These would NOT compile: // // session.run_test(used_token); → ERROR: use of moved value // // running_session.report(); → ERROR: no method `report` on DiagSession ``` -------------------------------- ### Rust Fetch Data Async Example with Tokio Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch13-1-asyncawait-deep-dive.md Illustrates asynchronous data fetching in Rust using the reqwest library and the tokio runtime. Requires an explicit runtime setup via #[tokio::main]. ```rust // Rust — No built-in async runtime. You choose an executor. // The most popular is tokio. async fn fetch_data(url: &str) -> Result { let body = reqwest::get(url).await?.text().await?; Ok(body) } // You MUST have a runtime to execute async code: #[tokio::main] // This macro sets up the tokio runtime async fn main() { let data = fetch_data("https://example.com").await.unwrap(); println!("{}", &data[..100]); } ``` -------------------------------- ### Crate Module Structure Example Source: https://github.com/microsoft/rusttraining/blob/main/rust-patterns-book/src/ch15-crate-architecture-and-api-design.md Illustrates a typical directory layout for a Rust crate, including source files, tests, benchmarks, and examples. ```text my_crate/ ├── Cargo.toml ├── src/ │ ├── lib.rs # Crate root — re-exports and public API │ ├── config.rs # Feature module │ ├── parser/ # Complex module with sub-modules │ │ ├── mod.rs # or parser.rs at parent level (Rust 2018+) │ │ ├── lexer.rs │ │ └── ast.rs │ ├── error.rs # Error types │ └── utils.rs # Internal helpers (pub(crate)) ├── tests/ │ └── integration.rs # Integration tests ├── benches/ │ └── perf.rs # Benchmarks └── examples/ └── basic.rs # cargo run --example basic ``` -------------------------------- ### Install and Initialize cargo-deny Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch06-dependency-management-and-supply-chain-s.md Install `cargo-deny` for comprehensive policy enforcement across advisories, licenses, bans, and sources. Use `cargo deny init` to create a documented `deny.toml` configuration file. ```bash cargo install cargo-deny ``` ```bash cargo deny init ``` -------------------------------- ### Install mdbook and mdbook-mermaid Source: https://github.com/microsoft/rusttraining/blob/main/README.md Install the required tools for building and serving the Rust Training books locally. ```bash cargo install mdbook@0.4.52 mdbook-mermaid@0.14.0 ``` -------------------------------- ### Install Git Hooks Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch11-putting-it-all-together-a-production-cic.md Installs git hooks by configuring the core.hooksPath and making the pre-commit script executable. ```bash git config core.hooksPath .githooks chmod +x .githooks/pre-commit ``` -------------------------------- ### Install Rust Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch02-getting-started.md Installs Rust using the official script. This command works across Windows, macOS, and Linux. ```bash # Install Rust (works on Windows, macOS, Linux) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # On Windows, you can also download from: https://rustup.rs/ ``` -------------------------------- ### Install and Initialize cargo-fuzz Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch05-miri-valgrind-and-sanitizers-verifying-u.md Install the `cargo-fuzz` tool globally and initialize a new fuzz target for your project. This sets up the necessary files and configurations for fuzzing. ```bash # Install cargo install cargo-fuzz # Initialize a fuzz target cargo fuzz init cargo fuzz add parse_gpu_csv ``` -------------------------------- ### Build New Services in Rust: Authentication Service Example Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch15-2-incremental-adoption-strategy.md Example of an authentication service built with Axum, JWT, and bcrypt for password verification. Requires database connection and JWT secret. ```rust // Build new services from scratch in Rust // Example: Authentication service use axum::{ extract::{Query, State}, http::StatusCode, response::Json, routing::{get, post}, Router, }; use jsonwebtoken::{encode, decode, Header, Validation, EncodingKey, DecodingKey}; use serde::{Deserialize, Serialize}; use sqlx::{Pool, Postgres}; use uuid::Uuid; use bcrypt::{hash, verify, DEFAULT_COST}; #[derive(Clone)] struct AppState { db: Pool, jwt_secret: String, } #[derive(Serialize, Deserialize)] struct Claims { sub: String, exp: usize, } #[derive(Deserialize)] struct LoginRequest { email: String, password: String, } #[derive(Serialize)] struct LoginResponse { token: String, user_id: Uuid, } async fn login( State(state): State, Json(request): Json, ) -> Result, StatusCode> { // Note: sqlx::query!() is compile-time checked and requires DATABASE_URL // pointing to a live database during build. For runtime-checked queries, // use sqlx::query() or sqlx::query_as() instead. let user = sqlx::query!( "SELECT id, password_hash FROM users WHERE email = $1", request.email ) .fetch_optional(&state.db) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let user = user.ok_or(StatusCode::UNAUTHORIZED)?; if !verify(&request.password, &user.password_hash) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? { return Err(StatusCode::UNAUTHORIZED); } let claims = Claims { sub: user.id.to_string(), exp: (chrono::Utc::now() + chrono::Duration::hours(24)).timestamp() as usize, }; let token = encode( &Header::default(), &claims, &EncodingKey::from_secret(state.jwt_secret.as_ref()), ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok(Json(LoginResponse { token, user_id: user.id, })) } #[tokio::main] async fn main() -> Result<(), Box> { let database_url = std::env::var("DATABASE_URL")?; let jwt_secret = std::env::var("JWT_SECRET")?; let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(20) .connect(&database_url) .await?; let app_state = AppState { db: pool, jwt_secret, }; let app = Router::new() .route("/login", post(login)) .with_state(app_state); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?; axum::serve(listener, app).await?; Ok(()) } ``` -------------------------------- ### Install Rust using rustup Source: https://github.com/microsoft/rusttraining/blob/main/python-book/src/ch02-getting-started.md Use this command to install the Rust toolchain on Linux, macOS, or WSL. It includes the compiler and Cargo build tool. ```bash # Install Rust via rustup (Linux/macOS/WSL) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ```bash # Verify installation rustc --version # Rust compiler cargo --version # Build tool + package manager (like pip + setuptools combined) ``` ```bash # Update Rust rustup update ``` -------------------------------- ### Server Startup and Handler Simulation Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch18-redfish-server-walkthrough.md This `main` function demonstrates the initialization of various data sources and simulates a call to the `handle_get_computer_system` handler. It prints the resulting JSON response, with a note to handle errors appropriately in production. ```rust // ──── Server Startup ──── fn main() { // Initialize all data sources — each returns an availability token let smbios = init_smbios(); let sensors = init_sensors(); let sel = init_sel(); // Simulate handler call let response = handle_get_computer_system( &smbios, &sensors, &sel, PowerStateValue::On, Some("2.10.1".into()), ); // NOTE: .unwrap() is used for brevity — handle errors in production. println!("{}", serde_json::to_string_pretty(&response).unwrap()); } ``` -------------------------------- ### Install cargo-husky Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch11-putting-it-all-together-a-production-cic.md Installs the cargo-husky tool, which can automate the setup of git hooks via a build script. ```bash cargo install cargo-husky ``` -------------------------------- ### Rust Deployment Example Source: https://github.com/microsoft/rusttraining/blob/main/python-book/src/ch01-introduction-and-motivation.md Illustrates how to build and deploy a Rust application as a single static binary or within a minimal Docker image. This approach avoids Python runtimes and dependencies, resulting in small binary sizes and fast startup times. ```rust // Rust deployment: single static binary, no runtime needed // cargo build --release → one binary, ~5-20 MB // Copy it anywhere — no Python, no venv, no dependencies // Docker image: ~5 MB (from scratch or distroless) // FROM scratch // COPY target/release/my_app /my_app // CMD ["/my_app"] // Startup time: <1ms // Cross-compile: cargo build --target x86_64-unknown-linux-musl ``` -------------------------------- ### Full Firmware Update Sequence Example Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch17-redfish-applied-walkthrough.md Demonstrates the complete, type-safe firmware update workflow, chaining the push, verify, apply, and reboot operations in the correct order. ```rust // ── Usage ── fn update_bmc_firmware( session: &RedfishSession, manager_proof: &ConfigureManagerToken, image: &[u8], ) -> Result<(), RedfishError> { // Each step returns the next state — the old state is consumed let uploaded = FirmwareUpdate::push_image(session, manager_proof, image)?; let verified = uploaded.verify()?; let needs_reboot = verified.apply()?; needs_reboot.reboot(session, manager_proof)?; // ❌ Compile error: use of moved value `verified` // verified.apply()?; // ❌ Compile error: FirmwareUpdate has no .apply() method // uploaded.apply()?; // must verify first! // ❌ Compile error: push_image requires &ConfigureManagerToken // FirmwareUpdate::push_image(session, &login_token, image)?; Ok(()) } ``` -------------------------------- ### Serve Rust Training Books Locally Source: https://github.com/microsoft/rusttraining/blob/main/README.md Clone the repository, install necessary tools, and serve the books locally for offline reading or development. ```bash git clone https://github.com/microsoft/RustTraining.git cd RustTraining cargo install mdbook mdbook-mermaid cargo xtask serve # http://localhost:3000 ``` -------------------------------- ### Basic Cargo Embed Command Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch15-1-embedded-deep-dive.md This command flashes the specified chip and opens the RTT console. It's the simplest way to get started with probe-rs. ```bash cargo embed --chip STM32F401RE ``` -------------------------------- ### Example of a Complete ComputerSystemBuilder Build Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch18-redfish-server-walkthrough.md Demonstrates how to correctly use the builder with all required fields set, including optional ones, to successfully build a ComputerSystem object. This showcases the type-state enforcement where .build() is available. ```rust ComputerSystemBuilder::new() .name("PowerEdge R750".into()) .uuid("4c4c4544-...".into()) .power_state(PowerStateValue::On) .status(ResourceStatus { ... }) .manufacturer("Dell".into()) .build("1") ``` -------------------------------- ### Typestate Builder Pattern Example Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch13-reference-card.md Shows the 'Typestate Builder' pattern with `DerBuilder`. This prevents incomplete construction by guiding the builder through necessary states. ```rust DerBuilder ``` -------------------------------- ### PyO3 Project Setup and Configuration Source: https://github.com/microsoft/rusttraining/blob/main/python-book/src/ch14-unsafe-rust-and-ffi.md Shows the necessary commands to initialize a PyO3 project and the essential configurations in `Cargo.toml` for creating a Python extension. ```bash # Setup pip install maturin # Build tool for Rust Python extensions maturin init # Creates project structure # Project structure: # my_extension/ # ├── Cargo.toml # ├── pyproject.toml # └── src/ # └── lib.rs ``` ```toml # Cargo.toml [package] name = "my_extension" version = "0.1.0" edition = "2021" [lib] crate-type = ["cdylib"] # Shared library for Python [dependencies] pyo3 = { version = "0.22", features = ["extension-module"] } ``` -------------------------------- ### Lifetime Elision Rule 1 Example Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch07-1-lifetimes-and-borrowing-deep-dive.md Illustrates the first lifetime elision rule where each input reference gets its own lifetime parameter. The compiler infers `'a` for the input `&str`. ```rust // What you write: fn first_word(s: &str) -> &str { ... } // What the compiler sees after Rule 1: fn first_word<'a>(s: &'a str) -> &str { ... } // Only one input lifetime → Rule 2 applies ``` -------------------------------- ### Build and Serve All Rust Training Books Source: https://github.com/microsoft/rusttraining/blob/main/README.md Build all books in the repository and serve them locally for preview. The site will be available at http://localhost:3000. ```bash cargo xtask build # Build all books into site/ (local preview) cargo xtask serve # Build and serve at http://localhost:3000 cargo xtask deploy # Build all books into docs/ (for GitHub Pages) cargo xtask clean # Remove site/ and docs/ ``` -------------------------------- ### Firmware Update Workflow Example Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch05-protocol-state-machines-type-state-for-r.md Demonstrates a typical usage of the FwUpdate FSM, showing the correct sequence of calls and highlighting compile-time errors for invalid transitions or misuse of tokens. ```rust fn firmware_workflow() { let fw = FwUpdate::new(); // fw.finish_upload(); // ❌ no method `finish_upload` on FwUpdate let admin = FirmwareAdminToken { _private: () }; // from auth system let fw = fw.begin_upload(&admin, "2.10.1"); let fw = fw.finish_upload(); let digest = [0xAB; 32]; // computed during verification let (fw, token) = fw.verify_ok(digest); let fw = fw.apply(token); // fw.apply(token); // ❌ use of moved value: `token` let fw = fw.apply_complete(); fw.reboot(); } ``` -------------------------------- ### Refactor Async Handler: Original Code Source: https://github.com/microsoft/rusttraining/blob/main/async-book/src/ch14-async-is-an-optimization-not-an-architecture.md The original axum handler mixes business logic with I/O operations. This example serves as the starting point for refactoring into a synchronous core and an asynchronous shell. ```rust use axum::{Json, extract::Path}; async fn get_device_report(Path(device_id): Path) -> Result, AppError> { // Fetch raw telemetry from the device over HTTP let raw = reqwest::get(format!("http://bmc-{device_id}/telemetry")) .await?; .json::() .await?; // Business logic: convert raw sensor readings to calibrated values let mut readings = Vec::new(); for sensor in &raw.sensors { let calibrated = (sensor.raw_value as f64) * sensor.scale + sensor.offset; if calibrated < sensor.min_valid || calibrated > sensor.max_valid { return Err(AppError::SensorOutOfRange { name: sensor.name.clone(), value: calibrated, }); } readings.push(CalibratedReading { name: sensor.name.clone(), value: calibrated, unit: sensor.unit.clone(), }); } // Business logic: classify device health let critical_count = readings.iter() .filter(|r| r.value > 90.0) .count(); let health = if critical_count > 2 { Health::Critical } else if critical_count > 0 { Health::Warning } else { Health::Ok }; // Fetch device metadata from inventory service let meta = reqwest::get(format!("http://inventory/devices/{device_id}")) .await?; .json::() .await?; Ok(Json(Report { device_id, device_name: meta.name, health, readings, timestamp: chrono::Utc::now(), })) } ``` -------------------------------- ### Compiler Warning for Unused `#[must_use]` Value Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch11-fourteen-tricks-from-the-trenches.md This example shows the compiler output when a value marked with `#[must_use]` is intentionally ignored. The warning includes a custom message specified in the attribute, guiding the developer on the correct usage. ```text warning: unused `CalibrationToken` that must be used --> src/main.rs:5:5 | 5 | CalibrationToken { _private: () }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: calibration token must be passed to calibrate(), not dropped ``` -------------------------------- ### Rust Safe Vec Access with Option and Match Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/RustBootstrapForCSharp.md Shows Rust's idiomatic safe access to Vec using `get()` which returns an Option. Examples include using `match` for explicit handling and `unwrap_or` for providing a default value. ```rust // Rust - Option-based safe access fn safe_access(vec: &Vec, index: usize) -> Option { vec.get(index).copied() // Returns Option } fn main() { let vec = vec![1, 2, 3]; // Safe access patterns match vec.get(10) { Some(value) => println!("Value: {}", value), None => println!("Index out of bounds"), } // Or with unwrap_or let value = vec.get(10).copied().unwrap_or(-1); println!("Value: {}", value); } ``` -------------------------------- ### Task Transition Implementation Example Source: https://github.com/microsoft/rusttraining/blob/main/rust-patterns-book/src/ch19-capstone-project.md Provides an example implementation for transitioning a Task from the Pending state to the Running state. This method consumes the current task instance and returns a new instance with the updated state. ```rust impl Task { fn start(self) -> Task { Task { id: self.id, name: self.name, _state: PhantomData, _result: PhantomData, } } } ``` -------------------------------- ### Full SEL Pipeline: Raw Bytes to Redfish Health Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch07-validated-boundaries-parse-dont-validate.md This example demonstrates a complete data processing pipeline, starting from raw SEL bytes and transforming them into structured, typed health summaries suitable for Redfish integration. It showcases parsing, classification, linearization, and aggregation steps. ```rust use std::collections::HashMap; fn full_sel_pipeline() { // ── Raw SEL data from BMC ── let raw_entries: Vec<[u8; 16]> = vec![ // Memory correctable ECC on sensor #3 [0x01,0x00, 0x02, 0x00,0x00,0x00,0x00, 0x20,0x00, 0x04, 0x0C, 0x03, 0x6F, 0x00, 0x00,0x00], // Temperature upper critical on sensor #1, reading=95, threshold=90 [0x02,0x00, 0x02, 0x00,0x00,0x00,0x00, 0x20,0x00, 0x04, 0x01, 0x01, 0x01, 0x09, 0x5F,0x5A], // PSU failure on sensor #5 [0x03,0x00, 0x02, 0x00,0x00,0x00,0x00, 0x20,0x00, 0x04, 0x08, 0x05, 0x6F, 0x01, 0x00,0x00], ]; // ── Step 0: Parse at the boundary (ch07 TryFrom) ── let records: Vec = raw_entries.iter() .filter_map(|raw| ValidSelRecord::try_from(RawSelRecord(*raw)).ok()) .collect(); // ── Step 1-3: Classify + linearize + aggregate ── let mut sdr_table = HashMap::new(); sdr_table.insert(1u8, SdrLinearization { sensor_type: SensorType::Temperature, m: 1, b: 0, r_exp: 0, b_exp: 0, // 1:1 mapping for this example }); let summary = summarize_sel(&records, &sdr_table); // ── Result: structured, typed, Redfish-ready ── println!("SEL Summary:"); println!(" Total entries: {}", summary.total_entries); println!(" Processor: {:?}", summary.processor_health); // OK println!(" Memory: {:?}", summary.memory_health); // OK (correctable → OK) println!(" Power: {:?}", summary.power_health); // Critical (PSU failure) println!(" Thermal: {:?}", summary.thermal_health); // Critical (upper critical) println!(" Fan: {:?}", summary.fan_health); // OK println!(" Security: {:?}", summary.security_health); // OK // Dimensional readings preserved from threshold events: for r in &summary.threshold_readings { println!(" Threshold: sensor {:?} #{} — {:?} crossed {:?}", r.sensor_type, r.sensor_number, r.trigger_reading, r.crossing); // trigger_reading is LinearizedReading::Temperature(Celsius(95.0)) // — not a raw byte, not an untyped f64 } // ── This summary feeds directly into ch18's health rollup ── // compute_system_health() can now use per-subsystem values // instead of a single `has_critical_events: bool` } ``` -------------------------------- ### Exercise 1: Audit Dependencies Solution Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch06-dependency-management-and-supply-chain-s.md This solution provides the commands to run `cargo audit` and `cargo deny` for auditing dependencies, checking advisories, and listing license categories. It also shows how to interpret the output. ```bash cargo audit # Note any advisories — often chrono, time, or older crates cargo deny init cargo deny list # Shows license breakdown: MIT (N), Apache-2.0 (N), etc. cargo deny check # Shows full audit across all four dimensions ``` -------------------------------- ### Install hyperfine Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch03-benchmarking-measuring-what-matters.md Installs the `hyperfine` command-line benchmarking tool. It can be installed via cargo or system package managers. ```bash # Install cargo install hyperfine # Or: sudo apt install hyperfine (Ubuntu 23.04+) ``` -------------------------------- ### Install the `cross` Tool Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch02-cross-compilation-one-source-many-target.md Installs the `cross` utility, a tool that simplifies cross-compilation by leveraging Docker containers with pre-configured toolchains. It can be installed from crates.io or directly from its Git repository. ```bash cargo install cross # Or from git for latest features (less stable): # cargo install cross --git https://github.com/cross-rs/cross ``` -------------------------------- ### Usage Example: Handling ComputerSystem Reset Source: https://github.com/microsoft/rusttraining/blob/main/type-driven-correctness-book/src/ch18-redfish-server-walkthrough.md Demonstrates how to use the `dispatch_action` function to handle an incoming `ComputerSystemReset` action. Shows how serde errors prevent `execute` from being called with invalid or incomplete payloads. ```rust // ── Usage ── fn handle_reset_action(body: &str) -> Result<(), RedfishError> { // Type-safe: ResetParams is validated by serde before execute() dispatch_action(&ComputerSystemReset, body)?; Ok(()) // Invalid JSON: {"ResetType": "Explode"} // → serde error: "unknown variant `Explode`" // → execute() never called // Missing field: {} // → serde error: "missing field `ResetType`" // → execute() never called } ``` -------------------------------- ### Install Valgrind Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch05-miri-valgrind-and-sanitizers-verifying-u.md Commands to install Valgrind on Debian/Ubuntu and Fedora systems. ```bash # Install Valgrind sudo apt install valgrind # Debian/Ubuntu sudo dnf install valgrind # Fedora ``` -------------------------------- ### C# Project Structure Example Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch08-crates-and-modules.md Illustrates a typical C# project directory structure, showing organization of models, services, controllers, and the main program file. ```text MyApp/ ├── MyApp.csproj ├── Models/ │ ├── User.cs │ └── Product.cs ├── Services/ │ ├── UserService.cs │ └── ProductService.cs ├── Controllers/ │ └── ApiController.cs └── Program.cs ``` -------------------------------- ### Tokio Quick Start with Tasks and Join Source: https://github.com/microsoft/rusttraining/blob/main/rust-patterns-book/src/ch16-asyncawait-essentials.md Demonstrates how to use Tokio to spawn concurrent tasks and wait for their completion using `tokio::join!`. Ensure you have `tokio` with the `full` feature enabled in your `Cargo.toml`. ```toml [dependencies] tokio = { version = "1", features = ["full"] } ``` ```rust use tokio::time::{sleep, Duration}; use tokio::task; #[tokio::main] async fn main() { let handle_a = task::spawn(async { sleep(Duration::from_millis(100)).await; "task A done" }); let handle_b = task::spawn(async { sleep(Duration::from_millis(50)).await; "task B done" }); let (a, b) = tokio::join!(handle_a, handle_b); println!("{}, {}", a.unwrap(), b.unwrap()); } ``` -------------------------------- ### Install cargo-hack Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch09-no-std-and-feature-verification.md Installs the `cargo-hack` tool, which is used for systematic feature verification. ```bash cargo install cargo-hack ``` -------------------------------- ### Install cargo-tarpaulin Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch04-code-coverage-seeing-what-tests-miss.md Install the cargo-tarpaulin tool, a Linux-specific coverage tool that is simpler to set up. ```bash cargo install cargo-tarpaulin ``` -------------------------------- ### Rust Application Entry Point and Usage Example Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/RustTrainingForCSharp.md Demonstrates the main function for a Rust application, analogous to a C# Main method. It initializes logging, creates a `UserService` instance, and calls its methods to create and retrieve a user asynchronously. Includes necessary imports and error handling. ```Rust use serde::{Deserialize, Serialize}; use reqwest; use tokio; use thiserror::Error; use chrono::{DateTime, Utc}; use uuid::Uuid; // Data models (like C# POCOs with attributes) #[derive(Debug, Clone, Serialize, Deserialize)] pub struct User { pub id: Uuid, pub name: String, pub email: String, #[serde(with = "chrono::serde::ts_seconds")] pub created_at: DateTime, } // Custom error types (like custom exceptions) #[derive(Error, Debug)] pub enum ApiError { #[error("HTTP request failed: {0}")] Http(#[from] reqwest::Error), #[error("Serialization failed: {0}")] Serialization(#[from] serde_json::Error), #[error("User not found: {id}")] UserNotFound { id: Uuid }, #[error("Validation failed: {message}")] Validation { message: String }, } // Service class equivalent pub struct UserService { client: reqwest::Client, base_url: String, } impl UserService { pub fn new(base_url: String) -> Self { let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(30)) .build() .expect("Failed to create HTTP client"); UserService { client, base_url } } // Async method (like C# async Task) pub async fn get_user(&self, id: Uuid) -> Result { let url = format!("{}/users/{}", self.base_url, id); let response = self.client .get(&url) .send() .await?; if response.status() == 404 { return Err(ApiError::UserNotFound { id }); } let user = response.json::().await?; Ok(user) } // Create user (like C# async Task) pub async fn create_user(&self, name: String, email: String) -> Result { if name.trim().is_empty() { return Err(ApiError::Validation { message: "Name cannot be empty".to_string(), }); } let new_user = User { id: Uuid::new_v4(), name, email, created_at: Utc::now(), }; let response = self.client .post(&format!("{}/users", self.base_url)) .json(&new_user) .send() .await?; let created_user = response.json::().await?; Ok(created_user) } } // Usage example (like C# Main method) #[tokio::main] async fn main() -> Result<(), ApiError> { // Initialize logging (like configuring ILogger) env_logger::init(); let service = UserService::new("https://api.example.com".to_string()); // Create user let user = service.create_user( "John Doe".to_string(), "john@example.com".to_string(), ).await?; println!("Created user: {:?}", user); // Get user let retrieved_user = service.get_user(user.id).await?; println!("Retrieved user: {:?}", retrieved_user); Ok(()) } ``` -------------------------------- ### Rust Module File Structure Example Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch08-crates-and-modules.md Shows a typical Rust project's source directory structure, including how modules are organized using `mod.rs` and separate files. ```text my_app/ ├── Cargo.toml └── src/ ├── main.rs (or lib.rs) ├── models/ │ ├── mod.rs // Module declaration │ ├── user.rs │ └── product.rs ├── services/ │ ├── mod.rs // Module declaration │ ├── user_service.rs │ └── product_service.rs └── controllers/ ├── mod.rs └── api_controller.rs ``` -------------------------------- ### Install Cross-Linker Toolchain Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch02-cross-compilation-one-source-many-target.md Install the GCC toolchain for a specific architecture, such as aarch64, when the cross-linker is not found. ```bash sudo apt install gcc-aarch64-linux-gnu ``` -------------------------------- ### Install QEMU for Cross-Compiled Testing Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch02-cross-compilation-one-source-many-target.md Installs QEMU user-mode emulation tools, which allow running binaries compiled for different architectures on your current host system. This is essential for testing cross-compiled code without dedicated hardware. ```bash sudo apt install qemu-user qemu-user-static binfmt-support ``` -------------------------------- ### Install grcov Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch04-code-coverage-seeing-what-tests-miss.md Install grcov, Mozilla's coverage aggregator tool, using cargo. ```bash cargo install grcov ``` -------------------------------- ### Tokio Runtime Example Source: https://github.com/microsoft/rusttraining/blob/main/async-book/src/ch07-executors-and-runtimes.md Demonstrates fetching a URL and reading a file concurrently using the tokio runtime. Requires the 'full' features for tokio. ```rust // ----- tokio version ----- // Cargo.toml: tokio = { version = "1", features = ["full"] } #[tokio::main] async fn main() { let (url_result, file_result) = tokio::join!( async { tokio::time::sleep(std::time::Duration::from_millis(100)).await; "Response from URL" }, async { tokio::time::sleep(std::time::Duration::from_millis(50)).await; "Contents of file" }, ); println!("URL: {url_result}, File: {file_result}"); } ``` -------------------------------- ### Install cargo-dist Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch11-putting-it-all-together-a-production-cic.md Installs the cargo-dist tool, which is used to generate downloadable release binaries for GitHub Releases. ```bash # Install cargo install cargo-dist ``` -------------------------------- ### Rust Project Setup and Dependencies Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch17-capstone-project.md Initializes a new Rust project using Cargo and specifies necessary dependencies in Cargo.toml for building a CLI application. Includes equivalents for C# project setup. ```bash cargo new weather-cli cd weather-cli ``` ```toml [package] name = "weather-cli" version = "0.1.0" edition = "2021" [dependencies] clap = { version = "4", features = ["derive"] } # CLI args (like System.CommandLine) reqwest = { version = "0.12", features = ["json"] } # HTTP client (like HttpClient) serde = { version = "1", features = ["derive"] } # Serialization (like System.Text.Json) serde_json = "1" thiserror = "2" # Error types tokio = { version = "1", features = ["full"] } # Async runtime ``` ```csharp // C# equivalent dependencies: // dotnet add package System.CommandLine // dotnet add package System.Net.Http.Json // (System.Text.Json and HttpClient are built-in) ``` -------------------------------- ### Install cargo-release Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch11-putting-it-all-together-a-production-cic.md Installs the cargo-release tool, used for automating version bumping, tagging, and publishing crates. ```bash # Install cargo install cargo-release ``` -------------------------------- ### C# Configuration Class with Constructors Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch05-1-constructor-patterns.md Demonstrates default and parameterized constructors, along with a factory method for creating a specific configuration instance in C#. ```csharp public class Configuration { public string DatabaseUrl { get; set; } public int MaxConnections { get; set; } public bool EnableLogging { get; set; } // Default constructor public Configuration() { DatabaseUrl = "localhost"; MaxConnections = 10; EnableLogging = false; } // Parameterized constructor public Configuration(string databaseUrl, int maxConnections) { DatabaseUrl = databaseUrl; MaxConnections = maxConnections; EnableLogging = false; } // Factory method public static Configuration ForProduction() { return new Configuration("prod.db.server", 100) { EnableLogging = true }; } } ``` -------------------------------- ### Install cargo-llvm-cov Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch04-code-coverage-seeing-what-tests-miss.md Install the cargo-llvm-cov tool using cargo or as a rustup component for raw LLVM tools. ```bash cargo install cargo-llvm-cov ``` ```bash rustup component add llvm-tools-preview ``` -------------------------------- ### Recommended Cargo Deny and Audit Setup Source: https://github.com/microsoft/rusttraining/blob/main/engineering-book/src/ch06-dependency-management-and-supply-chain-s.md Add these commands to your CI pipeline for comprehensive dependency security checks. `cargo deny init` is a one-time setup, while `check` and `audit` should run regularly. ```bash # Add to CI pipeline: cargo deny init # One-time setup cargo deny check # Every PR — licenses, advisories, bans cargo audit --deny warnings # Every push — vulnerability scanning cargo outdated --workspace # Weekly — track available updates ``` -------------------------------- ### Install evcxr_repl Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch02-getting-started.md Command to install the Rust REPL tool. This allows for interactive Rust code execution. ```bash cargo install --locked evcxr_repl ``` -------------------------------- ### C# Project Configuration (.csproj) Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch02-getting-started.md Example of a C# project file (.csproj) showing output type, target framework, and package references for libraries like Newtonsoft.Json and Serilog. ```xml Exe net8.0 ``` -------------------------------- ### Rust Configuration with Serde and Environment Variables Source: https://github.com/microsoft/rusttraining/blob/main/csharp-book/src/ch15-migration-patterns-and-case-studies.md Illustrates loading application settings in Rust using the `config` crate, supporting configuration files and environment variables. Requires `serde` for deserialization. ```rust use config::{Config, ConfigError, Environment, File}; use serde::Deserialize; #[derive(Debug, Deserialize)] struct AppSettings { database_url: String, port: u16, } impl AppSettings { pub fn new() -> Result { let s = Config::builder() .add_source(File::with_name("config/default")) .add_source(Environment::with_prefix("APP")) .build()?; s.try_deserialize() } } // Usage let settings = AppSettings::new()?; ``` -------------------------------- ### Install probe-rs Tools Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch15-1-embedded-deep-dive.md Installs the `probe-rs` toolchain, which includes `cargo-flash` and `cargo-embed`, for debugging embedded Rust applications. ```Bash cargo install probe-rs-tools ``` -------------------------------- ### Install Rust on Linux/WSL Source: https://github.com/microsoft/rusttraining/blob/main/c-cpp-book/src/ch02-getting-started.md Command to install Rust using the official script on Linux or Windows Subsystem for Linux. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ```