Comprehensive Rust

repository·main·Indexed 12 days ago

https://github.com/google/comprehensive-rust

A multi-day training course developed by the Google Android team to teach Rust to experienced software engineers, covering basic syntax, concurrency, and bare-metal development. The repository includes the course content and supporting tools such as the mdbook-course preprocessor for managing course timing and structure, and the mdbook-exerciser for generating exercise templates.

Tokens
216.9K
Snippets
560
Records
832
Agent score
99%

What's inside Comprehensive Rust

  1. What is Rust?

    main

    Rust is a statically compiled programming language designed for high performance and reliability. It serves a similar role to C++, offering high flexibility and control without a runtime or garbage collection. This makes it suitable for a wide range of applications, from highly constrained microcontrollers and firmware to servers and desktops.

    Key characteristics include:

    • Statically compiled: Uses rustc with an LLVM backend.
    • No Runtime/GC: Focuses on performance and safety without the overhead of garbage collection.
    • Platform Support: Supports various architectures (x86, ARM, WebAssembly) and operating systems (Linux, macOS, Windows).
  2. Overview of the Unsafe Rust Deep Dive course

    main

    The Unsafe Rust Deep Dive is a specialized module designed to enable productive work with Unsafe Rust. The course follows a 'spiral model' of teaching, revisiting topics with increasing depth.

    Key learning objectives include:

    1. Establishing a Mental Model

    • Understanding the unsafe keyword.
    • Learning a shared vocabulary for safety.
    • Developing a mental model of memory.
    • Identifying common patterns and expectations for unsafe code.

    2. Practicing Unsafe Rust

    • Reading and writing both code and documentation.
    • Using existing unsafe APIs.
    • Designing and implementing new unsafe APIs.

    3. Code Review

    • Gaining the confidence to self-review simple cases.
    • Developing the knowledge to detect complex cases that require senior engineers.
  3. Overview of probe-rs and cargo-embed for embedded debugging

    main

    probe-rs

    probe-rs is a toolset for embedded debugging designed as an alternative to OpenOCD. It provides:

    • Support for SWD (Serial Wire Debug) and JTAG via probes like CMSIS-DAP, ST-Link, and J-Link.
    • A GDB stub and Microsoft DAP (Debug Adapter Protocol) server for IDE integration (e.g., VSCode).
    • Deep Cargo integration for Rust workflows.
    • A library that can be integrated into custom tools.

    cargo-embed

    cargo-embed is a cargo subcommand built using the probe-rs library. It is used to:

    • Build and flash binaries to the target microcontroller.
    • Log RTT (Real Time Transfers) output, which allows data transfer between the host and target via ring buffers.
    • Connect to a GDB session.

    Configuration for cargo-embed is handled via an Embed.toml file located in your project directory.

  4. Overview of the Idiomatic Rust course

    main

    The Idiomatic Rust course is an opinionated guide designed to help developers move beyond basic syntax to using Rust effectively in professional projects. It focuses on patterns that make code readable, predictable, and safe by leveraging Rust's unique features like the type system and borrow checker.

    Note: This course is under active development and the material may change frequently.

  5. Overview of Day 4: Building Robust Applications

    main

    Day 4 of the Comprehensive Rust course transitions from core language mechanics to applying Rust's safety model to build robust, large-scale applications. This session builds upon previously mastered concepts including:

    • Foundations & Abstraction: Traits, generics, and the standard library.
    • Ownership: Move semantics and the Drop trait.
    • Memory Management: Borrowing rules (& vs &mut) and lifetimes.
    • Smart Pointers: Box, Rc, and RefCell for complex data structures.

    The focus shifts from understanding how Rust guarantees memory safety at compile time to practical application in larger software architectures.

  6. Overview of the `embedded-hal` crate

    main

    The embedded-hal crate provides a set of hardware abstraction layer (HAL) traits that cover common microcontroller peripherals. These traits allow hardware drivers (e.g., an accelerometer driver) to be written in a platform-agnostic way by depending on these traits rather than specific hardware implementations.

    Supported peripheral categories include:

    • GPIO
    • PWM
    • Delay timers
    • I2C and SPI (buses and devices)

    Note that these traits focus on using peripherals. They do not cover the initialization or configuration of hardware, as those steps are highly platform-specific.

  7. Overview of Rust Fundamentals Day 1

    main

    Day 1 of the Rust Fundamentals course covers the core syntax and basic building blocks of the Rust programming language. The curriculum focuses on topics that provide immediate parallels to other programming languages, establishing a foundation before moving into advanced Rust concepts in later days.

    Key topics covered:

    • Basic Syntax: Variables, scalar and compound types, enums, structs, references, functions, and methods.
    • Type System: Types and type inference.
    • Control Flow: Loops, conditionals, and other control constructs.
    • User-defined Types: Structs and enums.
  8. Key benefits and safety guarantees of Rust

    main

    Rust provides several core safety and performance benefits that distinguish it from other languages:

    Compile-time Memory Safety

    Rust prevents many common memory bugs during compilation using its borrow checker:

    • No uninitialized variables
    • No double-frees
    • No use-after-free
    • No NULL pointers
    • No forgotten locked mutexes
    • No data races between threads
    • No iterator invalidation

    Defined Runtime Behavior

    Rust avoids undefined behavior by ensuring language statements have specified outcomes:

    • Array access is bounds checked.
    • Integer overflow is defined (either via panic or wrap-around).

    Modern Language Features

    Rust offers high-level ergonomics with zero-cost abstractions:

    • Enums and pattern matching
    • Generics
    • No-overhead FFI (Foreign Function Interface)
    • Built-in dependency management (Cargo)
    • Built-in testing support
    • Excellent Language Server Protocol (LSP) support
  9. Use the `zerocopy` crate for safe byte conversions

    main

    The zerocopy crate (from Fuchsia) provides traits and macros for safely converting between byte sequences and other types. It is particularly useful for working with structures shared with hardware (e.g., via DMA) or data sent over external interfaces.

    Note: This crate is not suitable for MMIO (Memory-Mapped I/O) because it does not use volatile reads and writes.

    Key Concepts

    • FromBytes trait: Can be implemented for types where any byte pattern is considered valid. This allows for safe conversion from untrusted byte sequences.
    • Safety Constraint: You cannot derive FromBytes for types where not all possible byte patterns are valid discriminants (for example, an enum that does not use all possible values of its underlying integer type).
    • Byte Order: Use zerocopy::byteorder for numeric primitives that require specific byte-order awareness.
  10. Chromium Development with Rust

    main

    The Chromium section provides guidance on integrating Rust into the Chromium project. Key topics include:

    • Setup and Build Rules: Environment setup, understanding Chromium's policy, and managing unsafe code or dependencies from C++.
    • Testing: Using the rust_gtest_interop library, GN rules for Rust tests, and the chromium::import! macro.
    • Interoperability with C++: Using the CXX tool for bindings, handling errors across the language boundary, and managing shared types/enums.
    • Adding Third-Party Crates: The process for adding, configuring (Cargo.toml, gnrt_config.toml), downloading, and generating GN build rules for external crates, including review and audit requirements.
  11. Concurrency in Rust

    main

    The Concurrency sections cover both synchronous and asynchronous programming models.

    Concurrency: Morning (Synchronous)

    • Threads: Using plain threads and scoped threads.
    • Channels: Implementing communication via unbounded and bounded channels (senders and receivers).
    • Shared State: Managing shared data using Arc (Atomic Reference Counting) and Mutex (Mutual Exclusion).
    • Marker Traits: Understanding the Send and Sync traits and how they govern thread safety.

    Concurrency: Afternoon (Asynchronous)

    • Async Basics: Using async/await, understanding Futures, state machines, and choosing runtimes like Tokio.
    • Async Control Flow: Managing tasks and using async channels, join!, and select! macros.
    • Pitfalls: Avoiding common issues like blocking the executor, understanding Pin, working with async traits, and managing cancellation.