repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/bye.rs | yazi-dds/src/ember/bye.rs | use mlua::{ExternalResult, IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use super::Ember;
#[derive(Debug, Deserialize, Serialize)]
pub struct EmberBye;
impl EmberBye {
pub fn owned() -> Ember<'static> { Self.into() }
}
impl From<EmberBye> for Ember<'_> {
fn from(value: EmberBye) -> Self { Self::Bye(value) }
}
impl IntoLua for EmberBye {
fn into_lua(self, _: &Lua) -> mlua::Result<Value> {
Err("BodyBye cannot be converted to Lua").into_lua_err()
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/mount.rs | yazi-dds/src/ember/mount.rs | use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use super::Ember;
#[derive(Debug, Deserialize, Serialize)]
pub struct EmberMount;
impl EmberMount {
pub fn owned() -> Ember<'static> { Self.into() }
pub fn borrowed() -> Ember<'static> { Self::owned() }
}
impl From<EmberMount> for Ember<'_> {
fn from(value: EmberMount) -> Self { Self::Mount(value) }
}
impl IntoLua for EmberMount {
fn into_lua(self, _: &Lua) -> mlua::Result<Value> { Ok(Value::Nil) }
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/duplicate.rs | yazi-dds/src/ember/duplicate.rs | use std::borrow::Cow;
use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::url::UrlBuf;
use super::Ember;
#[derive(Debug, Deserialize, Serialize)]
pub struct EmberDuplicate<'a> {
pub items: Cow<'a, Vec<BodyDuplicateItem>>,
}
impl<'a> EmberDuplicate<'a> {
pub fn borrowed(items: &'a Vec<BodyDuplicateItem>) -> Ember<'a> {
Self { items: Cow::Borrowed(items) }.into()
}
}
impl EmberDuplicate<'static> {
pub fn owned(items: Vec<BodyDuplicateItem>) -> Ember<'static> {
Self { items: Cow::Owned(items) }.into()
}
}
impl<'a> From<EmberDuplicate<'a>> for Ember<'a> {
fn from(value: EmberDuplicate<'a>) -> Self { Self::Duplicate(value) }
}
impl IntoLua for EmberDuplicate<'_> {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
lua.create_table_from([("items", self.items.into_owned())])?.into_lua(lua)
}
}
// --- Item
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BodyDuplicateItem {
pub from: UrlBuf,
pub to: UrlBuf,
}
impl IntoLua for BodyDuplicateItem {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
lua
.create_table_from([
("from", yazi_binding::Url::new(self.from)),
("to", yazi_binding::Url::new(self.to)),
])?
.into_lua(lua)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/delete.rs | yazi-dds/src/ember/delete.rs | use std::borrow::Cow;
use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::url::UrlBuf;
use super::Ember;
#[derive(Debug, Deserialize, Serialize)]
pub struct EmberDelete<'a> {
pub urls: Cow<'a, Vec<UrlBuf>>,
}
impl<'a> EmberDelete<'a> {
pub fn borrowed(urls: &'a Vec<UrlBuf>) -> Ember<'a> { Self { urls: Cow::Borrowed(urls) }.into() }
}
impl EmberDelete<'static> {
pub fn owned(urls: Vec<UrlBuf>) -> Ember<'static> { Self { urls: Cow::Owned(urls) }.into() }
}
impl<'a> From<EmberDelete<'a>> for Ember<'a> {
fn from(value: EmberDelete<'a>) -> Self { Self::Delete(value) }
}
impl IntoLua for EmberDelete<'_> {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
let urls =
lua.create_sequence_from(self.urls.into_owned().into_iter().map(yazi_binding::Url::new))?;
lua.create_table_from([("urls", urls)])?.into_lua(lua)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/custom.rs | yazi-dds/src/ember/custom.rs | use mlua::{IntoLua, Lua, Value};
use serde::Serialize;
use yazi_shared::data::Data;
use super::Ember;
use crate::Sendable;
#[derive(Debug)]
pub struct EmberCustom {
pub kind: String,
pub data: Data,
}
impl EmberCustom {
pub fn from_str(kind: &str, data: &str) -> anyhow::Result<Ember<'static>> {
Ok(Self { kind: kind.to_owned(), data: serde_json::from_str(data)? }.into())
}
pub fn from_lua(lua: &Lua, kind: &str, data: Value) -> mlua::Result<Ember<'static>> {
Ok(Self { kind: kind.to_owned(), data: Sendable::value_to_data(lua, data)? }.into())
}
}
impl From<EmberCustom> for Ember<'_> {
fn from(value: EmberCustom) -> Self { Self::Custom(value) }
}
impl IntoLua for EmberCustom {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> { Sendable::data_to_value(lua, self.data) }
}
impl Serialize for EmberCustom {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(&self.data, serializer)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
sxyazi/yazi | https://github.com/sxyazi/yazi/blob/3c39a326abaacb37d9ff15af7668756d60624dfa/yazi-dds/src/ember/tab.rs | yazi-dds/src/ember/tab.rs | use mlua::{IntoLua, Lua, Value};
use serde::{Deserialize, Serialize};
use yazi_shared::Id;
use super::Ember;
#[derive(Debug, Deserialize, Serialize)]
pub struct EmberTab {
pub id: Id,
}
impl EmberTab {
pub fn owned(id: Id) -> Ember<'static> { Self { id }.into() }
pub fn borrowed(id: Id) -> Ember<'static> { Self::owned(id) }
}
impl From<EmberTab> for Ember<'_> {
fn from(value: EmberTab) -> Self { Self::Tab(value) }
}
impl IntoLua for EmberTab {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
lua.create_table_from([("idx", self.id.get())])?.into_lua(lua)
}
}
| rust | MIT | 3c39a326abaacb37d9ff15af7668756d60624dfa | 2026-01-04T15:33:17.426354Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/rust-on-exercism/health-statistics.rs | third_party/rust-on-exercism/health-statistics.rs | // ANCHOR: solution
// ANCHOR: setup
#![allow(dead_code)]
pub struct User {
name: String,
age: u32,
height: f32,
visit_count: u32,
last_blood_pressure: Option<(u32, u32)>,
}
pub struct Measurements {
height: f32,
blood_pressure: (u32, u32),
}
pub struct HealthReport<'a> {
patient_name: &'a str,
visit_count: u32,
height_change: f32,
blood_pressure_change: Option<(i32, i32)>,
}
impl User {
pub fn new(name: String, age: u32, height: f32) -> Self {
Self { name, age, height, visit_count: 0, last_blood_pressure: None }
}
// ANCHOR_END: setup
// ANCHOR: User_visit_doctor
pub fn visit_doctor(&mut self, measurements: Measurements) -> HealthReport<'_> {
// ANCHOR_END: User_visit_doctor
self.visit_count += 1;
let bp = measurements.blood_pressure;
let report = HealthReport {
patient_name: &self.name,
visit_count: self.visit_count,
height_change: measurements.height - self.height,
blood_pressure_change: self
.last_blood_pressure
.map(|lbp| (bp.0 as i32 - lbp.0 as i32, bp.1 as i32 - lbp.1 as i32)),
};
self.height = measurements.height;
self.last_blood_pressure = Some(bp);
report
}
}
// ANCHOR: tests
#[test]
fn test_visit() {
let mut bob = User::new(String::from("Bob"), 32, 155.2);
assert_eq!(bob.visit_count, 0);
let report =
bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (120, 80) });
assert_eq!(report.patient_name, "Bob");
assert_eq!(report.visit_count, 1);
assert_eq!(report.blood_pressure_change, None);
assert!((report.height_change - 0.9).abs() < 0.00001);
let report =
bob.visit_doctor(Measurements { height: 156.1, blood_pressure: (115, 76) });
assert_eq!(report.visit_count, 2);
assert_eq!(report.blood_pressure_change, Some((-5, -4)));
assert_eq!(report.height_change, 0.0);
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/cxx/book/snippets.rs | third_party/cxx/book/snippets.rs | //! This file contains various code snippets taken from the CXX book and
//! tutorial. Some have been modified to fit the course better.
// ANCHOR: rust_bridge
#[cxx::bridge]
mod ffi {
extern "Rust" {
type MyType; // Opaque type
fn foo(&self); // Method on `MyType`
fn bar() -> Box<MyType>; // Free function
}
}
struct MyType(i32);
impl MyType {
fn foo(&self) {
println!("{}", self.0);
}
}
fn bar() -> Box<MyType> {
Box::new(MyType(123))
}
// ANCHOR_END: rust_bridge
// ANCHOR: cpp_bridge
#[cxx::bridge]
mod ffi {
extern "C++" {
include!("demo/include/blobstore.h");
type BlobstoreClient;
fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
fn put(&self, parts: &mut MultiBuf) -> u64;
}
unsafe extern "C++" {
fn f(); // safe to call
}
}
// ANCHOR_END: cpp_bridge
// ANCHOR: shared_types
#[cxx::bridge]
mod ffi {
#[derive(Clone, Debug, Hash)]
struct PlayingCard {
suit: Suit,
value: u8, // A=1, J=11, Q=12, K=13
}
enum Suit {
Clubs,
Diamonds,
Hearts,
Spades,
}
}
// ANCHOR_END: shared_types
// ANCHOR: shared_enums_bridge
#[cxx::bridge]
mod ffi {
enum Suit {
Clubs,
Diamonds,
Hearts,
Spades,
}
}
// ANCHOR_END: shared_enums_bridge
// ANCHOR: shared_enums_rust
#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct Suit {
pub repr: u8,
}
#[allow(non_upper_case_globals)]
impl Suit {
pub const Clubs: Self = Suit { repr: 0 };
pub const Diamonds: Self = Suit { repr: 1 };
pub const Hearts: Self = Suit { repr: 2 };
pub const Spades: Self = Suit { repr: 3 };
}
// ANCHOR_END: shared_enums_rust
// ANCHOR: rust_result
#[cxx::bridge]
mod ffi {
extern "Rust" {
fn fallible(depth: usize) -> Result<String>;
}
}
fn fallible(depth: usize) -> anyhow::Result<String> {
if depth == 0 {
return Err(anyhow::Error::msg("fallible1 requires depth > 0"));
}
Ok("Success!".into())
}
// ANCHOR_END: rust_result
// ANCHOR: cpp_exception
#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
include!("example/include/example.h");
fn fallible(depth: usize) -> Result<String>;
}
}
fn main() {
if let Err(err) = ffi::fallible(99) {
eprintln!("Error: {}", err);
process::exit(1);
}
}
// ANCHOR_END: cpp_exception
// ANCHOR: cxx_overview
#[cxx::bridge]
mod ffi {
extern "Rust" {
type MultiBuf;
fn next_chunk(buf: &mut MultiBuf) -> &[u8];
}
unsafe extern "C++" {
include!("example/include/blobstore.h");
type BlobstoreClient;
fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
fn put(self: &BlobstoreClient, buf: &mut MultiBuf) -> Result<u64>;
}
}
// Definitions of Rust types and functions go here
// ANCHOR_END: cxx_overview | rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/cxx/blobstore/build.rs | third_party/cxx/blobstore/build.rs | fn main() {
// Find target directory, either from CARGO_TARGET_DIR or in-tree if unset.
let mut src_dir =
std::env::var_os("CARGO_TARGET_DIR").unwrap_or("../../../target".into());
src_dir.push("/cxxbridge/demo/src");
cxx_build::bridge("src/main.rs")
.file("src/blobstore.cc")
.flag_if_supported("-std=c++14")
.include(".")
.include(src_dir)
.compile("cxxbridge-demo");
println!("cargo:rerun-if-changed=src/main.rs");
println!("cargo:rerun-if-changed=src/blobstore.cc");
println!("cargo:rerun-if-changed=include/blobstore.h");
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/cxx/blobstore/src/main.rs | third_party/cxx/blobstore/src/main.rs | //! Example project demonstrating usage of CXX.
// ANCHOR: bridge
#[allow(unsafe_op_in_unsafe_fn)]
#[cxx::bridge(namespace = "org::blobstore")]
mod ffi {
// Shared structs with fields visible to both languages.
struct BlobMetadata {
size: usize,
tags: Vec<String>,
}
// ANCHOR: rust_bridge
// Rust types and signatures exposed to C++.
extern "Rust" {
type MultiBuf;
fn next_chunk(buf: &mut MultiBuf) -> &[u8];
}
// ANCHOR_END: rust_bridge
// ANCHOR: cpp_bridge
// C++ types and signatures exposed to Rust.
unsafe extern "C++" {
include!("include/blobstore.h");
type BlobstoreClient;
fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
fn put(self: Pin<&mut BlobstoreClient>, parts: &mut MultiBuf) -> u64;
fn tag(self: Pin<&mut BlobstoreClient>, blobid: u64, tag: &str);
fn metadata(&self, blobid: u64) -> BlobMetadata;
}
// ANCHOR_END: cpp_bridge
}
// ANCHOR_END: bridge
/// An iterator over contiguous chunks of a discontiguous file object.
///
/// Toy implementation uses a Vec<Vec<u8>> but in reality this might be
/// iterating over some more complex Rust data structure like a rope, or maybe
/// loading chunks lazily from somewhere.
pub struct MultiBuf {
chunks: Vec<Vec<u8>>,
pos: usize,
}
/// Pulls the next chunk from the buffer.
pub fn next_chunk(buf: &mut MultiBuf) -> &[u8] {
let next = buf.chunks.get(buf.pos);
buf.pos += 1;
next.map_or(&[], Vec::as_slice)
}
fn main() {
let mut client = ffi::new_blobstore_client();
// Upload a blob.
let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()];
let mut buf = MultiBuf { chunks, pos: 0 };
let blobid = client.pin_mut().put(&mut buf);
println!("blobid = {}", blobid);
// Add a tag.
client.pin_mut().tag(blobid, "rust");
// Read back the tags.
let metadata = client.metadata(blobid);
println!("tags = {:?}", metadata.tags);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/rust-by-example/destructuring-arrays.rs | third_party/rust-by-example/destructuring-arrays.rs | #[rustfmt::skip]
fn main() {
let triple = [0, -2, 3];
println!("Tell me about {triple:?}");
match triple {
[0, y, z] => println!("First is 0, y = {y}, and z = {z}"),
[1, ..] => println!("First is 1 and the rest were ignored"),
_ => println!("All elements were ignored"),
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/rust-by-example/destructuring-structs.rs | third_party/rust-by-example/destructuring-structs.rs | struct Foo {
x: (u32, u32),
y: u32,
}
#[rustfmt::skip]
fn main() {
let foo = Foo { x: (1, 2), y: 3 };
match foo {
Foo { y: 2, x: i } => println!("y = 2, x = {i:?}"),
Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"),
Foo { y, .. } => println!("y = {y}, other fields were ignored"),
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/rust-by-example/webevent.rs | third_party/rust-by-example/webevent.rs | enum WebEvent {
PageLoad, // Variant without payload
KeyPress(char), // Tuple struct variant
Click { x: i64, y: i64 }, // Full struct variant
}
#[rustfmt::skip]
fn inspect(event: WebEvent) {
match event {
WebEvent::PageLoad => println!("page loaded"),
WebEvent::KeyPress(c) => println!("pressed '{c}'"),
WebEvent::Click { x, y } => println!("clicked at x={x}, y={y}"),
}
}
fn main() {
let load = WebEvent::PageLoad;
let press = WebEvent::KeyPress('x');
let click = WebEvent::Click { x: 20, y: 80 };
inspect(load);
inspect(press);
inspect(click);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/third_party/rust-by-example/match-guards.rs | third_party/rust-by-example/match-guards.rs | #[rustfmt::skip]
fn main() {
let pair = (2, -2);
println!("Tell me about {pair:?}");
match pair {
(x, y) if x == y => println!("These are twins"),
(x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
(x, _) if x % 2 == 1 => println!("The first one is odd"),
_ => println!("No correlation..."),
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-exerciser/src/lib.rs | mdbook-exerciser/src/lib.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use log::{info, trace};
use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use std::fs::{File, create_dir_all};
use std::io::Write;
use std::path::Path;
const FILENAME_START: &str = "<!-- File ";
const FILENAME_END: &str = " -->";
pub fn process(output_directory: &Path, input_contents: &str) -> anyhow::Result<()> {
let parser = Parser::new(input_contents);
// Find a specially-formatted comment followed by a code block, and then call
// `write_output` with the contents of the code block, to write to a file
// named by the comment. Code blocks without matching comments will be
// ignored, as will comments which are not followed by a code block.
let mut next_filename: Option<String> = None;
let mut current_file: Option<File> = None;
for event in parser {
trace!("{:?}", event);
match event {
Event::Html(html) => {
let html = html.trim();
if html.starts_with(FILENAME_START) && html.ends_with(FILENAME_END) {
next_filename = Some(
html[FILENAME_START.len()..html.len() - FILENAME_END.len()]
.to_string(),
);
info!("Next file: {:?}:", next_filename);
}
}
Event::Start(Tag::CodeBlock(x)) => {
info!("Start {:?}", x);
if let Some(filename) = &next_filename {
let full_filename = output_directory.join(filename);
info!("Opening {:?}", full_filename);
if let Some(directory) = full_filename.parent() {
create_dir_all(directory)?;
}
current_file = Some(File::create(full_filename)?);
next_filename = None;
}
}
Event::Text(text) => {
info!("Text: {:?}", text);
if let Some(output_file) = &mut current_file {
output_file.write_all(text.as_bytes())?;
}
}
Event::End(TagEnd::CodeBlock) => {
info!("End");
current_file = None;
}
_ => {}
}
}
Ok(())
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-exerciser/src/main.rs | mdbook-exerciser/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use anyhow::Context;
use log::trace;
use mdbook::BookItem;
use mdbook::book::Book;
use mdbook::renderer::RenderContext;
use mdbook_exerciser::process;
use std::fs::{create_dir, remove_dir_all};
use std::io::stdin;
use std::path::Path;
fn main() -> anyhow::Result<()> {
pretty_env_logger::init();
let context = RenderContext::from_json(&mut stdin()).context("Parsing stdin")?;
let config = context
.config
.get_renderer("exerciser")
.context("Missing output.exerciser configuration")?;
let output_directory = Path::new(
config
.get("output-directory")
.context(
"Missing output.exerciser.output-directory configuration value",
)?
.as_str()
.context("Expected a string for output.exerciser.output-directory")?,
);
let _ = remove_dir_all(output_directory);
create_dir(output_directory).with_context(|| {
format!("Failed to create output directory {:?}", output_directory)
})?;
process_all(&context.book, output_directory)?;
Ok(())
}
fn process_all(book: &Book, output_directory: &Path) -> anyhow::Result<()> {
for item in book.iter() {
if let BookItem::Chapter(chapter) = item {
trace!("Chapter {:?} / {:?}", chapter.path, chapter.source_path);
if let Some(chapter_path) = &chapter.path {
// Put the exercises in a subdirectory named after the chapter file,
// without its parent directories.
let chapter_output_directory =
output_directory.join(chapter_path.file_stem().with_context(
|| format!("Chapter {:?} has no file stem", chapter_path),
)?);
process(&chapter_output_directory, &chapter.content)?;
}
}
}
Ok(())
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/generics/exercise.rs | src/generics/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: solution
use std::cmp::Ordering;
fn min<T: Ord>(l: T, r: T) -> T {
match l.cmp(&r) {
Ordering::Less | Ordering::Equal => l,
Ordering::Greater => r,
}
}
// ANCHOR: tests
#[test]
fn integers() {
assert_eq!(min(0, 10), 0);
assert_eq!(min(500, 123), 123);
}
#[test]
fn chars() {
assert_eq!(min('a', 'z'), 'a');
assert_eq!(min('7', '1'), '1');
}
#[test]
fn strings() {
assert_eq!(min("hello", "goodbye"), "goodbye");
assert_eq!(min("bat", "armadillo"), "armadillo");
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/lifetimes/exercise.rs | src/lifetimes/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: solution
// ANCHOR: preliminaries
/// A wire type as seen on the wire.
enum WireType {
/// The Varint WireType indicates the value is a single VARINT.
Varint,
// The I64 WireType indicates that the value is precisely 8 bytes in
// little-endian order containing a 64-bit signed integer or double type.
//I64, -- not needed for this exercise
/// The Len WireType indicates that the value is a length represented as a
/// VARINT followed by exactly that number of bytes.
Len,
// The I32 WireType indicates that the value is precisely 4 bytes in
// little-endian order containing a 32-bit signed integer or float type.
//I32, -- not needed for this exercise
}
#[derive(Debug)]
/// A field's value, typed based on the wire type.
enum FieldValue<'a> {
Varint(u64),
//I64(i64), -- not needed for this exercise
Len(&'a [u8]),
//I32(i32), -- not needed for this exercise
}
#[derive(Debug)]
/// A field, containing the field number and its value.
struct Field<'a> {
field_num: u64,
value: FieldValue<'a>,
}
trait ProtoMessage<'a>: Default {
fn add_field(&mut self, field: Field<'a>);
}
impl From<u64> for WireType {
fn from(value: u64) -> Self {
match value {
0 => WireType::Varint,
//1 => WireType::I64, -- not needed for this exercise
2 => WireType::Len,
//5 => WireType::I32, -- not needed for this exercise
_ => panic!("Invalid wire type: {value}"),
}
}
}
impl<'a> FieldValue<'a> {
fn as_str(&self) -> &'a str {
let FieldValue::Len(data) = self else {
panic!("Expected string to be a `Len` field");
};
std::str::from_utf8(data).expect("Invalid string")
}
fn as_bytes(&self) -> &'a [u8] {
let FieldValue::Len(data) = self else {
panic!("Expected bytes to be a `Len` field");
};
data
}
fn as_u64(&self) -> u64 {
let FieldValue::Varint(value) = self else {
panic!("Expected `u64` to be a `Varint` field");
};
*value
}
}
/// Parse a VARINT, returning the parsed value and the remaining bytes.
fn parse_varint(data: &[u8]) -> (u64, &[u8]) {
for i in 0..7 {
let Some(b) = data.get(i) else {
panic!("Not enough bytes for varint");
};
if b & 0x80 == 0 {
// This is the last byte of the VARINT, so convert it to
// a u64 and return it.
let mut value = 0u64;
for b in data[..=i].iter().rev() {
value = (value << 7) | (b & 0x7f) as u64;
}
return (value, &data[i + 1..]);
}
}
// More than 7 bytes is invalid.
panic!("Too many bytes for varint");
}
/// Convert a tag into a field number and a WireType.
fn unpack_tag(tag: u64) -> (u64, WireType) {
let field_num = tag >> 3;
let wire_type = WireType::from(tag & 0x7);
(field_num, wire_type)
}
// ANCHOR_END: preliminaries
// ANCHOR: parse_field
/// Parse a field, returning the remaining bytes
fn parse_field(data: &[u8]) -> (Field<'_>, &[u8]) {
let (tag, remainder) = parse_varint(data);
let (field_num, wire_type) = unpack_tag(tag);
let (fieldvalue, remainder) = match wire_type {
// ANCHOR_END: parse_field
WireType::Varint => {
let (value, remainder) = parse_varint(remainder);
(FieldValue::Varint(value), remainder)
}
WireType::Len => {
let (len, remainder) = parse_varint(remainder);
let len = len as usize; // cast for simplicity
let (value, remainder) = remainder.split_at(len);
(FieldValue::Len(value), remainder)
}
};
(Field { field_num, value: fieldvalue }, remainder)
}
// ANCHOR: parse_message
/// Parse a message in the given data, calling `T::add_field` for each field in
/// the message.
///
/// The entire input is consumed.
fn parse_message<'a, T: ProtoMessage<'a>>(mut data: &'a [u8]) -> T {
let mut result = T::default();
while !data.is_empty() {
let parsed = parse_field(data);
result.add_field(parsed.0);
data = parsed.1;
}
result
}
// ANCHOR_END: parse_message
#[derive(PartialEq)]
// ANCHOR: message_phone_number_type
#[derive(Debug, Default)]
struct PhoneNumber<'a> {
number: &'a str,
type_: &'a str,
}
// ANCHOR_END: message_phone_number_type
#[derive(PartialEq)]
// ANCHOR: message_person_type
#[derive(Debug, Default)]
struct Person<'a> {
name: &'a str,
id: u64,
phone: Vec<PhoneNumber<'a>>,
}
// ANCHOR_END: message_person_type
impl<'a> ProtoMessage<'a> for Person<'a> {
fn add_field(&mut self, field: Field<'a>) {
match field.field_num {
1 => self.name = field.value.as_str(),
2 => self.id = field.value.as_u64(),
3 => self.phone.push(parse_message(field.value.as_bytes())),
_ => {} // skip everything else
}
}
}
impl<'a> ProtoMessage<'a> for PhoneNumber<'a> {
fn add_field(&mut self, field: Field<'a>) {
match field.field_num {
1 => self.number = field.value.as_str(),
2 => self.type_ = field.value.as_str(),
_ => {} // skip everything else
}
}
}
// ANCHOR: tests
#[test]
fn test_id() {
let person_id: Person = parse_message(&[0x10, 0x2a]);
assert_eq!(person_id, Person { name: "", id: 42, phone: vec![] });
}
#[test]
fn test_name() {
let person_name: Person = parse_message(&[
0x0a, 0x0e, 0x62, 0x65, 0x61, 0x75, 0x74, 0x69, 0x66, 0x75, 0x6c, 0x20,
0x6e, 0x61, 0x6d, 0x65,
]);
assert_eq!(person_name, Person { name: "beautiful name", id: 0, phone: vec![] });
}
#[test]
fn test_just_person() {
let person_name_id: Person =
parse_message(&[0x0a, 0x04, 0x45, 0x76, 0x61, 0x6e, 0x10, 0x16]);
assert_eq!(person_name_id, Person { name: "Evan", id: 22, phone: vec![] });
}
#[test]
fn test_phone() {
let phone: Person = parse_message(&[
0x0a, 0x00, 0x10, 0x00, 0x1a, 0x16, 0x0a, 0x0e, 0x2b, 0x31, 0x32, 0x33,
0x34, 0x2d, 0x37, 0x37, 0x37, 0x2d, 0x39, 0x30, 0x39, 0x30, 0x12, 0x04,
0x68, 0x6f, 0x6d, 0x65,
]);
assert_eq!(
phone,
Person {
name: "",
id: 0,
phone: vec![PhoneNumber { number: "+1234-777-9090", type_: "home" },],
}
);
}
// Put that all together into a single parse.
#[test]
fn test_full_person() {
let person: Person = parse_message(&[
0x0a, 0x07, 0x6d, 0x61, 0x78, 0x77, 0x65, 0x6c, 0x6c, 0x10, 0x2a, 0x1a,
0x16, 0x0a, 0x0e, 0x2b, 0x31, 0x32, 0x30, 0x32, 0x2d, 0x35, 0x35, 0x35,
0x2d, 0x31, 0x32, 0x31, 0x32, 0x12, 0x04, 0x68, 0x6f, 0x6d, 0x65, 0x1a,
0x18, 0x0a, 0x0e, 0x2b, 0x31, 0x38, 0x30, 0x30, 0x2d, 0x38, 0x36, 0x37,
0x2d, 0x35, 0x33, 0x30, 0x38, 0x12, 0x06, 0x6d, 0x6f, 0x62, 0x69, 0x6c,
0x65,
]);
assert_eq!(
person,
Person {
name: "maxwell",
id: 42,
phone: vec![
PhoneNumber { number: "+1202-555-1212", type_: "home" },
PhoneNumber { number: "+1800-867-5308", type_: "mobile" },
]
}
);
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/unsafe-rust/exercise.rs | src/unsafe-rust/exercise.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// `DIR` matches name of C struct.
#[allow(clippy::upper_case_acronyms)]
// ANCHOR: solution
// ANCHOR: ffi
mod ffi {
use std::os::raw::{c_char, c_int};
#[cfg(not(target_os = "macos"))]
use std::os::raw::{c_long, c_uchar, c_ulong, c_ushort};
// Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.
#[repr(C)]
pub struct DIR {
_data: [u8; 0],
_marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}
// Layout according to the Linux man page for readdir(3), where ino_t and
// off_t are resolved according to the definitions in
// /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.
#[cfg(not(target_os = "macos"))]
#[repr(C)]
pub struct dirent {
pub d_ino: c_ulong,
pub d_off: c_long,
pub d_reclen: c_ushort,
pub d_type: c_uchar,
pub d_name: [c_char; 256],
}
// Layout according to the macOS man page for dir(5).
#[cfg(target_os = "macos")]
#[repr(C)]
pub struct dirent {
pub d_fileno: u64,
pub d_seekoff: u64,
pub d_reclen: u16,
pub d_namlen: u16,
pub d_type: u8,
pub d_name: [c_char; 1024],
}
unsafe extern "C" {
pub unsafe fn opendir(s: *const c_char) -> *mut DIR;
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
pub unsafe fn readdir(s: *mut DIR) -> *const dirent;
// See https://github.com/rust-lang/libc/issues/414 and the section on
// _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).
//
// "Platforms that existed before these updates were available" refers
// to macOS (as opposed to iOS / wearOS / etc.) on Intel and PowerPC.
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
#[link_name = "readdir$INODE64"]
pub unsafe fn readdir(s: *mut DIR) -> *const dirent;
pub unsafe fn closedir(s: *mut DIR) -> c_int;
}
}
use std::ffi::{CStr, CString, OsStr, OsString};
use std::os::unix::ffi::OsStrExt;
#[derive(Debug)]
struct DirectoryIterator {
path: CString,
dir: *mut ffi::DIR,
}
// ANCHOR_END: ffi
// ANCHOR: DirectoryIterator
impl DirectoryIterator {
fn new(path: &str) -> Result<DirectoryIterator, String> {
// Call opendir and return a Ok value if that worked,
// otherwise return Err with a message.
// ANCHOR_END: DirectoryIterator
let path =
CString::new(path).map_err(|err| format!("Invalid path: {err}"))?;
// SAFETY: path.as_ptr() cannot be NULL.
let dir = unsafe { ffi::opendir(path.as_ptr()) };
if dir.is_null() {
Err(format!("Could not open {path:?}"))
} else {
Ok(DirectoryIterator { path, dir })
}
}
}
// ANCHOR: Iterator
impl Iterator for DirectoryIterator {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
// Keep calling readdir until we get a NULL pointer back.
// ANCHOR_END: Iterator
// SAFETY: self.dir is never NULL.
let dirent = unsafe { ffi::readdir(self.dir) };
if dirent.is_null() {
// We have reached the end of the directory.
return None;
}
// SAFETY: dirent is not NULL and dirent.d_name is NUL
// terminated.
let d_name = unsafe { CStr::from_ptr((*dirent).d_name.as_ptr()) };
let os_str = OsStr::from_bytes(d_name.to_bytes());
Some(os_str.to_owned())
}
}
// ANCHOR: Drop
impl Drop for DirectoryIterator {
fn drop(&mut self) {
// Call closedir as needed.
// ANCHOR_END: Drop
// SAFETY: self.dir is never NULL.
if unsafe { ffi::closedir(self.dir) } != 0 {
panic!("Could not close {:?}", self.path);
}
}
}
// ANCHOR: main
fn main() -> Result<(), String> {
let iter = DirectoryIterator::new(".")?;
println!("files: {:#?}", iter.collect::<Vec<_>>());
Ok(())
}
// ANCHOR_END: main
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
#[test]
fn test_nonexisting_directory() {
let iter = DirectoryIterator::new("no-such-directory");
assert!(iter.is_err());
}
#[test]
fn test_empty_directory() -> Result<(), Box<dyn Error>> {
let tmp = tempfile::TempDir::new()?;
let iter = DirectoryIterator::new(
tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
)?;
let mut entries = iter.collect::<Vec<_>>();
entries.sort();
assert_eq!(entries, &[".", ".."]);
Ok(())
}
#[test]
fn test_nonempty_directory() -> Result<(), Box<dyn Error>> {
let tmp = tempfile::TempDir::new()?;
std::fs::write(tmp.path().join("foo.txt"), "The Foo Diaries\n")?;
std::fs::write(tmp.path().join("bar.png"), "<PNG>\n")?;
std::fs::write(tmp.path().join("crab.rs"), "//! Crab\n")?;
let iter = DirectoryIterator::new(
tmp.path().to_str().ok_or("Non UTF-8 character in path")?,
)?;
let mut entries = iter.collect::<Vec<_>>();
entries.sort();
assert_eq!(entries, &[".", "..", "bar.png", "crab.rs", "foo.txt"]);
Ok(())
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/idiomatic/leveraging-the-type-system/typestate-pattern/typestate-generics.rs | src/idiomatic/leveraging-the-type-system/typestate-pattern/typestate-generics.rs | // ANCHOR: Complete
use std::fmt::Write as _;
// ANCHOR: Serializer-def
struct Serializer<S> {
// [...]
indent: usize,
buffer: String,
state: S,
}
// ANCHOR_END: Serializer-def
// ANCHOR: Root-def
struct Root;
// ANCHOR_END: Root-def
// ANCHOR: Struct-def
struct Struct<S>(S);
// ANCHOR_END: Struct-def
// ANCHOR: List-def
struct List<S>(S);
// ANCHOR_END: List-def
// ANCHOR: Property-def
struct Property<S>(S);
// ANCHOR_END: Property-def
// ANCHOR: Root-impl
impl Serializer<Root> {
fn new() -> Self {
// [...]
Self { indent: 0, buffer: String::new(), state: Root }
}
fn serialize_struct(mut self, name: &str) -> Serializer<Struct<Root>> {
// [...]
writeln!(self.buffer, "{name} {{").unwrap();
Serializer {
indent: self.indent + 1,
buffer: self.buffer,
state: Struct(self.state),
}
}
fn finish(self) -> String {
// [...]
self.buffer
}
}
// ANCHOR_END: Root-impl
// ANCHOR: Struct-impl
impl<S> Serializer<Struct<S>> {
fn serialize_property(mut self, name: &str) -> Serializer<Property<Struct<S>>> {
// [...]
write!(self.buffer, "{}{name}: ", " ".repeat(self.indent * 2)).unwrap();
Serializer {
indent: self.indent,
buffer: self.buffer,
state: Property(self.state),
}
}
fn finish_struct(mut self) -> Serializer<S> {
// [...]
self.indent -= 1;
writeln!(self.buffer, "{}}}", " ".repeat(self.indent * 2)).unwrap();
Serializer { indent: self.indent, buffer: self.buffer, state: self.state.0 }
}
}
// ANCHOR_END: Struct-impl
// ANCHOR: Property-impl
impl<S> Serializer<Property<Struct<S>>> {
fn serialize_struct(mut self, name: &str) -> Serializer<Struct<Struct<S>>> {
// [...]
writeln!(self.buffer, "{name} {{").unwrap();
Serializer {
indent: self.indent + 1,
buffer: self.buffer,
state: Struct(self.state.0),
}
}
fn serialize_list(mut self) -> Serializer<List<Struct<S>>> {
// [...]
writeln!(self.buffer, "[").unwrap();
Serializer {
indent: self.indent + 1,
buffer: self.buffer,
state: List(self.state.0),
}
}
fn serialize_string(mut self, value: &str) -> Serializer<Struct<S>> {
// [...]
writeln!(self.buffer, "{value},").unwrap();
Serializer { indent: self.indent, buffer: self.buffer, state: self.state.0 }
}
}
// ANCHOR_END: Property-impl
// ANCHOR: List-impl
impl<S> Serializer<List<S>> {
fn serialize_struct(mut self, name: &str) -> Serializer<Struct<List<S>>> {
// [...]
writeln!(self.buffer, "{}{name} {{", " ".repeat(self.indent * 2)).unwrap();
Serializer {
indent: self.indent + 1,
buffer: self.buffer,
state: Struct(self.state),
}
}
fn serialize_string(mut self, value: &str) -> Self {
// [...]
writeln!(self.buffer, "{}{value},", " ".repeat(self.indent * 2)).unwrap();
self
}
fn finish_list(mut self) -> Serializer<S> {
// [...]
self.indent -= 1;
writeln!(self.buffer, "{}]", " ".repeat(self.indent * 2)).unwrap();
Serializer { indent: self.indent, buffer: self.buffer, state: self.state.0 }
}
}
// ANCHOR_END: List-impl
// ANCHOR: main
fn main() {
#[rustfmt::skip]
let serializer = Serializer::new()
.serialize_struct("Foo")
.serialize_property("bar")
.serialize_struct("Bar")
.serialize_property("baz")
.serialize_list()
.serialize_string("abc")
.serialize_struct("Baz")
.serialize_property("partial")
.serialize_string("def")
.serialize_property("empty")
.serialize_struct("Empty")
.finish_struct()
.finish_struct()
.finish_list()
.finish_struct()
.finish_struct();
let output = serializer.finish();
println!("{output}");
// These will all fail at compile time:
// Serializer::new().serialize_list();
// Serializer::new().serialize_string("foo");
// Serializer::new().serialize_struct("Foo").serialize_string("bar");
// Serializer::new().serialize_struct("Foo").serialize_list();
// Serializer::new().serialize_property("foo");
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/closures/exercise.rs | src/closures/exercise.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: setup
pub trait Logger {
/// Log a message at the given verbosity level.
fn log(&self, verbosity: u8, message: &str);
}
struct StderrLogger;
impl Logger for StderrLogger {
fn log(&self, verbosity: u8, message: &str) {
eprintln!("verbosity={verbosity}: {message}");
}
}
// ANCHOR_END: setup
/// Only log messages matching a filtering predicate.
struct Filter<L, P> {
inner: L,
predicate: P,
}
impl<L, P> Filter<L, P>
where
L: Logger,
P: Fn(u8, &str) -> bool,
{
fn new(inner: L, predicate: P) -> Self {
Self { inner, predicate }
}
}
impl<L, P> Logger for Filter<L, P>
where
L: Logger,
P: Fn(u8, &str) -> bool,
{
fn log(&self, verbosity: u8, message: &str) {
if (self.predicate)(verbosity, message) {
self.inner.log(verbosity, message);
}
}
}
// ANCHOR: main
fn main() {
let logger = Filter::new(StderrLogger, |_verbosity, msg| msg.contains("yikes"));
logger.log(5, "FYI");
logger.log(1, "yikes, something went wrong");
logger.log(2, "uhoh");
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/exercises/bare-metal/rtc/build.rs | src/exercises/bare-metal/rtc/build.rs | // Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
fn main() {
println!("cargo:rustc-link-arg=-Timage.ld");
println!("cargo:rustc-link-arg=-Tmemory.ld");
println!("cargo:rerun-if-changed=memory.ld");
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/exercises/bare-metal/rtc/src/logger.rs | src/exercises/bare-metal/rtc/src/logger.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use arm_pl011_uart::Uart;
use core::fmt::Write;
use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};
use spin::mutex::SpinMutex;
static LOGGER: Logger = Logger { uart: SpinMutex::new(None) };
struct Logger {
uart: SpinMutex<Option<Uart<'static>>>,
}
impl Log for Logger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
writeln!(
self.uart.lock().as_mut().unwrap(),
"[{}] {}",
record.level(),
record.args()
)
.unwrap();
}
fn flush(&self) {}
}
/// Initialises UART logger.
pub fn init(
uart: Uart<'static>,
max_level: LevelFilter,
) -> Result<(), SetLoggerError> {
LOGGER.uart.lock().replace(uart);
log::set_logger(&LOGGER)?;
log::set_max_level(max_level);
Ok(())
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/exercises/bare-metal/rtc/src/main.rs | src/exercises/bare-metal/rtc/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: top
#![no_main]
#![no_std]
mod exceptions;
mod logger;
// ANCHOR_END: top
mod pl031;
use crate::pl031::Rtc;
use arm_gic::{IntId, Trigger, irq_enable, wfi};
use chrono::{TimeZone, Utc};
use core::hint::spin_loop;
// ANCHOR: imports
use aarch64_paging::descriptor::Attributes;
use aarch64_rt::{InitialPagetable, entry, initial_pagetable};
use arm_gic::gicv3::registers::{Gicd, GicrSgi};
use arm_gic::gicv3::{GicCpuInterface, GicV3};
use arm_pl011_uart::{PL011Registers, Uart, UniqueMmioPointer};
use core::panic::PanicInfo;
use core::ptr::NonNull;
use log::{LevelFilter, error, info, trace};
use smccc::Hvc;
use smccc::psci::system_off;
/// Base addresses of the GICv3.
const GICD_BASE_ADDRESS: NonNull<Gicd> = NonNull::new(0x800_0000 as _).unwrap();
const GICR_BASE_ADDRESS: NonNull<GicrSgi> = NonNull::new(0x80A_0000 as _).unwrap();
/// Base address of the primary PL011 UART.
const PL011_BASE_ADDRESS: NonNull<PL011Registers> =
NonNull::new(0x900_0000 as _).unwrap();
/// Attributes to use for device memory in the initial identity map.
const DEVICE_ATTRIBUTES: Attributes = Attributes::VALID
.union(Attributes::ATTRIBUTE_INDEX_0)
.union(Attributes::ACCESSED)
.union(Attributes::UXN);
/// Attributes to use for normal memory in the initial identity map.
const MEMORY_ATTRIBUTES: Attributes = Attributes::VALID
.union(Attributes::ATTRIBUTE_INDEX_1)
.union(Attributes::INNER_SHAREABLE)
.union(Attributes::ACCESSED)
.union(Attributes::NON_GLOBAL);
initial_pagetable!({
let mut idmap = [0; 512];
// 1 GiB of device memory.
idmap[0] = DEVICE_ATTRIBUTES.bits();
// 1 GiB of normal memory.
idmap[1] = MEMORY_ATTRIBUTES.bits() | 0x40000000;
// Another 1 GiB of device memory starting at 256 GiB.
idmap[256] = DEVICE_ATTRIBUTES.bits() | 0x4000000000;
InitialPagetable(idmap)
});
// ANCHOR_END: imports
/// Base address of the PL031 RTC.
const PL031_BASE_ADDRESS: NonNull<pl031::Registers> =
NonNull::new(0x901_0000 as _).unwrap();
/// The IRQ used by the PL031 RTC.
const PL031_IRQ: IntId = IntId::spi(2);
// ANCHOR: main
entry!(main);
fn main(x0: u64, x1: u64, x2: u64, x3: u64) -> ! {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let uart = unsafe { Uart::new(UniqueMmioPointer::new(PL011_BASE_ADDRESS)) };
logger::init(uart, LevelFilter::Trace).unwrap();
info!("main({:#x}, {:#x}, {:#x}, {:#x})", x0, x1, x2, x3);
// SAFETY: `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the base
// addresses of a GICv3 distributor and redistributor respectively, and
// nothing else accesses those address ranges.
let mut gic = unsafe {
GicV3::new(
UniqueMmioPointer::new(GICD_BASE_ADDRESS),
GICR_BASE_ADDRESS,
1,
false,
)
};
gic.setup(0);
// ANCHOR_END: main
// SAFETY: `PL031_BASE_ADDRESS` is the base address of a PL031 device, and
// nothing else accesses that address range.
let mut rtc = unsafe { Rtc::new(UniqueMmioPointer::new(PL031_BASE_ADDRESS)) };
let timestamp = rtc.read();
let time = Utc.timestamp_opt(timestamp.into(), 0).unwrap();
info!("RTC: {time}");
GicCpuInterface::set_priority_mask(0xff);
gic.set_interrupt_priority(PL031_IRQ, None, 0x80).unwrap();
gic.set_trigger(PL031_IRQ, None, Trigger::Level).unwrap();
irq_enable();
gic.enable_interrupt(PL031_IRQ, None, true).unwrap();
// Wait for 3 seconds, without interrupts.
let target = timestamp + 3;
rtc.set_match(target);
info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap());
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
while !rtc.matched() {
spin_loop();
}
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
info!("Finished waiting");
// Wait another 3 seconds for an interrupt.
let target = timestamp + 6;
info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap());
rtc.set_match(target);
rtc.clear_interrupt();
rtc.enable_interrupt(true);
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
while !rtc.interrupt_pending() {
wfi();
}
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
info!("Finished waiting");
// ANCHOR: main_end
system_off::<Hvc>().unwrap();
panic!("system_off returned");
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
error!("{info}");
system_off::<Hvc>().unwrap();
loop {}
}
// ANCHOR_END: main_end
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/exercises/bare-metal/rtc/src/exceptions.rs | src/exercises/bare-metal/rtc/src/exceptions.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use aarch64_rt::{ExceptionHandlers, RegisterStateRef, exception_handlers};
use arm_gic::gicv3::{GicCpuInterface, InterruptGroup};
use log::{error, info, trace};
use smccc::Hvc;
use smccc::psci::system_off;
struct Handlers;
impl ExceptionHandlers for Handlers {
extern "C" fn sync_current(_state: RegisterStateRef) {
error!("sync_current");
system_off::<Hvc>().unwrap();
}
extern "C" fn irq_current(_state: RegisterStateRef) {
trace!("irq_current");
let intid =
GicCpuInterface::get_and_acknowledge_interrupt(InterruptGroup::Group1)
.expect("No pending interrupt");
info!("IRQ {intid:?}");
}
extern "C" fn fiq_current(_state: RegisterStateRef) {
error!("fiq_current");
system_off::<Hvc>().unwrap();
}
extern "C" fn serror_current(_state: RegisterStateRef) {
error!("serror_current");
system_off::<Hvc>().unwrap();
}
extern "C" fn sync_lower(_state: RegisterStateRef) {
error!("sync_lower");
system_off::<Hvc>().unwrap();
}
extern "C" fn irq_lower(_state: RegisterStateRef) {
error!("irq_lower");
system_off::<Hvc>().unwrap();
}
extern "C" fn fiq_lower(_state: RegisterStateRef) {
error!("fiq_lower");
system_off::<Hvc>().unwrap();
}
extern "C" fn serror_lower(_state: RegisterStateRef) {
error!("serror_lower");
system_off::<Hvc>().unwrap();
}
}
exception_handlers!(Handlers);
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/exercises/bare-metal/rtc/src/pl031.rs | src/exercises/bare-metal/rtc/src/pl031.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use safe_mmio::fields::{ReadPure, ReadPureWrite, WriteOnly};
use safe_mmio::{UniqueMmioPointer, field, field_shared};
// ANCHOR: solution
#[repr(C, align(4))]
pub struct Registers {
/// Data register
dr: ReadPure<u32>,
/// Match register
mr: ReadPureWrite<u32>,
/// Load register
lr: ReadPureWrite<u32>,
/// Control register
cr: ReadPureWrite<u8>,
_reserved0: [u8; 3],
/// Interrupt Mask Set or Clear register
imsc: ReadPureWrite<u8>,
_reserved1: [u8; 3],
/// Raw Interrupt Status
ris: ReadPure<u8>,
_reserved2: [u8; 3],
/// Masked Interrupt Status
mis: ReadPure<u8>,
_reserved3: [u8; 3],
/// Interrupt Clear Register
icr: WriteOnly<u8>,
_reserved4: [u8; 3],
}
/// Driver for a PL031 real-time clock.
#[derive(Debug)]
pub struct Rtc<'a> {
registers: UniqueMmioPointer<'a, Registers>,
}
impl<'a> Rtc<'a> {
/// Constructs a new instance of the RTC driver for a PL031 device with the
/// given set of registers.
pub fn new(registers: UniqueMmioPointer<'a, Registers>) -> Self {
Self { registers }
}
/// Reads the current RTC value.
pub fn read(&self) -> u32 {
field_shared!(self.registers, dr).read()
}
/// Writes a match value. When the RTC value matches this then an interrupt
/// will be generated (if it is enabled).
pub fn set_match(&mut self, value: u32) {
field!(self.registers, mr).write(value);
}
/// Returns whether the match register matches the RTC value, whether or not
/// the interrupt is enabled.
pub fn matched(&self) -> bool {
let ris = field_shared!(self.registers, ris).read();
(ris & 0x01) != 0
}
/// Returns whether there is currently an interrupt pending.
///
/// This should be true if and only if `matched` returns true and the
/// interrupt is masked.
pub fn interrupt_pending(&self) -> bool {
let mis = field_shared!(self.registers, mis).read();
(mis & 0x01) != 0
}
/// Sets or clears the interrupt mask.
///
/// When the mask is true the interrupt is enabled; when it is false the
/// interrupt is disabled.
pub fn enable_interrupt(&mut self, mask: bool) {
let imsc = if mask { 0x01 } else { 0x00 };
field!(self.registers, imsc).write(imsc);
}
/// Clears a pending interrupt, if any.
pub fn clear_interrupt(&mut self) {
field!(self.registers, icr).write(0x01);
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/exercises/bare-metal/compass/src/main.rs | src/exercises/bare-metal/compass/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: top
#![no_main]
#![no_std]
extern crate panic_halt as _;
use core::fmt::Write;
use cortex_m_rt::entry;
// ANCHOR_END: top
use embedded_hal::digital::InputPin;
use lsm303agr::{
AccelMode, AccelOutputDataRate, Lsm303agr, MagMode, MagOutputDataRate,
};
use microbit::Board;
use microbit::display::blocking::Display;
use microbit::hal::twim::Twim;
use microbit::hal::uarte::{Baudrate, Parity, Uarte};
use microbit::hal::{Delay, Timer};
use microbit::pac::twim0::frequency::FREQUENCY_A;
const COMPASS_SCALE: i32 = 30000;
const ACCELEROMETER_SCALE: i32 = 700;
// ANCHOR: main
#[entry]
fn main() -> ! {
let mut board = Board::take().unwrap();
// Configure serial port.
let mut serial = Uarte::new(
board.UARTE0,
board.uart.into(),
Parity::EXCLUDED,
Baudrate::BAUD115200,
);
// Use the system timer as a delay provider.
let mut delay = Delay::new(board.SYST);
// Set up the I2C controller and Inertial Measurement Unit.
// ANCHOR_END: main
writeln!(serial, "Setting up IMU...").unwrap();
let i2c = Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100);
let mut imu = Lsm303agr::new_with_i2c(i2c);
imu.init().unwrap();
imu.set_mag_mode_and_odr(
&mut delay,
MagMode::HighResolution,
MagOutputDataRate::Hz50,
)
.unwrap();
imu.set_accel_mode_and_odr(
&mut delay,
AccelMode::Normal,
AccelOutputDataRate::Hz50,
)
.unwrap();
let mut imu = imu.into_mag_continuous().ok().unwrap();
// Set up display and timer.
let mut timer = Timer::new(board.TIMER0);
let mut display = Display::new(board.display_pins);
let mut mode = Mode::Compass;
let mut button_pressed = false;
// ANCHOR: loop
writeln!(serial, "Ready.").unwrap();
loop {
// Read compass data and log it to the serial port.
// ANCHOR_END: loop
while !(imu.mag_status().unwrap().xyz_new_data()
&& imu.accel_status().unwrap().xyz_new_data())
{}
let compass_reading = imu.magnetic_field().unwrap();
let accelerometer_reading = imu.acceleration().unwrap();
writeln!(
serial,
"{},{},{}\t{},{},{}",
compass_reading.x_nt(),
compass_reading.y_nt(),
compass_reading.z_nt(),
accelerometer_reading.x_mg(),
accelerometer_reading.y_mg(),
accelerometer_reading.z_mg(),
)
.unwrap();
let mut image = [[0; 5]; 5];
let (x, y) = match mode {
Mode::Compass => (
scale(-compass_reading.x_nt(), -COMPASS_SCALE, COMPASS_SCALE, 0, 4)
as usize,
scale(compass_reading.y_nt(), -COMPASS_SCALE, COMPASS_SCALE, 0, 4)
as usize,
),
Mode::Accelerometer => (
scale(
accelerometer_reading.x_mg(),
-ACCELEROMETER_SCALE,
ACCELEROMETER_SCALE,
0,
4,
) as usize,
scale(
-accelerometer_reading.y_mg(),
-ACCELEROMETER_SCALE,
ACCELEROMETER_SCALE,
0,
4,
) as usize,
),
};
image[y][x] = 255;
display.show(&mut timer, image, 100);
// If button A is pressed, switch to the next mode and briefly blink all LEDs
// on.
if board.buttons.button_a.is_low().unwrap() {
if !button_pressed {
mode = mode.next();
display.show(&mut timer, [[255; 5]; 5], 200);
}
button_pressed = true;
} else {
button_pressed = false;
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Mode {
Compass,
Accelerometer,
}
impl Mode {
fn next(self) -> Self {
match self {
Self::Compass => Self::Accelerometer,
Self::Accelerometer => Self::Compass,
}
}
}
fn scale(value: i32, min_in: i32, max_in: i32, min_out: i32, max_out: i32) -> i32 {
let range_in = max_in - min_in;
let range_out = max_out - min_out;
let scaled = min_out + range_out * (value - min_in) / range_in;
scaled.clamp(min_out, max_out)
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/concurrency/async-exercises/dining-philosophers.rs | src/concurrency/async-exercises/dining-philosophers.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: Philosopher
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use tokio::time;
struct Chopstick;
struct Philosopher {
name: String,
// ANCHOR_END: Philosopher
left_chopstick: Arc<Mutex<Chopstick>>,
right_chopstick: Arc<Mutex<Chopstick>>,
thoughts: mpsc::Sender<String>,
}
// ANCHOR: Philosopher-think
impl Philosopher {
async fn think(&self) {
self.thoughts
.send(format!("Eureka! {} has a new idea!", &self.name))
.await
.unwrap();
}
// ANCHOR_END: Philosopher-think
// ANCHOR: Philosopher-eat
async fn eat(&self) {
// Keep trying until we have both chopsticks
// ANCHOR_END: Philosopher-eat
// Pick up chopsticks...
let _left_chopstick = self.left_chopstick.lock().await;
let _right_chopstick = self.right_chopstick.lock().await;
// ANCHOR: Philosopher-eat-body
println!("{} is eating...", &self.name);
time::sleep(time::Duration::from_millis(5)).await;
// ANCHOR_END: Philosopher-eat-body
// The locks are dropped here
// ANCHOR: Philosopher-eat-end
}
}
// tokio scheduler doesn't deadlock with 5 philosophers, so have 2.
static PHILOSOPHERS: &[&str] = &["Socrates", "Hypatia"];
#[tokio::main]
async fn main() {
// ANCHOR_END: Philosopher-eat-end
// Create chopsticks
let mut chopsticks = vec![];
PHILOSOPHERS
.iter()
.for_each(|_| chopsticks.push(Arc::new(Mutex::new(Chopstick))));
// Create philosophers
let (philosophers, mut rx) = {
let mut philosophers = vec![];
let (tx, rx) = mpsc::channel(10);
for (i, name) in PHILOSOPHERS.iter().enumerate() {
let mut left_chopstick = Arc::clone(&chopsticks[i]);
let mut right_chopstick =
Arc::clone(&chopsticks[(i + 1) % PHILOSOPHERS.len()]);
if i == PHILOSOPHERS.len() - 1 {
std::mem::swap(&mut left_chopstick, &mut right_chopstick);
}
philosophers.push(Philosopher {
name: name.to_string(),
left_chopstick,
right_chopstick,
thoughts: tx.clone(),
});
}
(philosophers, rx)
// tx is dropped here, so we don't need to explicitly drop it later
};
// Make them think and eat
for phil in philosophers {
tokio::spawn(async move {
for _ in 0..100 {
phil.think().await;
phil.eat().await;
}
});
}
// Output their thoughts
while let Some(thought) = rx.recv().await {
println!("Here is a thought: {thought}");
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/concurrency/async-exercises/chat-async/src/bin/client.rs | src/concurrency/async-exercises/chat-async/src/bin/client.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: setup
use futures_util::SinkExt;
use futures_util::stream::StreamExt;
use http::Uri;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio_websockets::{ClientBuilder, Message};
#[tokio::main]
async fn main() -> Result<(), tokio_websockets::Error> {
let (mut ws_stream, _) =
ClientBuilder::from_uri(Uri::from_static("ws://127.0.0.1:2000"))
.connect()
.await?;
let stdin = tokio::io::stdin();
let mut stdin = BufReader::new(stdin).lines();
// ANCHOR_END: setup
// Continuous loop for concurrently sending and receiving messages.
loop {
tokio::select! {
incoming = ws_stream.next() => {
match incoming {
Some(Ok(msg)) => {
if let Some(text) = msg.as_text() {
println!("From server: {}", text);
}
},
Some(Err(err)) => return Err(err),
None => return Ok(()),
}
}
res = stdin.next_line() => {
match res {
Ok(None) => return Ok(()),
Ok(Some(line)) => ws_stream.send(Message::text(line.to_string())).await?,
Err(err) => return Err(err.into()),
}
}
}
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/concurrency/async-exercises/chat-async/src/bin/server.rs | src/concurrency/async-exercises/chat-async/src/bin/server.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: setup
use futures_util::sink::SinkExt;
use futures_util::stream::StreamExt;
use std::error::Error;
use std::net::SocketAddr;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::broadcast::{Sender, channel};
use tokio_websockets::{Message, ServerBuilder, WebSocketStream};
// ANCHOR_END: setup
// ANCHOR: handle_connection
async fn handle_connection(
addr: SocketAddr,
mut ws_stream: WebSocketStream<TcpStream>,
bcast_tx: Sender<String>,
) -> Result<(), Box<dyn Error + Send + Sync>> {
// ANCHOR_END: handle_connection
ws_stream
.send(Message::text("Welcome to chat! Type a message".to_string()))
.await?;
let mut bcast_rx = bcast_tx.subscribe();
// A continuous loop for concurrently performing two tasks: (1) receiving
// messages from `ws_stream` and broadcasting them, and (2) receiving
// messages on `bcast_rx` and sending them to the client.
loop {
tokio::select! {
incoming = ws_stream.next() => {
match incoming {
Some(Ok(msg)) => {
if let Some(text) = msg.as_text() {
println!("From client {addr:?} {text:?}");
bcast_tx.send(text.into())?;
}
}
Some(Err(err)) => return Err(err.into()),
None => return Ok(()),
}
}
msg = bcast_rx.recv() => {
ws_stream.send(Message::text(msg?)).await?;
}
}
}
// ANCHOR: main
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
let (bcast_tx, _) = channel(16);
let listener = TcpListener::bind("127.0.0.1:2000").await?;
println!("listening on port 2000");
loop {
let (socket, addr) = listener.accept().await?;
println!("New connection from {addr:?}");
let bcast_tx = bcast_tx.clone();
tokio::spawn(async move {
// Wrap the raw TCP stream into a websocket.
let (_req, ws_stream) = ServerBuilder::new().accept(socket).await?;
handle_connection(addr, ws_stream, bcast_tx).await
});
}
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/concurrency/sync-exercises/dining-philosophers.rs | src/concurrency/sync-exercises/dining-philosophers.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: Philosopher
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
use std::time::Duration;
struct Chopstick;
struct Philosopher {
name: String,
// ANCHOR_END: Philosopher
left_chopstick: Arc<Mutex<Chopstick>>,
right_chopstick: Arc<Mutex<Chopstick>>,
thoughts: mpsc::SyncSender<String>,
}
// ANCHOR: Philosopher-think
impl Philosopher {
fn think(&self) {
self.thoughts
.send(format!("Eureka! {} has a new idea!", &self.name))
.unwrap();
}
// ANCHOR_END: Philosopher-think
// ANCHOR: Philosopher-eat
fn eat(&self) {
// ANCHOR_END: Philosopher-eat
println!("{} is trying to eat", &self.name);
let _left = self.left_chopstick.lock().unwrap();
let _right = self.right_chopstick.lock().unwrap();
// ANCHOR: Philosopher-eat-end
println!("{} is eating...", &self.name);
thread::sleep(Duration::from_millis(10));
}
}
static PHILOSOPHERS: &[&str] =
&["Socrates", "Hypatia", "Plato", "Aristotle", "Pythagoras"];
fn main() {
// ANCHOR_END: Philosopher-eat-end
let (tx, rx) = mpsc::sync_channel(10);
let chopsticks = PHILOSOPHERS
.iter()
.map(|_| Arc::new(Mutex::new(Chopstick)))
.collect::<Vec<_>>();
for i in 0..chopsticks.len() {
let tx = tx.clone();
let mut left_chopstick = Arc::clone(&chopsticks[i]);
let mut right_chopstick =
Arc::clone(&chopsticks[(i + 1) % chopsticks.len()]);
// To avoid a deadlock, we have to break the symmetry
// somewhere. This will swap the chopsticks without deinitializing
// either of them.
if i == chopsticks.len() - 1 {
std::mem::swap(&mut left_chopstick, &mut right_chopstick);
}
let philosopher = Philosopher {
name: PHILOSOPHERS[i].to_string(),
thoughts: tx,
left_chopstick,
right_chopstick,
};
thread::spawn(move || {
for _ in 0..100 {
philosopher.eat();
philosopher.think();
}
});
}
drop(tx);
for thought in rx {
println!("{thought}");
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/concurrency/sync-exercises/link-checker.rs | src/concurrency/sync-exercises/link-checker.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
// ANCHOR: setup
use reqwest::Url;
use reqwest::blocking::Client;
use scraper::{Html, Selector};
use thiserror::Error;
#[derive(Error, Debug)]
enum Error {
#[error("request error: {0}")]
ReqwestError(#[from] reqwest::Error),
#[error("bad http response: {0}")]
BadResponse(String),
}
// ANCHOR_END: setup
// ANCHOR: visit_page
#[derive(Debug)]
struct CrawlCommand {
url: Url,
extract_links: bool,
}
fn visit_page(client: &Client, command: &CrawlCommand) -> Result<Vec<Url>, Error> {
println!("Checking {:#}", command.url);
let response = client.get(command.url.clone()).send()?;
if !response.status().is_success() {
return Err(Error::BadResponse(response.status().to_string()));
}
let mut link_urls = Vec::new();
if !command.extract_links {
return Ok(link_urls);
}
let base_url = response.url().to_owned();
let body_text = response.text()?;
let document = Html::parse_document(&body_text);
let selector = Selector::parse("a").unwrap();
let href_values = document
.select(&selector)
.filter_map(|element| element.value().attr("href"));
for href in href_values {
match base_url.join(href) {
Ok(link_url) => {
link_urls.push(link_url);
}
Err(err) => {
println!("On {base_url:#}: ignored unparsable {href:?}: {err}");
}
}
}
Ok(link_urls)
}
// ANCHOR_END: visit_page
struct CrawlState {
domain: String,
visited_pages: std::collections::HashSet<String>,
}
impl CrawlState {
fn new(start_url: &Url) -> CrawlState {
let mut visited_pages = std::collections::HashSet::new();
visited_pages.insert(start_url.as_str().to_string());
CrawlState { domain: start_url.domain().unwrap().to_string(), visited_pages }
}
/// Determine whether links within the given page should be extracted.
fn should_extract_links(&self, url: &Url) -> bool {
let Some(url_domain) = url.domain() else {
return false;
};
url_domain == self.domain
}
/// Mark the given page as visited, returning false if it had already
/// been visited.
fn mark_visited(&mut self, url: &Url) -> bool {
self.visited_pages.insert(url.as_str().to_string())
}
}
type CrawlResult = Result<Vec<Url>, (Url, Error)>;
fn spawn_crawler_threads(
command_receiver: mpsc::Receiver<CrawlCommand>,
result_sender: mpsc::Sender<CrawlResult>,
thread_count: u32,
) {
// To multiplex the non-cloneable Receiver, wrap it in Arc<Mutex<_>>.
let command_receiver = Arc::new(Mutex::new(command_receiver));
for _ in 0..thread_count {
let result_sender = result_sender.clone();
let command_receiver = Arc::clone(&command_receiver);
thread::spawn(move || {
let client = Client::new();
loop {
let command_result = {
let receiver_guard = command_receiver.lock().unwrap();
receiver_guard.recv()
};
let Ok(crawl_command) = command_result else {
// The sender got dropped. No more commands coming in.
break;
};
let crawl_result = match visit_page(&client, &crawl_command) {
Ok(link_urls) => Ok(link_urls),
Err(error) => Err((crawl_command.url, error)),
};
result_sender.send(crawl_result).unwrap();
}
});
}
}
fn control_crawl(
start_url: Url,
command_sender: mpsc::Sender<CrawlCommand>,
result_receiver: mpsc::Receiver<CrawlResult>,
) -> Vec<Url> {
let mut crawl_state = CrawlState::new(&start_url);
let start_command = CrawlCommand { url: start_url, extract_links: true };
command_sender.send(start_command).unwrap();
let mut pending_urls = 1;
let mut bad_urls = Vec::new();
while pending_urls > 0 {
let crawl_result = result_receiver.recv().unwrap();
pending_urls -= 1;
match crawl_result {
Ok(link_urls) => {
for url in link_urls {
if crawl_state.mark_visited(&url) {
let extract_links = crawl_state.should_extract_links(&url);
let crawl_command = CrawlCommand { url, extract_links };
command_sender.send(crawl_command).unwrap();
pending_urls += 1;
}
}
}
Err((url, error)) => {
bad_urls.push(url);
println!("Got crawling error: {:#}", error);
continue;
}
}
}
bad_urls
}
fn check_links(start_url: Url) -> Vec<Url> {
let (result_sender, result_receiver) = mpsc::channel::<CrawlResult>();
let (command_sender, command_receiver) = mpsc::channel::<CrawlCommand>();
spawn_crawler_threads(command_receiver, result_sender, 16);
control_crawl(start_url, command_sender, result_receiver)
}
fn main() {
let start_url = reqwest::Url::parse("https://www.google.org").unwrap();
let bad_urls = check_links(start_url);
println!("Bad URLs: {:#?}", bad_urls);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/references/exercise.rs | src/references/exercise.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
/// Calculate the magnitude of the given vector.
fn magnitude(vector: &[f64; 3]) -> f64 {
let mut mag_squared = 0.0;
for coord in vector {
mag_squared += coord * coord;
}
mag_squared.sqrt()
}
/// Change the magnitude of the vector to 1.0 without changing its direction.
fn normalize(vector: &mut [f64; 3]) {
let mag = magnitude(vector);
for item in vector {
*item /= mag;
}
}
// ANCHOR: main
fn main() {
println!("Magnitude of a unit vector: {}", magnitude(&[0.0, 1.0, 0.0]));
let mut v = [1.0, 2.0, 9.0];
println!("Magnitude of {v:?}: {}", magnitude(&v));
normalize(&mut v);
println!("Magnitude of {v:?} after normalization: {}", magnitude(&v));
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/memory-management/exercise.rs | src/memory-management/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: solution
// ANCHOR: Package
#[derive(Debug)]
enum Language {
Rust,
Java,
Perl,
}
#[derive(Clone, Debug)]
struct Dependency {
name: String,
version_expression: String,
}
/// A representation of a software package.
#[derive(Debug)]
struct Package {
name: String,
version: String,
authors: Vec<String>,
dependencies: Vec<Dependency>,
language: Option<Language>,
}
impl Package {
// ANCHOR_END: Package
// ANCHOR: as_dependency
/// Return a representation of this package as a dependency, for use in
/// building other packages.
fn as_dependency(&self) -> Dependency {
// ANCHOR_END: as_dependency
Dependency {
name: self.name.clone(),
version_expression: self.version.clone(),
}
}
}
// ANCHOR: PackageBuilder
/// A builder for a Package. Use `build()` to create the `Package` itself.
struct PackageBuilder(Package);
impl PackageBuilder {
// ANCHOR_END: PackageBuilder
// ANCHOR: new
fn new(name: impl Into<String>) -> Self {
// ANCHOR_END: new
Self(Package {
name: name.into(),
version: "0.1".into(),
authors: Vec::new(),
dependencies: Vec::new(),
language: None,
})
}
// ANCHOR: version
/// Set the package version.
fn version(mut self, version: impl Into<String>) -> Self {
self.0.version = version.into();
self
}
// ANCHOR_END: version
// ANCHOR: authors
/// Set the package authors.
fn authors(mut self, authors: Vec<String>) -> Self {
// ANCHOR_END: authors
self.0.authors = authors;
self
}
// ANCHOR: dependency
/// Add an additional dependency.
fn dependency(mut self, dependency: Dependency) -> Self {
// ANCHOR_END: dependency
self.0.dependencies.push(dependency);
self
}
// ANCHOR: language
/// Set the language. If not set, language defaults to None.
fn language(mut self, language: Language) -> Self {
// ANCHOR_END: language
self.0.language = Some(language);
self
}
// ANCHOR: build
fn build(self) -> Package {
self.0
}
}
// ANCHOR_END: build
// ANCHOR: main
fn main() {
let base64 = PackageBuilder::new("base64").version("0.13").build();
dbg!(&base64);
let log =
PackageBuilder::new("log").version("0.4").language(Language::Rust).build();
dbg!(&log);
let serde = PackageBuilder::new("serde")
.authors(vec!["djmitche".into()])
.version(String::from("4.0"))
.dependency(base64.as_dependency())
.dependency(log.as_dependency())
.build();
dbg!(serde);
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/tuples-and-arrays/exercise.rs | src/tuples-and-arrays/exercise.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Iterators are covered later.
#[allow(clippy::needless_range_loop)]
// ANCHOR: solution
// ANCHOR: transpose
fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
// ANCHOR_END: transpose
let mut result = [[0; 3]; 3];
for i in 0..3 {
for j in 0..3 {
result[j][i] = matrix[i][j];
}
}
result
}
// ANCHOR: main
fn main() {
let matrix = [
[101, 102, 103], // <-- the comment makes rustfmt add a newline
[201, 202, 203],
[301, 302, 303],
];
println!("Original:");
for row in &matrix {
println!("{:?}", row);
}
let transposed = transpose(matrix);
println!("\nTransposed:");
for row in &transposed {
println!("{:?}", row);
}
}
// ANCHOR_END: main
// ANCHOR_END: solution
// This test does not appear in the exercise, as this is very early in the
// course, but it verifies that the solution is correct.
#[test]
fn test_transpose() {
let matrix = [
[101, 102, 103], //
[201, 202, 203],
[301, 302, 303],
];
let transposed = transpose(matrix);
assert_eq!(
transposed,
[
[101, 201, 301], //
[102, 202, 302],
[103, 203, 303],
]
);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/control-flow-basics/exercise.rs | src/control-flow-basics/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: collatz_length
/// Determine the length of the collatz sequence beginning at `n`.
fn collatz_length(mut n: i32) -> u32 {
// ANCHOR_END: collatz_length
let mut len = 1;
while n > 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
len += 1;
}
len
}
// ANCHOR: main
fn main() {
println!("Length: {}", collatz_length(11)); // should be 15
}
// ANCHOR_END: main
// ANCHOR_END: solution
#[test]
fn test_collatz_length() {
assert_eq!(collatz_length(11), 15);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/modules/exercise.rs | src/modules/exercise.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: single-module
pub trait Widget {
/// Natural width of `self`.
fn width(&self) -> usize;
/// Draw the widget into a buffer.
fn draw_into(&self, buffer: &mut dyn std::fmt::Write);
/// Draw the widget on standard output.
fn draw(&self) {
let mut buffer = String::new();
self.draw_into(&mut buffer);
println!("{buffer}");
}
}
pub struct Label {
label: String,
}
impl Label {
fn new(label: &str) -> Label {
Label { label: label.to_owned() }
}
}
pub struct Button {
label: Label,
}
impl Button {
fn new(label: &str) -> Button {
Button { label: Label::new(label) }
}
}
pub struct Window {
title: String,
widgets: Vec<Box<dyn Widget>>,
}
impl Window {
fn new(title: &str) -> Window {
Window { title: title.to_owned(), widgets: Vec::new() }
}
fn add_widget(&mut self, widget: Box<dyn Widget>) {
self.widgets.push(widget);
}
fn inner_width(&self) -> usize {
std::cmp::max(
self.title.chars().count(),
self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),
)
}
}
impl Widget for Window {
fn width(&self) -> usize {
// Add 4 paddings for borders
self.inner_width() + 4
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
let mut inner = String::new();
for widget in &self.widgets {
widget.draw_into(&mut inner);
}
let inner_width = self.inner_width();
// TODO: Change draw_into to return Result<(), std::fmt::Error>. Then use the
// ?-operator here instead of .unwrap().
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
writeln!(buffer, "| {:^inner_width$} |", &self.title).unwrap();
writeln!(buffer, "+={:=<inner_width$}=+", "").unwrap();
for line in inner.lines() {
writeln!(buffer, "| {:inner_width$} |", line).unwrap();
}
writeln!(buffer, "+-{:-<inner_width$}-+", "").unwrap();
}
}
impl Widget for Button {
fn width(&self) -> usize {
self.label.width() + 8 // add a bit of padding
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
let width = self.width();
let mut label = String::new();
self.label.draw_into(&mut label);
writeln!(buffer, "+{:-<width$}+", "").unwrap();
for line in label.lines() {
writeln!(buffer, "|{:^width$}|", &line).unwrap();
}
writeln!(buffer, "+{:-<width$}+", "").unwrap();
}
}
impl Widget for Label {
fn width(&self) -> usize {
self.label.lines().map(|line| line.chars().count()).max().unwrap_or(0)
}
fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {
writeln!(buffer, "{}", &self.label).unwrap();
}
}
fn main() {
let mut window = Window::new("Rust GUI Demo 1.23");
window.add_widget(Box::new(Label::new("This is a small text GUI demo.")));
window.add_widget(Box::new(Button::new("Click me!")));
window.draw();
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/smart-pointers/exercise.rs | src/smart-pointers/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: solution
use std::cmp::Ordering;
// ANCHOR: types
/// A node in the binary tree.
#[derive(Debug)]
struct Node<T: Ord> {
value: T,
left: Subtree<T>,
right: Subtree<T>,
}
/// A possibly-empty subtree.
#[derive(Debug)]
struct Subtree<T: Ord>(Option<Box<Node<T>>>);
/// A container storing a set of values, using a binary tree.
///
/// If the same value is added multiple times, it is only stored once.
#[derive(Debug)]
pub struct BinaryTree<T: Ord> {
root: Subtree<T>,
}
impl<T: Ord> BinaryTree<T> {
fn new() -> Self {
Self { root: Subtree::new() }
}
fn insert(&mut self, value: T) {
self.root.insert(value);
}
fn has(&self, value: &T) -> bool {
self.root.has(value)
}
fn len(&self) -> usize {
self.root.len()
}
}
// ANCHOR_END: types
impl<T: Ord> Subtree<T> {
fn new() -> Self {
Self(None)
}
fn insert(&mut self, value: T) {
match &mut self.0 {
None => self.0 = Some(Box::new(Node::new(value))),
Some(n) => match value.cmp(&n.value) {
Ordering::Less => n.left.insert(value),
Ordering::Equal => {}
Ordering::Greater => n.right.insert(value),
},
}
}
fn has(&self, value: &T) -> bool {
match &self.0 {
None => false,
Some(n) => match value.cmp(&n.value) {
Ordering::Less => n.left.has(value),
Ordering::Equal => true,
Ordering::Greater => n.right.has(value),
},
}
}
fn len(&self) -> usize {
match &self.0 {
None => 0,
Some(n) => 1 + n.left.len() + n.right.len(),
}
}
}
impl<T: Ord> Node<T> {
fn new(value: T) -> Self {
Self { value, left: Subtree::new(), right: Subtree::new() }
}
}
// ANCHOR: tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn len() {
let mut tree = BinaryTree::new();
assert_eq!(tree.len(), 0);
tree.insert(2);
assert_eq!(tree.len(), 1);
tree.insert(1);
assert_eq!(tree.len(), 2);
tree.insert(2); // not a unique item
assert_eq!(tree.len(), 2);
tree.insert(3);
assert_eq!(tree.len(), 3);
}
#[test]
fn has() {
let mut tree = BinaryTree::new();
fn check_has(tree: &BinaryTree<i32>, exp: &[bool]) {
let got: Vec<bool> =
(0..exp.len()).map(|i| tree.has(&(i as i32))).collect();
assert_eq!(&got, exp);
}
check_has(&tree, &[false, false, false, false, false]);
tree.insert(0);
check_has(&tree, &[true, false, false, false, false]);
tree.insert(4);
check_has(&tree, &[true, false, false, false, true]);
tree.insert(4);
check_has(&tree, &[true, false, false, false, true]);
tree.insert(3);
check_has(&tree, &[true, false, false, true, true]);
}
#[test]
fn unbalanced() {
let mut tree = BinaryTree::new();
for i in 0..100 {
tree.insert(i);
}
assert_eq!(tree.len(), 100);
assert!(tree.has(&50));
}
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/testing/exercise.rs | src/testing/exercise.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// This is the buggy version that appears in the problem.
#[cfg(never)]
// ANCHOR: luhn
pub fn luhn(cc_number: &str) -> bool {
let mut sum = 0;
let mut double = false;
for c in cc_number.chars().rev() {
if let Some(digit) = c.to_digit(10) {
if double {
let double_digit = digit * 2;
sum +=
if double_digit > 9 { double_digit - 9 } else { double_digit };
} else {
sum += digit;
}
double = !double;
} else {
continue;
}
}
sum % 10 == 0
}
// ANCHOR_END: luhn
// This is the solution and passes all of the tests below.
// ANCHOR: solution
pub fn luhn(cc_number: &str) -> bool {
let mut sum = 0;
let mut double = false;
let mut digits = 0;
for c in cc_number.chars().rev() {
if let Some(digit) = c.to_digit(10) {
digits += 1;
if double {
let double_digit = digit * 2;
sum +=
if double_digit > 9 { double_digit - 9 } else { double_digit };
} else {
sum += digit;
}
double = !double;
} else if c.is_whitespace() {
// New: accept whitespace.
continue;
} else {
// New: reject all other characters.
return false;
}
}
// New: check that we have at least two digits
digits >= 2 && sum % 10 == 0
}
// ANCHOR: unit-tests
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_valid_cc_number() {
assert!(luhn("4263 9826 4026 9299"));
assert!(luhn("4539 3195 0343 6467"));
assert!(luhn("7992 7398 713"));
}
#[test]
fn test_invalid_cc_number() {
assert!(!luhn("4223 9826 4026 9299"));
assert!(!luhn("4539 3195 0343 6476"));
assert!(!luhn("8273 1232 7352 0569"));
}
// ANCHOR_END: unit-tests
#[test]
fn test_non_digit_cc_number() {
assert!(!luhn("foo"));
assert!(!luhn("foo 0 0"));
}
#[test]
fn test_empty_cc_number() {
assert!(!luhn(""));
assert!(!luhn(" "));
assert!(!luhn(" "));
assert!(!luhn(" "));
}
#[test]
fn test_single_digit_cc_number() {
assert!(!luhn("0"));
}
#[test]
fn test_two_digit_cc_number() {
assert!(luhn(" 0 0 "));
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/user-defined-types/exercise.rs | src/user-defined-types/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: event
#![allow(dead_code)]
#[derive(Debug)]
/// An event in the elevator system that the controller must react to.
enum Event {
// ANCHOR_END: event
/// A button was pressed.
ButtonPressed(Button),
/// The car has arrived at the given floor.
CarArrived(Floor),
/// The car's doors have opened.
CarDoorOpened,
/// The car's doors have closed.
CarDoorClosed,
}
/// A floor is represented as an integer.
type Floor = i32;
// ANCHOR: direction
/// A direction of travel.
#[derive(Debug)]
enum Direction {
Up,
Down,
}
// ANCHOR_END: direction
/// A user-accessible button.
#[derive(Debug)]
enum Button {
/// A button in the elevator lobby on the given floor.
LobbyCall(Direction, Floor),
/// A floor button within the car.
CarFloor(Floor),
}
// ANCHOR: car_arrived
/// The car has arrived on the given floor.
fn car_arrived(floor: i32) -> Event {
// ANCHOR_END: car_arrived
Event::CarArrived(floor)
}
// ANCHOR: car_door_opened
/// The car doors have opened.
fn car_door_opened() -> Event {
// ANCHOR_END: car_door_opened
Event::CarDoorOpened
}
// ANCHOR: car_door_closed
/// The car doors have closed.
fn car_door_closed() -> Event {
// ANCHOR_END: car_door_closed
Event::CarDoorClosed
}
// ANCHOR: lobby_call_button_pressed
/// A directional button was pressed in an elevator lobby on the given floor.
fn lobby_call_button_pressed(floor: i32, dir: Direction) -> Event {
// ANCHOR_END: lobby_call_button_pressed
Event::ButtonPressed(Button::LobbyCall(dir, floor))
}
// ANCHOR: car_floor_button_pressed
/// A floor button was pressed in the elevator car.
fn car_floor_button_pressed(floor: i32) -> Event {
// ANCHOR_END: car_floor_button_pressed
Event::ButtonPressed(Button::CarFloor(floor))
}
// ANCHOR: main
fn main() {
println!(
"A ground floor passenger has pressed the up button: {:?}",
lobby_call_button_pressed(0, Direction::Up)
);
println!("The car has arrived on the ground floor: {:?}", car_arrived(0));
println!("The car door opened: {:?}", car_door_opened());
println!(
"A passenger has pressed the 3rd floor button: {:?}",
car_floor_button_pressed(3)
);
println!("The car door closed: {:?}", car_door_closed());
println!("The car has arrived on the 3rd floor: {:?}", car_arrived(3));
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/std-traits/exercise.rs | src/std-traits/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(unused_variables, dead_code)]
// ANCHOR: solution
// ANCHOR: head
use std::io::Read;
struct RotDecoder<R: Read> {
input: R,
rot: u8,
}
// ANCHOR_END: head
impl<R: Read> Read for RotDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let size = self.input.read(buf)?;
for b in &mut buf[..size] {
if b.is_ascii_alphabetic() {
let base = if b.is_ascii_uppercase() { 'A' } else { 'a' } as u8;
*b = (*b - base + self.rot) % 26 + base;
}
}
Ok(size)
}
}
// ANCHOR: tests
#[cfg(test)]
mod test {
use super::*;
#[test]
fn joke() {
let mut rot =
RotDecoder { input: "Gb trg gb gur bgure fvqr!".as_bytes(), rot: 13 };
let mut result = String::new();
rot.read_to_string(&mut result).unwrap();
assert_eq!(&result, "To get to the other side!");
}
#[test]
fn binary() {
let input: Vec<u8> = (0..=255u8).collect();
let mut rot = RotDecoder::<&[u8]> { input: input.as_slice(), rot: 13 };
let mut buf = [0u8; 256];
assert_eq!(rot.read(&mut buf).unwrap(), 256);
for i in 0..=255 {
if input[i] != buf[i] {
assert!(input[i].is_ascii_alphabetic());
assert!(buf[i].is_ascii_alphabetic());
}
}
}
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/std-types/exercise.rs | src/std-types/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(unused_variables, dead_code)]
// ANCHOR: solution
use std::collections::HashMap;
use std::hash::Hash;
/// Counter counts the number of times each value of type T has been seen.
struct Counter<T> {
values: HashMap<T, u64>,
}
impl<T: Eq + Hash> Counter<T> {
/// Create a new Counter.
fn new() -> Self {
Counter { values: HashMap::new() }
}
/// Count an occurrence of the given value.
fn count(&mut self, value: T) {
*self.values.entry(value).or_default() += 1;
}
/// Return the number of times the given value has been seen.
fn times_seen(&self, value: T) -> u64 {
self.values.get(&value).copied().unwrap_or_default()
}
}
// ANCHOR: main
fn main() {
let mut ctr = Counter::new();
ctr.count(13);
ctr.count(14);
ctr.count(16);
ctr.count(14);
ctr.count(14);
ctr.count(11);
for i in 10..20 {
println!("saw {} values equal to {}", ctr.times_seen(i), i);
}
let mut strctr = Counter::new();
strctr.count("apple");
strctr.count("orange");
strctr.count("apple");
println!("got {} apples", strctr.times_seen("apple"));
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/iterators/exercise.rs | src/iterators/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: solution
// ANCHOR: offset_differences
/// Calculate the differences between elements of `values` offset by `offset`,
/// wrapping around from the end of `values` to the beginning.
///
/// Element `n` of the result is `values[(n+offset)%len] - values[n]`.
fn offset_differences(offset: usize, values: Vec<i32>) -> Vec<i32> {
// ANCHOR_END: offset_differences
let a = values.iter();
let b = values.iter().cycle().skip(offset);
a.zip(b).map(|(a, b)| *b - *a).collect()
}
// ANCHOR: unit-tests
#[test]
fn test_offset_one() {
assert_eq!(offset_differences(1, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
assert_eq!(offset_differences(1, vec![1, 3, 5]), vec![2, 2, -4]);
assert_eq!(offset_differences(1, vec![1, 3]), vec![2, -2]);
}
#[test]
fn test_larger_offsets() {
assert_eq!(offset_differences(2, vec![1, 3, 5, 7]), vec![4, 4, -4, -4]);
assert_eq!(offset_differences(3, vec![1, 3, 5, 7]), vec![6, -2, -2, -2]);
assert_eq!(offset_differences(4, vec![1, 3, 5, 7]), vec![0, 0, 0, 0]);
assert_eq!(offset_differences(5, vec![1, 3, 5, 7]), vec![2, 2, 2, -6]);
}
#[test]
fn test_degenerate_cases() {
assert_eq!(offset_differences(1, vec![0]), vec![0]);
assert_eq!(offset_differences(1, vec![1]), vec![0]);
let empty: Vec<i32> = vec![];
assert_eq!(offset_differences(1, empty), vec![]);
}
// ANCHOR_END: unit-tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/logging/src/main.rs | src/android/logging/src/main.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
//! Rust logging demo.
use log::{debug, error, info};
/// Logs a greeting.
fn main() {
logger::init(
logger::Config::default()
.with_tag_on_device("rust")
.with_max_level(log::LevelFilter::Trace),
);
debug!("Starting program.");
info!("Things are going fine.");
error!("Something went wrong!");
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/aidl/birthday_service/src/lib.rs | src/android/aidl/birthday_service/src/lib.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implementation of the `IBirthdayService` AIDL interface.
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayInfoProvider::IBirthdayInfoProvider;
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::IBirthdayService;
use com_example_birthdayservice::aidl::com::example::birthdayservice::BirthdayInfo::BirthdayInfo;
use com_example_birthdayservice::binder::{self, ParcelFileDescriptor, SpIBinder, Strong};
use std::fs::File;
use std::io::Read;
// ANCHOR: IBirthdayService
/// The `IBirthdayService` implementation.
pub struct BirthdayService;
impl binder::Interface for BirthdayService {}
impl IBirthdayService for BirthdayService {
fn wishHappyBirthday(&self, name: &str, years: i32) -> binder::Result<String> {
Ok(format!("Happy Birthday {name}, congratulations with the {years} years!"))
}
// ANCHOR_END: IBirthdayService
fn wishWithInfo(&self, info: &BirthdayInfo) -> binder::Result<String> {
Ok(format!(
"Happy Birthday {}, congratulations with the {} years!",
info.name, info.years,
))
}
fn wishWithProvider(
&self,
provider: &Strong<dyn IBirthdayInfoProvider>,
) -> binder::Result<String> {
Ok(format!(
"Happy Birthday {}, congratulations with the {} years!",
provider.name()?,
provider.years()?,
))
}
fn wishWithErasedProvider(
&self,
provider: &SpIBinder,
) -> binder::Result<String> {
// Convert the `SpIBinder` to a concrete interface.
let provider =
provider.clone().into_interface::<dyn IBirthdayInfoProvider>()?;
Ok(format!(
"Happy Birthday {}, congratulations with the {} years!",
provider.name()?,
provider.years()?,
))
}
// ANCHOR: wishFromFile
fn wishFromFile(
&self,
info_file: &ParcelFileDescriptor,
) -> binder::Result<String> {
// Convert the file descriptor to a `File`. `ParcelFileDescriptor` wraps
// an `OwnedFd`, which can be cloned and then used to create a `File`
// object.
let mut info_file = info_file
.as_ref()
.try_clone()
.map(File::from)
.expect("Invalid file handle");
let mut contents = String::new();
info_file.read_to_string(&mut contents).unwrap();
let mut lines = contents.lines();
let name = lines.next().unwrap();
let years: i32 = lines.next().unwrap().parse().unwrap();
Ok(format!("Happy Birthday {name}, congratulations with the {years} years!"))
}
// ANCHOR_END: wishFromFile
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/aidl/birthday_service/src/client.rs | src/android/aidl/birthday_service/src/client.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Birthday service.
use com_example_birthdayservice::aidl::com::example::birthdayservice::BirthdayInfo::BirthdayInfo;
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayInfoProvider::{
BnBirthdayInfoProvider, IBirthdayInfoProvider,
};
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::IBirthdayService;
use com_example_birthdayservice::binder::{self, BinderFeatures, ParcelFileDescriptor};
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
// ANCHOR: main
const SERVICE_IDENTIFIER: &str = "birthdayservice";
/// Call the birthday service.
fn main() -> Result<(), Box<dyn Error>> {
let name = std::env::args().nth(1).unwrap_or_else(|| String::from("Bob"));
let years = std::env::args()
.nth(2)
.and_then(|arg| arg.parse::<i32>().ok())
.unwrap_or(42);
binder::ProcessState::start_thread_pool();
let service = binder::get_interface::<dyn IBirthdayService>(SERVICE_IDENTIFIER)
.map_err(|_| "Failed to connect to BirthdayService")?;
// Call the service.
let msg = service.wishHappyBirthday(&name, years)?;
println!("{msg}");
// ANCHOR_END: main
service.wishWithInfo(&BirthdayInfo { name: name.clone(), years })?;
// ANCHOR: wish_with_provider
// Create a binder object for the `IBirthdayInfoProvider` interface.
let provider = BnBirthdayInfoProvider::new_binder(
InfoProvider { name: name.clone(), age: years as u8 },
BinderFeatures::default(),
);
// Send the binder object to the service.
service.wishWithProvider(&provider)?;
// Perform the same operation but passing the provider as an `SpIBinder`.
service.wishWithErasedProvider(&provider.as_binder())?;
// ANCHOR_END: wish_with_provider
// ANCHOR: wish_with_file
// Open a file and put the birthday info in it.
let mut file = File::create("/data/local/tmp/birthday.info").unwrap();
writeln!(file, "{name}")?;
writeln!(file, "{years}")?;
// Create a `ParcelFileDescriptor` from the file and send it.
let file = ParcelFileDescriptor::new(file);
service.wishFromFile(&file)?;
// ANCHOR_END: wish_with_file
Ok(())
}
// ANCHOR: InfoProvider
/// Rust struct implementing the `IBirthdayInfoProvider` interface.
struct InfoProvider {
name: String,
age: u8,
}
impl binder::Interface for InfoProvider {}
impl IBirthdayInfoProvider for InfoProvider {
fn name(&self) -> binder::Result<String> {
Ok(self.name.clone())
}
fn years(&self) -> binder::Result<i32> {
Ok(self.age as i32)
}
}
// ANCHOR_END: InfoProvider
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/aidl/birthday_service/src/server.rs | src/android/aidl/birthday_service/src/server.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
//! Birthday service.
use birthdayservice::BirthdayService;
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::BnBirthdayService;
use com_example_birthdayservice::binder;
const SERVICE_IDENTIFIER: &str = "birthdayservice";
/// Entry point for birthday service.
fn main() {
let birthday_service = BirthdayService;
let birthday_service_binder = BnBirthdayService::new_binder(
birthday_service,
binder::BinderFeatures::default(),
);
binder::add_service(SERVICE_IDENTIFIER, birthday_service_binder.as_binder())
.expect("Failed to register service");
binder::ProcessState::join_thread_pool();
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/testing/googletest.rs | src/android/testing/googletest.rs | // ANCHOR: test_elements_are
use googletest::prelude::*;
#[googletest::test]
fn test_elements_are() {
let value = vec!["foo", "bar", "baz"];
expect_that!(value, elements_are!(eq(&"foo"), lt(&"xyz"), starts_with("b")));
}
// ANCHOR_END: test_elements_are
#[should_panic]
// ANCHOR: test_multiline_string_diff
#[test]
fn test_multiline_string_diff() {
let haiku = "Memory safety found,\n\
Rust's strong typing guides the way,\n\
Secure code you'll write.";
assert_that!(
haiku,
eq("Memory safety found,\n\
Rust's silly humor guides the way,\n\
Secure code you'll write.")
);
}
// ANCHOR_END: test_multiline_string_diff
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/testing/mockall.rs | src/android/testing/mockall.rs | // ANCHOR: simple_example
use std::time::Duration;
#[mockall::automock]
pub trait Pet {
fn is_hungry(&self, since_last_meal: Duration) -> bool;
}
#[test]
fn test_robot_dog() {
let mut mock_dog = MockPet::new();
mock_dog.expect_is_hungry().return_const(true);
assert!(mock_dog.is_hungry(Duration::from_secs(10)));
}
// ANCHOR_END: simple_example
// ANCHOR: extended_example
#[test]
fn test_robot_cat() {
let mut mock_cat = MockPet::new();
mock_cat
.expect_is_hungry()
.with(mockall::predicate::gt(Duration::from_secs(3 * 3600)))
.return_const(true);
mock_cat.expect_is_hungry().return_const(false);
assert!(mock_cat.is_hungry(Duration::from_secs(5 * 3600)));
assert!(!mock_cat.is_hungry(Duration::from_secs(5)));
}
// ANCHOR_END: extended_example
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/testing/src/lib.rs | src/android/testing/src/lib.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: leftpad
//! Left-padding library.
/// Left-pad `s` to `width`.
pub fn leftpad(s: &str, width: usize) -> String {
format!("{s:>width$}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_string() {
assert_eq!(leftpad("foo", 5), " foo");
}
#[test]
fn long_string() {
assert_eq!(leftpad("foobar", 6), "foobar");
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/interoperability/with-c/bindgen/main.rs | src/android/interoperability/with-c/bindgen/main.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
//! Bindgen demo.
use birthday_bindgen::{card, print_card};
fn main() {
let name = std::ffi::CString::new("Peter").unwrap();
let card = card { name: name.as_ptr(), years: 42 };
// SAFETY: The pointer we pass is valid because it came from a Rust
// reference, and the `name` it contains refers to `name` above which also
// remains valid. `print_card` doesn't store either pointer to use later
// after it returns.
unsafe {
print_card(&card);
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/interoperability/with-c/rust/libanalyze/analyze.rs | src/android/interoperability/with-c/rust/libanalyze/analyze.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: analyze_numbers
//! Rust FFI demo.
#![deny(improper_ctypes_definitions)]
use std::os::raw::c_int;
/// Analyze the numbers.
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
pub extern "C" fn analyze_numbers(x: c_int, y: c_int) {
if x < y {
println!("x ({x}) is smallest!");
} else {
println!("y ({y}) is probably larger than x ({x})");
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/interoperability/java/src/lib.rs | src/android/interoperability/java/src/lib.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: hello
//! Rust <-> Java FFI demo.
use jni::JNIEnv;
use jni::objects::{JClass, JString};
use jni::sys::jstring;
/// HelloWorld::hello method implementation.
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
pub extern "system" fn Java_HelloWorld_hello(
mut env: JNIEnv,
_class: JClass,
name: JString,
) -> jstring {
let input: String = env.get_string(&name).unwrap().into();
let greeting = format!("Hello, {input}!");
let output = env.new_string(greeting).unwrap();
output.into_raw()
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/build-rules/library/src/lib.rs | src/android/build-rules/library/src/lib.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: greeting
//! Greeting library.
/// Greet `name`.
pub fn greeting(name: &str) -> String {
format!("Hello {name}, it is very nice to meet you!")
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/build-rules/library/src/main.rs | src/android/build-rules/library/src/main.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
//! Rust demo.
use greetings::greeting;
use textwrap::fill;
/// Prints a greeting to standard output.
fn main() {
println!("{}", fill(&greeting("Bob"), 24));
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/android/build-rules/binary/src/main.rs | src/android/build-rules/binary/src/main.rs | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
//! Rust demo.
/// Prints a greeting to standard output.
fn main() {
println!("Hello from Rust!");
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/methods-and-traits/exercise.rs | src/methods-and-traits/exercise.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: solution
// ANCHOR: setup
trait Logger {
/// Log a message at the given verbosity level.
fn log(&self, verbosity: u8, message: &str);
}
struct StderrLogger;
impl Logger for StderrLogger {
fn log(&self, verbosity: u8, message: &str) {
eprintln!("verbosity={verbosity}: {message}");
}
}
/// Only log messages up to the given verbosity level.
struct VerbosityFilter {
max_verbosity: u8,
inner: StderrLogger,
}
// ANCHOR_END: setup
impl Logger for VerbosityFilter {
fn log(&self, verbosity: u8, message: &str) {
if verbosity <= self.max_verbosity {
self.inner.log(verbosity, message);
}
}
}
// ANCHOR: main
fn main() {
let logger = VerbosityFilter { max_verbosity: 3, inner: StderrLogger };
logger.log(5, "FYI");
logger.log(2, "Uhoh");
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/pattern-matching/exercise.rs | src/pattern-matching/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: solution
// ANCHOR: Operation
/// An operation to perform on two subexpressions.
#[derive(Debug)]
enum Operation {
Add,
Sub,
Mul,
Div,
}
// ANCHOR_END: Operation
// ANCHOR: Expression
/// An expression, in tree form.
#[derive(Debug)]
enum Expression {
/// An operation on two subexpressions.
Op { op: Operation, left: Box<Expression>, right: Box<Expression> },
/// A literal value
Value(i64),
}
// ANCHOR_END: Expression
// ANCHOR: eval
fn eval(e: Expression) -> i64 {
// ANCHOR_END: eval
match e {
Expression::Op { op, left, right } => {
let left = eval(*left);
let right = eval(*right);
match op {
Operation::Add => left + right,
Operation::Sub => left - right,
Operation::Mul => left * right,
Operation::Div => left / right,
}
}
Expression::Value(v) => v,
}
}
// ANCHOR: tests
#[test]
fn test_value() {
assert_eq!(eval(Expression::Value(19)), 19);
}
#[test]
fn test_sum() {
assert_eq!(
eval(Expression::Op {
op: Operation::Add,
left: Box::new(Expression::Value(10)),
right: Box::new(Expression::Value(20)),
}),
30
);
}
#[test]
fn test_recursion() {
let term1 = Expression::Op {
op: Operation::Mul,
left: Box::new(Expression::Value(10)),
right: Box::new(Expression::Value(9)),
};
let term2 = Expression::Op {
op: Operation::Mul,
left: Box::new(Expression::Op {
op: Operation::Sub,
left: Box::new(Expression::Value(3)),
right: Box::new(Expression::Value(4)),
}),
right: Box::new(Expression::Value(5)),
};
assert_eq!(
eval(Expression::Op {
op: Operation::Add,
left: Box::new(term1),
right: Box::new(term2),
}),
85
);
}
#[test]
fn test_zeros() {
assert_eq!(
eval(Expression::Op {
op: Operation::Add,
left: Box::new(Expression::Value(0)),
right: Box::new(Expression::Value(0))
}),
0
);
assert_eq!(
eval(Expression::Op {
op: Operation::Mul,
left: Box::new(Expression::Value(0)),
right: Box::new(Expression::Value(0))
}),
0
);
assert_eq!(
eval(Expression::Op {
op: Operation::Sub,
left: Box::new(Expression::Value(0)),
right: Box::new(Expression::Value(0))
}),
0
);
}
#[test]
fn test_div() {
assert_eq!(
eval(Expression::Op {
op: Operation::Div,
left: Box::new(Expression::Value(10)),
right: Box::new(Expression::Value(2)),
}),
5
)
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/types-and-values/exercise.rs | src/types-and-values/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Omitting `return` is covered later.
#[allow(clippy::needless_return)]
// ANCHOR: solution
// ANCHOR: fib
fn fib(n: u32) -> u32 {
// ANCHOR_END: fib
if n < 2 {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
// ANCHOR: main
fn main() {
let n = 20;
println!("fib({n}) = {}", fib(n));
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/board_support.rs | src/bare-metal/microcontrollers/examples/src/bin/board_support.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Example
#![no_main]
#![no_std]
extern crate panic_halt as _;
use cortex_m_rt::entry;
use embedded_hal::digital::OutputPin;
use microbit::Board;
#[entry]
fn main() -> ! {
let mut board = Board::take().unwrap();
board.display_pins.col1.set_low().unwrap();
board.display_pins.row1.set_high().unwrap();
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/pac.rs | src/bare-metal/microcontrollers/examples/src/bin/pac.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Example
#![no_main]
#![no_std]
extern crate panic_halt as _;
use cortex_m_rt::entry;
use nrf52833_pac::Peripherals;
#[entry]
fn main() -> ! {
let p = Peripherals::take().unwrap();
let gpio0 = p.P0;
// Configure GPIO 0 pins 21 and 28 as push-pull outputs.
gpio0.pin_cnf[21].write(|w| {
w.dir().output();
w.input().disconnect();
w.pull().disabled();
w.drive().s0s1();
w.sense().disabled();
w
});
gpio0.pin_cnf[28].write(|w| {
w.dir().output();
w.input().disconnect();
w.pull().disabled();
w.drive().s0s1();
w.sense().disabled();
w
});
// Set pin 28 low and pin 21 high to turn the LED on.
gpio0.outclr.write(|w| w.pin28().clear());
gpio0.outset.write(|w| w.pin21().set());
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/typestate.rs | src/bare-metal/microcontrollers/examples/src/bin/typestate.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![no_main]
#![no_std]
extern crate panic_halt as _;
use cortex_m_rt::entry;
use embedded_hal::digital::{InputPin, OutputPin};
use nrf52833_hal::gpio::p0::{self, P0_01, P0_02, P0_03};
use nrf52833_hal::gpio::{
Disconnected, Floating, Input, Level, OpenDrain, OpenDrainConfig, Output,
PushPull,
};
use nrf52833_hal::pac::Peripherals;
// ANCHOR: Example
#[entry]
fn main() -> ! {
let p = Peripherals::take().unwrap();
let gpio0 = p0::Parts::new(p.P0);
let pin: P0_01<Disconnected> = gpio0.p0_01;
// let gpio0_01_again = gpio0.p0_01; // Error, moved.
let mut pin_input: P0_01<Input<Floating>> = pin.into_floating_input();
if pin_input.is_high().unwrap() {
// ...
}
let mut pin_output: P0_01<Output<OpenDrain>> = pin_input
.into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, Level::Low);
pin_output.set_high().unwrap();
// pin_input.is_high(); // Error, moved.
let _pin2: P0_02<Output<OpenDrain>> = gpio0
.p0_02
.into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, Level::Low);
let _pin3: P0_03<Output<PushPull>> =
gpio0.p0_03.into_push_pull_output(Level::Low);
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/hal.rs | src/bare-metal/microcontrollers/examples/src/bin/hal.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Example
#![no_main]
#![no_std]
extern crate panic_halt as _;
use cortex_m_rt::entry;
use embedded_hal::digital::OutputPin;
use nrf52833_hal::gpio::{Level, p0};
use nrf52833_hal::pac::Peripherals;
#[entry]
fn main() -> ! {
let p = Peripherals::take().unwrap();
// Create HAL wrapper for GPIO port 0.
let gpio0 = p0::Parts::new(p.P0);
// Configure GPIO 0 pins 21 and 28 as push-pull outputs.
let mut col1 = gpio0.p0_28.into_push_pull_output(Level::High);
let mut row1 = gpio0.p0_21.into_push_pull_output(Level::Low);
// Set pin 28 low and pin 21 high to turn the LED on.
col1.set_low().unwrap();
row1.set_high().unwrap();
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/minimal.rs | src/bare-metal/microcontrollers/examples/src/bin/minimal.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Example
#![no_main]
#![no_std]
extern crate panic_halt as _;
mod interrupts;
use cortex_m_rt::entry;
#[entry]
fn main() -> ! {
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/mmio.rs | src/bare-metal/microcontrollers/examples/src/bin/mmio.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Example
#![no_main]
#![no_std]
extern crate panic_halt as _;
mod interrupts;
use core::mem::size_of;
use cortex_m_rt::entry;
/// GPIO port 0 peripheral address
const GPIO_P0: usize = 0x5000_0000;
// GPIO peripheral offsets
const PIN_CNF: usize = 0x700;
const OUTSET: usize = 0x508;
const OUTCLR: usize = 0x50c;
// PIN_CNF fields
const DIR_OUTPUT: u32 = 0x1;
const INPUT_DISCONNECT: u32 = 0x1 << 1;
const PULL_DISABLED: u32 = 0x0 << 2;
const DRIVE_S0S1: u32 = 0x0 << 8;
const SENSE_DISABLED: u32 = 0x0 << 16;
#[entry]
fn main() -> ! {
// Configure GPIO 0 pins 21 and 28 as push-pull outputs.
let pin_cnf_21 = (GPIO_P0 + PIN_CNF + 21 * size_of::<u32>()) as *mut u32;
let pin_cnf_28 = (GPIO_P0 + PIN_CNF + 28 * size_of::<u32>()) as *mut u32;
// SAFETY: The pointers are to valid peripheral control registers, and no
// aliases exist.
unsafe {
pin_cnf_21.write_volatile(
DIR_OUTPUT
| INPUT_DISCONNECT
| PULL_DISABLED
| DRIVE_S0S1
| SENSE_DISABLED,
);
pin_cnf_28.write_volatile(
DIR_OUTPUT
| INPUT_DISCONNECT
| PULL_DISABLED
| DRIVE_S0S1
| SENSE_DISABLED,
);
}
// Set pin 28 low and pin 21 high to turn the LED on.
let gpio0_outset = (GPIO_P0 + OUTSET) as *mut u32;
let gpio0_outclr = (GPIO_P0 + OUTCLR) as *mut u32;
// SAFETY: The pointers are to valid peripheral control registers, and no
// aliases exist.
unsafe {
gpio0_outclr.write_volatile(1 << 28);
gpio0_outset.write_volatile(1 << 21);
}
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/microcontrollers/examples/src/bin/interrupts/mod.rs | src/bare-metal/microcontrollers/examples/src/bin/interrupts/mod.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[unsafe(link_section = ".vector_table.interrupts")]
// SAFETY: There is no other global variable of this name.
#[unsafe(no_mangle)]
pub static __INTERRUPTS: [usize; 1] = [0];
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/useful-crates/allocator-example/src/main.rs | src/bare-metal/useful-crates/allocator-example/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
use buddy_system_allocator::FrameAllocator;
use core::alloc::Layout;
fn main() {
let mut allocator = FrameAllocator::<32>::new();
allocator.add_frame(0x200_0000, 0x400_0000);
let layout = Layout::from_size_align(0x100, 0x100).unwrap();
let bar = allocator
.alloc_aligned(layout)
.expect("Failed to allocate 0x100 byte MMIO region");
println!("Allocated 0x100 byte MMIO region at {:#x}", bar);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/useful-crates/zerocopy-example/src/main.rs | src/bare-metal/useful-crates/zerocopy-example/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: main
use zerocopy::{Immutable, IntoBytes};
#[repr(u32)]
#[derive(Debug, Default, Immutable, IntoBytes)]
enum RequestType {
#[default]
In = 0,
Out = 1,
Flush = 4,
}
#[repr(C)]
#[derive(Debug, Default, Immutable, IntoBytes)]
struct VirtioBlockRequest {
request_type: RequestType,
reserved: u32,
sector: u64,
}
fn main() {
let request = VirtioBlockRequest {
request_type: RequestType::Flush,
sector: 42,
..Default::default()
};
assert_eq!(
request.as_bytes(),
&[4, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0]
);
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/alloc-example/src/main.rs | src/bare-metal/alloc-example/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Alloc
#![no_main]
#![no_std]
extern crate alloc;
extern crate panic_halt as _;
use alloc::string::ToString;
use alloc::vec::Vec;
use buddy_system_allocator::LockedHeap;
#[global_allocator]
static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();
const HEAP_SIZE: usize = 65536;
static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
pub fn entry() {
// SAFETY: `HEAP` is only used here and `entry` is only called once.
unsafe {
// Give the allocator some memory to allocate.
HEAP_ALLOCATOR.lock().init(&raw mut HEAP as usize, HEAP_SIZE);
}
// Now we can do things that require heap allocation.
let mut v = Vec::new();
v.push("A string".to_string());
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/main_psci.rs | src/bare-metal/aps/examples/src/main_psci.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
#![no_main]
#![no_std]
use core::arch::asm;
use core::panic::PanicInfo;
mod asm;
mod exceptions;
const PSCI_SYSTEM_OFF: u32 = 0x84000008;
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn main(_x0: u64, _x1: u64, _x2: u64, _x3: u64) {
// SAFETY: this only uses the declared registers and doesn't do anything
// with memory.
unsafe {
asm!("hvc #0",
inout("w0") PSCI_SYSTEM_OFF => _,
inout("w1") 0 => _,
inout("w2") 0 => _,
inout("w3") 0 => _,
inout("w4") 0 => _,
inout("w5") 0 => _,
inout("w6") 0 => _,
inout("w7") 0 => _,
options(nomem, nostack)
);
}
loop {}
}
// ANCHOR_END: main
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/main_minimal.rs | src/bare-metal/aps/examples/src/main_minimal.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
#![no_main]
#![no_std]
mod asm;
mod exceptions;
mod pl011_minimal;
use crate::pl011_minimal::Uart;
use core::fmt::Write;
use core::panic::PanicInfo;
use log::error;
use smccc::Hvc;
use smccc::psci::system_off;
/// Base address of the primary PL011 UART.
const PL011_BASE_ADDRESS: *mut u8 = 0x900_0000 as _;
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let mut uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };
writeln!(uart, "main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})").unwrap();
system_off::<Hvc>().unwrap();
}
// ANCHOR_END: main
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
error!("{}", info);
system_off::<Hvc>().unwrap();
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/asm.rs | src/bare-metal/aps/examples/src/asm.rs | // Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::arch::global_asm;
global_asm!(include_str!("entry.S"));
global_asm!(include_str!("exceptions.S"));
global_asm!(include_str!("idmap.S"));
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/logger.rs | src/bare-metal/aps/examples/src/logger.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
use crate::pl011::Uart;
use core::fmt::Write;
use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};
use spin::mutex::SpinMutex;
static LOGGER: Logger = Logger { uart: SpinMutex::new(None) };
struct Logger {
uart: SpinMutex<Option<Uart<'static>>>,
}
impl Log for Logger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
writeln!(
self.uart.lock().as_mut().unwrap(),
"[{}] {}",
record.level(),
record.args()
)
.unwrap();
}
fn flush(&self) {}
}
/// Initialises UART logger.
pub fn init(
uart: Uart<'static>,
max_level: LevelFilter,
) -> Result<(), SetLoggerError> {
LOGGER.uart.lock().replace(uart);
log::set_logger(&LOGGER)?;
log::set_max_level(max_level);
Ok(())
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/pl011.rs | src/bare-metal/aps/examples/src/pl011.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
use core::fmt::{self, Write};
// ANCHOR: Flags
use bitflags::bitflags;
use zerocopy::{FromBytes, IntoBytes};
/// Flags from the UART flag register.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, FromBytes, IntoBytes, PartialEq)]
struct Flags(u16);
bitflags! {
impl Flags: u16 {
/// Clear to send.
const CTS = 1 << 0;
/// Data set ready.
const DSR = 1 << 1;
/// Data carrier detect.
const DCD = 1 << 2;
/// UART busy transmitting data.
const BUSY = 1 << 3;
/// Receive FIFO is empty.
const RXFE = 1 << 4;
/// Transmit FIFO is full.
const TXFF = 1 << 5;
/// Receive FIFO is full.
const RXFF = 1 << 6;
/// Transmit FIFO is empty.
const TXFE = 1 << 7;
/// Ring indicator.
const RI = 1 << 8;
}
}
// ANCHOR_END: Flags
/// Flags from the UART Receive Status Register / Error Clear Register.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, FromBytes, IntoBytes, PartialEq)]
struct ReceiveStatus(u16);
bitflags! {
impl ReceiveStatus: u16 {
/// Framing error.
const FE = 1 << 0;
/// Parity error.
const PE = 1 << 1;
/// Break error.
const BE = 1 << 2;
/// Overrun error.
const OE = 1 << 3;
}
}
// ANCHOR: Registers
use safe_mmio::fields::{ReadPure, ReadPureWrite, ReadWrite, WriteOnly};
#[repr(C, align(4))]
pub struct Registers {
dr: ReadWrite<u16>,
_reserved0: [u8; 2],
rsr: ReadPure<ReceiveStatus>,
_reserved1: [u8; 19],
fr: ReadPure<Flags>,
_reserved2: [u8; 6],
ilpr: ReadPureWrite<u8>,
_reserved3: [u8; 3],
ibrd: ReadPureWrite<u16>,
_reserved4: [u8; 2],
fbrd: ReadPureWrite<u8>,
_reserved5: [u8; 3],
lcr_h: ReadPureWrite<u8>,
_reserved6: [u8; 3],
cr: ReadPureWrite<u16>,
_reserved7: [u8; 3],
ifls: ReadPureWrite<u8>,
_reserved8: [u8; 3],
imsc: ReadPureWrite<u16>,
_reserved9: [u8; 2],
ris: ReadPure<u16>,
_reserved10: [u8; 2],
mis: ReadPure<u16>,
_reserved11: [u8; 2],
icr: WriteOnly<u16>,
_reserved12: [u8; 2],
dmacr: ReadPureWrite<u8>,
_reserved13: [u8; 3],
}
// ANCHOR_END: Registers
// ANCHOR: Uart
use safe_mmio::{UniqueMmioPointer, field, field_shared};
/// Driver for a PL011 UART.
#[derive(Debug)]
pub struct Uart<'a> {
registers: UniqueMmioPointer<'a, Registers>,
}
impl<'a> Uart<'a> {
/// Constructs a new instance of the UART driver for a PL011 device with the
/// given set of registers.
pub fn new(registers: UniqueMmioPointer<'a, Registers>) -> Self {
Self { registers }
}
/// Writes a single byte to the UART.
pub fn write_byte(&mut self, byte: u8) {
// Wait until there is room in the TX buffer.
while self.read_flag_register().contains(Flags::TXFF) {}
// Write to the TX buffer.
field!(self.registers, dr).write(byte.into());
// Wait until the UART is no longer busy.
while self.read_flag_register().contains(Flags::BUSY) {}
}
/// Reads and returns a pending byte, or `None` if nothing has been
/// received.
pub fn read_byte(&mut self) -> Option<u8> {
if self.read_flag_register().contains(Flags::RXFE) {
None
} else {
let data = field!(self.registers, dr).read();
// TODO: Check for error conditions in bits 8-11.
Some(data as u8)
}
}
fn read_flag_register(&self) -> Flags {
field_shared!(self.registers, fr).read()
}
}
// ANCHOR_END: Uart
impl Write for Uart<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.as_bytes() {
self.write_byte(*c);
}
Ok(())
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/main_safemmio.rs | src/bare-metal/aps/examples/src/main_safemmio.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
#![no_main]
#![no_std]
mod asm;
mod exceptions;
mod pl011;
use crate::pl011::Uart;
use core::fmt::Write;
use core::panic::PanicInfo;
use core::ptr::NonNull;
use log::error;
use safe_mmio::UniqueMmioPointer;
use smccc::Hvc;
use smccc::psci::system_off;
/// Base address of the primary PL011 UART.
const PL011_BASE_ADDRESS: NonNull<pl011::Registers> =
NonNull::new(0x900_0000 as _).unwrap();
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let mut uart = Uart::new(unsafe { UniqueMmioPointer::new(PL011_BASE_ADDRESS) });
writeln!(uart, "main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})").unwrap();
loop {
if let Some(byte) = uart.read_byte() {
uart.write_byte(byte);
match byte {
b'\r' => uart.write_byte(b'\n'),
b'q' => break,
_ => continue,
}
}
}
writeln!(uart, "\n\nBye!").unwrap();
system_off::<Hvc>().unwrap();
}
// ANCHOR_END: main
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
error!("{info}");
system_off::<Hvc>().unwrap();
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/main_improved.rs | src/bare-metal/aps/examples/src/main_improved.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
#![no_main]
#![no_std]
mod asm;
mod exceptions;
mod pl011_struct;
use crate::pl011_struct::Uart;
use core::fmt::Write;
use core::panic::PanicInfo;
use log::error;
use smccc::Hvc;
use smccc::psci::system_off;
/// Base address of the primary PL011 UART.
const PL011_BASE_ADDRESS: *mut pl011_struct::Registers = 0x900_0000 as _;
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let mut uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };
writeln!(uart, "main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})").unwrap();
loop {
if let Some(byte) = uart.read_byte() {
uart.write_byte(byte);
match byte {
b'\r' => uart.write_byte(b'\n'),
b'q' => break,
_ => continue,
}
}
}
writeln!(uart, "\n\nBye!").unwrap();
system_off::<Hvc>().unwrap();
}
// ANCHOR_END: main
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
error!("{info}");
system_off::<Hvc>().unwrap();
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/pl011_minimal.rs | src/bare-metal/aps/examples/src/pl011_minimal.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: Example
const FLAG_REGISTER_OFFSET: usize = 0x18;
const FR_BUSY: u8 = 1 << 3;
const FR_TXFF: u8 = 1 << 5;
/// Minimal driver for a PL011 UART.
#[derive(Debug)]
pub struct Uart {
base_address: *mut u8,
}
impl Uart {
/// Constructs a new instance of the UART driver for a PL011 device at the
/// given base address.
///
/// # Safety
///
/// The given base address must point to the 8 MMIO control registers of a
/// PL011 device, which must be mapped into the address space of the process
/// as device memory and not have any other aliases.
pub unsafe fn new(base_address: *mut u8) -> Self {
Self { base_address }
}
/// Writes a single byte to the UART.
pub fn write_byte(&self, byte: u8) {
// Wait until there is room in the TX buffer.
while self.read_flag_register() & FR_TXFF != 0 {}
// SAFETY: We know that the base address points to the control
// registers of a PL011 device which is appropriately mapped.
unsafe {
// Write to the TX buffer.
self.base_address.write_volatile(byte);
}
// Wait until the UART is no longer busy.
while self.read_flag_register() & FR_BUSY != 0 {}
}
fn read_flag_register(&self) -> u8 {
// SAFETY: We know that the base address points to the control
// registers of a PL011 device which is appropriately mapped.
unsafe { self.base_address.add(FLAG_REGISTER_OFFSET).read_volatile() }
}
}
// ANCHOR_END: Example
// ANCHOR: Traits
use core::fmt::{self, Write};
impl Write for Uart {
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.as_bytes() {
self.write_byte(*c);
}
Ok(())
}
}
// SAFETY: `Uart` just contains a pointer to device memory, which can be
// accessed from any context.
unsafe impl Send for Uart {}
// ANCHOR_END: Traits
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/main_rt.rs | src/bare-metal/aps/examples/src/main_rt.rs | // Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
#![no_main]
#![no_std]
mod exceptions_rt;
use aarch64_paging::descriptor::Attributes;
use aarch64_rt::{InitialPagetable, entry, initial_pagetable};
use arm_pl011_uart::{PL011Registers, Uart, UniqueMmioPointer};
use core::fmt::Write;
use core::panic::PanicInfo;
use core::ptr::NonNull;
use smccc::Hvc;
use smccc::psci::system_off;
/// Base address of the primary PL011 UART.
const PL011_BASE_ADDRESS: NonNull<PL011Registers> =
NonNull::new(0x900_0000 as _).unwrap();
/// Attributes to use for device memory in the initial identity map.
const DEVICE_ATTRIBUTES: Attributes = Attributes::VALID
.union(Attributes::ATTRIBUTE_INDEX_0)
.union(Attributes::ACCESSED)
.union(Attributes::UXN);
/// Attributes to use for normal memory in the initial identity map.
const MEMORY_ATTRIBUTES: Attributes = Attributes::VALID
.union(Attributes::ATTRIBUTE_INDEX_1)
.union(Attributes::INNER_SHAREABLE)
.union(Attributes::ACCESSED)
.union(Attributes::NON_GLOBAL);
initial_pagetable!({
let mut idmap = [0; 512];
// 1 GiB of device memory.
idmap[0] = DEVICE_ATTRIBUTES.bits();
// 1 GiB of normal memory.
idmap[1] = MEMORY_ATTRIBUTES.bits() | 0x40000000;
// Another 1 GiB of device memory starting at 256 GiB.
idmap[256] = DEVICE_ATTRIBUTES.bits() | 0x4000000000;
InitialPagetable(idmap)
});
entry!(main);
fn main(x0: u64, x1: u64, x2: u64, x3: u64) -> ! {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let mut uart = unsafe { Uart::new(UniqueMmioPointer::new(PL011_BASE_ADDRESS)) };
writeln!(uart, "main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})").unwrap();
system_off::<Hvc>().unwrap();
panic!("system_off returned");
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
system_off::<Hvc>().unwrap();
loop {}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/main_logger.rs | src/bare-metal/aps/examples/src/main_logger.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: main
#![no_main]
#![no_std]
mod asm;
mod exceptions;
mod logger;
mod pl011;
use crate::pl011::Uart;
use core::panic::PanicInfo;
use core::ptr::NonNull;
use log::{LevelFilter, error, info};
use safe_mmio::UniqueMmioPointer;
use smccc::Hvc;
use smccc::psci::system_off;
/// Base address of the primary PL011 UART.
const PL011_BASE_ADDRESS: NonNull<pl011::Registers> =
NonNull::new(0x900_0000 as _).unwrap();
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let uart = unsafe { Uart::new(UniqueMmioPointer::new(PL011_BASE_ADDRESS)) };
logger::init(uart, LevelFilter::Trace).unwrap();
info!("main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})");
assert_eq!(x1, 42);
system_off::<Hvc>().unwrap();
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
error!("{info}");
system_off::<Hvc>().unwrap();
loop {}
}
// ANCHOR_END: main
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/pl011_struct.rs | src/bare-metal/aps/examples/src/pl011_struct.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
use core::fmt::{self, Write};
// ANCHOR: Flags
use bitflags::bitflags;
bitflags! {
/// Flags from the UART flag register.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Flags: u16 {
/// Clear to send.
const CTS = 1 << 0;
/// Data set ready.
const DSR = 1 << 1;
/// Data carrier detect.
const DCD = 1 << 2;
/// UART busy transmitting data.
const BUSY = 1 << 3;
/// Receive FIFO is empty.
const RXFE = 1 << 4;
/// Transmit FIFO is full.
const TXFF = 1 << 5;
/// Receive FIFO is full.
const RXFF = 1 << 6;
/// Transmit FIFO is empty.
const TXFE = 1 << 7;
/// Ring indicator.
const RI = 1 << 8;
}
}
// ANCHOR_END: Flags
bitflags! {
/// Flags from the UART Receive Status Register / Error Clear Register.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct ReceiveStatus: u16 {
/// Framing error.
const FE = 1 << 0;
/// Parity error.
const PE = 1 << 1;
/// Break error.
const BE = 1 << 2;
/// Overrun error.
const OE = 1 << 3;
}
}
// ANCHOR: Registers
#[repr(C, align(4))]
pub struct Registers {
dr: u16,
_reserved0: [u8; 2],
rsr: ReceiveStatus,
_reserved1: [u8; 19],
fr: Flags,
_reserved2: [u8; 6],
ilpr: u8,
_reserved3: [u8; 3],
ibrd: u16,
_reserved4: [u8; 2],
fbrd: u8,
_reserved5: [u8; 3],
lcr_h: u8,
_reserved6: [u8; 3],
cr: u16,
_reserved7: [u8; 3],
ifls: u8,
_reserved8: [u8; 3],
imsc: u16,
_reserved9: [u8; 2],
ris: u16,
_reserved10: [u8; 2],
mis: u16,
_reserved11: [u8; 2],
icr: u16,
_reserved12: [u8; 2],
dmacr: u8,
_reserved13: [u8; 3],
}
// ANCHOR_END: Registers
// ANCHOR: Uart
/// Driver for a PL011 UART.
#[derive(Debug)]
pub struct Uart {
registers: *mut Registers,
}
impl Uart {
/// Constructs a new instance of the UART driver for a PL011 device with the
/// given set of registers.
///
/// # Safety
///
/// The given pointer must point to the 8 MMIO control registers of a PL011
/// device, which must be mapped into the address space of the process as
/// device memory and not have any other aliases.
pub unsafe fn new(registers: *mut Registers) -> Self {
Self { registers }
}
/// Writes a single byte to the UART.
pub fn write_byte(&mut self, byte: u8) {
// Wait until there is room in the TX buffer.
while self.read_flag_register().contains(Flags::TXFF) {}
// SAFETY: We know that self.registers points to the control registers
// of a PL011 device which is appropriately mapped.
unsafe {
// Write to the TX buffer.
(&raw mut (*self.registers).dr).write_volatile(byte.into());
}
// Wait until the UART is no longer busy.
while self.read_flag_register().contains(Flags::BUSY) {}
}
/// Reads and returns a pending byte, or `None` if nothing has been
/// received.
pub fn read_byte(&mut self) -> Option<u8> {
if self.read_flag_register().contains(Flags::RXFE) {
None
} else {
// SAFETY: We know that self.registers points to the control
// registers of a PL011 device which is appropriately mapped.
let data = unsafe { (&raw const (*self.registers).dr).read_volatile() };
// TODO: Check for error conditions in bits 8-11.
Some(data as u8)
}
}
fn read_flag_register(&self) -> Flags {
// SAFETY: We know that self.registers points to the control registers
// of a PL011 device which is appropriately mapped.
unsafe { (&raw const (*self.registers).fr).read_volatile() }
}
}
// ANCHOR_END: Uart
impl Write for Uart {
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.as_bytes() {
self.write_byte(*c);
}
Ok(())
}
}
// Safe because it just contains a pointer to device memory, which can be
// accessed from any context.
unsafe impl Send for Uart {}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/exceptions_rt.rs | src/bare-metal/aps/examples/src/exceptions_rt.rs | // Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: exceptions
use aarch64_rt::{ExceptionHandlers, RegisterStateRef, exception_handlers};
use log::error;
use smccc::Hvc;
use smccc::psci::system_off;
struct Handlers;
impl ExceptionHandlers for Handlers {
extern "C" fn sync_current(_state: RegisterStateRef) {
error!("sync_current");
system_off::<Hvc>().unwrap();
}
extern "C" fn irq_current(_state: RegisterStateRef) {
error!("irq_current");
system_off::<Hvc>().unwrap();
}
extern "C" fn fiq_current(_state: RegisterStateRef) {
error!("fiq_current");
system_off::<Hvc>().unwrap();
}
extern "C" fn serror_current(_state: RegisterStateRef) {
error!("serror_current");
system_off::<Hvc>().unwrap();
}
}
exception_handlers!(Handlers);
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/bare-metal/aps/examples/src/exceptions.rs | src/bare-metal/aps/examples/src/exceptions.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ANCHOR: exceptions
use log::error;
use smccc::Hvc;
use smccc::psci::system_off;
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn sync_current(_elr: u64, _spsr: u64) {
error!("sync_current");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn irq_current(_elr: u64, _spsr: u64) {
error!("irq_current");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
error!("fiq_current");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn serror_current(_elr: u64, _spsr: u64) {
error!("serror_current");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
error!("sync_lower");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
error!("irq_lower");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
error!("fiq_lower");
system_off::<Hvc>().unwrap();
}
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn serror_lower(_elr: u64, _spsr: u64) {
error!("serror_lower");
system_off::<Hvc>().unwrap();
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/src/error-handling/exercise.rs | src/error-handling/exercise.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(dead_code)]
// ANCHOR: types
/// An operation to perform on two subexpressions.
#[derive(Debug)]
enum Operation {
Add,
Sub,
Mul,
Div,
}
/// An expression, in tree form.
#[derive(Debug)]
enum Expression {
/// An operation on two subexpressions.
Op { op: Operation, left: Box<Expression>, right: Box<Expression> },
/// A literal value
Value(i64),
}
#[derive(PartialEq, Eq, Debug)]
struct DivideByZeroError;
// ANCHOR_END: types
/*
// ANCHOR: eval
// The original implementation of the expression evaluator. Update this to
// return a `Result` and produce an error when dividing by 0.
fn eval(e: Expression) -> i64 {
match e {
Expression::Op { op, left, right } => {
let left = eval(*left);
let right = eval(*right);
match op {
Operation::Add => left + right,
Operation::Sub => left - right,
Operation::Mul => left * right,
Operation::Div => if right != 0 {
left / right
} else {
panic!("Cannot divide by zero!");
},
}
}
Expression::Value(v) => v,
}
}
// ANCHOR_END: eval
*/
// ANCHOR: solution
fn eval(e: Expression) -> Result<i64, DivideByZeroError> {
match e {
Expression::Op { op, left, right } => {
let left = eval(*left)?;
let right = eval(*right)?;
Ok(match op {
Operation::Add => left + right,
Operation::Sub => left - right,
Operation::Mul => left * right,
Operation::Div => {
if right == 0 {
return Err(DivideByZeroError);
} else {
left / right
}
}
})
}
Expression::Value(v) => Ok(v),
}
}
// ANCHOR_END: solution
// ANCHOR: tests
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_error() {
assert_eq!(
eval(Expression::Op {
op: Operation::Div,
left: Box::new(Expression::Value(99)),
right: Box::new(Expression::Value(0)),
}),
Err(DivideByZeroError)
);
}
#[test]
fn test_ok() {
let expr = Expression::Op {
op: Operation::Sub,
left: Box::new(Expression::Value(20)),
right: Box::new(Expression::Value(10)),
};
assert_eq!(eval(expr), Ok(10));
}
}
// ANCHOR_END: tests
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/course.rs | mdbook-course/src/course.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Representation of Comprehensive Rust as a hierarchy of types.
//!
//! ```ignore
//! Courses -- a collection of courses
//! Course -- the level of content at which students enroll (fundamentals, android, etc.)
//! Session -- a block of instructional time (typically morning or afternoon)
//! Segment -- a collection of slides with a related theme
//! Slide -- a single topic (may be represented by multiple mdBook chapters)
//! ```
//!
//! This structure is parsed from the format of the book using a combination of
//! the order in which chapters are listed in `SUMMARY.md` and annotations in
//! the frontmatter of each chapter.
//!
//! A book contains a sequence of BookItems, each of which can contain
//! sub-items. A top-level item can potentially introduce a new course, session,
//! segment, and slide all in the same item. If the item has a `course` property
//! in its frontmatter, then it introduces a new course. If it has a `session`
//! property, then it introduces a new session. A top-level item always
//! corresponds 1-to-1 with a segment (as long as it is a chapter), and that
//! item becomes the first slide in that segment. Any other sub-items of the
//! top-level item are treated as further slides in the same segment.
use crate::frontmatter::{Frontmatter, split_frontmatter};
use crate::markdown::{Table, duration};
use mdbook::book::{Book, BookItem, Chapter};
use std::fmt::Write;
use std::path::PathBuf;
/// Duration, in minutes, of breaks between segments in the course.
const BREAK_DURATION: u64 = 10;
/// Courses is simply a collection of Courses.
///
/// Non-instructional material (such as the introduction) has `course: none` and
/// is not included in this data structure.
#[derive(Default, Debug)]
pub struct Courses {
pub courses: Vec<Course>,
}
/// A Course is the level of content at which students enroll.
///
/// Courses are identified by the `course` property in a session's frontmatter.
/// All sessions with the same value for `course` are grouped into a Course.
#[derive(Default, Debug)]
pub struct Course {
pub name: String,
pub sessions: Vec<Session>,
}
/// A Session is a block of instructional time, containing segments. Typically a
/// full day of instruction contains two sessions: morning and afternoon.
///
/// A session is identified by the `session` property in the session's
/// frontmatter. There can be only one session with a given name in a course.
#[derive(Default, Debug)]
pub struct Session {
pub name: String,
pub segments: Vec<Segment>,
target_minutes: u64,
}
/// A Segment is a collection of slides with a related theme.
///
/// A segment is identified as a top-level chapter within a session.
#[derive(Default, Debug)]
pub struct Segment {
pub name: String,
pub slides: Vec<Slide>,
}
/// A Slide presents a single topic. It may contain multiple mdBook chapters.
///
/// A slide is identified as an sub-chapter of a segment. Any sub-items of
/// that chapter are also included in the slide.
#[derive(Default, Debug)]
pub struct Slide {
pub name: String,
/// Minutes this slide should take to teach.
pub minutes: u64,
/// Source paths (`.md` files) in this slide.
pub source_paths: Vec<PathBuf>,
}
impl Courses {
/// Extract the course structure from the book. As a side-effect, the
/// frontmatter is stripped from each slide.
pub fn extract_structure(mut book: Book) -> anyhow::Result<(Self, Book)> {
let mut courses = Courses::default();
let mut current_course_name = None;
let mut current_session_name = None;
for item in &mut book.sections {
// We only want to process chapters, omitting part titles and separators.
let BookItem::Chapter(chapter) = item else {
continue;
};
let (frontmatter, content) = split_frontmatter(chapter)?;
chapter.content = content;
// If 'course' is given, use that course (if not 'none') and reset the
// session.
if let Some(course_name) = &frontmatter.course {
current_session_name = None;
if course_name == "none" {
current_course_name = None;
} else {
current_course_name = Some(course_name.clone());
}
}
// If 'session' is given, use that session.
if let Some(session_name) = &frontmatter.session {
current_session_name = Some(session_name.clone());
}
if current_course_name.is_some() && current_session_name.is_none() {
anyhow::bail!(
"{:?}: 'session' must appear in frontmatter when 'course' appears",
chapter.path
);
}
// If we have a course and session, then add this chapter to it as a
// segment.
if let (Some(course_name), Some(session_name)) =
(¤t_course_name, ¤t_session_name)
{
let course = courses.course_mut(course_name);
let session = course.session_mut(session_name);
session.target_minutes += frontmatter.target_minutes.unwrap_or(0);
session.add_segment(frontmatter, chapter)?;
}
}
Ok((courses, book))
}
/// Get a reference to a course, adding a new one if none by this name
/// exists.
fn course_mut(&mut self, name: impl AsRef<str>) -> &mut Course {
let name = name.as_ref();
if let Some(found_idx) =
self.courses.iter().position(|course| course.name == name)
{
return &mut self.courses[found_idx];
}
let course = Course::new(name);
self.courses.push(course);
self.courses.last_mut().unwrap()
}
/// Find a course by name.
pub fn find_course(&self, name: impl AsRef<str>) -> Option<&Course> {
let name = name.as_ref();
self.courses.iter().find(|c| c.name == name)
}
/// Find the slide generated from the given Chapter within these courses,
/// returning the "path" to that slide.
pub fn find_slide(
&self,
chapter: &Chapter,
) -> Option<(&Course, &Session, &Segment, &Slide)> {
let source_path = chapter.source_path.as_ref()?;
for course in self {
for session in course {
for segment in session {
for slide in segment {
if slide.source_paths.contains(source_path) {
return Some((course, session, segment, slide));
}
}
}
}
}
None
}
}
impl<'a> IntoIterator for &'a Courses {
type Item = &'a Course;
type IntoIter = std::slice::Iter<'a, Course>;
fn into_iter(self) -> Self::IntoIter {
self.courses.iter()
}
}
impl Course {
fn new(name: impl Into<String>) -> Self {
Course { name: name.into(), ..Default::default() }
}
/// Get a reference to a session, adding a new one if none by this name
/// exists.
fn session_mut(&mut self, name: impl AsRef<str>) -> &mut Session {
let name = name.as_ref();
if let Some(found_idx) =
self.sessions.iter().position(|session| session.name == name)
{
return &mut self.sessions[found_idx];
}
let session = Session::new(name);
self.sessions.push(session);
self.sessions.last_mut().unwrap()
}
/// Return the total duration of this course, as the sum of all segment
/// durations.
///
/// This includes breaks between segments, but does not count time between
/// between sessions.
pub fn minutes(&self) -> u64 {
self.into_iter().map(|s| s.minutes()).sum()
}
/// Return the target duration of this course, as the sum of all segment
/// target durations.
///
/// This includes breaks between segments, but does not count time between
/// sessions.
pub fn target_minutes(&self) -> u64 {
self.into_iter().map(|s| s.target_minutes()).sum()
}
/// Generate a Markdown schedule for this course, for placement at the given
/// path.
pub fn schedule(&self) -> String {
let mut outline = String::from("Course schedule:\n");
for session in self {
writeln!(
&mut outline,
" * {} ({}, including breaks)\n",
session.name,
duration(session.minutes())
)
.unwrap();
let mut segments = Table::new(["Segment".into(), "Duration".into()]);
for segment in session {
// Skip short segments (welcomes, wrap-up, etc.)
if segment.minutes() == 0 {
continue;
}
segments
.add_row([segment.name.clone(), duration(segment.minutes())]);
}
writeln!(&mut outline, "{}\n", segments).unwrap();
}
outline
}
}
impl<'a> IntoIterator for &'a Course {
type Item = &'a Session;
type IntoIter = std::slice::Iter<'a, Session>;
fn into_iter(self) -> Self::IntoIter {
self.sessions.iter()
}
}
impl Session {
fn new(name: impl Into<String>) -> Self {
Session { name: name.into(), ..Default::default() }
}
/// Add a new segment to the session, representing sub-items as slides.
fn add_segment(
&mut self,
frontmatter: Frontmatter,
chapter: &mut Chapter,
) -> anyhow::Result<()> {
let mut segment = Segment::new(&chapter.name);
segment.add_slide(frontmatter, chapter, false)?;
for sub_chapter in &mut chapter.sub_items {
let BookItem::Chapter(sub_chapter) = sub_chapter else {
continue;
};
let (frontmatter, content) = split_frontmatter(sub_chapter)?;
sub_chapter.content = content;
segment.add_slide(frontmatter, sub_chapter, true)?;
}
self.segments.push(segment);
Ok(())
}
/// Generate a Markdown outline for this session, for placement at the given
/// path.
pub fn outline(&self) -> String {
let mut segments = Table::new(["Segment".into(), "Duration".into()]);
for segment in self {
// Skip short segments (welcomes, wrap-up, etc.)
if segment.minutes() == 0 {
continue;
}
segments.add_row([segment.name.clone(), duration(segment.minutes())]);
}
format!(
"Including {BREAK_DURATION} minute breaks, this session should take about {}. It contains:\n\n{}",
duration(self.minutes()),
segments
)
}
/// Return the total duration of this session.
pub fn minutes(&self) -> u64 {
let instructional_time: u64 = self.into_iter().map(|s| s.minutes()).sum();
if instructional_time == 0 {
return instructional_time;
}
let breaks = (self.into_iter().filter(|s| s.minutes() > 0).count() - 1)
as u64
* BREAK_DURATION;
instructional_time + breaks
}
/// Return the target duration of this session.
///
/// This includes breaks between segments.
pub fn target_minutes(&self) -> u64 {
if self.target_minutes > 0 { self.target_minutes } else { self.minutes() }
}
}
impl<'a> IntoIterator for &'a Session {
type Item = &'a Segment;
type IntoIter = std::slice::Iter<'a, Segment>;
fn into_iter(self) -> Self::IntoIter {
self.segments.iter()
}
}
impl Segment {
fn new(name: impl Into<String>) -> Self {
Segment { name: name.into(), ..Default::default() }
}
/// Create a slide from a chapter. If `recurse` is true, sub-items of this
/// chapter are included in this slide as well.
fn add_slide(
&mut self,
frontmatter: Frontmatter,
chapter: &mut Chapter,
recurse: bool,
) -> anyhow::Result<()> {
let mut slide = Slide::new(frontmatter, chapter);
if recurse {
slide.add_sub_chapters(chapter)?;
}
self.slides.push(slide);
Ok(())
}
/// Return the total duration of this segment (the sum of the durations of
/// the enclosed slides).
pub fn minutes(&self) -> u64 {
self.into_iter().map(|s| s.minutes()).sum()
}
pub fn outline(&self) -> String {
let mut slides = Table::new(["Slide".into(), "Duration".into()]);
for slide in self {
if slide.minutes() == 0 {
continue;
}
slides.add_row([slide.name.clone(), duration(slide.minutes())]);
}
format!(
"This segment should take about {}. It contains:\n\n{}",
duration(self.minutes()),
slides,
)
}
}
impl<'a> IntoIterator for &'a Segment {
type Item = &'a Slide;
type IntoIter = std::slice::Iter<'a, Slide>;
fn into_iter(self) -> Self::IntoIter {
self.slides.iter()
}
}
impl Slide {
fn new(frontmatter: Frontmatter, chapter: &Chapter) -> Self {
let mut slide = Self { name: chapter.name.clone(), ..Default::default() };
slide.add_frontmatter(&frontmatter);
slide.push_source_path(&chapter.source_path);
slide
}
fn add_frontmatter(&mut self, frontmatter: &Frontmatter) {
self.minutes += frontmatter.minutes.unwrap_or(0);
}
fn push_source_path(&mut self, source_path: &Option<PathBuf>) {
if let Some(source_path) = &source_path {
self.source_paths.push(source_path.clone());
}
}
/// Add sub-chapters of this chapter to this slide (recursively).
fn add_sub_chapters(&mut self, chapter: &mut Chapter) -> anyhow::Result<()> {
for sub_slide in &mut chapter.sub_items {
let BookItem::Chapter(sub_slide) = sub_slide else {
continue;
};
let (frontmatter, content) = split_frontmatter(sub_slide)?;
sub_slide.content = content;
if frontmatter.course.is_some() || frontmatter.session.is_some() {
anyhow::bail!(
"{:?}: sub-slides may not have 'course' or 'session' set",
sub_slide.path
);
}
self.add_frontmatter(&frontmatter);
self.push_source_path(&sub_slide.source_path);
self.add_sub_chapters(sub_slide)?;
}
Ok(())
}
/// Determine whether the given chapter is a sub-chapter of this slide.
pub fn is_sub_chapter(&self, chapter: &Chapter) -> bool {
// The first `source_path` in the slide is the "parent" chapter, so anything
// else is a sub-chapter.
chapter.source_path.as_ref() != self.source_paths.first()
}
/// Return the total duration of this slide.
pub fn minutes(&self) -> u64 {
self.minutes
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/lib.rs | mdbook-course/src/lib.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod course;
pub mod frontmatter;
pub mod markdown;
pub mod replacements;
pub mod timing_info;
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/replacements.rs | mdbook-course/src/replacements.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::course::{Course, Courses, Segment, Session};
use mdbook::book::Chapter;
use regex::Regex;
lazy_static::lazy_static! {
static ref DIRECTIVE: Regex = Regex::new(r#"\{\{%([^}]*)}}"#).unwrap();
}
/// Replace supported directives with the relevant content.
///
/// See the mdbook-course README for details.
#[allow(unused_variables)]
pub fn replace(
courses: &Courses,
course: Option<&Course>,
session: Option<&Session>,
segment: Option<&Segment>,
chapter: &mut Chapter,
) {
let Some(source_path) = &chapter.source_path else {
return;
};
chapter.content = DIRECTIVE
.replace_all(&chapter.content, |captures: ®ex::Captures| {
let directive_str = captures[1].trim();
let directive: Vec<_> = directive_str.split_whitespace().collect();
match directive.as_slice() {
["session", "outline"] if session.is_some() => {
session.unwrap().outline()
}
["segment", "outline"] if segment.is_some() => {
segment.unwrap().outline()
}
["course", "outline"] if course.is_some() => {
course.unwrap().schedule()
}
["course", "outline", course_name @ ..] => {
let course_name = course_name.join(" ");
let Some(course) = courses.find_course(course_name) else {
return format!("not found - {}", &captures[0]);
};
course.schedule()
}
_ => directive_str.to_owned(),
}
})
.to_string();
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/timing_info.rs | mdbook-course/src/timing_info.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::course::Slide;
use mdbook::book::Chapter;
/// Insert timing information for this slide into the speaker notes.
pub fn insert_timing_info(slide: &Slide, chapter: &mut Chapter) {
if slide.minutes > 0
&& !slide.is_sub_chapter(chapter)
&& chapter.content.contains("<details>")
{
// Include the minutes in the speaker notes.
let minutes = slide.minutes;
let plural = if slide.minutes == 1 { "minute" } else { "minutes" };
let mut subslides = "";
if slide.source_paths.len() > 1 {
subslides = "and its sub-slides ";
}
let timing_message =
format!("This slide {subslides}should take about {minutes} {plural}. ");
chapter.content = chapter
.content
.replace("<details>", &format!("<details>\n{timing_message}"));
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/markdown.rs | mdbook-course/src/markdown.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
use std::path::Path;
/// Given a source_path for the markdown file being rendered and a source_path
/// for the target, generate a relative link.
pub fn relative_link(
doc_path: impl AsRef<Path>,
target_path: impl AsRef<Path>,
) -> String {
let doc_path = doc_path.as_ref();
let target_path = target_path.as_ref();
let mut dotdot = -1;
for parent in doc_path.ancestors() {
if target_path.starts_with(parent) {
break;
}
dotdot += 1;
}
if dotdot > 0 {
format!("{}{}", "../".repeat(dotdot as usize), target_path.display())
} else {
format!("./{}", target_path.display())
}
}
/// Represent the given duration in a human-readable way.
///
/// This will round times longer than 5 minutes to the next 5-minute interval.
pub fn duration(mut minutes: u64) -> String {
if minutes > 5 {
minutes += 4;
minutes -= minutes % 5;
}
let (hours, minutes) = (minutes / 60, minutes % 60);
match (hours, minutes) {
(0, 1) => "1 minute".into(),
(0, m) => format!("{m} minutes"),
(1, 0) => "1 hour".into(),
(1, m) => format!("1 hour and {m} minutes"),
(h, 0) => format!("{h} hours"),
(h, m) => format!("{h} hours and {m} minutes"),
}
}
/// Table implements Display to format a two-dimensional table as markdown,
/// following https://github.github.com/gfm/#tables-extension-.
pub struct Table<const N: usize> {
header: [String; N],
rows: Vec<[String; N]>,
}
impl<const N: usize> Table<N> {
pub fn new(header: [String; N]) -> Self {
Self { header, rows: Vec::new() }
}
pub fn add_row(&mut self, row: [String; N]) {
self.rows.push(row);
}
fn write_row<'a, I: Iterator<Item = &'a str>>(
&self,
f: &mut fmt::Formatter<'_>,
iter: I,
) -> fmt::Result {
write!(f, "|")?;
for cell in iter {
write!(f, " {} |", cell)?;
}
writeln!(f)
}
}
impl<const N: usize> fmt::Display for Table<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.write_row(f, self.header.iter().map(|s| s.as_str()))?;
self.write_row(f, self.header.iter().map(|_| "-"))?;
for row in &self.rows {
self.write_row(f, row.iter().map(|s| s.as_str()))?;
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn relative_link_same_dir() {
assert_eq!(
relative_link(Path::new("welcome.md"), Path::new("hello-world.md")),
"./hello-world.md".to_string()
);
}
#[test]
fn relative_link_subdir() {
assert_eq!(
relative_link(
Path::new("hello-world.md"),
Path::new("hello-world/foo.md")
),
"./hello-world/foo.md".to_string()
);
}
#[test]
fn relative_link_parent_dir() {
assert_eq!(
relative_link(
Path::new("references/foo.md"),
Path::new("hello-world.md")
),
"../hello-world.md".to_string()
);
}
#[test]
fn relative_link_deep_parent_dir() {
assert_eq!(
relative_link(
Path::new("references/foo/bar.md"),
Path::new("hello-world.md")
),
"../../hello-world.md".to_string()
);
}
#[test]
fn relative_link_peer_dir() {
assert_eq!(
relative_link(
Path::new("references/foo.md"),
Path::new("hello-world/foo.md")
),
"../hello-world/foo.md".to_string()
);
}
#[test]
fn duration_no_time() {
assert_eq!(duration(0), "0 minutes");
}
#[test]
fn duration_single_minute() {
assert_eq!(duration(1), "1 minute");
}
#[test]
fn duration_two_minutes() {
assert_eq!(duration(2), "2 minutes");
}
#[test]
fn duration_seven_minutes() {
assert_eq!(duration(7), "10 minutes");
}
#[test]
fn duration_hour() {
assert_eq!(duration(60), "1 hour");
}
#[test]
fn duration_hour_mins() {
assert_eq!(duration(61), "1 hour and 5 minutes");
}
#[test]
fn duration_hours() {
assert_eq!(duration(120), "2 hours");
}
#[test]
fn duration_hours_mins() {
assert_eq!(duration(130), "2 hours and 10 minutes");
}
#[test]
fn table() {
let mut table = Table::new(["a".into(), "b".into()]);
table.add_row(["a1".into(), "b1".into()]);
table.add_row(["a2".into(), "b2".into()]);
assert_eq!(
format!("{}", table),
"| a | b |\n| - | - |\n| a1 | b1 |\n| a2 | b2 |\n"
);
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/frontmatter.rs | mdbook-course/src/frontmatter.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use anyhow::Context;
use matter::matter;
use mdbook::book::Chapter;
use serde::Deserialize;
#[derive(Deserialize, Debug, Default)]
pub struct Frontmatter {
pub minutes: Option<u64>,
pub target_minutes: Option<u64>,
pub course: Option<String>,
pub session: Option<String>,
}
/// Split a chapter's contents into frontmatter and the remaining contents.
pub fn split_frontmatter(
chapter: &Chapter,
) -> anyhow::Result<(Frontmatter, String)> {
if let Some((frontmatter, content)) = matter(&chapter.content) {
let frontmatter: Frontmatter = serde_yaml::from_str(&frontmatter)
.with_context(|| {
format!("error parsing frontmatter in {:?}", chapter.source_path)
})?;
Ok((frontmatter, content))
} else {
Ok((Frontmatter::default(), chapter.content.clone()))
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/bin/mdbook-course.rs | mdbook-course/src/bin/mdbook-course.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap::{Arg, Command};
use mdbook::book::BookItem;
use mdbook::preprocess::CmdPreprocessor;
use mdbook_course::course::Courses;
use mdbook_course::{replacements, timing_info};
use std::io::{stdin, stdout};
use std::process;
fn main() {
pretty_env_logger::init();
let app = Command::new("mdbook-course")
.about("mdbook preprocessor for Comprehensive Rust")
.subcommand(
Command::new("supports").arg(Arg::new("renderer").required(true)),
);
let matches = app.get_matches();
if matches.subcommand_matches("supports").is_some() {
// Support all renderers.
process::exit(0);
}
if let Err(e) = preprocess() {
eprintln!("{}", e);
process::exit(1);
}
}
fn preprocess() -> anyhow::Result<()> {
let (_, book) = CmdPreprocessor::parse_input(stdin())?;
let (courses, mut book) = Courses::extract_structure(book)?;
book.for_each_mut(|chapter| {
if let BookItem::Chapter(chapter) = chapter {
if let Some((course, session, segment, slide)) =
courses.find_slide(chapter)
{
timing_info::insert_timing_info(slide, chapter);
replacements::replace(
&courses,
Some(course),
Some(session),
Some(segment),
chapter,
);
} else {
// Outside of a course, just perform replacements.
replacements::replace(&courses, None, None, None, chapter);
}
}
});
serde_json::to_writer(stdout(), &book)?;
Ok(())
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/bin/course-content.rs | mdbook-course/src/bin/course-content.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use mdbook::MDBook;
use mdbook_course::course::Courses;
use std::fs;
use std::path::Path;
fn main() {
pretty_env_logger::init();
let root_dir = ".";
let mdbook = MDBook::load(root_dir).expect("Unable to load the book");
let (courses, _) = Courses::extract_structure(mdbook.book)
.expect("Unable to extract course structure");
let src_dir = Path::new("src");
for course in &courses {
println!("# COURSE: {}", course.name);
for session in course {
println!("# SESSION: {}", session.name);
for segment in session {
println!("# SEGMENT: {}", segment.name);
for slide in segment {
println!("# SLIDE: {}", slide.name);
for path in &slide.source_paths {
let content =
fs::read_to_string(src_dir.join(path)).unwrap();
println!("{}", content);
}
}
}
}
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/mdbook-course/src/bin/course-schedule.rs | mdbook-course/src/bin/course-schedule.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap::Command;
use mdbook::MDBook;
use mdbook_course::course::Courses;
use mdbook_course::markdown::duration;
fn main() {
pretty_env_logger::init();
let app = Command::new("mdbook-course")
.about("mdbook preprocessor for Comprehensive Rust")
.subcommand(Command::new("sessions").about("Show session summary (default)"))
.subcommand(Command::new("segments").about("Show segment summary"))
.subcommand(Command::new("pr").about("Show summary for a PR"));
let matches = app.get_matches();
let root_dir = ".";
let mdbook = MDBook::load(root_dir).expect("Unable to load the book");
let (courses, _) = Courses::extract_structure(mdbook.book)
.expect("Unable to extract course structure");
match matches.subcommand() {
Some(("session", _)) | None => session_summary(&courses),
Some(("pr", _)) => pr_summary(&courses),
_ => unreachable!(),
}
}
fn timediff(actual: u64, target: u64, slop: u64) -> String {
if actual > target + slop {
format!(
"{} (\u{23f0} *{} too long*)",
duration(actual),
duration(actual - target),
)
} else if actual + slop < target {
format!("{}: ({} short)", duration(actual), duration(target - actual),)
} else {
duration(actual).to_string()
}
}
fn session_summary(courses: &Courses) {
for course in courses {
if course.target_minutes() == 0 {
return;
}
for session in course {
println!("### {} // {}", course.name, session.name);
println!(
"_{}_",
timediff(session.minutes(), session.target_minutes(), 15)
);
println!();
for segment in session {
println!("* {} - _{}_", segment.name, duration(segment.minutes()));
}
println!();
}
}
}
fn pr_summary(courses: &Courses) {
println!("## Course Schedule");
println!("With this pull request applied, the course schedule is as follows:");
for course in courses {
if course.target_minutes() == 0 {
return;
}
println!("### {}", course.name);
println!("_{}_", timediff(course.minutes(), course.target_minutes(), 15));
for session in course {
println!(
"* {} - _{}_",
session.name,
timediff(session.minutes(), session.target_minutes(), 5)
);
}
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
google/comprehensive-rust | https://github.com/google/comprehensive-rust/blob/da6f4f6e13474fcf59ce927b406a300c402a8ca3/xtask/src/main.rs | xtask/src/main.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! This binary allows us to execute tasks within the project by running
//! `cargo xtask <task>`. It can thus be used as a task automation tool.
//! For example instead of repeatedly running `cargo install` from the CLI
//! to install all the necessary tools for the project we can just run
//! `cargo xtask install-tools` and the logic defined here will install
//! the tools.
use anyhow::{Context, Result, anyhow};
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{env, fs};
use walkdir::WalkDir;
fn main() -> Result<()> {
execute_task()
}
#[derive(Parser)]
#[command(
about = "Binary for executing tasks within the Comprehensive Rust project"
)]
struct Cli {
/// The task to execute
#[command(subcommand)]
task: Task,
}
#[derive(Subcommand)]
enum Task {
/// Installs the tools the project depends on.
InstallTools {
/// Use cargo-binstall for faster installation.
#[arg(long)]
binstall: bool,
},
/// Runs the web driver tests in the tests directory.
WebTests {
/// Optional 'book html' directory - if set, will also refresh the list
/// of slides used by slide size test.
#[arg(short, long)]
dir: Option<PathBuf>,
},
/// (Re)creates the slides.list.ts file based on the given book html
/// directory.
CreateSlideList {
/// The book html directory
#[arg(short, long)]
dir: PathBuf,
},
/// Tests all included Rust snippets.
RustTests,
/// Starts a web server with the course.
Serve {
/// ISO 639 language code (e.g. da for the Danish translation).
#[arg(short, long)]
language: Option<String>,
/// Directory to place the build. If not provided, defaults to the book/
/// directory (or the book/xx directory if a language is provided).
#[arg(short, long)]
output: Option<PathBuf>,
},
/// Create a static version of the course.
Build {
/// ISO 639 language code (e.g. da for the Danish translation).
#[arg(short, long)]
language: Option<String>,
/// Directory to place the build. If not provided, defaults to the book/
/// directory (or the book/xx directory if a language is provided).
#[arg(short, long)]
output: Option<PathBuf>,
},
}
fn execute_task() -> Result<()> {
let cli = Cli::parse();
match cli.task {
Task::InstallTools { binstall } => install_tools(binstall),
Task::WebTests { dir } => run_web_tests(dir),
Task::CreateSlideList { dir } => create_slide_list(dir),
Task::RustTests => run_rust_tests(),
Task::Serve { language, output } => start_web_server(language, output),
Task::Build { language, output } => build(language, output),
}
}
/// Executes a command and returns an error if it fails.
fn run_command(cmd: &mut Command) -> Result<()> {
let command_display = format!("{cmd:?}");
println!("> {command_display}");
let status = cmd
.status()
.with_context(|| format!("Failed to execute command: {command_display}"))?;
if !status.success() {
let exit_description = if let Some(code) = status.code() {
format!("exited with status code: {}", code)
} else {
"was terminated by a signal".to_string()
};
return Err(anyhow!("Command `{command_display}` {exit_description}"));
}
Ok(())
}
fn install_tools(binstall: bool) -> Result<()> {
println!("Installing project tools...");
let cargo = env!("CARGO");
let install_command = if binstall { "binstall" } else { "install" };
const PINNED_NIGHTLY: &str = "nightly-2025-09-01";
// Install rustup components
let rustup_steps = [
["toolchain", "install", "--profile", "minimal", PINNED_NIGHTLY],
["component", "add", "rustfmt", "--toolchain", PINNED_NIGHTLY],
];
for args in rustup_steps {
let mut cmd = Command::new("rustup");
cmd.args(args);
run_command(&mut cmd)?;
}
// The --locked flag is important for reproducible builds.
let tools = [
("mdbook", "0.4.52"),
("mdbook-svgbob", "0.2.2"),
("mdbook-pandoc", "0.10.4"),
("mdbook-i18n-helpers", "0.3.6"),
("i18n-report", "0.2.0"),
("mdbook-linkcheck2", "0.9.1"),
];
for (tool, version) in tools {
let mut cmd = Command::new(cargo);
cmd.args([install_command, tool, "--version", version, "--locked"]);
run_command(&mut cmd)?;
}
// Install local tools from the workspace.
let workspace_dir = Path::new(env!("CARGO_WORKSPACE_DIR"));
// cargo-binstall does not support --path, so we always use cargo install here.
let local_tools = ["mdbook-exerciser", "mdbook-course"];
for tool in local_tools {
let mut cmd = Command::new(cargo);
cmd.args(["install", "--path"])
.arg(workspace_dir.join(tool))
.arg("--locked");
run_command(&mut cmd)?;
}
// Uninstall original linkcheck if currently installed (see issue no 2773)
uninstall_mdbook_linkcheck()?;
Ok(())
}
fn uninstall_mdbook_linkcheck() -> Result<()> {
println!("Uninstalling old mdbook-linkcheck if installed...");
let output = Command::new(env!("CARGO"))
.args(["uninstall", "mdbook-linkcheck"])
.output()
.context("Failed to execute `cargo uninstall mdbook-linkcheck`")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
// This specific error is OK, it just means the package wasn't installed.
if !stderr.contains("did not match any packages") {
return Err(anyhow!(
"Failed to uninstall `mdbook-linkcheck`.\n--- stderr:\n{stderr}"
));
}
println!("mdbook-linkcheck not installed. Continuing...");
}
Ok(())
}
fn run_web_tests(dir: Option<PathBuf>) -> Result<()> {
println!("Running web tests...");
let workspace_dir = Path::new(env!("CARGO_WORKSPACE_DIR"));
let absolute_dir = dir.map(|d| d.canonicalize()).transpose()?;
if let Some(d) = &absolute_dir {
println!("Refreshing slide lists...");
create_slide_list(d.clone())?;
}
let tests_dir = workspace_dir.join("tests");
let mut cmd = Command::new("npm");
cmd.current_dir(tests_dir).arg("test");
if let Some(d) = absolute_dir {
cmd.env("TEST_BOOK_DIR", d);
}
run_command(&mut cmd)
}
// Creates a list of .html slides from the html directory containing the
// index.html to check the slides.
// - CI environment: Only modified files are listed
// - Otherwise: All existing html files
fn create_slide_list(html_directory: PathBuf) -> Result<()> {
let workspace_dir = Path::new(env!("CARGO_WORKSPACE_DIR"));
let tests_dir = workspace_dir.join("tests");
// Check if the provided directory is correct
if !html_directory.join("index.html").exists() {
return Err(anyhow!(
"Could not find index.html in {}. Please check if the correct directory is used (e.g. book/html).",
html_directory.display()
));
}
// These special slides are not checked against the style guide
let exclude_paths = [
"exercise.html",
"solution.html",
"toc.html",
"print.html",
"404.html",
"glossary.html",
"index.html",
"course-structure.html",
]
.map(PathBuf::from);
// Collect the files relevant for evaluation.
// - CI environment variable is set: all modified markdown files in the src/
// directory
// - all html files in the provided directory otherwise
let candidate_slides: Vec<PathBuf> = if env::var("CI").is_ok() {
println!("CI environment detected, checking only modified slides.");
// GITHUB_BASE_REF is available in PRs. Default to 'main' for other CI
// contexts.
let base_ref = env::var("GITHUB_BASE_REF").unwrap_or("main".to_string());
let mut cmd = Command::new("git");
cmd.arg("diff")
.arg("--name-only")
.arg(format!("{}...", base_ref))
.arg("--")
// Retrieve all modified files in the src directory.
// Pathspec syntax: https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-pathspec
// `*` can match path separators, thus matches also files in
// subdirectories
.arg("src/*.md");
println!("> {cmd:?}");
let output = cmd.output().context("Failed to run git diff")?;
String::from_utf8(output.stdout)?
.lines()
.map(|line| {
let path = Path::new(line);
// We know the path starts with "src/" because of the pathspec in the
// `git diff` command, and we need it relative to the html base
// directory
let stripped_path = path.strip_prefix("src").unwrap();
let mut html_path = stripped_path.to_path_buf();
// replace the .md extension with .html
html_path.set_extension("html");
html_path
})
.collect()
} else {
println!("Local environment, checking all slides.");
WalkDir::new(&html_directory)
.into_iter()
.filter_map(|e| e.ok())
// only files with .html extension
.filter(|e| e.path().extension().is_some_and(|ext| ext == "html"))
// relative path inside the html directory
.map(|e| e.path().strip_prefix(&html_directory).unwrap().to_path_buf())
.collect()
};
// Filter the candidate slides
let mut slides = Vec::new();
for slide in candidate_slides {
// Skip excluded files
if exclude_paths.iter().any(|exclude_path| slide.ends_with(exclude_path)) {
continue;
}
// Test if the html files actually exist
let full_path = html_directory.join(&slide);
if !full_path.exists() {
continue;
}
// Optimization: check if these are redirection html files and skip these
let content = fs::read_to_string(&full_path)
.with_context(|| format!("Failed to read slide: {}", slide.display()))?;
if content.contains("Redirecting to...") {
continue;
}
slides.push(slide);
}
if env::var("CI").is_ok() {
println!("The following slides have been modified and will be checked:");
for slide in &slides {
println!("{}", slide.display());
}
}
// Write the file list into a .ts file that can be read by the JS based webtest
let output_path = tests_dir.join("src").join("slides").join("slides.list.ts");
let mut output_content = "export const slides = [\n".to_string();
for slide in slides {
output_content.push_str(&format!(" \"{}\",\n", slide.display()));
}
output_content.push_str("];\n");
fs::write(&output_path, output_content)
.with_context(|| format!("Failed to write to {}", output_path.display()))?;
Ok(())
}
fn run_rust_tests() -> Result<()> {
println!("Running rust tests...");
let workspace_root = Path::new(env!("CARGO_WORKSPACE_DIR"));
let mut cmd = Command::new("mdbook");
cmd.current_dir(workspace_root).arg("test");
run_command(&mut cmd)
}
fn run_mdbook_command(
subcommand: &str,
language: Option<String>,
output_arg: Option<PathBuf>,
) -> Result<()> {
let workspace_root = Path::new(env!("CARGO_WORKSPACE_DIR"));
let mut cmd = Command::new("mdbook");
cmd.current_dir(workspace_root).arg(subcommand);
if let Some(language) = &language {
println!("Language: {language}");
cmd.env("MDBOOK_BOOK__LANGUAGE", language);
}
cmd.arg("-d");
cmd.arg(get_output_dir(language, output_arg));
run_command(&mut cmd)
}
fn start_web_server(
language: Option<String>,
output_arg: Option<PathBuf>,
) -> Result<()> {
println!("Starting web server ...");
run_mdbook_command("serve", language, output_arg)
}
fn build(language: Option<String>, output_arg: Option<PathBuf>) -> Result<()> {
println!("Building course...");
run_mdbook_command("build", language, output_arg)
}
fn get_output_dir(language: Option<String>, output_arg: Option<PathBuf>) -> PathBuf {
// If the 'output' arg is specified by the caller, use that, otherwise output to
// the 'book/' directory (or the 'book/xx' directory if a language was
// specified).
if let Some(d) = output_arg {
d
} else {
Path::new("book").join(language.unwrap_or("".to_string()))
}
}
| rust | Apache-2.0 | da6f4f6e13474fcf59ce927b406a300c402a8ca3 | 2026-01-04T15:32:35.184838Z | false |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/lib.rs | src/acpi-tables/src/lib.rs | // Copyright © 2019 Intel Corporation
// Copyright 2023 Rivos, Inc.
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError};
pub mod aml;
pub mod dsdt;
pub mod fadt;
pub mod madt;
pub mod mcfg;
pub mod rsdp;
pub mod xsdt;
pub use aml::Aml;
pub use dsdt::Dsdt;
pub use fadt::Fadt;
pub use madt::Madt;
pub use mcfg::Mcfg;
pub use rsdp::Rsdp;
pub use xsdt::Xsdt;
use zerocopy::little_endian::{U32, U64};
use zerocopy::{Immutable, IntoBytes};
// This is the creator ID that we will embed in ACPI tables that are created using this crate.
const FC_ACPI_CREATOR_ID: [u8; 4] = *b"FCAT";
// This is the created ID revision that we will embed in ACPI tables that are created using this
// crate.
const FC_ACPI_CREATOR_REVISION: u32 = 0x20240119;
fn checksum(buf: &[&[u8]]) -> u8 {
(255 - buf
.iter()
.flat_map(|b| b.iter())
.fold(0u8, |acc, x| acc.wrapping_add(*x)))
.wrapping_add(1)
}
#[derive(Debug, thiserror::Error, displaydoc::Display)]
pub enum AcpiError {
/// Guest memory error: {0}
GuestMemory(#[from] GuestMemoryError),
/// Invalid guest address
InvalidGuestAddress,
/// Invalid register size
InvalidRegisterSize,
}
pub type Result<T> = std::result::Result<T, AcpiError>;
/// ACPI type representing memory addresses
#[repr(C, packed)]
#[derive(IntoBytes, Immutable, Clone, Copy, Debug, Default)]
pub struct GenericAddressStructure {
pub address_space_id: u8,
pub register_bit_width: u8,
pub register_bit_offset: u8,
pub access_size: u8,
pub address: U64,
}
impl GenericAddressStructure {
pub fn new(
address_space_id: u8,
register_bit_width: u8,
register_bit_offset: u8,
access_size: u8,
address: u64,
) -> Self {
Self {
address_space_id,
register_bit_width,
register_bit_offset,
access_size,
address: U64::new(address),
}
}
}
/// Header included in all System Descriptor Tables
#[repr(C, packed)]
#[derive(Clone, Debug, Copy, Default, IntoBytes, Immutable)]
pub struct SdtHeader {
pub signature: [u8; 4],
pub length: U32,
pub revision: u8,
pub checksum: u8,
pub oem_id: [u8; 6],
pub oem_table_id: [u8; 8],
pub oem_revision: U32,
pub creator_id: [u8; 4],
pub creator_revision: U32,
}
impl SdtHeader {
pub(crate) fn new(
signature: [u8; 4],
length: u32,
table_revision: u8,
oem_id: [u8; 6],
oem_table_id: [u8; 8],
oem_revision: u32,
) -> Self {
SdtHeader {
signature,
length: U32::new(length),
revision: table_revision,
checksum: 0,
oem_id,
oem_table_id,
oem_revision: U32::new(oem_revision),
creator_id: FC_ACPI_CREATOR_ID,
creator_revision: U32::new(FC_ACPI_CREATOR_REVISION),
}
}
}
/// A trait for functionality around System Descriptor Tables.
pub trait Sdt {
/// Get the length of the table
fn len(&self) -> usize;
/// Return true if Sdt is empty
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Write the table in guest memory
fn write_to_guest<M: GuestMemory>(&mut self, mem: &M, address: GuestAddress) -> Result<()>;
}
#[cfg(test)]
mod tests {
use super::checksum;
#[test]
fn test_checksum() {
assert_eq!(checksum(&[&[]]), 0u8);
assert_eq!(checksum(&[]), 0u8);
assert_eq!(checksum(&[&[1, 2, 3]]), 250u8);
assert_eq!(checksum(&[&[1, 2, 3], &[]]), 250u8);
assert_eq!(checksum(&[&[1, 2], &[3]]), 250u8);
assert_eq!(checksum(&[&[1, 2], &[3], &[250]]), 0u8);
assert_eq!(checksum(&[&[255]]), 1u8);
assert_eq!(checksum(&[&[1, 2], &[3], &[250], &[255]]), 1u8);
}
}
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | false |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/xsdt.rs | src/acpi-tables/src/xsdt.rs | // Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright 2023 Rivos, Inc.
//
// SPDX-License-Identifier: Apache-2.0
use std::mem::size_of;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory};
use zerocopy::IntoBytes;
use crate::{AcpiError, Result, Sdt, SdtHeader, checksum};
/// Extended System Description Table (XSDT)
///
/// This table provides 64bit addresses to the rest of the ACPI tables defined by the platform
/// More information about this table can be found in the ACPI specification:
/// https://uefi.org/specs/ACPI/6.5/05_ACPI_Software_Programming_Model.html#extended-system-description-table-xsdt
#[derive(Clone, Default, Debug)]
pub struct Xsdt {
header: SdtHeader,
tables: Vec<u8>,
}
impl Xsdt {
pub fn new(
oem_id: [u8; 6],
oem_table_id: [u8; 8],
oem_revision: u32,
tables: Vec<u64>,
) -> Self {
let mut tables_bytes = Vec::with_capacity(8 * tables.len());
for addr in tables {
tables_bytes.extend(&addr.to_le_bytes());
}
let header = SdtHeader::new(
*b"XSDT",
(std::mem::size_of::<SdtHeader>() + tables_bytes.len())
.try_into()
.unwrap(),
1,
oem_id,
oem_table_id,
oem_revision,
);
let mut xsdt = Xsdt {
header,
tables: tables_bytes,
};
xsdt.header.checksum = checksum(&[xsdt.header.as_bytes(), (xsdt.tables.as_slice())]);
xsdt
}
}
impl Sdt for Xsdt {
fn len(&self) -> usize {
std::mem::size_of::<SdtHeader>() + self.tables.len()
}
fn write_to_guest<M: GuestMemory>(&mut self, mem: &M, address: GuestAddress) -> Result<()> {
mem.write_slice(self.header.as_bytes(), address)?;
let address = address
.checked_add(size_of::<SdtHeader>() as u64)
.ok_or(AcpiError::InvalidGuestAddress)?;
mem.write_slice(self.tables.as_slice(), address)?;
Ok(())
}
}
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | false |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/aml.rs | src/acpi-tables/src/aml.rs | // Copyright © 2019 Intel Corporation
// Copyright © 2023 Rivos, Inc.
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
#![allow(missing_debug_implementations)]
use std::marker::PhantomData;
#[derive(Debug, Clone, thiserror::Error, displaydoc::Display)]
pub enum AmlError {
/// Aml Path is empty
NameEmpty,
/// Invalid name part length
InvalidPartLength,
/// Invalid address range
AddressRange,
}
pub trait Aml {
fn append_aml_bytes(&self, _v: &mut Vec<u8>) -> Result<(), AmlError>;
fn to_aml_bytes(&self) -> Result<Vec<u8>, AmlError> {
let mut v = Vec::new();
self.append_aml_bytes(&mut v)?;
Ok(v)
}
}
pub const ZERO: Zero = Zero {};
pub struct Zero {}
impl Aml for Zero {
fn append_aml_bytes(&self, v: &mut Vec<u8>) -> Result<(), AmlError> {
v.push(0u8);
Ok(())
}
}
pub const ONE: One = One {};
pub struct One {}
impl Aml for One {
fn append_aml_bytes(&self, v: &mut Vec<u8>) -> Result<(), AmlError> {
v.push(1u8);
Ok(())
}
}
pub const ONES: Ones = Ones {};
pub struct Ones {}
impl Aml for Ones {
fn append_aml_bytes(&self, v: &mut Vec<u8>) -> Result<(), AmlError> {
v.push(0xffu8);
Ok(())
}
}
pub struct Path {
root: bool,
name_parts: Vec<[u8; 4]>,
}
impl Aml for Path {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
if self.root {
bytes.push(b'\\');
}
match self.name_parts.len() {
0 => return Err(AmlError::NameEmpty),
1 => {}
2 => {
bytes.push(0x2e); // DualNamePrefix
}
n => {
bytes.push(0x2f); // MultiNamePrefix
bytes.push(n.try_into().unwrap());
}
};
for part in &self.name_parts {
bytes.extend_from_slice(part);
}
Ok(())
}
}
impl Path {
pub fn new(name: &str) -> Result<Self, AmlError> {
let root = name.starts_with('\\');
let offset = root.into();
let mut name_parts = Vec::new();
for part in name[offset..].split('.') {
if part.len() != 4 {
return Err(AmlError::InvalidPartLength);
}
let mut name_part = [0u8; 4];
name_part.copy_from_slice(part.as_bytes());
name_parts.push(name_part);
}
Ok(Path { root, name_parts })
}
}
impl TryFrom<&str> for Path {
type Error = AmlError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
Path::new(s)
}
}
pub type Byte = u8;
impl Aml for Byte {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x0a); // BytePrefix
bytes.push(*self);
Ok(())
}
}
pub type Word = u16;
impl Aml for Word {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x0b); // WordPrefix
bytes.extend_from_slice(&self.to_le_bytes());
Ok(())
}
}
pub type DWord = u32;
impl Aml for DWord {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x0c); // DWordPrefix
bytes.extend_from_slice(&self.to_le_bytes());
Ok(())
}
}
pub type QWord = u64;
impl Aml for QWord {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x0e); // QWordPrefix
bytes.extend_from_slice(&self.to_le_bytes());
Ok(())
}
}
pub struct Name {
bytes: Vec<u8>,
}
impl Aml for Name {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
// TODO: Refactor this to make more efficient but there are
// lifetime/ownership challenges.
bytes.extend_from_slice(&self.bytes);
Ok(())
}
}
impl Name {
pub fn new(path: Path, inner: &dyn Aml) -> Result<Self, AmlError> {
let mut bytes = vec![0x08]; // NameOp
path.append_aml_bytes(&mut bytes)?;
inner.append_aml_bytes(&mut bytes)?;
Ok(Name { bytes })
}
}
pub struct Package<'a> {
children: Vec<&'a dyn Aml>,
}
impl Aml for Package<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = vec![self.children.len().try_into().unwrap()];
for child in &self.children {
child.append_aml_bytes(&mut tmp)?;
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x12); // PackageOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
impl<'a> Package<'a> {
pub fn new(children: Vec<&'a dyn Aml>) -> Self {
Package { children }
}
}
// From the ACPI spec for PkgLength:
//
// "The high 2 bits of the first byte reveal how many follow bytes are in the PkgLength. If the
// PkgLength has only one byte, bit 0 through 5 are used to encode the package length (in other
// words, values 0-63). If the package length value is more than 63, more than one byte must be
// used for the encoding in which case bit 4 and 5 of the PkgLeadByte are reserved and must be zero.
// If the multiple bytes encoding is used, bits 0-3 of the PkgLeadByte become the least significant
// 4 bits of the resulting package length value. The next ByteData will become the next least
// significant 8 bits of the resulting value and so on, up to 3 ByteData bytes. Thus, the maximum
// package length is 2**28."
//
// Also used for NamedField but in that case the length is not included in itself
fn create_pkg_length(data: &[u8], include_self: bool) -> Vec<u8> {
let mut result = Vec::new();
// PkgLength is inclusive and includes the length bytes
let length_length = if data.len() < (2usize.pow(6) - 1) {
1
} else if data.len() < (2usize.pow(12) - 2) {
2
} else if data.len() < (2usize.pow(20) - 3) {
3
} else {
4
};
let length = data.len() + if include_self { length_length } else { 0 };
match length_length {
1 => result.push(length.try_into().unwrap()),
2 => {
result.push((1u8 << 6) | TryInto::<u8>::try_into(length & 0xf).unwrap());
result.push(TryInto::<u8>::try_into(length >> 4).unwrap())
}
3 => {
result.push((2u8 << 6) | TryInto::<u8>::try_into(length & 0xf).unwrap());
result.push(((length >> 4) & 0xff).try_into().unwrap());
result.push(((length >> 12) & 0xff).try_into().unwrap());
}
_ => {
result.push((3u8 << 6) | TryInto::<u8>::try_into(length & 0xf).unwrap());
result.push(((length >> 4) & 0xff).try_into().unwrap());
result.push(((length >> 12) & 0xff).try_into().unwrap());
result.push(((length >> 20) & 0xff).try_into().unwrap());
}
}
result
}
pub struct EisaName {
value: DWord,
}
impl EisaName {
pub fn new(name: &str) -> Result<Self, AmlError> {
if name.len() != 7 {
return Err(AmlError::InvalidPartLength);
}
let data = name.as_bytes();
let value: u32 = ((u32::from(data[0] - 0x40) << 26)
| (u32::from(data[1] - 0x40) << 21)
| (u32::from(data[2] - 0x40) << 16)
| (name.chars().nth(3).unwrap().to_digit(16).unwrap() << 12)
| (name.chars().nth(4).unwrap().to_digit(16).unwrap() << 8)
| (name.chars().nth(5).unwrap().to_digit(16).unwrap() << 4)
| name.chars().nth(6).unwrap().to_digit(16).unwrap())
.swap_bytes();
Ok(EisaName { value })
}
}
impl Aml for EisaName {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
self.value.append_aml_bytes(bytes)
}
}
pub type Usize = usize;
impl Aml for Usize {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
if *self <= u8::MAX.into() {
TryInto::<u8>::try_into(*self)
.unwrap()
.append_aml_bytes(bytes)
} else if *self <= u16::MAX.into() {
TryInto::<u16>::try_into(*self)
.unwrap()
.append_aml_bytes(bytes)
} else if *self <= u32::MAX as usize {
TryInto::<u32>::try_into(*self)
.unwrap()
.append_aml_bytes(bytes)
} else {
TryInto::<u64>::try_into(*self)
.unwrap()
.append_aml_bytes(bytes)
}
}
}
fn append_aml_string(v: &str, bytes: &mut Vec<u8>) {
bytes.push(0x0D); // String Op
bytes.extend_from_slice(v.as_bytes());
bytes.push(0x0); // NullChar
}
pub type AmlStr = &'static str;
impl Aml for AmlStr {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
append_aml_string(self, bytes);
Ok(())
}
}
pub type AmlString = String;
impl Aml for AmlString {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
append_aml_string(self, bytes);
Ok(())
}
}
pub struct ResourceTemplate<'a> {
children: Vec<&'a dyn Aml>,
}
impl Aml for ResourceTemplate<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
// Add buffer data
for child in &self.children {
child.append_aml_bytes(&mut tmp)?;
}
// Mark with end and mark checksum as as always valid
tmp.push(0x79); // EndTag
tmp.push(0); // zero checksum byte
// Buffer length is an encoded integer including buffer data
// and EndTag and checksum byte
let mut buffer_length = tmp.len().to_aml_bytes()?;
buffer_length.reverse();
for byte in buffer_length {
tmp.insert(0, byte);
}
// PkgLength is everything else
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x11); // BufferOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
impl<'a> ResourceTemplate<'a> {
pub fn new(children: Vec<&'a dyn Aml>) -> Self {
ResourceTemplate { children }
}
}
pub struct Memory32Fixed {
read_write: bool, // true for read & write, false for read only
base: u32,
length: u32,
}
impl Memory32Fixed {
pub fn new(read_write: bool, base: u32, length: u32) -> Self {
Memory32Fixed {
read_write,
base,
length,
}
}
}
impl Aml for Memory32Fixed {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x86); // Memory32Fixed
bytes.extend_from_slice(&9u16.to_le_bytes());
// 9 bytes of payload
bytes.push(self.read_write.into());
bytes.extend_from_slice(&self.base.to_le_bytes());
bytes.extend_from_slice(&self.length.to_le_bytes());
Ok(())
}
}
#[derive(Copy, Clone)]
enum AddressSpaceType {
Memory,
Io,
BusNumber,
}
#[derive(Copy, Clone)]
pub enum AddressSpaceCacheable {
NotCacheable,
Cacheable,
WriteCombining,
PreFetchable,
}
pub struct AddressSpace<T> {
r#type: AddressSpaceType,
min: T,
max: T,
type_flags: u8,
}
impl<T> AddressSpace<T>
where
T: PartialOrd,
{
pub fn new_memory(
cacheable: AddressSpaceCacheable,
read_write: bool,
min: T,
max: T,
) -> Result<Self, AmlError> {
if min > max {
return Err(AmlError::AddressRange);
}
Ok(AddressSpace {
r#type: AddressSpaceType::Memory,
min,
max,
type_flags: ((cacheable as u8) << 1) | u8::from(read_write),
})
}
pub fn new_io(min: T, max: T) -> Result<Self, AmlError> {
if min > max {
return Err(AmlError::AddressRange);
}
Ok(AddressSpace {
r#type: AddressSpaceType::Io,
min,
max,
type_flags: 3, // EntireRange
})
}
pub fn new_bus_number(min: T, max: T) -> Result<Self, AmlError> {
if min > max {
return Err(AmlError::AddressRange);
}
Ok(AddressSpace {
r#type: AddressSpaceType::BusNumber,
min,
max,
type_flags: 0,
})
}
fn push_header(&self, bytes: &mut Vec<u8>, descriptor: u8, length: usize) {
bytes.push(descriptor); // Word Address Space Descriptor
bytes.extend_from_slice(&(TryInto::<u16>::try_into(length).unwrap()).to_le_bytes());
bytes.push(self.r#type as u8); // type
let generic_flags = (1 << 2) /* Min Fixed */ | (1 << 3); // Max Fixed
bytes.push(generic_flags);
bytes.push(self.type_flags);
}
}
impl Aml for AddressSpace<u16> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
self.push_header(
bytes,
0x88, // Word Address Space Descriptor
3 + 5 * std::mem::size_of::<u16>(), // 3 bytes of header + 5 u16 fields
);
bytes.extend_from_slice(&0u16.to_le_bytes()); // Granularity
bytes.extend_from_slice(&self.min.to_le_bytes()); // Min
bytes.extend_from_slice(&self.max.to_le_bytes()); // Max
bytes.extend_from_slice(&0u16.to_le_bytes()); // Translation
let len = self.max - self.min + 1;
bytes.extend_from_slice(&len.to_le_bytes()); // Length
Ok(())
}
}
impl Aml for AddressSpace<u32> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
self.push_header(
bytes,
0x87, // DWord Address Space Descriptor
3 + 5 * std::mem::size_of::<u32>(), // 3 bytes of header + 5 u32 fields
);
bytes.extend_from_slice(&0u32.to_le_bytes()); // Granularity
bytes.extend_from_slice(&self.min.to_le_bytes()); // Min
bytes.extend_from_slice(&self.max.to_le_bytes()); // Max
bytes.extend_from_slice(&0u32.to_le_bytes()); // Translation
let len = self.max - self.min + 1;
bytes.extend_from_slice(&len.to_le_bytes()); // Length
Ok(())
}
}
impl Aml for AddressSpace<u64> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
self.push_header(
bytes,
0x8A, // QWord Address Space Descriptor
3 + 5 * std::mem::size_of::<u64>(), // 3 bytes of header + 5 u64 fields
);
bytes.extend_from_slice(&0u64.to_le_bytes()); // Granularity
bytes.extend_from_slice(&self.min.to_le_bytes()); // Min
bytes.extend_from_slice(&self.max.to_le_bytes()); // Max
bytes.extend_from_slice(&0u64.to_le_bytes()); // Translation
let len = self.max - self.min + 1;
bytes.extend_from_slice(&len.to_le_bytes()); // Length
Ok(())
}
}
pub struct Io {
min: u16,
max: u16,
alignment: u8,
length: u8,
}
impl Io {
pub fn new(min: u16, max: u16, alignment: u8, length: u8) -> Self {
Io {
min,
max,
alignment,
length,
}
}
}
impl Aml for Io {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x47); // Io Port Descriptor
bytes.push(1); // IODecode16
bytes.extend_from_slice(&self.min.to_le_bytes());
bytes.extend_from_slice(&self.max.to_le_bytes());
bytes.push(self.alignment);
bytes.push(self.length);
Ok(())
}
}
pub struct Interrupt {
consumer: bool,
edge_triggered: bool,
active_low: bool,
shared: bool,
number: u32,
}
impl Interrupt {
pub fn new(
consumer: bool,
edge_triggered: bool,
active_low: bool,
shared: bool,
number: u32,
) -> Self {
Interrupt {
consumer,
edge_triggered,
active_low,
shared,
number,
}
}
}
impl Aml for Interrupt {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x89); // Extended IRQ Descriptor
bytes.extend_from_slice(&6u16.to_le_bytes());
let flags = (u8::from(self.shared) << 3)
| (u8::from(self.active_low) << 2)
| (u8::from(self.edge_triggered) << 1)
| u8::from(self.consumer);
bytes.push(flags);
bytes.push(1u8); // count
bytes.extend_from_slice(&self.number.to_le_bytes());
Ok(())
}
}
pub struct Device<'a> {
path: Path,
children: Vec<&'a dyn Aml>,
}
impl Aml for Device<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.path.append_aml_bytes(&mut tmp)?;
for child in &self.children {
child.append_aml_bytes(&mut tmp)?;
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x5b); // ExtOpPrefix
bytes.push(0x82); // DeviceOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
impl<'a> Device<'a> {
pub fn new(path: Path, children: Vec<&'a dyn Aml>) -> Self {
Device { path, children }
}
}
pub struct Scope<'a> {
path: Path,
children: Vec<&'a dyn Aml>,
}
impl Aml for Scope<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.path.append_aml_bytes(&mut tmp)?;
for child in &self.children {
child.append_aml_bytes(&mut tmp)?;
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x10); // ScopeOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
impl<'a> Scope<'a> {
pub fn new(path: Path, children: Vec<&'a dyn Aml>) -> Self {
Scope { path, children }
}
}
pub struct Method<'a> {
path: Path,
children: Vec<&'a dyn Aml>,
args: u8,
serialized: bool,
}
impl<'a> Method<'a> {
pub fn new(path: Path, args: u8, serialized: bool, children: Vec<&'a dyn Aml>) -> Self {
Method {
path,
children,
args,
serialized,
}
}
}
impl Aml for Method<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.path.append_aml_bytes(&mut tmp)?;
let flags: u8 = (self.args & 0x7) | (u8::from(self.serialized) << 3);
tmp.push(flags);
for child in &self.children {
child.append_aml_bytes(&mut tmp)?;
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x14); // MethodOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
pub struct Return<'a> {
value: &'a dyn Aml,
}
impl<'a> Return<'a> {
pub fn new(value: &'a dyn Aml) -> Self {
Return { value }
}
}
impl Aml for Return<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0xa4); // ReturnOp
self.value.append_aml_bytes(bytes)?;
Ok(())
}
}
#[derive(Clone, Copy)]
pub enum FieldAccessType {
Any,
Byte,
Word,
DWord,
QWord,
Buffer,
}
#[derive(Clone, Copy)]
pub enum FieldUpdateRule {
Preserve = 0,
WriteAsOnes = 1,
WriteAsZeroes = 2,
}
pub enum FieldEntry {
Named([u8; 4], usize),
Reserved(usize),
}
pub struct Field {
path: Path,
fields: Vec<FieldEntry>,
access_type: FieldAccessType,
update_rule: FieldUpdateRule,
}
impl Field {
pub fn new(
path: Path,
access_type: FieldAccessType,
update_rule: FieldUpdateRule,
fields: Vec<FieldEntry>,
) -> Self {
Field {
path,
fields,
access_type,
update_rule,
}
}
}
impl Aml for Field {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.path.append_aml_bytes(&mut tmp)?;
let flags: u8 = self.access_type as u8 | ((self.update_rule as u8) << 5);
tmp.push(flags);
for field in self.fields.iter() {
match field {
FieldEntry::Named(name, length) => {
tmp.extend_from_slice(name);
tmp.extend_from_slice(&create_pkg_length(&vec![0; *length], false));
}
FieldEntry::Reserved(length) => {
tmp.push(0x0);
tmp.extend_from_slice(&create_pkg_length(&vec![0; *length], false));
}
}
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x5b); // ExtOpPrefix
bytes.push(0x81); // FieldOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
#[derive(Clone, Copy)]
pub enum OpRegionSpace {
SystemMemory,
SystemIo,
PConfig,
EmbeddedControl,
Smbus,
SystemCmos,
PciBarTarget,
Ipmi,
GeneralPurposeIo,
GenericSerialBus,
}
pub struct OpRegion {
path: Path,
space: OpRegionSpace,
offset: usize,
length: usize,
}
impl OpRegion {
pub fn new(path: Path, space: OpRegionSpace, offset: usize, length: usize) -> Self {
OpRegion {
path,
space,
offset,
length,
}
}
}
impl Aml for OpRegion {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x5b); // ExtOpPrefix
bytes.push(0x80); // OpRegionOp
self.path.append_aml_bytes(bytes)?;
bytes.push(self.space as u8);
self.offset.append_aml_bytes(bytes)?; // RegionOffset
self.length.append_aml_bytes(bytes)?; // RegionLen
Ok(())
}
}
pub struct If<'a> {
predicate: &'a dyn Aml,
if_children: Vec<&'a dyn Aml>,
}
impl<'a> If<'a> {
pub fn new(predicate: &'a dyn Aml, if_children: Vec<&'a dyn Aml>) -> Self {
If {
predicate,
if_children,
}
}
}
impl Aml for If<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.predicate.append_aml_bytes(&mut tmp)?;
for child in self.if_children.iter() {
child.append_aml_bytes(&mut tmp)?;
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0xa0); // IfOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
pub struct Equal<'a> {
left: &'a dyn Aml,
right: &'a dyn Aml,
}
impl<'a> Equal<'a> {
pub fn new(left: &'a dyn Aml, right: &'a dyn Aml) -> Self {
Equal { left, right }
}
}
impl Aml for Equal<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x93); // LEqualOp
self.left.append_aml_bytes(bytes)?;
self.right.append_aml_bytes(bytes)?;
Ok(())
}
}
pub struct LessThan<'a> {
left: &'a dyn Aml,
right: &'a dyn Aml,
}
impl<'a> LessThan<'a> {
pub fn new(left: &'a dyn Aml, right: &'a dyn Aml) -> Self {
LessThan { left, right }
}
}
impl Aml for LessThan<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x95); // LLessOp
self.left.append_aml_bytes(bytes)?;
self.right.append_aml_bytes(bytes)?;
Ok(())
}
}
pub struct Arg(pub u8);
impl Aml for Arg {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
if self.0 > 6 {
return Err(AmlError::InvalidPartLength);
}
bytes.push(0x68 + self.0); // Arg0Op
Ok(())
}
}
pub struct Local(pub u8);
impl Aml for Local {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
if self.0 > 7 {
return Err(AmlError::InvalidPartLength);
}
bytes.push(0x60 + self.0); // Local0Op
Ok(())
}
}
pub struct Store<'a> {
name: &'a dyn Aml,
value: &'a dyn Aml,
}
impl<'a> Store<'a> {
pub fn new(name: &'a dyn Aml, value: &'a dyn Aml) -> Self {
Store { name, value }
}
}
impl Aml for Store<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x70); // StoreOp
self.value.append_aml_bytes(bytes)?;
self.name.append_aml_bytes(bytes)?;
Ok(())
}
}
pub struct Mutex {
path: Path,
sync_level: u8,
}
impl Mutex {
pub fn new(path: Path, sync_level: u8) -> Self {
Self { path, sync_level }
}
}
impl Aml for Mutex {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x5b); // ExtOpPrefix
bytes.push(0x01); // MutexOp
self.path.append_aml_bytes(bytes)?;
bytes.push(self.sync_level);
Ok(())
}
}
pub struct Acquire {
mutex: Path,
timeout: u16,
}
impl Acquire {
pub fn new(mutex: Path, timeout: u16) -> Self {
Acquire { mutex, timeout }
}
}
impl Aml for Acquire {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x5b); // ExtOpPrefix
bytes.push(0x23); // AcquireOp
self.mutex.append_aml_bytes(bytes)?;
bytes.extend_from_slice(&self.timeout.to_le_bytes());
Ok(())
}
}
pub struct Release {
mutex: Path,
}
impl Release {
pub fn new(mutex: Path) -> Self {
Release { mutex }
}
}
impl Aml for Release {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x5b); // ExtOpPrefix
bytes.push(0x27); // ReleaseOp
self.mutex.append_aml_bytes(bytes)?;
Ok(())
}
}
pub struct Notify<'a> {
object: &'a dyn Aml,
value: &'a dyn Aml,
}
impl<'a> Notify<'a> {
pub fn new(object: &'a dyn Aml, value: &'a dyn Aml) -> Self {
Notify { object, value }
}
}
impl Aml for Notify<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x86); // NotifyOp
self.object.append_aml_bytes(bytes)?;
self.value.append_aml_bytes(bytes)?;
Ok(())
}
}
pub struct While<'a> {
predicate: &'a dyn Aml,
while_children: Vec<&'a dyn Aml>,
}
impl<'a> While<'a> {
pub fn new(predicate: &'a dyn Aml, while_children: Vec<&'a dyn Aml>) -> Self {
While {
predicate,
while_children,
}
}
}
impl Aml for While<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.predicate.append_aml_bytes(&mut tmp)?;
for child in self.while_children.iter() {
child.append_aml_bytes(&mut tmp)?;
}
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0xa2); // WhileOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
macro_rules! binary_op {
($name:ident, $opcode:expr) => {
pub struct $name<'a> {
a: &'a dyn Aml,
b: &'a dyn Aml,
target: &'a dyn Aml,
}
impl<'a> $name<'a> {
pub fn new(target: &'a dyn Aml, a: &'a dyn Aml, b: &'a dyn Aml) -> Self {
$name { a, b, target }
}
}
impl<'a> Aml for $name<'a> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push($opcode); // Op for the binary operator
self.a.append_aml_bytes(bytes)?;
self.b.append_aml_bytes(bytes)?;
self.target.append_aml_bytes(bytes)
}
}
};
}
// binary operators: TermArg TermArg Target
binary_op!(Add, 0x72);
binary_op!(Concat, 0x73);
binary_op!(Subtract, 0x74);
binary_op!(Multiply, 0x77);
binary_op!(ShiftLeft, 0x79);
binary_op!(ShiftRight, 0x7A);
binary_op!(And, 0x7B);
binary_op!(Nand, 0x7C);
binary_op!(Or, 0x7D);
binary_op!(Nor, 0x7E);
binary_op!(Xor, 0x7F);
binary_op!(ConateRes, 0x84);
binary_op!(Mod, 0x85);
binary_op!(Index, 0x88);
binary_op!(ToString, 0x9C);
pub struct MethodCall<'a> {
name: Path,
args: Vec<&'a dyn Aml>,
}
impl<'a> MethodCall<'a> {
pub fn new(name: Path, args: Vec<&'a dyn Aml>) -> Self {
MethodCall { name, args }
}
}
impl Aml for MethodCall<'_> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
self.name.append_aml_bytes(bytes)?;
for arg in self.args.iter() {
arg.append_aml_bytes(bytes)?;
}
Ok(())
}
}
pub struct Buffer {
data: Vec<u8>,
}
impl Buffer {
pub fn new(data: Vec<u8>) -> Self {
Buffer { data }
}
}
impl Aml for Buffer {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
let mut tmp = Vec::new();
self.data.len().append_aml_bytes(&mut tmp)?;
tmp.extend_from_slice(&self.data);
let pkg_length = create_pkg_length(&tmp, true);
bytes.push(0x11); // BufferOp
bytes.extend_from_slice(&pkg_length);
bytes.extend_from_slice(&tmp);
Ok(())
}
}
pub struct CreateField<'a, T> {
buffer: &'a dyn Aml,
offset: &'a dyn Aml,
field: Path,
phantom: PhantomData<&'a T>,
}
impl<'a, T> CreateField<'a, T> {
pub fn new(buffer: &'a dyn Aml, offset: &'a dyn Aml, field: Path) -> Self {
CreateField::<T> {
buffer,
offset,
field,
phantom: PhantomData,
}
}
}
impl Aml for CreateField<'_, u64> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x8f); // CreateQWordFieldOp
self.buffer.append_aml_bytes(bytes)?;
self.offset.append_aml_bytes(bytes)?;
self.field.append_aml_bytes(bytes)
}
}
impl Aml for CreateField<'_, u32> {
fn append_aml_bytes(&self, bytes: &mut Vec<u8>) -> Result<(), AmlError> {
bytes.push(0x8a); // CreateDWordFieldOp
self.buffer.append_aml_bytes(bytes)?;
self.offset.append_aml_bytes(bytes)?;
self.field.append_aml_bytes(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_device() {
// Device (_SB.COM1)
// {
// Name (_HID, EisaId ("PNP0501") /* 16550A-compatible COM Serial Port */) // _HID:
// Hardware ID Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
// {
// Interrupt (ResourceConsumer, Edge, ActiveHigh, Exclusive, ,, )
// {
// 0x00000004,
// }
// IO (Decode16,
// 0x03F8, // Range Minimum
// 0x03F8, // Range Maximum
// 0x00, // Alignment
// 0x08, // Length
// )
// }
// }
let com1_device = [
0x5B, 0x82, 0x30, 0x2E, 0x5F, 0x53, 0x42, 0x5F, 0x43, 0x4F, 0x4D, 0x31, 0x08, 0x5F,
0x48, 0x49, 0x44, 0x0C, 0x41, 0xD0, 0x05, 0x01, 0x08, 0x5F, 0x43, 0x52, 0x53, 0x11,
0x16, 0x0A, 0x13, 0x89, 0x06, 0x00, 0x03, 0x01, 0x04, 0x00, 0x00, 0x00, 0x47, 0x01,
0xF8, 0x03, 0xF8, 0x03, 0x00, 0x08, 0x79, 0x00,
];
assert_eq!(
Device::new(
"_SB_.COM1".try_into().unwrap(),
vec![
&Name::new(
"_HID".try_into().unwrap(),
&EisaName::new("PNP0501").unwrap()
)
.unwrap(),
&Name::new(
"_CRS".try_into().unwrap(),
&ResourceTemplate::new(vec![
&Interrupt::new(true, true, false, false, 4),
&Io::new(0x3f8, 0x3f8, 0, 0x8)
])
)
.unwrap()
]
)
.to_aml_bytes()
.unwrap(),
&com1_device[..]
);
}
#[test]
fn test_scope() {
// Scope (_SB.MBRD)
// {
// Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
// {
// Memory32Fixed (ReadWrite,
// 0xE8000000, // Address Base
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | true |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/mcfg.rs | src/acpi-tables/src/mcfg.rs | // Copyright © 2019 Intel Corporation
// Copyright © 2023 Rivos, Inc.
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
use std::mem::size_of;
use vm_memory::{Bytes, GuestAddress, GuestMemory};
use zerocopy::{Immutable, IntoBytes};
use crate::{Result, Sdt, SdtHeader, checksum};
#[allow(dead_code)]
#[repr(C, packed)]
#[derive(Default, Debug, IntoBytes, Clone, Copy, Immutable)]
struct PciRangeEntry {
pub base_address: u64,
pub segment: u16,
pub start: u8,
pub end: u8,
_reserved: u32,
}
#[allow(dead_code)]
#[repr(C, packed)]
#[derive(Clone, Copy, Debug, Default, IntoBytes, Immutable)]
pub struct Mcfg {
header: SdtHeader,
_reserved: u64,
pci_range_entry: PciRangeEntry,
}
impl Mcfg {
pub fn new(
oem_id: [u8; 6],
oem_table_id: [u8; 8],
oem_revision: u32,
pci_mmio_config_addr: u64,
) -> Self {
let header = SdtHeader::new(
*b"MCFG",
size_of::<Mcfg>().try_into().unwrap(),
1,
oem_id,
oem_table_id,
oem_revision,
);
let mut mcfg = Mcfg {
header,
pci_range_entry: PciRangeEntry {
base_address: pci_mmio_config_addr,
segment: 0,
start: 0,
end: 0,
..Default::default()
},
..Default::default()
};
mcfg.header.checksum = checksum(&[mcfg.as_bytes()]);
mcfg
}
}
impl Sdt for Mcfg {
fn len(&self) -> usize {
self.as_bytes().len()
}
fn write_to_guest<M: GuestMemory>(&mut self, mem: &M, address: GuestAddress) -> Result<()> {
mem.write_slice(self.as_bytes(), address)?;
Ok(())
}
}
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | false |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/madt.rs | src/acpi-tables/src/madt.rs | // Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright 2023 Rivos, Inc.
//
// SPDX-License-Identifier: Apache-2.0
use std::mem::size_of;
use vm_memory::{Address, Bytes, GuestAddress, GuestMemory};
use zerocopy::little_endian::U32;
use zerocopy::{Immutable, IntoBytes};
use crate::{AcpiError, Result, Sdt, SdtHeader, checksum};
const MADT_CPU_ENABLE_FLAG: u32 = 0;
// clippy doesn't understand that we actually "use" the fields of this struct when we serialize
// them as bytes in guest memory, so here we just ignore dead code to avoid having to name
// everything with an underscore prefix
#[allow(dead_code)]
#[repr(C, packed)]
#[derive(Copy, Clone, Debug, Default, IntoBytes, Immutable)]
pub struct LocalAPIC {
r#type: u8,
length: u8,
processor_uid: u8,
apic_id: u8,
flags: U32,
}
impl LocalAPIC {
pub fn new(cpu_id: u8) -> Self {
Self {
r#type: 0,
length: 8,
processor_uid: cpu_id,
apic_id: cpu_id,
flags: U32::new(1u32 << MADT_CPU_ENABLE_FLAG),
}
}
}
// clippy doesn't understand that we actually "use" the fields of this struct when we serialize
// them as bytes in guest memory, so here we just ignore dead code to avoid having to name
// everything with an underscore prefix
#[allow(dead_code)]
#[repr(C, packed)]
#[derive(Copy, Clone, Debug, Default, IntoBytes, Immutable)]
pub struct IoAPIC {
r#type: u8,
length: u8,
ioapic_id: u8,
reserved: u8,
apic_address: U32,
gsi_base: U32,
}
impl IoAPIC {
pub fn new(ioapic_id: u8, apic_address: u32) -> Self {
IoAPIC {
r#type: 1,
length: 12,
ioapic_id,
reserved: 0,
apic_address: U32::new(apic_address),
gsi_base: U32::ZERO,
}
}
}
// clippy doesn't understand that we actually "use" the fields of this struct when we serialize
// them as bytes in guest memory, so here we just ignore dead code to avoid having to name
// everything with an underscore prefix
#[allow(dead_code)]
#[repr(C, packed)]
#[derive(Debug, IntoBytes, Immutable)]
struct MadtHeader {
sdt: SdtHeader,
base_address: U32,
flags: U32,
}
/// Multiple APIC Description Table (MADT)
///
/// This table includes information about the interrupt controllers of the device.
/// More information about this table can be found in the ACPI specification:
/// https://uefi.org/specs/ACPI/6.5/05_ACPI_Software_Programming_Model.html#multiple-apic-description-table-madt
#[derive(Debug)]
pub struct Madt {
header: MadtHeader,
interrupt_controllers: Vec<u8>,
}
impl Madt {
pub fn new(
oem_id: [u8; 6],
oem_table_id: [u8; 8],
oem_revision: u32,
base_address: u32,
interrupt_controllers: Vec<u8>,
) -> Self {
let length = size_of::<MadtHeader>() + interrupt_controllers.len();
let sdt_header = SdtHeader::new(
*b"APIC",
// It is ok to unwrap the conversion of `length` to u32. `SdtHeader` is 36 bytes long,
// so `length` here has a value of 44.
length.try_into().unwrap(),
6,
oem_id,
oem_table_id,
oem_revision,
);
let mut header = MadtHeader {
sdt: sdt_header,
base_address: U32::new(base_address),
flags: U32::ZERO,
};
header.sdt.checksum = checksum(&[header.as_bytes(), interrupt_controllers.as_bytes()]);
Madt {
header,
interrupt_controllers,
}
}
}
impl Sdt for Madt {
fn len(&self) -> usize {
self.header.sdt.length.get().try_into().unwrap()
}
fn write_to_guest<M: GuestMemory>(&mut self, mem: &M, address: GuestAddress) -> Result<()> {
mem.write_slice(self.header.as_bytes(), address)?;
let address = address
.checked_add(size_of::<MadtHeader>() as u64)
.ok_or(AcpiError::InvalidGuestAddress)?;
mem.write_slice(self.interrupt_controllers.as_bytes(), address)?;
Ok(())
}
}
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | false |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/fadt.rs | src/acpi-tables/src/fadt.rs | // Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright 2023 Rivos, Inc.
//
// SPDX-License-Identifier: Apache-2.0
use vm_memory::{Bytes, GuestAddress, GuestMemory};
use zerocopy::little_endian::{U16, U32, U64};
use zerocopy::{Immutable, IntoBytes};
use crate::{GenericAddressStructure, Result, Sdt, SdtHeader, checksum};
#[cfg(target_arch = "x86_64")]
pub const IAPC_BOOT_ARG_FLAGS_VGA_NOT_PRESENT: u16 = 2;
#[cfg(target_arch = "x86_64")]
pub const IAPC_BOOT_ARG_FLAGS_MSI_NOT_PRESENT: u16 = 3;
#[cfg(target_arch = "x86_64")]
pub const IAPC_BOOT_ARG_FLAGS_PCI_ASPM: u16 = 4;
// ACPI Flags. Reading from the specification here:
// https://uefi.org/specs/ACPI/6.5/05_ACPI_Software_Programming_Model.html#fixed-acpi-description-table-fixed-feature-flags
/// Flag for the Power Button functionality.
/// If the system does not have a power button, this value would be “1” and no power button device
/// would be present
pub const FADT_F_PWR_BUTTON: u8 = 4;
/// Flag for the Sleep Button Functionality.
/// If the system does not have a sleep button, this value would be “1” and no power button device
/// would be present
pub const FADT_F_SLP_BUTTON: u8 = 5;
/// Flag for Hardware Reduced API. If enabled, software-only alternatives are used for supported
/// fixed features.
pub const FADT_F_HW_REDUCED_ACPI: u8 = 20;
// clippy doesn't understand that we actually "use" the fields of this struct when we serialize
// them as bytes in guest memory, so here we just ignore dead code to avoid having to name
// everything with an underscore prefix
#[allow(dead_code)]
/// Fixed ACPI Description Table (FADT)
///
/// This table includes fixed hardware ACPI information such as addresses of register blocks and
/// the pointer to the DSDT table.
/// More information about this table can be found in the ACPI specification:
/// https://uefi.org/specs/ACPI/6.5/05_ACPI_Software_Programming_Model.html#fixed-acpi-description-table-fadt
#[repr(C, packed)]
#[derive(Debug, Copy, Clone, Default, IntoBytes, Immutable)]
pub struct Fadt {
header: SdtHeader,
firmware_control: U32,
dsdt: U32,
reserved_1: u8,
preferred_pm_profile: u8,
// In HW-reduced mode, fields starting from SCI_INT until CENTURY are ignored
sci_int: U16,
smi_cmd: U32,
acpi_enable: u8,
acpi_disable: u8,
s4bios_req: u8,
pstate_cnt: u8,
pm1a_evt_blk: U32,
pm1b_evt_blk: U32,
pm1a_cnt_blk: U32,
pm1b_cnt_blk: U32,
pm2_cnt_blk: U32,
pm_tmr_blk: U32,
gpe0_blk: U32,
gpe1_blk: U32,
pm1_evt_len: u8,
pm1_cnt_len: u8,
pm2_cnt_len: u8,
pm_tmr_len: u8,
gpe0_blk_len: u8,
gpe1_blk_len: u8,
gpe1_base: u8,
cst_cnt: u8,
p_lvl2_lat: U16,
p_lvl3_lat: U16,
flush_size: U16,
flush_stride: U16,
duty_offset: u8,
duty_width: u8,
day_alrm: u8,
mon_alrm: u8,
century: u8,
iapc_boot_arch: U16,
reserved_2: u8,
flags: U32,
reset_reg: GenericAddressStructure,
reset_value: u8,
arm_boot_arch: U16,
fadt_minor_version: u8,
x_firmware_ctrl: U64,
x_dsdt: U64,
// In HW-reduced mode, fields starting from X_PM1a_EVT_BLK through X_GPE1_BLK
// are ignored
x_pm1a_evt_blk: GenericAddressStructure,
x_pm1b_evt_blk: GenericAddressStructure,
x_pm1a_cnt_blk: GenericAddressStructure,
x_pm1b_cnt_blk: GenericAddressStructure,
x_pm2_cnt_blk: GenericAddressStructure,
x_pm_tmr_blk: GenericAddressStructure,
x_gpe0_blk: GenericAddressStructure,
x_gpe1_blk: GenericAddressStructure,
sleep_control_reg: GenericAddressStructure,
sleep_status_reg: GenericAddressStructure,
hypervisor_vendor_id: [u8; 8],
}
impl Fadt {
pub fn new(oem_id: [u8; 6], oem_table_id: [u8; 8], oem_revision: u32) -> Self {
let header = SdtHeader::new(
*b"FACP",
// It's fine to unwrap here, we know that the size of the Fadt structure fits in 32
// bits.
std::mem::size_of::<Self>().try_into().unwrap(),
6, // revision 6
oem_id,
oem_table_id,
oem_revision,
);
Fadt {
header,
fadt_minor_version: 5,
..Default::default()
}
}
/// Set the address of the DSDT table
///
/// This sets the 64bit variant, X_DSDT field of the FADT table
pub fn set_x_dsdt(&mut self, addr: u64) {
self.x_dsdt = U64::new(addr);
}
/// Set the FADT flags
pub fn set_flags(&mut self, flags: u32) {
self.flags = U32::new(flags);
}
/// Set the IA-PC specific flags
pub fn setup_iapc_flags(&mut self, flags: u16) {
self.iapc_boot_arch = U16::new(flags);
}
/// Set the hypervisor vendor ID
pub fn set_hypervisor_vendor_id(&mut self, hypervisor_vendor_id: [u8; 8]) {
self.hypervisor_vendor_id = hypervisor_vendor_id;
}
}
impl Sdt for Fadt {
fn len(&self) -> usize {
self.header.length.get().try_into().unwrap()
}
fn write_to_guest<M: GuestMemory>(&mut self, mem: &M, address: GuestAddress) -> Result<()> {
self.header.checksum = checksum(&[self.as_bytes()]);
mem.write_slice(self.as_bytes(), address)?;
Ok(())
}
}
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | false |
firecracker-microvm/firecracker | https://github.com/firecracker-microvm/firecracker/blob/f0691f8253d4bde225b9f70ecabf39b7ad796935/src/acpi-tables/src/rsdp.rs | src/acpi-tables/src/rsdp.rs | // Copyright © 2019 Intel Corporation
// Copyright © 2023 Rivos, Inc.
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
use vm_memory::{Bytes, GuestAddress, GuestMemory};
use zerocopy::little_endian::{U32, U64};
use zerocopy::{Immutable, IntoBytes};
use crate::{Result, Sdt, checksum};
// clippy doesn't understand that we actually "use" the fields of this struct when we serialize
// them as bytes in guest memory, so here we just ignore dead code to avoid having to name
// everything with an underscore prefix
#[allow(dead_code)]
/// Root System Description Pointer
///
/// This is the root pointer to the ACPI hierarchy. This is what OSs
/// are looking for in the memory when initializing ACPI. It includes
/// a pointer to XSDT
/// More information about this structure can be found in the ACPI specification:
/// https://uefi.org/specs/ACPI/6.5/05_ACPI_Software_Programming_Model.html#root-system-description-pointer-rsdp
#[repr(C, packed)]
#[derive(Clone, Copy, Debug, Default, IntoBytes, Immutable)]
pub struct Rsdp {
signature: [u8; 8],
checksum: u8,
oem_id: [u8; 6],
revision: u8,
rsdt_addr: U32,
length: U32,
xsdt_addr: U64,
extended_checksum: u8,
reserved: [u8; 3],
}
impl Rsdp {
pub fn new(oem_id: [u8; 6], xsdt_addr: u64) -> Self {
let mut rsdp = Rsdp {
// Space in the end of string is needed!
signature: *b"RSD PTR ",
checksum: 0,
oem_id,
revision: 2,
rsdt_addr: U32::ZERO,
length: U32::new(std::mem::size_of::<Rsdp>().try_into().unwrap()),
xsdt_addr: U64::new(xsdt_addr),
extended_checksum: 0,
reserved: [0u8; 3],
};
rsdp.checksum = checksum(&[&rsdp.as_bytes()[..20]]);
rsdp.extended_checksum = checksum(&[rsdp.as_bytes()]);
rsdp
}
}
impl Sdt for Rsdp {
fn len(&self) -> usize {
self.as_bytes().len()
}
fn write_to_guest<M: GuestMemory>(&mut self, mem: &M, address: GuestAddress) -> Result<()> {
mem.write_slice(self.as_bytes(), address)?;
Ok(())
}
}
| rust | Apache-2.0 | f0691f8253d4bde225b9f70ecabf39b7ad796935 | 2026-01-04T15:33:15.697747Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.