### Fuchsia Emulator Setup and Management Source: https://doc.rust-lang.org/stable/rustc/platform-support/fuchsia Commands to get and start a Fuchsia emulator, and to watch its logs. Requires setting SDK_PATH and ARCH environment variables. ```bash # Get the Fuchsia product bundle for the specified architecture ${SDK_PATH}/tools/${ARCH}/ffx product-bundle get workstation_eng.qemu-${ARCH} # Start the Fuchsia emulator in headless mode ${SDK_PATH}/tools/${ARCH}/ffx emu start workstation_eng.qemu-${ARCH} --headless # Watch emulator logs since a specific time ${SDK_PATH}/tools/${ARCH}/ffx log \ --since now ``` -------------------------------- ### Getting Started with Embedded Rust Source: https://doc.rust-lang.org/stable/embedded-book/start/index An overview of the 'Getting Started' section of 'The Embedded Rust Book'. It explains the process of writing, building, flashing, and debugging embedded programs, utilizing QEMU for emulation and OpenOCD for hardware programming. ```APIDOC Section: Getting Started Purpose: Guide users through writing, building, flashing, and debugging embedded programs. Tools: - QEMU: For emulating hardware and trying examples without special hardware. - OpenOCD: For programming an STM32F3DISCOVERY board (required for the Hardware section). Content: - Covers basics using QEMU. - Requires hardware for the specific 'Hardware' section. ``` -------------------------------- ### Cargo Install Binary and Example Selection Source: https://doc.rust-lang.org/stable/cargo/commands/cargo-install Allows installation of specific binaries or examples from a crate, or all of them by default. ```rust `--bin` _name_ … Install only the specified binary. `--bins` Install all binaries. This is the default behavior. `--example` _name_ … Install only the specified example. `--examples` Install all examples. ``` -------------------------------- ### Cargo Install Examples Source: https://doc.rust-lang.org/stable/cargo/commands/cargo-install Demonstrates how to install or upgrade packages using Cargo, including installing from crates.io, installing from a local path, and listing installed packages. ```rust cargo install ripgrep ``` ```rust cargo install --path . ``` ```rust cargo install --list ``` -------------------------------- ### Download and Setup Cortex-M Quickstart Template Source: https://doc.rust-lang.org/stable/embedded-book/print Steps to download the latest snapshot of the cortex-m-quickstart template using curl and unzip, and then move it to an application directory. ```bash curl -LO https://github.com/rust-embedded/cortex-m-quickstart/archive/master.zip unzip master.zip mv cortex-m-quickstart-master app cd app ``` -------------------------------- ### Rust: Documenting Code Examples with Error Handling Source: https://doc.rust-lang.org/stable/rustdoc/print Demonstrates how to write Rust documentation examples that handle potential errors, such as parsing integers, by including necessary setup code within the example block. ```rust /// Example /// ```rust /// # fn main() -> Result<(), std::num::ParseIntError> { /// let fortytwo = "42".parse::()?; /// println!("{} + 10 = {}", fortytwo, fortytwo+10); /// # Ok(()) /// # } /// ``` ``` -------------------------------- ### Rust Embedded Project Setup Source: https://doc.rust-lang.org/stable/embedded-book/start/hardware Commands for adding a new target architecture and building an embedded Rust project. It includes installing the target and performing a clean build if the memory configuration changes. ```Shell rustup target add thumbv7em-none-eabihf cargo clean cargo build --example hello ``` -------------------------------- ### Install Clippy from Source Source: https://doc.rust-lang.org/stable/clippy/development/basics Instructions for building and installing Clippy binaries from source into a new toolchain. This process involves using `cargo dev setup toolchain` to create a 'clippy' toolchain, which can then be used to run Clippy on projects. ```rust cargo dev setup toolchain ``` ```rust cd my-project cargo +clippy clippy ``` ```rust clippy-driver +clippy ``` ```rust rustup toolchain uninstall clippy ``` -------------------------------- ### Rust Hello World Example Source: https://doc.rust-lang.org/stable/reference/introduction A basic Rust program that prints 'hello world' to the console. This is a standard entry point for learning Rust. ```rust #![allow(unused)] fn main() { println!("hello world"); } ``` -------------------------------- ### Hiding Code Lines in Rust Doc Tests Source: https://doc.rust-lang.org/stable/rustdoc/write-documentation/documentation-tests Demonstrates how to hide lines of code in Rust documentation examples using the '#' prefix. This is useful for including setup code or parts of the code that are not relevant to the specific explanation, while still ensuring the example compiles correctly. Lines starting with '# ' are hidden from the output but processed during compilation. ```rust #![allow(unused)] fn main() { /// ``` /// /// Some documentation. /// # fn foo() {} // this function will be hidden /// println!("Hello, World!"); /// ``` fn f() {} } ``` ```rust #![allow(unused)] fn main() { /// Some documentation. fn foo() {} println!("Hello, World!"); } ``` ```rust #![allow(unused)] fn main() { let x = 5; let y = 6; println!("{}", x + y); } ``` ```rust First, we set `x` to five: ``` let x = 5; # let y = 6; # println!("{}", x + y); ``` Next, we set `y` to six: ``` # let x = 5; let y = 6; # println!("{}", x + y); ``` Finally, we print the sum of `x` and `y`: ``` # let x = 5; # let y = 6; println!("{}", x + y); ``` ``` ```rust #![allow(unused)] fn main() { let s = "foo # bar # baz"; } ``` ```rust /// let s = "foo /// ## bar # baz"; ``` -------------------------------- ### Hiding Code Lines in Rust Doc Tests Source: https://doc.rust-lang.org/stable/rustdoc/documentation-tests Demonstrates how to hide lines of code in Rust documentation examples using the '#' prefix. This is useful for including setup code or parts of the code that are not relevant to the specific explanation, while still ensuring the example compiles correctly. Lines starting with '# ' are hidden from the output but processed during compilation. ```rust #![allow(unused)] fn main() { /// ``` /// /// Some documentation. /// # fn foo() {} // this function will be hidden /// println!("Hello, World!"); /// ``` fn f() {} } ``` ```rust #![allow(unused)] fn main() { /// Some documentation. fn foo() {} println!("Hello, World!"); } ``` ```rust #![allow(unused)] fn main() { let x = 5; let y = 6; println!("{}", x + y); } ``` ```rust First, we set `x` to five: ``` let x = 5; # let y = 6; # println!("{}", x + y); ``` Next, we set `y` to six: ``` # let x = 5; let y = 6; # println!("{}", x + y); ``` Finally, we print the sum of `x` and `y`: ``` # let x = 5; # let y = 6; println!("{}", x + y); ``` ``` ```rust #![allow(unused)] fn main() { let s = "foo # bar # baz"; } ``` ```rust /// let s = "foo /// ## bar # baz"; ``` -------------------------------- ### Rust Hello World Example Source: https://doc.rust-lang.org/stable/reference/index A basic Rust program that prints 'hello world' to the console. This is a standard entry point for learning Rust. ```rust #![allow(unused)] fn main() { println!("hello world"); } ``` -------------------------------- ### Cargo Install: Pre-Installation Package Determination Source: https://doc.rust-lang.org/stable/cargo/CHANGELOG Cargo will now determine all packages to install before starting the installation process, improving error reporting for partial installations. ```Rust ### Changed * `cargo install` will now determine all of the packages to install before starting the installation, which should help with reporting errors without partially installing. #9793 ``` -------------------------------- ### Clone cortex-m-quickstart repository Source: https://doc.rust-lang.org/stable/embedded-book/start/qemu Clones the cortex-m-quickstart project template from GitHub into a directory named 'app'. ```rust git clone https://github.com/rust-embedded/cortex-m-quickstart app ``` -------------------------------- ### Cargo Install Configuration Discovery Source: https://doc.rust-lang.org/stable/cargo/commands/cargo-install This command ignores local configuration discovery and starts configuration discovery from $CARGO_HOME/config.toml. If installed with --path, it uses local configuration starting at $PATH/.cargo/config.toml. ```rust # Configuration discovery starts at: # 1. $CARGO_HOME/config.toml (system/user level) # 2. $PATH/.cargo/config.toml (if installed with --path) ``` -------------------------------- ### Rust Embedded Hello World Example Source: https://doc.rust-lang.org/stable/embedded-book/start/qemu A simple Rust program for embedded systems that prints 'Hello, world!' to the console using semihosting and then exits. ```rust use panic_halt as _; use cortex_m_rt::entry; use cortex_m_semihosting::{debug, hprintln}; #[entry] fn main() -> ! { hprintln!("Hello, world!").unwrap(); // exit QEMU debug::exit(debug::EXIT_SUCCESS); } ``` -------------------------------- ### Rust Get Stack Start (Solaris/Illumos) Source: https://doc.rust-lang.org/stable/src/std/sys/pal/unix/stack_overflow Retrieves the starting address of the current stack on Solaris and Illumos systems. It uses `libc::stack_getbounds` to get stack information and returns the base address of the stack. ```rust #[cfg(any(target_os = "solaris", target_os = "illumos"))] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut current_stack: libc::stack_t = crate::mem::zeroed(); assert_eq!(libc::stack_getbounds(&mut current_stack), 0); Some(current_stack.ss_sp) } ``` -------------------------------- ### Rust WASI Target Setup and Build Source: https://doc.rust-lang.org/stable/rustc/platform-support/wasm32-wasip1 Instructions for setting up and building Rust programs for the `wasm32-wasip1` target, including installing the target via rustup and compiling with rustc. ```bash rustup target add wasm32-wasip1 ``` ```rust rustc --target wasm32-wasip1 your-code.rs ``` -------------------------------- ### Rust Import Ordering Example Source: https://doc.rust-lang.org/stable/style-guide/items Demonstrates the correct ordering of import groups in Rust. Imports within a group must be version-sorted, and groups are separated by blank lines or other items. Attributes like `macro_use` also necessitate starting a new group. ```rust #![allow(unused)] fn main() { use d; use c; use b; use a; } ``` ```rust #![allow(unused)] fn main() { use c; use d; use a; use b; } ``` -------------------------------- ### Download and extract project template Source: https://doc.rust-lang.org/stable/embedded-book/start/qemu Downloads the latest snapshot of the cortex-m-quickstart template as a zip file and extracts it into a directory named 'app'. ```shell curl -LO https://github.com/rust-embedded/cortex-m-quickstart/archive/master.zip unzip master.zip mv cortex-m-quickstart-master app cd app ``` -------------------------------- ### Create Project Directory (Linux/macOS/PowerShell) Source: https://doc.rust-lang.org/stable/book/ch01-02-hello-world Commands to create a 'projects' directory and a 'hello_world' subdirectory, then navigate into it. This sets up the environment for the first Rust program. ```bash $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world ``` -------------------------------- ### Cargo Contrib: UI Example Update Source: https://doc.rust-lang.org/stable/cargo/CHANGELOG Updated the UI example code in the contributor guide for Cargo. -------------------------------- ### Running the Rust File Example Source: https://doc.rust-lang.org/stable/rust-by-example/zh/std_misc/file/open Provides the command to create a sample 'hello.txt' file, compile the Rust code using `rustc`, and then execute the compiled program to demonstrate reading the file content. ```Shell $ echo "Hello World!" > hello.txt $ rustc open.rs && ./open hello.txt's contents: Hello World! ``` -------------------------------- ### Fuchsia Package Serving and Registration Source: https://doc.rust-lang.org/stable/rustc/platform-support/fuchsia Commands to start a package repository server and register it with the Fuchsia system running in the emulator. Assumes a package is built and located in the 'pkg-repo' directory. ```bash # Start a background package repository server ${SDK_PATH}/tools/${ARCH}/ffx repository server start \ --background --repository hello-fuchsia --repo-path pkg-repo # Register the package repository with the Fuchsia target ${SDK_PATH}/tools/${ARCH}/ffx target repository register \ --repository hello-fuchsia ``` -------------------------------- ### Cargo Uninstall Command Source: https://doc.rust-lang.org/stable/cargo/commands/cargo-uninstall Removes a Rust binary installed with `cargo install`. It allows specifying which binaries or examples to remove and defines the precedence for determining the installation root directory. ```APIDOC cargo-uninstall(1) NAME cargo-uninstall — Remove a Rust binary SYNOPSIS `cargo uninstall` [_options_] [_spec_ …] DESCRIPTION This command removes a package installed with cargo-install(1). The _spec_ argument is a package ID specification of the package to remove (see cargo-pkgid(1)). By default all binaries are removed for a crate but the `--bin` and `--example` flags can be used to only remove particular binaries. The installation root is determined, in order of precedence: * `--root` option * `CARGO_INSTALL_ROOT` environment variable * `install.root` Cargo config value * `CARGO_HOME` environment variable * `$HOME/.cargo` OPTIONS Uninstall Options -p `--package` _spec_ … Package to uninstall. --bin _name_ … Only uninstall the binary _name_. --root _dir_ Directory to uninstall packages from. ``` -------------------------------- ### Rust Get Stack Start (Linux/Android/FreeBSD etc.) Source: https://doc.rust-lang.org/stable/src/std/sys/pal/unix/stack_overflow Retrieves the starting address of the current stack for various Unix-like systems including Linux, Android, and FreeBSD. It initializes thread attributes and uses `pthread_attr_init` to get stack information. ```rust #[cfg(any( target_os = "android", target_os = "freebsd", target_os = "netbsd", target_os = "hurd", target_os = "linux", target_os = "l4re" ))] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut ret = None; let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); if !cfg!(target_os = "freebsd") { attr = mem::MaybeUninit::zeroed(); } #[cfg(target_os = "freebsd")] assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); #[cfg(target_os = "freebsd")] ``` -------------------------------- ### Rust Panic Migration Examples Source: https://doc.rust-lang.org/stable/edition-guide/rust-2021/panic-macro-consistency Examples demonstrating how to manually migrate panic invocations to be compatible with Rust 2021 Edition. ```rust std::panic::panic_any(MyStruct) ``` ```rust panic!("{}", "Some curlies: {{}}") ``` ```rust panic!("Some curlies: {{}}") ``` -------------------------------- ### Create and Spawn Process Source: https://doc.rust-lang.org/stable/src/std/process Shows how to create a new process using Command::new and immediately spawn it. It highlights the default configuration and how to use builder methods. ```rust use std::process::Command; Command::new("sh") .spawn() .expect("sh command failed to start"); ``` -------------------------------- ### Testing UEFI Applications with uefi-run Source: https://doc.rust-lang.org/stable/rustc/platform-support/unknown-uefi Provides instructions on installing and using the `uefi-run` tool, a wrapper around QEMU, to execute UEFI applications in an emulated environment. ```bash cargo install uefi-run uefi-run ./application.efi ``` -------------------------------- ### Travis CI Setup for Clippy Source: https://doc.rust-lang.org/stable/clippy/print Demonstrates how to integrate Clippy into a Travis CI build. It specifies the Rust toolchain, adds the `clippy` component, and runs `cargo clippy`. The example shows how to fail the build on warnings using `cargo clippy -- -D warnings` and how to include all targets and features with `cargo clippy --all-targets --all-features -- -D warnings`. ```yaml language: rust rust: - stable - beta before_script: - rustup component add clippy script: - cargo clippy # if you want the build job to fail when encountering warnings, use - cargo clippy -- -D warnings # in order to also check tests and non-default crate features, use - cargo clippy --all-targets --all-features -- -D warnings - cargo test # etc. ``` -------------------------------- ### Rustdoc Front-Page Documentation Example Source: https://doc.rust-lang.org/stable/rustdoc/how-to-write-documentation Demonstrates the use of `//!` for crate-level documentation, including a summary sentence and links to further details. It also shows an example of module-level documentation using `///`. ```rust #![allow(unused)] fn main() { //! Fast and easy queue abstraction. //! //! Provides an abstraction over a queue. When the abstraction is used //! there are these advantages: //! - Fast //! - [`Easy`] //! //! [`Easy`]: http://thatwaseasy.example.com /// This module makes it easy. pub mod easy { /// Use the abstraction function to do this specific thing. pub fn abstraction() {} } } ``` -------------------------------- ### Rust Range (start..end) Source: https://doc.rust-lang.org/stable/src/core/ops/range Defines a half-open range from a start value (inclusive) to an end value (exclusive). The range `start..end` includes values where `start <= x < end`. It is considered empty if `start >= end`. Examples show its use in slicing and calculating sums. ```rust /// A (half-open) range bounded inclusively below and exclusively above /// (`start..end`). /// /// The range `start..end` contains all values with `start <= x < end`. /// It is empty if `start >= end`. /// /// # Examples /// /// The `start..end` syntax is a `Range`: /// /// ``` /// assert_eq!((3..5), std::ops::Range { start: 3, end: 5 }); /// assert_eq!(3 + 4 + 5, (3..6).sum()); /// ``` /// /// ``` /// let arr = [0, 1, 2, 3, 4]; /// assert_eq!(arr[ .. ], [0, 1, 2, 3, 4]); /// assert_eq!(arr[ .. 3], [0, 1, 2 ]); /// assert_eq!(arr[ ..=3], [0, 1, 2, 3 ]); /// assert_eq!(arr[1.. ], [ 1, 2, 3, 4]); /// assert_eq!(arr[1.. 3], [ 1, 2 ]); // This is a `Range` /// assert_eq!(arr[1..=3], [ 1, 2, 3 ]); /// ``` #[lang = "Range"] #[doc(alias = "..")] #[derive(Clone, Default, PartialEq, Eq, Hash)] // not Copy -- see #27186 #[stable(feature = "rust1", since = "1.0.0")] pub struct Range { /// The lower bound of the range (inclusive). #[stable(feature = "rust1", since = "1.0.0")] pub start: Idx, /// The upper bound of the range (exclusive). #[stable(feature = "rust1", since = "1.0.0")] pub end: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for Range { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { self.start.fmt(fmt)?; write!(fmt, "..")?; self.end.fmt(fmt)?; Ok(()) } } impl> Range { /// Returns `true` if `item` is contained in the range. /// /// # Examples /// /// ``` /// assert!(!(3..5).contains(&2)); /// assert!( (3..5).contains(&3)); /// assert!( (3..5).contains(&4)); /// assert!(!(3..5).contains(&5)); /// /// assert!(!(3..3).contains(&3)); /// assert!(!(3..2).contains(&3)); /// /// assert!( (0.0..1.0).contains(&0.5)); /// assert!(!(0.0..1.0).contains(&f32::NAN)); /// assert!(!(0.0..f32::NAN).contains(&0.5)); /// assert!(!(f32::NAN..1.0).contains(&0.5)); /// ``` #[inline] #[stable(feature = "range_contains", since = "1.35.0")] pub fn contains(&self, item: &U) -> bool where Idx: PartialOrd, U: ?Sized + PartialOrd, { >::contains(self, item) } /// Returns `true` if the range contains no items. /// /// # Examples /// /// ``` /// assert!(!(3..5).is_empty()); /// assert!( (3..3).is_empty()); /// assert!( (3..2).is_empty()); /// ``` /// /// The range is empty if either side is incomparable: /// /// ``` /// assert!(!(3.0..5.0).is_empty()); /// assert!( (3.0..f32::NAN).is_empty()); /// assert!( (f32::NAN..5.0).is_empty()); /// ``` #[inline] #[stable(feature = "range_is_empty", since = "1.47.0")] pub fn is_empty(&self) -> bool { !(self.start < self.end) } } ``` -------------------------------- ### Compile Rust Example with Specific Rustc and Coverage Source: https://doc.rust-lang.org/stable/rustc/instrument-coverage This example shows how to compile a specific example binary from a Rust project using a custom `rustc` path and enabling LLVM instrumentation-based code coverage. ```Shell $ RUSTC=$HOME/rust/build/x86_64-unknown-linux-gnu/stage1/bin/rustc \ RUSTFLAGS="-C instrument-coverage" \ cargo build --example formatjson5 ``` -------------------------------- ### Rust Code Example with Anonymous Parameter Source: https://doc.rust-lang.org/stable/edition-guide/print An example of Rust code that uses an anonymous parameter, which is not supported in Rust 2018 and requires migration. ```rust #![allow(unused)] fn main() { trait Foo { fn foo(&self, i32); } } ``` -------------------------------- ### Create Project Directory (Windows CMD) Source: https://doc.rust-lang.org/stable/book/ch01-02-hello-world Commands for Windows Command Prompt to create a 'projects' directory and a 'hello_world' subdirectory, then navigate into it. ```batch > mkdir "%USERPROFILE%\projects" > cd /d "%USERPROFILE%\projects" > mkdir hello_world > cd hello_world ``` -------------------------------- ### Rustdoc Combined Tests Source: https://doc.rust-lang.org/stable/edition-guide/rust-2024/rustdoc-doctests Starting with the 2024 Edition, rustdoc combines documentation tests into a single binary for improved performance. Previously, each doctest was compiled as a separate executable, causing a performance burden. This change reduces compilation overhead by placing examples in separate functions within one binary, while tests still run independently. ```Rust #![allow(unused)] fn main() { /// Adds two numbers /// /// ``` /// assert_eq!(add(1, 1), 2); /// ``` pub fn add(left: u64, right: u64) -> u64 { left + right } /// Subtracts two numbers /// /// ``` /// assert_eq!(subtract(2, 1), 1); /// ``` pub fn subtract(left: u64, right: u64) -> u64 { left - right } } ``` -------------------------------- ### OpenOCD Configuration and Startup Source: https://doc.rust-lang.org/stable/embedded-book/start/hardware This snippet shows the OpenOCD configuration commands and the initial output when starting the OpenOCD server for debugging an STM32F3x microcontroller. It includes adapter speed, target voltage, and CPU information. ```shell source [find interface/stlink-v2.cfg] source [find target/stm32f3x.cfg] ``` ```shell openocd Open On-Chip Debugger 0.10.0 Licensed under GNU GPL v2 For bug reports, read http://openocd.org/doc/doxygen/bugs.html Info : auto-selecting first available session transport "hla_swd". To override use 'transport select '. adapter speed: 1000 kHz adapter_nsrst_delay: 100 Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD none separate Info : Unable to match requested speed 1000 kHz, using 950 kHz Info : Unable to match requested speed 1000 kHz, using 950 kHz Info : clock speed 950 kHz Info : STLINK v2 JTAG v27 API v2 SWIM v15 VID 0x0483 PID 0x374B Info : using stlink api v2 Info : Target voltage: 2.913879 Info : stm32f3x.cpu: hardware has 6 breakpoints, 4 watchpoints ``` -------------------------------- ### Rust split_at_unchecked Examples Source: https://doc.rust-lang.org/stable/std/bstr/struct Provides examples for `split_at_unchecked`, which divides a slice into two without bounds checking. The examples cover splitting at the start, middle, and end, emphasizing the need for manual bounds assurance. ```rust let v = ['a', 'b', 'c']; unsafe { let (left, right) = v.split_at_unchecked(0); assert_eq!(left, []); assert_eq!(right, ['a', 'b', 'c']); } unsafe { let (left, right) = v.split_at_unchecked(2); assert_eq!(left, ['a', 'b']); assert_eq!(right, ['c']); } unsafe { let (left, right) = v.split_at_unchecked(3); assert_eq!(left, ['a', 'b', 'c']); assert_eq!(right, []); } ``` -------------------------------- ### Setup Debian Chroot for Rust Development Source: https://doc.rust-lang.org/stable/rustc/platform-support/armv7-unknown-linux-uclibceabi Instructions for setting up a Debian chroot environment for cross-compiling Rust projects. This involves debootstrapping, entering the chroot, mounting necessary file systems, and installing Rust and toolchains. ```bash sudo debootstrap --arch armel bullseye $HOME/debian sudo chroot $HOME/debian/ /bin/bash mount proc /proc -t proc mount -t sysfs /sys sys/ export PATH=/mmc/bin:/mmc/sbin:$PATH # Inside chroot: tar zxvf arm-soft-mmc.tgz -C /mmc source /mmc/etc/profile sudo /mmc/bin/apt update && sudo /mmc/bin/apt install rust ``` -------------------------------- ### Rust Embedded 'Hello, World!' with Semihosting Source: https://doc.rust-lang.org/stable/embedded-book/start/qemu A basic Rust program for embedded systems that prints 'Hello, world!' to the host console using semihosting and then exits QEMU gracefully. It requires the `cortex-m-rt` and `panic-halt` crates. ```Rust #![no_main] #![no_std] use panic_halt as _; use cortex_m_rt::entry; use cortex_m_semihosting::{debug, hprintln}; #[entry] fn main() -> ! { hprintln!("Hello, world!").unwrap(); // exit QEMU // NOTE do not run this on hardware; it can corrupt OpenOCD state debug::exit(debug::EXIT_SUCCESS); loop {} } ``` -------------------------------- ### Rustfmt Migration Error Example Source: https://doc.rust-lang.org/stable/edition-guide/print An example of a compilation error encountered after migrating to Rust 2024 if doctest paths are not updated, indicating a failure to find the included file. ```rust error: couldn't read `../examples/data.bin`: No such file or directory (os error 2) --> src/../README.md:2:24 | 2 | let _ = include_bytes!("../examples/data.bin"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in the macro `include_bytes` (in Nightly builds, run with -Z macro-backtrace for more info) help: there is a file with the same name in a different directory | 2 | let _ = include_bytes!("examples/data.bin"); | ~~~~~~~~~~~~~~~~~~~ ``` -------------------------------- ### Rust MaybeUninit as_bytes Example Source: https://doc.rust-lang.org/stable/std/mem/union Demonstrates how to get a slice of bytes from a `MaybeUninit` value. This example shows converting an `i32` to its byte representation using `as_bytes` and `assume_init_ref`. ```Rust #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)] use std::mem::MaybeUninit; let val = 0x12345678_i32; let uninit = MaybeUninit::new(val); let uninit_bytes = uninit.as_bytes(); let bytes = unsafe { uninit_bytes.assume_init_ref() }; assert_eq!(bytes, val.to_ne_bytes()); ``` -------------------------------- ### Rust Command Example: Echo Hello Source: https://doc.rust-lang.org/stable/src/std/process Demonstrates how to use the Command builder to spawn a process that echoes 'hello'. It includes platform-specific commands for Windows (cmd /C echo hello) and Unix-like systems (sh -c echo hello). ```rust use std::process::Command; let output = if cfg!(target_os = "windows") { Command::new("cmd") .args(["/C", "echo hello"]) .output() .expect("failed to execute process") } else { Command::new("sh") .arg("-c") .arg("echo hello") .output() .expect("failed to execute process") }; let hello = output.stdout; ``` -------------------------------- ### Start and stop QEMU virtual machine Source: https://doc.rust-lang.org/stable/rustc/platform-support/nto-qnx Commands to manage the lifecycle of the QEMU virtual machine used for testing. '--run=-h' starts the machine, and '--stop' halts it. ```shell mkqnximage --run=-h ``` ```shell mkqnximage --stop ``` -------------------------------- ### Rust: unsafe_op_in_unsafe_fn fix example Source: https://doc.rust-lang.org/stable/edition-guide/rust-2024/unsafe-op-in-unsafe-fn Provides the corrected version of the `unsafe_op_in_unsafe_fn` lint example in Rust, where the unsafe operation is properly enclosed within an `unsafe` block. ```Rust #![allow(unused)] fn main() { #![deny(unsafe_op_in_unsafe_fn)] unsafe fn get_unchecked(x: &[T], i: usize) -> &T { unsafe { x.get_unchecked(i) } } ``` -------------------------------- ### Rust Edition Guide - Introduction Source: https://doc.rust-lang.org/stable/edition-guide An introductory section to The Rust Edition Guide, explaining the concept of Rust editions as a mechanism for managing backward-incompatible language changes. ```Text # The Rust Edition Guide # Introduction Welcome to The Rust Edition Guide! "Editions" are Rust's way of introducing changes into the language that would not otherwise be backwards compatible. In this guide, we'll discuss: * What editions are * Which changes are contained in each edition * How to migrate your code from one edition to another ``` -------------------------------- ### Hello World in Rust Source: https://doc.rust-lang.org/stable/rust-by-example/print A traditional "Hello, world!" program to start with Rust. ```Rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Rust 2015 `use` Paths Source: https://doc.rust-lang.org/stable/edition-guide/rust-2018/path-changes Demonstrates the path handling in `use` declarations in Rust 2015, highlighting the crate root starting point and the implicit scope start in other code. ```Rust extern crate futures; use futures::Future; mod foo { pub struct Bar; } use foo::Bar; fn my_poll() -> futures::Poll { ... } enum SomeEnum { V1(usize), V2(String), } fn func() { let five = std::sync::Arc::new(5); use SomeEnum::*; match ... { V1(i) => { ... } V2(s) => { ... } } } ``` -------------------------------- ### Install ripgrep using cargo install Source: https://doc.rust-lang.org/stable/book/ch14-04-installing-binaries Demonstrates the process of installing the `ripgrep` binary crate using `cargo install`. It shows the typical output, including updating the index, downloading, compiling, and installing the executable. ```bash $ cargo install ripgrep Updating crates.io index Downloaded ripgrep v14.1.1 Downloaded 1 crate (213.6 KB) in 0.40s Installing ripgrep v14.1.1 --snip-- Compiling grep v0.3.2 Finished `release` profile [optimized + debuginfo] target(s) in 6.73s Installing ~/.cargo/bin/rg Installed package `ripgrep v14.1.1` (executable `rg`) ``` -------------------------------- ### Create and Run a Rust Project with Cargo Source: https://doc.rust-lang.org/stable/book/ch02-00-guessing-game-tutorial Demonstrates how to create a new Rust project using Cargo and run the default 'Hello, world!' program. This is the initial setup for the guessing game project. ```Shell $ cargo new guessing_game $ cd guessing_game ``` ```Shell $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s Running `target/debug/guessing_game` Hello, world! ``` -------------------------------- ### Rust Code Example with Anonymous Parameter Source: https://doc.rust-lang.org/stable/edition-guide/editions/transitioning-an-existing-project-to-a-new-edition An example of Rust code that uses an anonymous parameter within a trait definition. This syntax is not supported in Rust 2018 and requires an update. ```Rust #![allow(unused)] fn main() { trait Foo { fn foo(&self, i32); } } ``` -------------------------------- ### Building Rust Toolchain for QNX Targets Source: https://doc.rust-lang.org/stable/rustc/platform-support/nto-qnx Shell script example for setting environment variables and building the Rust toolchain for specified host and QNX targets. It configures cross-compilation tools and flags. ```Shell export build_env=' CC_aarch64_unknown_nto_qnx710=qcc CFLAGS_aarch64_unknown_nto_qnx710=-Vgcc_ntoaarch64le_cxx CXX_aarch64_unknown_nto_qnx710=qcc AR_aarch64_unknown_nto_qnx710=ntoaarch64-ar ' env $build_env \ ./x.py build \ --target x86_64-unknown-linux-gnu,aarch64-unknown-nto-qnx710 \ rustc library/core library/alloc library/std ``` -------------------------------- ### UnsafePinned Usage Example Source: https://doc.rust-lang.org/stable/std/pin/struct A basic example demonstrating the usage of UnsafePinned::new, get, and get_mut_unchecked to manipulate the wrapped value, highlighting the need for unsafe blocks. ```rust #![feature(unsafe_pinned)] use std::pin::UnsafePinned; unsafe { let mut x = UnsafePinned::new(0); let ptr = x.get(); x.get_mut_unchecked().write(1); assert_eq!(ptr.read(), 1); } ``` -------------------------------- ### Rust Test Suite Execution Setup Source: https://doc.rust-lang.org/stable/rustc/platform-support/fuchsia Commands and environment variable setup for running the Rust compiler test suite on an emulated Fuchsia device. Requires the Fuchsia SDK and a specific test runner script. ```bash # Navigate to the Rust source checkout cd ${RUST_SRC_PATH} # Set environment variables for the test toolchain temporary directory # Ensure the path is less than 108 characters for compatibility with qemu export TEST_TOOLCHAIN_TMP_DIR="/tmp/rust-tmp" ``` -------------------------------- ### Rust Get Stack Start (macOS) Source: https://doc.rust-lang.org/stable/src/std/sys/pal/unix/stack_overflow Retrieves the starting address of the current stack on macOS. It uses `pthread_get_stackaddr_np` and `pthread_get_stacksize_np` to calculate the stack's base address. ```rust #[cfg(target_os = "macos")] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let th = libc::pthread_self(); let stackptr = libc::pthread_get_stackaddr_np(th); Some(stackptr.map_addr(|addr| addr - libc::pthread_get_stacksize_np(th))) } ``` -------------------------------- ### Rust MaybeUninit as_bytes Example Source: https://doc.rust-lang.org/stable/core/mem/union Demonstrates how to get a slice of bytes from a `MaybeUninit` value. This example shows converting an initialized `MaybeUninit` to its byte representation and asserting its correctness. ```rust #![feature(maybe_uninit_as_bytes, maybe_uninit_slice)] use std::mem::MaybeUninit; let val = 0x12345678_i32; let uninit = MaybeUninit::new(val); let uninit_bytes = uninit.as_bytes(); let bytes = unsafe { uninit_bytes.assume_init_ref() }; assert_eq!(bytes, val.to_ne_bytes()); ``` -------------------------------- ### Compiling and Running Rust Code Source: https://doc.rust-lang.org/stable/rust-by-example/hello Demonstrates how to compile a Rust source file (`hello.rs`) using `rustc` and then execute the resulting binary to produce the 'Hello World!' output. ```Shell $ rustc hello.rs $ ./hello Hello World! ``` -------------------------------- ### Rust Source Code for Fuchsia Example Source: https://doc.rust-lang.org/stable/rustc/platform-support/fuchsia Example `src/main.rs` file for a Rust project targeting Fuchsia. Includes a simple print statement and a basic test. ```rust fn main() { println!("Hello Fuchsia!"); } #[test] fn it_works() { assert_eq!(2 + 2, 4); } ```