### Bad Rust Documentation Example Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md This example shows a Rust function with documentation that includes implementation details like opening connections, starting transactions, and specific SQL queries. Such details are prone to change and are not essential for the user to know. ```rust // bad /// Saves a `User` record to the Postgres database. /// /// This function opens a new connection and begins a transaction. It checks /// if a user with the given ID exists with a `SELECT` query. If a user is /// not found, performs an `INSERT`. /// /// # Errors /// /// Returns an error if any database operation fails. pub fn save_user(user: &User) -> Result<(), db::Error> { // ... } ``` -------------------------------- ### Clone and Set Up Comprehensive Rust Project Source: https://github.com/google/comprehensive-rust/blob/main/src/unsafe-deep-dive/setup.md Clone the Comprehensive Rust repository and install necessary tools. Then, start a local development server to view the course materials in a browser. ```console $ git clone --depth=1 https://github.com/google/comprehensive-rust.git Cloning into 'comprehensive-rust'... ... $ cd comprehensive-rust $ cargo install-tools ... $ cargo serve # then open http://127.0.0.1:3000/ in a browser ``` -------------------------------- ### Start Embedded Application with Debugging Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/microcontrollers/debugging.md Run this command in the terminal from your project's example directory to build and flash the board support binary, making it ready for debugging. ```sh cargo embed --bin board_support debug ``` -------------------------------- ### Install Bare Metal Development Tools on Linux Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal.md Installs necessary tools like GDB, picocom, QEMU, and Rust toolchains for bare-metal development on Linux. Also installs probe-rs for debugging. ```bash sudo apt install gdb-multiarch libudev-dev picocom pkg-config qemu-system-arm build-essential rustup update rustup target add aarch64-unknown-none thumbv7em-none-eabihf rustup component add llvm-tools-preview cargo install cargo-binutils curl --proto '=https' --tlsv1.2 -LsSf https://github.com/probe-rs/probe-rs/releases/latest/download/probe-rs-tools-installer.sh | sh ``` -------------------------------- ### Install Dprint on Linux Source: https://github.com/google/comprehensive-rust/blob/main/CONTRIBUTING.md Instructions for installing the dprint formatting tool on Linux systems via their official installation instructions. ```bash sudo apt install yapf3 gettext texlive texlive-luatex texlive-lang-cjk texlive-lang-arabic librsvg2-bin fonts-noto ``` -------------------------------- ### Example of HAL Crate Usage Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/microcontrollers/hals.md This example demonstrates basic interaction with microcontroller peripherals using HAL crates. It requires the `embedded-hal` crate and specific HAL implementations for your target microcontroller. The example is intended to be compiled with `cargo embed --bin hal`. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use embedded_hal::digital::v2::OutputPin; // Assume `led` is an instance of a type that implements `OutputPin` // For example, a GPIO pin configured as an output. // let mut led: SomeLedType; // Turn the LED on // led.set_high().unwrap(); // Turn the LED off // led.set_low().unwrap(); ``` -------------------------------- ### Install Bare Metal Development Tools on macOS Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal.md Installs essential tools like GDB, picocom, QEMU, and Rust toolchains for bare-metal development on macOS. Also installs probe-rs for debugging. ```bash xcode-select --install brew install gdb picocom qemu ustup update rustup target add aarch64-unknown-none thumbv7em-none-eabihf rustup component add llvm-tools-preview cargo install cargo-binutils curl --proto '=https' --tlsv1.2 -LsSf https://github.com/probe-rs/probe-rs/releases/latest/download/probe-rs-tools-installer.sh | sh ``` -------------------------------- ### Client Setup Code Source: https://github.com/google/comprehensive-rust/blob/main/src/concurrency/async-exercises/chat-app.md Establishes a WebSocket connection to the server and prepares for message exchange. ```rust # // Copyright 2024 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use std::error::Error; use tokio_websockets::{Client, Message}; #[tokio::main] async fn main() -> Result<(), Box> { let server_addr = "ws://127.0.0.1:5000".to_string(); // Connect to the WebSocket server. let (ws, _response) = Client::connect(&server_addr).await?; // Split the WebSocket into a sender and receiver. let (sender, receiver) = ws.split(); // Spawn a task to handle sending messages from stdin to the server. tokio::spawn(send_messages(sender)); // Spawn a task to handle receiving messages from the server and printing them. tokio::spawn(receive_messages(receiver)); // Keep the main task alive indefinitely. // In a real application, you might want a more graceful shutdown mechanism. tokio::signal::ctrl_c().await?; // TODO: For a hint, see the description of the task below. } ``` -------------------------------- ### Install Development Tools on MacOS Source: https://github.com/google/comprehensive-rust/blob/main/CONTRIBUTING.md Install dprint, yapf, and gettext on MacOS using Homebrew for development. ```bash brew install dprint yapf gettext ``` -------------------------------- ### Rust Board Support Crate Example Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/microcontrollers/board-support.md This example demonstrates a board support crate in Rust. It provides more convenient names and initialization logic for a specific board. The crate may also include drivers for on-board devices, such as the LED matrix on the `microbit-v2`. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # // This is a placeholder for the actual board support crate example. // In a real scenario, this would include specific board initialization // and potentially drivers for on-board peripherals. // Example of a simplified board support structure: struct MyBoard { // Peripherals would be listed here } impl MyBoard { // Constructor to initialize the board pub fn new() -> Self { // Initialization logic would go here println!("Initializing MyBoard..."); MyBoard {} } // Example method for a board feature pub fn led_on(&self) { println!("LED is ON"); } } fn main() { let board = MyBoard::new(); board.led_on(); } ``` -------------------------------- ### Server Setup Code Source: https://github.com/google/comprehensive-rust/blob/main/src/concurrency/async-exercises/chat-app.md Initializes the Tokio runtime and sets up the WebSocket server to listen for incoming connections. ```rust # // Copyright 2024 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use std::collections::HashMap; use std::net::SocketAddr; use tokio::sync::{broadcast, mpsc}; use tokio_websockets::{WebSocket, WebSocketUpgrade, Message}; #[derive(Debug, Clone)] struct MessagePayload { sender: SocketAddr, message: String, } async fn run( acceptor: WebSocketUpgrade ) -> Result<(), Box> { let (ws, _addr) = acceptor.await?; // Split the WebSocket into a sender and receiver. let (sender, receiver) = ws.split(); // Use a broadcast channel to send messages to all connected clients. let (broadcast_tx, _broadcast_rx) = broadcast::channel(100); let (mpsc_tx, mpsc_rx) = mpsc::channel(100); // Spawn a task to handle the connection. tokio::spawn(handle_connection(sender, receiver, broadcast_tx, mpsc_rx)); Ok(()) } ``` -------------------------------- ### Example logcat output Source: https://github.com/google/comprehensive-rust/blob/main/src/android/logging.md This is an example of the output you would see in `adb logcat` when running the Rust logging example. It shows messages at different log levels (Debug, Info, Error) tagged with 'rust'. ```text 09-08 08:38:32.454 2420 2420 D rust: hello_rust_logs: Starting program. 09-08 08:38:32.454 2420 2420 I rust: hello_rust_logs: Things are going fine. 09-08 08:38:32.454 2420 2420 E rust: hello_rust_logs: Something went wrong! ``` -------------------------------- ### Run Peripheral Access Crate Example Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/microcontrollers/pacs.md This command demonstrates how to build and run the peripheral access crate example using cargo embed. This command is used to flash and run the embedded application on a target device. ```sh cargo embed --bin pac ``` -------------------------------- ### Rust `zerocopy` example Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/useful-crates/zerocopy.md This example demonstrates the usage of the `zerocopy` crate for safe byte conversions. It is not suitable for MMIO due to the lack of volatile reads/writes. Run with `cargo run` in the specified directory. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use zerocopy::{AsBytes, FromBytes, U32, U64}; #[derive(Clone, Copy, AsBytes, FromBytes)] #[repr(C)] struct RequestType { discriminant: U32, payload: U64, } fn main() { let request = RequestType { discriminant: U32::new(1), payload: U64::new(0x0123456789ABCDEF), }; let bytes = request.as_bytes(); println!("Bytes: {:?}", bytes); let request_from_bytes = RequestType::read_from(bytes).unwrap(); println!("Request from bytes: {:?}", request_from_bytes); assert_eq!(request.discriminant.get(), 1); assert_eq!(request.payload.get(), 0x0123456789ABCDEF); } ``` -------------------------------- ### Install Project Tools with Cargo Xtask Source: https://github.com/google/comprehensive-rust/blob/main/CONTRIBUTING.md Use this command to install the necessary development tools and dependencies for the project, including pinned versions of rustfmt. ```bash cargo xtask install-tools ``` -------------------------------- ### Tokio TCP Server Example Source: https://github.com/google/comprehensive-rust/blob/main/src/concurrency/async/tasks.md This example demonstrates a basic TCP server using Tokio that listens for incoming connections, accepts them, and spawns a new task for each connection to handle communication. It writes a greeting, reads a name, and sends a personalized reply. Use this to understand asynchronous I/O and task spawning in Rust. ```rust # // Copyright 2024 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:0").await?; println!("listening on port {}", listener.local_addr()?.port()); loop { let (mut socket, addr) = listener.accept().await?; println!("connection from {addr:?}"); tokio::spawn(async move { socket.write_all(b"Who are you?\n").await.expect("socket error"); let mut buf = vec![0; 1024]; let name_size = socket.read(&mut buf).await.expect("socket error"); let name = std::str::from_utf8(&buf[..name_size]).unwrap().trim(); let reply = format!("Thanks for dialing in, {name}!\n"); socket.write_all(reply.as_bytes()).await.expect("socket error"); }); } } ``` -------------------------------- ### Install Rustup on Debian/Ubuntu Source: https://github.com/google/comprehensive-rust/blob/main/src/cargo.md Use this command to install rustup, which includes the Cargo build tool and Rust compiler, on Debian or Ubuntu systems. ```shell sudo apt install rustup ``` -------------------------------- ### Initialize and Use Logger Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/aps/logging/using.md Initialize the logger before using it. This example demonstrates basic logger functionality. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # fn main() { // Initialize the logger // This must be done before any logging calls. log::info!("Hello, world!"); } ``` -------------------------------- ### Rust `from` Constructor Examples Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/from.md Illustrates various uses of the `from` function as a constructor for type conversions in Rust. ```APIDOC ## Rust `from` Constructor Functions ### Description This section details various Rust functions named `from` that act as constructors, primarily for type conversion purposes. These functions are distinct from `new` constructors, implying a transformation from one data type to another. ### Examples #### `CStr::from_ptr` - **Description**: Creates a `CStr` reference from a raw pointer. - **Method**: `unsafe fn from_ptr<'a>(ptr: *const i8) -> &'a CStr` #### `Duration::from_days` - **Description**: Creates a `Duration` from a specified number of days. - **Method**: `fn from_days(days: u64) -> Duration` #### `Vec::from_raw_parts` - **Description**: Creates a `Vec` from raw parts (pointer, length, capacity). - **Method**: `fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec` #### `i32::from_ascii` - **Description**: Attempts to parse a byte slice as an ASCII integer into an `i32`. - **Method**: `fn from_ascii(src: &[u8]) -> Result` #### `u32::from_le_bytes` - **Description**: Creates a `u32` from a 4-byte array representing little-endian data. - **Method**: `fn from_le_bytes(bytes: [u8; 4]) -> u32` ### Discussion Points - **`from` vs. `new`**: `from` implies type conversion, while `new` is for general construction. - **Argument Type Inference**: The argument type for functions like `u32::from_be` can be inferred based on related functions (e.g., `u32::from_le_bytes`). - **`str::from_utf8`**: This function takes a byte slice (`&[u8]`) as input because any `str` is inherently valid UTF-8, and the simplest representation of UTF-8 data is a byte slice. - **Naming Conventions**: The principle of omitting needless words applies, hence `str::from_utf8` instead of `str::from_utf8_bytes`. ``` -------------------------------- ### Serve Comprehensive Rust Course Locally Source: https://github.com/google/comprehensive-rust/blob/main/GEMINI.md Start a local web server to view the Comprehensive Rust course content. Optional arguments allow specifying a language and output directory. ```bash cargo xtask serve [--language ] [--output ] ``` -------------------------------- ### Rust Code with Clippy Lint Source: https://github.com/google/comprehensive-rust/blob/main/src/testing/lints.md This example demonstrates a clippy lint for possible truncation during type casting. Ensure clippy is installed and configured to enable this lint. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # #[deny(clippy::cast_possible_truncation)] fn main() { let mut x = 3; while (x < 70000) { x *= 2; } println!("X probably fits in a u16, right? {}", x as u16); } ``` -------------------------------- ### Mutex Usage Example Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/leveraging-the-type-system/raii/mutex.md Demonstrates creating a Mutex, locking it to get a MutexGuard, modifying the contained data, and observing the automatic unlock via guard's drop. ```rust # // Copyright 2025 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use std::sync::Mutex; fn main() { let m = Mutex::new(vec![1, 2, 3]); let mut guard = m.lock().unwrap(); guard.push(4); guard.push(5); println!("{guard:?}"); } ``` -------------------------------- ### Initialize Cargo Project and Run Source: https://github.com/google/comprehensive-rust/blob/main/src/modules/exercise.md Set up a new Rust project using Cargo and run the initial project. This is a prerequisite for the exercise. ```shell cargo init gui-modules cd gui-modules cargo run ``` -------------------------------- ### Build Comprehensive Rust Course Source: https://github.com/google/comprehensive-rust/blob/main/GEMINI.md Create a static version of the Comprehensive Rust course, outputting the files to the `book/` directory. Language and output directory can be specified. ```bash cargo xtask build [--language ] [--output ] ``` -------------------------------- ### Rust Documentation Test Example Source: https://github.com/google/comprehensive-rust/blob/main/src/testing/other.md Rust supports built-in documentation tests within `///` comments. These code blocks are compiled and executed during `cargo test`. Lines starting with `#` are hidden in documentation but still run. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # /// Shortens a string to the given length. /// /// ``` /// # use playground::shorten_string; /// assert_eq!(shorten_string("Hello World", 5), "Hello"); /// assert_eq!(shorten_string("Hello World", 20), "Hello World"); /// ``` pub fn shorten_string(s: &str, length: usize) -> &str { &s[..std::cmp::min(length, s.len())] } ``` -------------------------------- ### Install Cargo Audit Source: https://github.com/google/comprehensive-rust/blob/main/src/chromium/adding-third-party-crates/reviews-and-audits.md Install the `cargo-audit` tool globally using `cargo install`. This tool helps identify security vulnerabilities in Rust dependencies. ```bash cargo install cargo-audit ``` -------------------------------- ### Implement Global Allocator with Buddy System Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/alloc.md This example demonstrates setting up a global allocator using the `buddy_system_allocator` crate. Ensure you have exactly one global allocator defined in your binary if any crate depends on `alloc`. The `panic_halt` crate is required for a panic handler. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # extern crate alloc_example; extern crate panic_halt as _; use alloc_example::LockedHeap; #[global_allocator] static mut ALLOCATOR: LockedHeap<32> = LockedHeap::new(); fn main() { // This example will build but not run, as it doesn't have an entry point. // To run this, you would need to add an entry point and potentially // initialize the heap. } ``` -------------------------------- ### Serve Course Content Locally Source: https://github.com/google/comprehensive-rust/blob/main/README.md Starts a local web server to view the course content at http://localhost:3000. Supports serving translated versions using the `--language` or `-l` flag followed by the ISO 639 language code. ```bash cargo xtask serve ``` ```bash cargo xtask serve -l da ``` -------------------------------- ### Basic Rust Program - Hello World Source: https://context7.com/google/comprehensive-rust/llms.txt Demonstrates the basic structure of a Rust program, including the main function, the `println!` macro for output, and UTF-8 string support. ```rust fn main() { println!("Hello 🌍!"); } ``` -------------------------------- ### Birthday Service Response Example Source: https://github.com/google/comprehensive-rust/blob/main/src/android/aidl/example-service/deploy.md Example output when calling the birthday service, showing the decoded 'Parcel' data. ```text Service birthdayservice: found ``` ```text Result: Parcel( 0x00000000: 00000000 00000036 00610048 00700070 '....6...H.a.p.p.' 0x00000010: 00200079 00690042 00740072 00640068 'y. .B.i.r.t.h.d.' 0x00000020: 00790061 00420020 0062006f 0020002c 'a.y. .B.o.b.,. .' 0x00000030: 006f0063 0067006e 00610072 00750074 'c.o.n.g.r.a.t.u.' 0x00000040: 0061006c 00690074 006e006f 00200073 'l.a.t.i.o.n.s. .' 0x00000050: 00690077 00680074 00740020 00650068 'w.i.t.h. .t.h.e.' 0x00000060: 00320020 00200034 00650079 00720061 ' .2.4. .y.e.a.r.' 0x00000070: 00210073 00000000 's.!..... ') ``` -------------------------------- ### Build Static Course Version Source: https://github.com/google/comprehensive-rust/blob/main/README.md Generates a static version of the course in the `book/` directory. Requires separate building and zipping of exercises. Supports translated versions via the `--language` or `-l` flag. ```bash cargo xtask build ``` ```bash cargo xtask build -l da ``` -------------------------------- ### Initialize a New Translation File Source: https://github.com/google/comprehensive-rust/blob/main/TRANSLATIONS.md Use `msginit` to create a new `.po` file for a specific language (e.g., 'xx') from the POT template. Ensure the language code is correct. ```shell msginit -i book/xgettext/messages.pot -l xx -o po/xx.po ``` -------------------------------- ### Examples of Poor Rust Doc Comments Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/foundations-api-design/meaningful-doc-comments.md These examples demonstrate doc comments that lack detail or are redundant. They should be improved to provide more meaningful information. ```rust /// API for the client // ❌ Lacks detail pub mod client {} ``` ```rust /// Function from A to B // ❌ Redundant fn a_to_b(a: A) -> B {...} ``` ```rust /// Connects to the database. // ❌ Lacks detail fn connect() -> Result<(), Error> {...} ``` -------------------------------- ### Basic vmbase Main Function Source: https://github.com/google/comprehensive-rust/blob/main/src/bare-metal/android/vmbase.md This example demonstrates the basic structure of a main function using the `vmbase` library. The `main!` macro is required to integrate your function with the `vmbase` entry point, which handles console initialization and VM shutdown. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # #![no_main] #![no_std] use vmbase::{main, println}; main!(main); pub fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) { println!("Hello world"); } ``` -------------------------------- ### Get Value or Default with HashMap Source: https://github.com/google/comprehensive-rust/blob/main/src/std-types/hashmap.md Use `unwrap_or` to get a value from the HashMap or a default if the key is not present. This avoids panics on missing keys. ```rust # // Copyright 2023 Google LLC # // SPDX-License-Identifier: Apache-2.0 # let pc1 = page_counts .get("Harry Potter and the Sorcerer's Stone") .unwrap_or(&336); ``` -------------------------------- ### Server Main Function Source: https://github.com/google/comprehensive-rust/blob/main/src/concurrency/async-exercises/chat-app.md Sets up the TCP listener and accepts incoming WebSocket connections, spawning a new task for each connection. ```rust async fn main() -> Result<(), Box> { let addr = "127.0.0.1:5000".parse()?; // Create the TCP listener. let listener = tokio::net::TcpListener::bind(&addr).await?; println!("Listening on {}", addr); // Create the WebSocket acceptor. let mut websocket_acceptor = WebSocketUpgrade::new(); loop { let (tcp_stream, _) = listener.accept().await?; // Clone the acceptor for each connection. let websocket_acceptor = websocket_acceptor.clone(); // Spawn a task to handle the WebSocket connection. tokio::spawn(async move { if let Err(e) = run(websocket_acceptor.accept(tcp_stream)).await { eprintln!("WebSocket Error: {}", e); } }); } } ``` -------------------------------- ### Rust Link Checker Setup and Main Function Source: https://github.com/google/comprehensive-rust/blob/main/src/concurrency/sync-exercises/link-checker.md This Rust code sets up the necessary components for the link checker, including creating an HTTP client and defining the main function to initiate the crawling process. It demonstrates how to parse a URL and call the `visit_page` function, printing the extracted links or any errors encountered. ```rust # // Copyright 2024 Google LLC # // SPDX-License-Identifier: Apache-2.0 # // Placeholder for setup code, e.g., imports and struct definitions // use reqwest::blocking::Client; // use url::Url; // use thiserror::Error; // // #[derive(Debug)] // struct CrawlCommand { // url: Url, // extract_links: bool, // } // // #[derive(Error, Debug)] // enum LinkCheckerError { // #[error("Network error: {0}")] // Network(#[from] reqwest::Error), // #[error("URL parse error: {0}")] // UrlParse(#[from] url::ParseError), // #[error("Link extraction error: {0}")] // ScraperError(String), // } // // fn visit_page(client: &Client, command: &CrawlCommand) -> Result, LinkCheckerError> { // // Placeholder for actual link visiting and extraction logic // Ok(vec![]) // } fn main() { let client = Client::new(); let start_url = Url::parse("https://www.google.org").unwrap(); let crawl_command = CrawlCommand{ url: start_url, extract_links: true }; match visit_page(&client, &crawl_command) { Ok(links) => println!("Links: {links:#?}"), Err(err) => println!("Could not extract links: {err:#}"), } } ``` -------------------------------- ### Iterator Advance By Example (Nightly) Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/by.md An example of `Iterator::advance_by()`, a nightly feature in Rust, demonstrating another linguistic usage of 'by' in method names. ```rust Iterator::advance_by() ``` -------------------------------- ### Initialize and Run a Rust Project with Tokio Source: https://github.com/google/comprehensive-rust/blob/main/src/running-the-course/course-structure.md Use this command to initialize a new Rust project, add the Tokio dependency with full features, and then run the project. Ensure you are in the project directory before running. ```shell cargo init concurrency cd concurrency cargo add tokio --features full cargo run ``` -------------------------------- ### Install cloud-translate Tool Source: https://github.com/google/comprehensive-rust/blob/main/TRANSLATIONS.md Install the `cloud-translate` tool using Cargo to assist with machine translation of new entries. This tool can be helpful for quickly populating initial translations. ```shell cargo install cloud-translate ``` -------------------------------- ### mdBook Course Structure Example Source: https://github.com/google/comprehensive-rust/blob/main/mdbook-course/README.md An example illustrating how the mdBook structure is interpreted to define course segments and slides. Nested chapters are treated as parts of the parent slide. ```ignore - [Frobnication](frobnication.md) - [Integer Frobnication](frobnication/integers.md) - [Frob Expansion](frobnication/expansion.md) - [Structs](frobnication/expansion-structs.md) - [Enums](frobnication/expansion-structs.md) - [Exercise](frobnication/exercise.md) - [Solution](frobnication/Solution.md) ``` -------------------------------- ### References Example with Safety Preconditions Source: https://github.com/google/comprehensive-rust/blob/main/src/SUMMARY.md Demonstrates the safety preconditions associated with references. This example implies that the underlying data must be valid and properly aligned for the references to be safe to use. ```rust fn process_reference(ptr: *const i32) { // This operation assumes `ptr` is valid and points to an initialized `i32`. // The caller must ensure these preconditions are met. unsafe { let value = *ptr; println!("Value: {}", value); } } ``` -------------------------------- ### Extended Mocking Example with Mockall Source: https://github.com/google/comprehensive-rust/blob/main/src/android/testing/mocking.md Illustrates advanced mocking features in Mockall, such as setting expectations based on arguments and time. This example mocks a cat's feeding behavior. ```rust # // Copyright 2024 Google LLC # // SPDX-License-Identifier: Apache-2.0 # use mockall::mock!; use std::time::{Duration, Instant}; mock! { pub trait Cat { fn feed(&mut self, amount: u32); fn is_hungry(&self) -> bool; } } fn main() { let mut cat = Cat::new(); let feed_time = Instant::now(); cat.expect_feed().withf_eq(10).times(1..); cat.expect_is_hungry().returning(|| { // Simulate hunger after 3 hours feed_time.elapsed() > Duration::from_secs(3 * 60 * 60) }); cat.feed(10); assert!(!cat.is_hungry()); } ``` -------------------------------- ### May Overflow Example Source: https://github.com/google/comprehensive-rust/blob/main/src/SUMMARY.md Provides an example of a function that may overflow, highlighting a scenario where `unsafe` operations might be necessary. This function demonstrates a potential for undefined behavior if not handled carefully. ```rust fn main() { let mut x = 10; let y = &mut x as *mut i32; unsafe { // This operation might overflow, leading to undefined behavior // if the result is not handled correctly. *y = 100; println!("Value: {}", *y); } } ``` -------------------------------- ### Build, Push, and Run Rust Binary Source: https://github.com/google/comprehensive-rust/blob/main/src/android/build-rules/binary.md Execute these shell commands to build the Rust binary, push it to the device, and run it. This demonstrates the end-to-end workflow for AOSP Rust projects. ```shell m hello_rust && adb push $TARGET_OUT/bin/hello_rust /data/local/tmp/ && adb shell /data/local/tmp/hello_rust ``` -------------------------------- ### Rust Dyn Compatibility Example Source: https://github.com/google/comprehensive-rust/blob/main/src/SUMMARY.md Illustrates the concept of 'dyn compatibility' in Rust, showing how different types can be used together through a common trait object. This example highlights the flexibility of dynamic dispatch. ```Rust trait Component { fn render(&self); } struct InputField { placeholder: String, } impl Component for InputField { fn render(&self) { println!("Rendering input field with placeholder: {}", self.placeholder); } } struct Checkbox { checked: bool, } impl Component for Checkbox { fn render(&self) { println!("Rendering checkbox, checked: {}", self.checked); } } fn render_component(component: &dyn Component) { component.render(); } fn main() { let input = InputField { placeholder: String::from("Enter text...") }; let checkbox = Checkbox { checked: true }; render_component(&input); render_component(&checkbox); } ``` -------------------------------- ### Generate `gn` Build Rules Source: https://github.com/google/comprehensive-rust/blob/main/src/chromium/adding-third-party-crates/generating-gn-build-rules.md Execute this command to generate `BUILD.gn` files for downloaded Rust crates. Ensure you have `vpython3` available and are in the correct directory. ```shell vpython3 tools/crates/run_gnrt.py -- gen ``` -------------------------------- ### Example of a Failing Test Error Source: https://github.com/google/comprehensive-rust/blob/main/tests/README.md This is an example of a common error message encountered during web tests, indicating that the WebDriver tab crashed. This may point to an issue with the web-tests themselves rather than the user's changes. ```log ERROR webdriver: WebDriverError: tab crashed ``` -------------------------------- ### Rust Function Documentation Examples Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md Illustrates the difference between insufficient and sufficient documentation for Rust functions. Use comments to clarify potential side effects or nuanced behaviors not evident from the signature alone. ```rust # // Copyright 2025 Google LLC # // SPDX-License-Identifier: Apache-2.0 # // bad /// Returns a future that resolves when operation completes. fn sync_to_server() -> Future; // good /// Sends local edits to the server, overwriting concurrent edits /// if any happened. fn sync_to_server() -> Future; // bad /// Returns an error if sending the email fails. fn send(&self, email: Email) -> Result<(), Error>; // good /// Queues the email for background delivery and returns immediately. /// Returns an error immediately if the email is malformed. fn send(&self, email: Email) -> Result<(), Error>; ``` -------------------------------- ### Example of `dyn Trait` usage for addition Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/polymorphism/from-oop-to-rust/dynamic-dispatch/pitfalls.md This example demonstrates a scenario where dynamic dispatch is used for addition. It requires downcasting to perform the operation and again to view the result, illustrating the complexity introduced by `dyn Trait`. ```rust use std::any::Any; pub trait AddDyn: Any { fn add_dyn(&self, rhs: &dyn AddDyn) -> Box; } impl AddDyn for i32 { fn add_dyn(&self, rhs: &dyn AddDyn) -> Box { if let Some(downcast) = (rhs as &dyn Any).downcast_ref::() { Box::new(self + downcast) } else { Box::new(*self) } } } fn main() { let i: &dyn AddDyn = &42; let j: &dyn AddDyn = &64; let k: Box = i.add_dyn(j); dbg!((k.as_ref() as &dyn Any).is::()); dbg!((k.as_ref() as &dyn Any).downcast_ref::()); } ``` -------------------------------- ### Main function to demonstrate PackageBuilder in Rust Source: https://github.com/google/comprehensive-rust/blob/main/src/memory-management/exercise.md The `main` function demonstrates how to use the `PackageBuilder` to create a `Package` instance. It shows setting various fields and then building the final package. ```rust fn main() { let package = PackageBuilder::new() .name("comprehensive-rust".to_string()) .version("1.0.0".to_string()) .authors(vec!["Jane Doe".to_string(), "John Smith".to_string()]) .dependency("serde".to_string()) .language("Rust".to_string()) .build(); println!("{:?}", package); } ``` -------------------------------- ### Rust Database Transaction Example Source: https://github.com/google/comprehensive-rust/blob/main/src/idiomatic/leveraging-the-type-system/borrow-checker-invariants/aliasing-xor-mutability.md This example demonstrates how a mutable borrow of a DatabaseConnection within a Transaction prevents access to the connection until the transaction is committed. Uncommenting the `db.results()` line after `tx.query()` will cause a compile error. ```rust pub struct QueryResult; pub struct DatabaseConnection {/* fields omitted */} impl DatabaseConnection { pub fn new() -> Self { Self {} } pub fn results(&self) -> &[QueryResult] { &[] // fake results } } pub struct Transaction<'a> { connection: &'a mut DatabaseConnection, } impl<'a> Transaction<'a> { pub fn new(connection: &'a mut DatabaseConnection) -> Self { Self { connection } } pub fn query(&mut self, _query: &str) { // Send the query over, but don't wait for results. } pub fn commit(self) { // Finish executing the transaction and retrieve the results. } } fn main() { let mut db = DatabaseConnection::new(); // The transaction `tx` mutably borrows `db`. let mut tx = Transaction::new(&mut db); tx.query("SELECT * FROM users"); // This won't compile because `db` is already mutably borrowed by `tx`. // let results = db.results(); // ❌🔨 // The borrow of `db` ends when `tx` is consumed by `commit()`. tx.commit(); // Now it is possible to borrow `db` again. let results = db.results(); } ``` -------------------------------- ### Rust Log Filter Exercise Setup Source: https://github.com/google/comprehensive-rust/blob/main/src/closures/exercise.md This code block provides the setup for the Rust log filter exercise, including necessary imports and the main function structure. It is intended to be compiled with a `Filter` implementation. ```rust # // Copyright 2025 Google LLC # // SPDX-License-Identifier: Apache-2.0 # ``` ```rust // TODO: Define and implement `Filter`. ``` ```rust # fn main() { # // Example usage (replace with actual test) # println!("Placeholder for main execution."); # } ``` -------------------------------- ### Android.bp Configuration for C Library Source: https://github.com/google/comprehensive-rust/blob/main/src/android/interoperability/with-c/c-library.md Build configuration for the C library using Soong build system. ```javascript cc_library_static { name: "libbirthday", srcs: ["libbirthday.c"], export_include_dirs: ["."], header_libs: ["libbase_headers"], export_header_libs: ["libbase_headers"], } ```