From bc5f7444ff0dd7545f562a196f63799afb710e5f Mon Sep 17 00:00:00 2001 From: GoldenPath1109 Date: Sun, 31 Dec 2023 00:15:07 +0100 Subject: [PATCH] Format all Markdown files with `dprint` (#1157) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is the result of running `dprint fmt` after removing `src/` from the list of excluded directories. This also reformats the Rust code: we might want to tweak this a bit in the future since some of the changes removes the hand-formatting. Of course, this formatting can be seen as a mis-feature, so maybe this is good overall. Thanks to mdbook-i18n-helpers 0.2, the POT file is nearly unchanged after this, meaning that all existing translations remain valid! A few messages were changed because of stray whitespace characters: msgid "" "Slices always borrow from another object. In this example, `a` has to remain " -"'alive' (in scope) for at least as long as our slice. " +"'alive' (in scope) for at least as long as our slice." msgstr "" The formatting is enforced in CI and we will have to see how annoying this is in practice for the many contributors. If it becomes annoying, we should look into fixing dprint/check#11 so that `dprint` can annotate the lines that need fixing directly, then I think we can consider more strict formatting checks. I added more customization to `rustfmt.toml`. This is to better emulate the dense style used in the course: - `max_width = 85` allows lines to take up the full width available in our code blocks (when taking margins and the line numbers into account). - `wrap_comments = true` ensures that we don't show very long comments in the code examples. I edited some comments to shorten them and avoid unnecessary line breaks — please trim other unnecessarily long comments when you see them! Remember we're writing code for slides :smile: - `use_small_heuristics = "Max"` allows for things like struct literals and if-statements to take up the full line width configured above. The formatting settings apply to all our Rust code right now — I think we could improve this with https://github.com/dprint/dprint/issues/711 which lets us add per-directory `dprint` configuration files. However, the `inherit: true` setting is not yet implemented (as far as I can tell), so a nested configuration file will have to copy most or all of the top-level file. --- dprint.json | 1 - mdbook-course/src/course.rs | 107 +++++++------ mdbook-course/src/frontmatter.rs | 8 +- mdbook-course/src/main.rs | 19 +-- mdbook-course/src/markdown.rs | 14 +- mdbook-course/src/timing_info.rs | 6 +- mdbook-exerciser/src/lib.rs | 8 +- mdbook-exerciser/src/main.rs | 8 +- po/pt-BR.po | 2 +- rustfmt.toml | 10 +- src/SUMMARY.md | 29 ++-- src/android.md | 23 +-- src/android/aidl.md | 10 +- .../aidl/birthday_service/src/client.rs | 7 +- src/android/aidl/birthday_service/src/lib.rs | 4 +- src/android/aidl/client.md | 4 +- src/android/aidl/implementation.md | 4 +- src/android/aidl/interface.md | 4 +- src/android/aidl/server.md | 4 +- src/android/build-rules.md | 15 +- src/android/build-rules/library.md | 4 +- src/android/interoperability.md | 4 +- .../interoperability/cpp/android-build-cpp.md | 6 +- .../cpp/android-cpp-genrules.md | 4 +- src/android/interoperability/cpp/bridge.md | 8 +- .../interoperability/cpp/cpp-bridge.md | 4 +- .../interoperability/cpp/cpp-exception.md | 4 +- .../interoperability/cpp/rust-bridge.md | 4 +- .../interoperability/cpp/rust-result.md | 6 +- .../interoperability/cpp/shared-enums.md | 2 +- .../interoperability/cpp/shared-types.md | 4 +- .../interoperability/cpp/type-mapping.md | 12 +- src/android/interoperability/java.md | 7 +- src/android/interoperability/with-c.md | 4 +- .../with-c/bindgen/c-library.md | 1 - .../interoperability/with-c/bindgen/main.rs | 5 +- .../interoperability/with-c/hand-written.md | 4 +- src/android/interoperability/with-c/rust.md | 6 +- src/android/setup.md | 15 +- src/async.md | 17 +- src/async/async-await.md | 22 +-- src/async/channels.md | 10 +- src/async/control-flow/join.md | 17 +- src/async/control-flow/select.md | 32 ++-- src/async/futures.md | 14 +- src/async/pitfalls.md | 4 +- src/async/pitfalls/async-traits.md | 23 +-- src/async/pitfalls/blocking-executor.md | 20 +-- src/async/pitfalls/cancellation.md | 71 +++++---- src/async/pitfalls/pin.md | 74 +++++---- src/async/runtimes.md | 22 +-- src/async/runtimes/tokio.md | 21 ++- src/async/tasks.md | 15 +- src/bare-metal.md | 27 ++-- src/bare-metal/alloc-example/src/main.rs | 4 +- src/bare-metal/alloc.md | 20 +-- src/bare-metal/android.md | 9 +- src/bare-metal/android/vmbase.md | 14 +- src/bare-metal/aps.md | 17 +- src/bare-metal/aps/better-uart.md | 6 +- src/bare-metal/aps/better-uart/bitflags.md | 7 +- src/bare-metal/aps/better-uart/driver.md | 4 +- src/bare-metal/aps/better-uart/registers.md | 11 +- src/bare-metal/aps/better-uart/using.md | 11 +- src/bare-metal/aps/entry-point.md | 54 ++++--- src/bare-metal/aps/examples/src/logger.rs | 4 +- src/bare-metal/aps/examples/src/pl011.rs | 7 +- src/bare-metal/aps/exceptions.md | 32 ++-- src/bare-metal/aps/inline-assembly.md | 39 +++-- src/bare-metal/aps/logging.md | 7 +- src/bare-metal/aps/logging/using.md | 5 +- src/bare-metal/aps/mmio.md | 24 +-- src/bare-metal/aps/other-projects.md | 46 +++--- src/bare-metal/aps/uart.md | 20 +-- src/bare-metal/aps/uart/traits.md | 9 +- src/bare-metal/microcontrollers.md | 14 +- .../microcontrollers/board-support.md | 15 +- src/bare-metal/microcontrollers/debugging.md | 11 ++ .../microcontrollers/embedded-hal.md | 28 ++-- .../microcontrollers/examples/src/bin/mmio.rs | 12 +- .../examples/src/bin/typestate.rs | 6 +- src/bare-metal/microcontrollers/hals.md | 13 +- src/bare-metal/microcontrollers/mmio.md | 7 +- .../microcontrollers/other-projects.md | 41 ++--- src/bare-metal/microcontrollers/pacs.md | 26 +-- src/bare-metal/microcontrollers/probe-rs.md | 39 +++-- src/bare-metal/microcontrollers/type-state.md | 22 +-- src/bare-metal/minimal.md | 18 ++- src/bare-metal/no_std.md | 52 +++--- src/bare-metal/useful-crates.md | 3 +- .../useful-crates/aarch64-paging.md | 13 +- .../useful-crates/buddy_system_allocator.md | 18 ++- src/bare-metal/useful-crates/spin.md | 23 +-- src/bare-metal/useful-crates/tinyvec.md | 15 +- src/bare-metal/useful-crates/zerocopy.md | 27 ++-- src/borrowing/borrowck.md | 31 ++-- src/borrowing/interior-mutability.md | 19 ++- src/borrowing/shared.md | 23 ++- src/cargo.md | 29 ++-- src/cargo/code-samples.md | 15 +- src/cargo/running-locally.md | 65 ++++---- src/cargo/rust-ecosystem.md | 71 ++++----- src/chromium.md | 9 +- src/chromium/adding-third-party-crates.md | 26 +-- .../adding-third-party-crates/checking-in.md | 16 +- .../configuring-cargo-toml.md | 11 +- .../configuring-gnrt-config-toml.md | 17 +- .../depending-on-a-crate.md | 6 +- .../downloading-crates.md | 19 ++- .../generating-gn-build-rules.md | 14 +- .../keeping-up-to-date.md | 8 +- .../resolving-problems.md | 20 +-- .../build-scripts-which-generate-code.md | 11 +- ...ld-scripts-which-take-arbitrary-actions.md | 20 +-- .../reviews-and-audits.md | 34 ++-- src/chromium/build-rules.md | 27 ++-- src/chromium/build-rules/depending.md | 2 +- src/chromium/build-rules/unsafe.md | 5 +- src/chromium/build-rules/vscode.md | 29 ++-- src/chromium/cargo.md | 62 ++++---- src/chromium/interoperability-with-cpp.md | 56 +++---- .../error-handling-png.md | 8 +- .../error-handling-qr.md | 9 +- .../error-handling.md | 28 ++-- .../example-bindings.md | 16 +- .../limitations-of-cxx.md | 16 +- .../using-cxx-in-chromium.md | 18 +-- src/chromium/policy.md | 17 +- src/chromium/setup.md | 13 +- src/chromium/testing.md | 39 ++--- src/chromium/testing/chromium-import-macro.md | 11 +- src/chromium/testing/rust-gtest-interop.md | 8 +- src/concurrency.md | 1 + src/concurrency/channels.md | 9 +- src/concurrency/channels/bounded.md | 14 +- src/concurrency/scoped-threads.md | 10 +- src/concurrency/send-sync.md | 20 +-- src/concurrency/send-sync/examples.md | 30 ++-- src/concurrency/send-sync/sync.md | 12 +- src/concurrency/shared_state.md | 6 +- src/concurrency/shared_state/arc.md | 19 +-- src/concurrency/shared_state/example.md | 16 +- src/concurrency/shared_state/mutex.md | 33 ++-- src/concurrency/threads.md | 14 +- src/control-flow-basics/blocks-and-scopes.md | 20 ++- src/control-flow-basics/break-continue.md | 10 +- src/control-flow-basics/conditionals.md | 25 ++- src/control-flow-basics/exercise.md | 17 +- src/control-flow-basics/functions.md | 21 ++- src/control-flow-basics/loops.md | 8 +- src/control-flow-basics/macros.md | 18 ++- src/credits.md | 8 +- src/error-handling/Cargo.toml | 2 +- src/error-handling/error.md | 11 +- src/error-handling/exercise.rs | 20 ++- src/error-handling/panics.md | 22 +-- src/error-handling/solution.md | 1 + src/error-handling/thiserror-and-anyhow.md | 41 ++--- src/error-handling/try-conversions.md | 13 +- src/error-handling/try.md | 14 +- src/exercises/android/morning.md | 4 +- src/exercises/bare-metal/compass.md | 38 +++-- src/exercises/bare-metal/compass/src/main.rs | 15 +- src/exercises/bare-metal/morning.md | 3 +- src/exercises/bare-metal/rtc.md | 34 ++-- .../bare-metal/rtc/src/exceptions.rs | 3 +- src/exercises/bare-metal/rtc/src/logger.rs | 4 +- src/exercises/bare-metal/rtc/src/main.rs | 10 +- src/exercises/bare-metal/rtc/src/pl011.rs | 7 +- src/exercises/bare-metal/rtc/src/pl031.rs | 4 +- .../chromium/bringing-it-together.md | 59 ++++--- src/exercises/chromium/build-rules.md | 41 ++--- .../chromium/interoperability-with-cpp.md | 86 +++++----- src/exercises/chromium/solutions.md | 5 +- src/exercises/chromium/testing.md | 12 +- src/exercises/chromium/third-party.md | 15 +- src/exercises/concurrency/afternoon.md | 6 +- src/exercises/concurrency/chat-app.md | 46 +++--- .../concurrency/chat-async/src/bin/server.rs | 4 +- .../concurrency/dining-philosophers-async.md | 18 +-- .../concurrency/dining-philosophers-async.rs | 8 +- src/exercises/concurrency/link-checker.md | 4 +- src/exercises/concurrency/link-checker.rs | 16 +- src/exercises/concurrency/morning.md | 4 +- .../concurrency/solutions-afternoon.md | 1 - src/generics/Cargo.toml | 1 - src/generics/exercise.rs | 15 +- src/generics/generic-data.md | 20 ++- src/generics/generic-functions.md | 11 +- src/generics/impl-trait.md | 18 ++- src/generics/trait-bounds.md | 17 +- src/glossary.md | 99 ++++++++---- src/hello-world/benefits.md | 13 +- src/hello-world/hello-world.md | 27 ++-- src/hello-world/playground.md | 8 +- src/hello-world/what-is-rust.md | 35 ++-- src/index.md | 43 +++-- src/iterators/exercise.md | 2 +- src/iterators/exercise.rs | 4 +- src/iterators/fromiterator.md | 14 +- src/iterators/intoiterator.md | 9 +- src/iterators/iterator.md | 21 +-- src/memory-management/approaches.md | 41 ++--- src/memory-management/clone.md | 3 +- src/memory-management/copy-types.md | 25 +-- src/memory-management/drop.md | 33 ++-- src/memory-management/exercise.rs | 6 +- src/memory-management/move.md | 42 ++--- src/memory-management/ownership.md | 5 +- src/memory-management/review.md | 25 +-- src/methods-and-traits/Cargo.toml | 1 - src/methods-and-traits/deriving.md | 2 +- src/methods-and-traits/exercise.md | 10 +- src/methods-and-traits/exercise.rs | 19 +-- src/methods-and-traits/methods.md | 58 ++++--- src/methods-and-traits/trait-objects.md | 35 ++-- src/methods-and-traits/traits.md | 23 ++- src/modules/exercise.md | 12 +- src/modules/filesystem.md | 30 ++-- src/modules/modules.md | 8 +- src/modules/paths.md | 26 +-- src/modules/solution.md | 24 +-- src/modules/visibility.md | 21 +-- src/other-resources.md | 44 +++--- src/pattern-matching/destructuring.md | 26 +-- src/pattern-matching/exercise.md | 17 +- src/pattern-matching/exercise.rs | 6 +- src/pattern-matching/let-control-flow.md | 39 +++-- src/references/exclusive.md | 13 +- src/references/exercise.rs | 5 +- src/references/shared.md | 35 ++-- src/running-the-course.md | 36 ++--- src/running-the-course/course-structure.md | 44 +++--- src/running-the-course/keyboard-shortcuts.md | 8 +- src/running-the-course/translations.md | 23 +-- src/slices-and-lifetimes/exercise.md | 9 +- src/slices-and-lifetimes/exercise.rs | 27 ++-- .../lifetime-annotations.md | 34 ++-- src/slices-and-lifetimes/lifetime-elision.md | 20 ++- src/slices-and-lifetimes/slices.md | 32 ++-- src/slices-and-lifetimes/solution.md | 1 + src/slices-and-lifetimes/str.md | 37 +++-- src/slices-and-lifetimes/struct-lifetimes.md | 18 ++- src/smart-pointers/Cargo.toml | 1 - src/smart-pointers/box.md | 41 +++-- src/smart-pointers/exercise.rs | 13 +- src/smart-pointers/rc.md | 25 +-- src/std-traits/casting.md | 18 ++- src/std-traits/closures.md | 38 ++--- src/std-traits/comparisons.md | 26 ++- src/std-traits/default.md | 24 +-- src/std-traits/exercise.md | 8 +- src/std-traits/exercise.rs | 17 +- src/std-traits/from-and-into.md | 9 +- src/std-traits/operators.md | 27 ++-- src/std-types/docs.md | 16 +- src/std-types/exercise.rs | 4 +- src/std-types/hashmap.md | 71 +++++---- src/std-types/option.md | 18 ++- src/std-types/result.md | 23 +-- src/std-types/std.md | 13 +- src/std-types/string.md | 43 +++-- src/std-types/vec.md | 22 +-- src/testing/exercise.md | 14 +- src/testing/exercise.rs | 14 +- src/testing/googletest.md | 31 ++-- src/testing/lints.md | 6 +- src/testing/mocking.md | 25 +-- src/testing/other.md | 16 +- src/testing/unit-tests.md | 10 +- src/testing/useful-crates.md | 8 +- src/thanks.md | 6 +- src/tuples-and-arrays/Cargo.toml | 1 - src/tuples-and-arrays/destructuring.md | 9 +- src/tuples-and-arrays/exercise.md | 1 + src/tuples-and-arrays/iteration.md | 13 +- src/tuples-and-arrays/match.md | 41 +++-- src/tuples-and-arrays/tuples-and-arrays.md | 51 +++--- src/types-and-values/arithmetic.md | 10 +- src/types-and-values/exercise.md | 8 +- src/types-and-values/inference.md | 11 +- src/types-and-values/strings.md | 19 +-- src/types-and-values/values.md | 18 ++- src/types-and-values/variables.md | 4 +- src/unsafe-rust/dereferencing.md | 19 +-- src/unsafe-rust/exercise.md | 22 +-- src/unsafe-rust/exercise.rs | 3 +- src/unsafe-rust/mutable-static.md | 20 ++- src/unsafe-rust/unions.md | 11 +- src/unsafe-rust/unsafe-functions.md | 13 +- src/unsafe-rust/unsafe-traits.md | 13 +- src/unsafe-rust/unsafe.md | 22 +-- src/user-defined-types/aliases.md | 6 +- src/user-defined-types/enums.md | 149 +++++++++--------- src/user-defined-types/exercise.rs | 5 +- src/user-defined-types/named-structs.md | 34 ++-- src/user-defined-types/static-and-const.md | 49 +++--- src/user-defined-types/tuple-structs.md | 23 ++- src/welcome-day-1.md | 31 ++-- src/welcome-day-2.md | 10 +- src/welcome-day-3.md | 5 +- src/welcome-day-4.md | 10 +- 302 files changed, 3093 insertions(+), 2648 deletions(-) diff --git a/dprint.json b/dprint.json index 8ebf7c3..b64d340 100644 --- a/dprint.json +++ b/dprint.json @@ -18,7 +18,6 @@ }, "excludes": [ "/book/", - "/src/", "/theme/*.hbs", "/third_party/", "target/" diff --git a/mdbook-course/src/course.rs b/mdbook-course/src/course.rs index d8d073d..8dd4889 100644 --- a/mdbook-course/src/course.rs +++ b/mdbook-course/src/course.rs @@ -22,16 +22,18 @@ //! 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. +//! 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. +//! 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::{split_frontmatter, Frontmatter}; use crate::markdown::{duration, relative_link}; @@ -53,19 +55,19 @@ pub struct Courses { /// 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. +/// 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, } -/// 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 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. +/// 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, @@ -95,8 +97,8 @@ pub struct Slide { } impl Courses { - /// Extract the course structure from the book. As a side-effect, the frontmatter is stripped - /// from each slide. + /// 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; @@ -111,7 +113,8 @@ impl Courses { let (frontmatter, content) = split_frontmatter(chapter)?; chapter.content = content; - // If 'course' is given, use that course (if not 'none') and reset the session. + // 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" { @@ -133,7 +136,8 @@ impl Courses { ); } - // If we have a course and session, then add this chapter to it as a segment. + // 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) { @@ -145,7 +149,8 @@ impl Courses { Ok((courses, book)) } - /// Get a reference to a course, adding a new one if none by this name exists. + /// Get a reference to a course, adding a new one if none by this name + /// exists. fn course_mut(&mut self, name: impl AsRef) -> &mut Course { let name = name.as_ref(); if let Some(found_idx) = @@ -164,8 +169,8 @@ impl Courses { 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. + /// Find the slide generated from the given Chapter within these courses, + /// returning the "path" to that slide. pub fn find_slide( &self, chapter: &Chapter, @@ -201,19 +206,15 @@ impl<'a> IntoIterator for &'a Courses { impl Course { fn new(name: impl Into) -> Self { - Course { - name: name.into(), - ..Default::default() - } + Course { name: name.into(), ..Default::default() } } - /// Get a reference to a session, adding a new one if none by this name exists. + /// Get a reference to a session, adding a new one if none by this name + /// exists. fn session_mut(&mut self, name: impl AsRef) -> &mut Session { let name = name.as_ref(); - if let Some(found_idx) = self - .sessions - .iter() - .position(|session| &session.name == name) + if let Some(found_idx) = + self.sessions.iter().position(|session| &session.name == name) { return &mut self.sessions[found_idx]; } @@ -222,15 +223,17 @@ impl Course { self.sessions.last_mut().unwrap() } - /// Return the total duration of this course, as the sum of all segment durations. + /// 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. + /// 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() } - /// Generate a Markdown schedule for this course, for placement at the given path. + /// Generate a Markdown schedule for this course, for placement at the given + /// path. pub fn schedule(&self, at_source_path: impl AsRef) -> String { let mut outline = String::from("Course schedule:\n"); for session in self { @@ -249,7 +252,10 @@ impl Course { &mut outline, " * [{}]({}) ({})", segment.name, - relative_link(&at_source_path, &segment.slides[0].source_paths[0]), + relative_link( + &at_source_path, + &segment.slides[0].source_paths[0] + ), duration(segment.minutes()) ) .unwrap(); @@ -270,10 +276,7 @@ impl<'a> IntoIterator for &'a Course { impl Session { fn new(name: impl Into) -> Self { - Session { - name: name.into(), - ..Default::default() - } + Session { name: name.into(), ..Default::default() } } /// Add a new segment to the session, representing sub-items as slides. @@ -297,7 +300,8 @@ impl Session { Ok(()) } - /// Generate a Markdown outline for this session, for placement at the given path. + /// Generate a Markdown outline for this session, for placement at the given + /// path. pub fn outline(&self, at_source_path: impl AsRef) -> String { let mut outline = String::from("In this session:\n"); for segment in self { @@ -324,7 +328,8 @@ impl Session { if instructional_time == 0 { return instructional_time; } - let breaks = (self.into_iter().filter(|s| s.minutes() > 0).count() - 1) as u64 + let breaks = (self.into_iter().filter(|s| s.minutes() > 0).count() - 1) + as u64 * BREAK_DURATION; instructional_time + breaks } @@ -341,14 +346,11 @@ impl<'a> IntoIterator for &'a Session { impl Segment { fn new(name: impl Into) -> Self { - Segment { - name: name.into(), - ..Default::default() - } + 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. + /// 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, @@ -364,8 +366,8 @@ impl Segment { Ok(()) } - /// Return the total duration of this segment (the sum of the durations of the enclosed - /// slides). + /// 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() } @@ -406,10 +408,7 @@ impl<'a> IntoIterator for &'a Segment { impl Slide { fn new(frontmatter: Frontmatter, chapter: &Chapter) -> Self { - let mut slide = Self { - name: chapter.name.clone(), - ..Default::default() - }; + let mut slide = Self { name: chapter.name.clone(), ..Default::default() }; slide.add_frontmatter(&frontmatter); slide.push_source_path(&chapter.source_path); slide diff --git a/mdbook-course/src/frontmatter.rs b/mdbook-course/src/frontmatter.rs index 2237cb0..7378df7 100644 --- a/mdbook-course/src/frontmatter.rs +++ b/mdbook-course/src/frontmatter.rs @@ -25,10 +25,12 @@ pub struct Frontmatter { } /// Split a chapter's contents into frontmatter and the remaining contents. -pub fn split_frontmatter(chapter: &Chapter) -> anyhow::Result<(Frontmatter, String)> { +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(|| { + let frontmatter: Frontmatter = serde_yaml::from_str(&frontmatter) + .with_context(|| { format!("error parsing frontmatter in {:?}", chapter.source_path) })?; diff --git a/mdbook-course/src/main.rs b/mdbook-course/src/main.rs index 18fcc6c..d1e4fcd 100644 --- a/mdbook-course/src/main.rs +++ b/mdbook-course/src/main.rs @@ -30,7 +30,9 @@ 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))); + .subcommand( + Command::new("supports").arg(Arg::new("renderer").required(true)), + ); let matches = app.get_matches(); if let Some(_) = matches.subcommand_matches("supports") { @@ -65,18 +67,11 @@ fn timediff(actual: u64, target: u64) -> String { } fn print_summary(fundamentals: &Course) { - eprintln!( - "Fundamentals: {}", - timediff(fundamentals.minutes(), 8 * 3 * 60) - ); + eprintln!("Fundamentals: {}", timediff(fundamentals.minutes(), 8 * 3 * 60)); eprintln!("Sessions:"); for session in fundamentals { - eprintln!( - " {}: {}", - session.name, - timediff(session.minutes(), 3 * 60) - ); + eprintln!(" {}: {}", session.name, timediff(session.minutes(), 3 * 60)); for segment in session { eprintln!(" {}: {}", segment.name, duration(segment.minutes())); } @@ -95,7 +90,9 @@ fn preprocess() -> anyhow::Result<()> { book.for_each_mut(|chapter| { if let BookItem::Chapter(chapter) = chapter { - if let Some((course, session, segment, slide)) = courses.find_slide(chapter) { + if let Some((course, session, segment, slide)) = + courses.find_slide(chapter) + { timing_info::insert_timing_info(slide, chapter); replacements::replace( &courses, diff --git a/mdbook-course/src/markdown.rs b/mdbook-course/src/markdown.rs index 0128fbe..c5726f9 100644 --- a/mdbook-course/src/markdown.rs +++ b/mdbook-course/src/markdown.rs @@ -14,8 +14,8 @@ 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. +/// 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, target_path: impl AsRef, @@ -72,7 +72,10 @@ mod test { #[test] fn relative_link_subdir() { assert_eq!( - relative_link(Path::new("hello-world.md"), Path::new("hello-world/foo.md")), + relative_link( + Path::new("hello-world.md"), + Path::new("hello-world/foo.md") + ), "./hello-world/foo.md".to_string() ); } @@ -80,7 +83,10 @@ mod test { #[test] fn relative_link_parent_dir() { assert_eq!( - relative_link(Path::new("references/foo.md"), Path::new("hello-world.md")), + relative_link( + Path::new("references/foo.md"), + Path::new("hello-world.md") + ), "../hello-world.md".to_string() ); } diff --git a/mdbook-course/src/timing_info.rs b/mdbook-course/src/timing_info.rs index 2bcfa4f..3be57e8 100644 --- a/mdbook-course/src/timing_info.rs +++ b/mdbook-course/src/timing_info.rs @@ -23,11 +23,7 @@ pub fn insert_timing_info(slide: &Slide, chapter: &mut Chapter) { { // Include the minutes in the speaker notes. let minutes = slide.minutes; - let plural = if slide.minutes == 1 { - "minute" - } else { - "minutes" - }; + let plural = if slide.minutes == 1 { "minute" } else { "minutes" }; let mut subslides = ""; if slide.source_paths.len() > 1 { subslides = "and its sub-slides "; diff --git a/mdbook-exerciser/src/lib.rs b/mdbook-exerciser/src/lib.rs index 937eab4..2d25c69 100644 --- a/mdbook-exerciser/src/lib.rs +++ b/mdbook-exerciser/src/lib.rs @@ -24,10 +24,10 @@ 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. + // 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 = None; let mut current_file: Option = None; for event in parser { diff --git a/mdbook-exerciser/src/main.rs b/mdbook-exerciser/src/main.rs index 398e472..57332ca 100644 --- a/mdbook-exerciser/src/main.rs +++ b/mdbook-exerciser/src/main.rs @@ -35,7 +35,9 @@ fn main() -> anyhow::Result<()> { let output_directory = Path::new( config .get("output-directory") - .context("Missing output.exerciser.output-directory configuration value")? + .context( + "Missing output.exerciser.output-directory configuration value", + )? .as_str() .context("Expected a string for output.exerciser.output-directory")?, ); @@ -55,8 +57,8 @@ fn process_all(book: &Book, output_directory: &Path) -> anyhow::Result<()> { 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. + // 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), diff --git a/po/pt-BR.po b/po/pt-BR.po index 3d56bc5..25face8 100644 --- a/po/pt-BR.po +++ b/po/pt-BR.po @@ -10081,7 +10081,7 @@ msgstr "\"Falha ao ler\"" #: src/error-handling/error-contexts.md:19 msgid "\"Found no username in {path}\"" -msgstr "\"Nome de usuário não encontrado em {caminho}\"" +msgstr "\"Nome de usuário não encontrado em {path}\"" #: src/error-handling/error-contexts.md:28 msgid "\"Error: {err:?}\"" diff --git a/rustfmt.toml b/rustfmt.toml index f3c72b9..131d9d6 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,2 +1,8 @@ -imports_granularity = "module" # Please use nightly for this setting. -max_width = 90 +# Please use a nightly rustfmt for these settings. +imports_granularity = "module" +wrap_comments = true + +# The code blocks get a scrollbar if they are wider than this. +max_width = 85 +# Allow all constructs to take up max_width columns. +use_small_heuristics = "Max" diff --git a/src/SUMMARY.md b/src/SUMMARY.md index fa3f953..2c936e7 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -1,6 +1,7 @@ - + [Welcome to Comprehensive Rust 🦀](index.md) + - [Running the Course](running-the-course.md) - [Course Structure](running-the-course/course-structure.md) - [Keyboard Shortcuts](running-the-course/keyboard-shortcuts.md) @@ -10,8 +11,7 @@ - [Code Samples](cargo/code-samples.md) - [Running Cargo Locally](cargo/running-locally.md) - ----- +--- # Day 1: Morning @@ -63,7 +63,7 @@ - [Exercise: Elevator Events](user-defined-types/exercise.md) - [Solution](user-defined-types/solution.md) ----- +--- # Day 2: Morning @@ -112,7 +112,7 @@ - [Exercise: ROT13](std-traits/exercise.md) - [Solution](std-traits/solution.md) ----- +--- # Day 3: Morning @@ -202,7 +202,7 @@ # Android ----- +--- - [Welcome](android.md) - [Setup](android/setup.md) @@ -237,11 +237,9 @@ - [With Java](android/interoperability/java.md) - [Exercises](exercises/android/morning.md) - - # Chromium ----- +--- - [Welcome](chromium.md) - [Setup](chromium/setup.md) @@ -261,8 +259,8 @@ - [Example Bindings](chromium/interoperability-with-cpp/example-bindings.md) - [Limitations of CXX](chromium/interoperability-with-cpp/limitations-of-cxx.md) - [CXX Error Handling](chromium/interoperability-with-cpp/error-handling.md) - - [Error Handling: QR Example](chromium/interoperability-with-cpp/error-handling-qr.md) - - [Error Handling: PNG Example](chromium/interoperability-with-cpp/error-handling-png.md) + - [Error Handling: QR Example](chromium/interoperability-with-cpp/error-handling-qr.md) + - [Error Handling: PNG Example](chromium/interoperability-with-cpp/error-handling-png.md) - [Using CXX in Chromium](chromium/interoperability-with-cpp/using-cxx-in-chromium.md) - [Exercise](exercises/chromium/interoperability-with-cpp.md) - [Adding Third Party Crates](chromium/adding-third-party-crates.md) @@ -281,10 +279,9 @@ - [Bringing It Together - Exercise](exercises/chromium/bringing-it-together.md) - [Exercise Solutions](exercises/chromium/solutions.md) - # Bare Metal: Morning ----- +--- - [Welcome](bare-metal.md) - [`no_std`](bare-metal/no_std.md) @@ -333,10 +330,9 @@ - [RTC Driver](exercises/bare-metal/rtc.md) - [Solutions](exercises/bare-metal/solutions-afternoon.md) - # Concurrency: Morning ----- +--- - [Welcome](concurrency.md) - [Threads](concurrency/threads.md) @@ -379,10 +375,9 @@ - [Broadcast Chat Application](exercises/concurrency/chat-app.md) - [Solutions](exercises/concurrency/solutions-afternoon.md) - # Final Words ----- +--- - [Thanks!](thanks.md) - [Glossary](glossary.md) diff --git a/src/android.md b/src/android.md index 238abb6..82bc767 100644 --- a/src/android.md +++ b/src/android.md @@ -2,11 +2,12 @@ course: Android session: Android --- + # Welcome to Rust in Android -Rust is supported for system software on Android. This means that -you can write new services, libraries, drivers or even firmware in Rust -(or improve existing code as needed). +Rust is supported for system software on Android. This means that you can write +new services, libraries, drivers or even firmware in Rust (or improve existing +code as needed). > We will attempt to call Rust from one of your own projects today. So try to > find a little corner of your code base where we can move some lines of code to @@ -15,15 +16,19 @@ you can write new services, libraries, drivers or even firmware in Rust
-The speaker may mention any of the following given the increased use of Rust -in Android: +The speaker may mention any of the following given the increased use of Rust in +Android: -- Service example: [DNS over HTTP](https://security.googleblog.com/2022/07/dns-over-http3-in-android.html) +- Service example: + [DNS over HTTP](https://security.googleblog.com/2022/07/dns-over-http3-in-android.html) -- Libraries: [Rutabaga Virtual Graphics Interface](https://crosvm.dev/book/appendix/rutabaga_gfx.html) +- Libraries: + [Rutabaga Virtual Graphics Interface](https://crosvm.dev/book/appendix/rutabaga_gfx.html) -- Kernel Drivers: [Binder](https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-0-08ba9197f637@google.com/) +- Kernel Drivers: + [Binder](https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-0-08ba9197f637@google.com/) -- Firmware: [pKVM firmware](https://security.googleblog.com/2023/10/bare-metal-rust-in-android.html) +- Firmware: + [pKVM firmware](https://security.googleblog.com/2023/10/bare-metal-rust-in-android.html)
diff --git a/src/android/aidl.md b/src/android/aidl.md index a055ce0..fe0c055 100644 --- a/src/android/aidl.md +++ b/src/android/aidl.md @@ -1,7 +1,9 @@ # AIDL -The [Android Interface Definition Language -(AIDL)](https://developer.android.com/guide/components/aidl) is supported in Rust: +The +[Android Interface Definition Language +(AIDL)](https://developer.android.com/guide/components/aidl) is supported in +Rust: -* Rust code can call existing AIDL servers, -* You can create new AIDL servers in Rust. +- Rust code can call existing AIDL servers, +- You can create new AIDL servers in Rust. diff --git a/src/android/aidl/birthday_service/src/client.rs b/src/android/aidl/birthday_service/src/client.rs index 0ac3e0d..5e6acb8 100644 --- a/src/android/aidl/birthday_service/src/client.rs +++ b/src/android/aidl/birthday_service/src/client.rs @@ -20,15 +20,14 @@ use com_example_birthdayservice::binder; const SERVICE_IDENTIFIER: &str = "birthdayservice"; /// Connect to the BirthdayService. -pub fn connect() -> Result, binder::StatusCode> { +pub fn connect() -> Result, binder::StatusCode> +{ binder::get_interface(SERVICE_IDENTIFIER) } /// Call the birthday service. fn main() -> Result<(), binder::Status> { - let name = std::env::args() - .nth(1) - .unwrap_or_else(|| String::from("Bob")); + 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::().ok()) diff --git a/src/android/aidl/birthday_service/src/lib.rs b/src/android/aidl/birthday_service/src/lib.rs index 88c7f5a..0b783ea 100644 --- a/src/android/aidl/birthday_service/src/lib.rs +++ b/src/android/aidl/birthday_service/src/lib.rs @@ -24,8 +24,6 @@ impl binder::Interface for BirthdayService {} impl IBirthdayService for BirthdayService { fn wishHappyBirthday(&self, name: &str, years: i32) -> binder::Result { - Ok(format!( - "Happy Birthday {name}, congratulations with the {years} years!" - )) + Ok(format!("Happy Birthday {name}, congratulations with the {years} years!")) } } diff --git a/src/android/aidl/client.md b/src/android/aidl/client.md index 01d4249..85af8ad 100644 --- a/src/android/aidl/client.md +++ b/src/android/aidl/client.md @@ -2,13 +2,13 @@ Finally, we can create a Rust client for our new service. -*birthday_service/src/client.rs*: +_birthday_service/src/client.rs_: ```rust,ignore {{#include birthday_service/src/client.rs:main}} ``` -*birthday_service/Android.bp*: +_birthday_service/Android.bp_: ```javascript {{#include birthday_service/Android.bp:birthday_client}} diff --git a/src/android/aidl/implementation.md b/src/android/aidl/implementation.md index 8999301..ed94853 100644 --- a/src/android/aidl/implementation.md +++ b/src/android/aidl/implementation.md @@ -2,13 +2,13 @@ We can now implement the AIDL service: -*birthday_service/src/lib.rs*: +_birthday_service/src/lib.rs_: ```rust,ignore {{#include birthday_service/src/lib.rs:IBirthdayService}} ``` -*birthday_service/Android.bp*: +_birthday_service/Android.bp_: ```javascript {{#include birthday_service/Android.bp:libbirthdayservice}} diff --git a/src/android/aidl/interface.md b/src/android/aidl/interface.md index fd75485..f138004 100644 --- a/src/android/aidl/interface.md +++ b/src/android/aidl/interface.md @@ -2,13 +2,13 @@ You declare the API of your service using an AIDL interface: -*birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl*: +_birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl_: ```java {{#include birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl:IBirthdayService}} ``` -*birthday_service/aidl/Android.bp*: +_birthday_service/aidl/Android.bp_: ```javascript {{#include birthday_service/aidl/Android.bp}} diff --git a/src/android/aidl/server.md b/src/android/aidl/server.md index de9217a..d3af180 100644 --- a/src/android/aidl/server.md +++ b/src/android/aidl/server.md @@ -2,13 +2,13 @@ Finally, we can create a server which exposes the service: -*birthday_service/src/server.rs*: +_birthday_service/src/server.rs_: ```rust,ignore {{#include birthday_service/src/server.rs:main}} ``` -*birthday_service/Android.bp*: +_birthday_service/Android.bp_: ```javascript {{#include birthday_service/Android.bp:birthday_server}} diff --git a/src/android/build-rules.md b/src/android/build-rules.md index b8f58ae..62b74f0 100644 --- a/src/android/build-rules.md +++ b/src/android/build-rules.md @@ -19,13 +19,20 @@ We will look at `rust_binary` and `rust_library` next. Additional items speaker may mention: -- Cargo is not optimized for multi-language repos, and also downloads packages from the internet. +- Cargo is not optimized for multi-language repos, and also downloads packages + from the internet. -- For compliance and performance, Android must have crates in-tree. It must also interop with C/C++/Java code. Soong fills that gap. +- For compliance and performance, Android must have crates in-tree. It must also + interop with C/C++/Java code. Soong fills that gap. -- Soong has many similarities to Bazel, which is the open-source variant of Blaze (used in google3). +- Soong has many similarities to Bazel, which is the open-source variant of + Blaze (used in google3). -- There is a plan to transition [Android](https://source.android.com/docs/setup/build/bazel/introduction), [ChromeOS](https://chromium.googlesource.com/chromiumos/bazel/), and [Fuchsia](https://source.android.com/docs/setup/build/bazel/introduction) to Bazel. +- There is a plan to transition + [Android](https://source.android.com/docs/setup/build/bazel/introduction), + [ChromeOS](https://chromium.googlesource.com/chromiumos/bazel/), and + [Fuchsia](https://source.android.com/docs/setup/build/bazel/introduction) to + Bazel. - Learning Bazel-like build rules is useful for all Rust OS developers. diff --git a/src/android/build-rules/library.md b/src/android/build-rules/library.md index 880004b..46c3b60 100644 --- a/src/android/build-rules/library.md +++ b/src/android/build-rules/library.md @@ -4,8 +4,8 @@ You use `rust_library` to create a new Rust library for Android. Here we declare a dependency on two libraries: -* `libgreeting`, which we define below, -* `libtextwrap`, which is a crate already vendored in +- `libgreeting`, which we define below, +- `libtextwrap`, which is a crate already vendored in [`external/rust/crates/`][crates]. [crates]: https://cs.android.com/android/platform/superproject/+/master:external/rust/crates/ diff --git a/src/android/interoperability.md b/src/android/interoperability.md index 4f665f2..9436af4 100644 --- a/src/android/interoperability.md +++ b/src/android/interoperability.md @@ -3,8 +3,8 @@ Rust has excellent support for interoperability with other languages. This means that you can: -* Call Rust functions from other languages. -* Call functions written in other languages from Rust. +- Call Rust functions from other languages. +- Call functions written in other languages from Rust. When you call functions in a foreign language we say that you're using a _foreign function interface_, also known as FFI. diff --git a/src/android/interoperability/cpp/android-build-cpp.md b/src/android/interoperability/cpp/android-build-cpp.md index e034bdf..4f3ded3 100644 --- a/src/android/interoperability/cpp/android-build-cpp.md +++ b/src/android/interoperability/cpp/android-build-cpp.md @@ -17,12 +17,12 @@ cc_library_static {
-* Point out that `libcxx_test_bridge_header` and `libcxx_test_bridge_code` are +- Point out that `libcxx_test_bridge_header` and `libcxx_test_bridge_code` are the dependencies for the CXX-generated C++ bindings. We'll show how these are setup on the next slide. -* Note that you also need to depend on the `cxx-bridge-header` library in order +- Note that you also need to depend on the `cxx-bridge-header` library in order to pull in common CXX definitions. -* Full docs for using CXX in Android can be found in [the Android docs]. You may +- Full docs for using CXX in Android can be found in [the Android docs]. You may want to share that link with the class so that students know where they can find these instructions again in the future. diff --git a/src/android/interoperability/cpp/android-cpp-genrules.md b/src/android/interoperability/cpp/android-cpp-genrules.md index 79f6693..e88a783 100644 --- a/src/android/interoperability/cpp/android-cpp-genrules.md +++ b/src/android/interoperability/cpp/android-cpp-genrules.md @@ -26,9 +26,9 @@ genrule {
-* The `cxxbridge` tool is a standalone tool that generates the C++ side of the +- The `cxxbridge` tool is a standalone tool that generates the C++ side of the bridge module. It is included in Android and available as a Soong tool. -* By convention, if your Rust source file is `lib.rs` your header file will be +- By convention, if your Rust source file is `lib.rs` your header file will be named `lib.rs.h` and your source file will be named `lib.rs.cc`. This naming convention isn't enforced, though. diff --git a/src/android/interoperability/cpp/bridge.md b/src/android/interoperability/cpp/bridge.md index 6cb2958..1a421a8 100644 --- a/src/android/interoperability/cpp/bridge.md +++ b/src/android/interoperability/cpp/bridge.md @@ -10,14 +10,14 @@ a Rust module annotated with the `#[cxx::bridge]` attribute macro.
-* The bridge is generally declared in an `ffi` module within your crate. -* From the declarations made in the bridge module, CXX will generate matching +- The bridge is generally declared in an `ffi` module within your crate. +- From the declarations made in the bridge module, CXX will generate matching Rust and C++ type/function definitions in order to expose those items to both languages. -* To view the generated Rust code, use [cargo-expand] to view the expanded proc +- To view the generated Rust code, use [cargo-expand] to view the expanded proc macro. For most of the examples you would use `cargo expand ::ffi` to expand just the `ffi` module (though this doesn't apply for Android projects). -* To view the generated C++ code, look in `target/cxxbridge`. +- To view the generated C++ code, look in `target/cxxbridge`. [cargo-expand]: https://github.com/dtolnay/cargo-expand diff --git a/src/android/interoperability/cpp/cpp-bridge.md b/src/android/interoperability/cpp/cpp-bridge.md index 50e902d..08d7eeb 100644 --- a/src/android/interoperability/cpp/cpp-bridge.md +++ b/src/android/interoperability/cpp/cpp-bridge.md @@ -43,10 +43,10 @@ impl BlobstoreClient {
-* The programmer does not need to promise that the signatures they have typed in +- The programmer does not need to promise that the signatures they have typed in are accurate. CXX performs static assertions that the signatures exactly correspond with what is declared in C++. -* `unsafe extern` blocks allow you to declare C++ functions that are safe to +- `unsafe extern` blocks allow you to declare C++ functions that are safe to call from Rust.
diff --git a/src/android/interoperability/cpp/cpp-exception.md b/src/android/interoperability/cpp/cpp-exception.md index 12c2dc6..bb96b43 100644 --- a/src/android/interoperability/cpp/cpp-exception.md +++ b/src/android/interoperability/cpp/cpp-exception.md @@ -6,9 +6,9 @@
-* C++ functions declared to return a `Result` will catch any thrown exception on +- C++ functions declared to return a `Result` will catch any thrown exception on the C++ side and return it as an `Err` value to the calling Rust function. -* If an exception is thrown from an extern "C++" function that is not declared +- If an exception is thrown from an extern "C++" function that is not declared by the CXX bridge to return `Result`, the program calls C++'s `std::terminate`. The behavior is equivalent to the same exception being thrown through a `noexcept` C++ function. diff --git a/src/android/interoperability/cpp/rust-bridge.md b/src/android/interoperability/cpp/rust-bridge.md index 7a55371..59df1d0 100644 --- a/src/android/interoperability/cpp/rust-bridge.md +++ b/src/android/interoperability/cpp/rust-bridge.md @@ -6,9 +6,9 @@
-* Items declared in the `extern "Rust"` reference items that are in scope in the +- Items declared in the `extern "Rust"` reference items that are in scope in the parent module. -* The CXX code generator uses your `extern "Rust"` section(s) to produce a C++ +- The CXX code generator uses your `extern "Rust"` section(s) to produce a C++ header file containing the corresponding C++ declarations. The generated header has the same path as the Rust source file containing the bridge, except with a .rs.h file extension. diff --git a/src/android/interoperability/cpp/rust-result.md b/src/android/interoperability/cpp/rust-result.md index 0631b95..5deecb0 100644 --- a/src/android/interoperability/cpp/rust-result.md +++ b/src/android/interoperability/cpp/rust-result.md @@ -6,12 +6,12 @@
-* Rust functions that return `Result` are translated to exceptions on the C++ +- Rust functions that return `Result` are translated to exceptions on the C++ side. -* The exception thrown will always be of type `rust::Error`, which primarily +- The exception thrown will always be of type `rust::Error`, which primarily exposes a way to get the error message string. The error message will come from the error type's `Display` impl. -* A panic unwinding from Rust to C++ will always cause the process to +- A panic unwinding from Rust to C++ will always cause the process to immediately terminate.
diff --git a/src/android/interoperability/cpp/shared-enums.md b/src/android/interoperability/cpp/shared-enums.md index dbf17d6..3db15da 100644 --- a/src/android/interoperability/cpp/shared-enums.md +++ b/src/android/interoperability/cpp/shared-enums.md @@ -18,7 +18,7 @@ Generated C++:
-* On the Rust side, the code generated for shared enums is actually a struct +- On the Rust side, the code generated for shared enums is actually a struct wrapping a numeric value. This is because it is not UB in C++ for an enum class to hold a value different from all of the listed variants, and our Rust representation needs to have the same behavior. diff --git a/src/android/interoperability/cpp/shared-types.md b/src/android/interoperability/cpp/shared-types.md index 3ef7dfe..a899479 100644 --- a/src/android/interoperability/cpp/shared-types.md +++ b/src/android/interoperability/cpp/shared-types.md @@ -6,8 +6,8 @@
-* Only C-like (unit) enums are supported. -* A limited number of traits are supported for `#[derive()]` on shared types. +- Only C-like (unit) enums are supported. +- A limited number of traits are supported for `#[derive()]` on shared types. Corresponding functionality is also generated for the C++ code, e.g. if you derive `Hash` also generates an implementation of `std::hash` for the corresponding C++ type. diff --git a/src/android/interoperability/cpp/type-mapping.md b/src/android/interoperability/cpp/type-mapping.md index 22867c8..ee99cbe 100644 --- a/src/android/interoperability/cpp/type-mapping.md +++ b/src/android/interoperability/cpp/type-mapping.md @@ -1,7 +1,7 @@ # Additional Types | Rust Type | C++ Type | -|-------------------|----------------------| +| ----------------- | -------------------- | | `String` | `rust::String` | | `&str` | `rust::Str` | | `CxxString` | `std::string` | @@ -13,14 +13,14 @@
-* These types can be used in the fields of shared structs and the arguments and +- These types can be used in the fields of shared structs and the arguments and returns of extern functions. -* Note that Rust's `String` does not map directly to `std::string`. There are a +- Note that Rust's `String` does not map directly to `std::string`. There are a few reasons for this: - * `std::string` does not uphold the UTF-8 invariant that `String` requires. - * The two types have different layouts in memory and so can't be passed + - `std::string` does not uphold the UTF-8 invariant that `String` requires. + - The two types have different layouts in memory and so can't be passed directly between languages. - * `std::string` requires move constructors that don't match Rust's move + - `std::string` requires move constructors that don't match Rust's move semantics, so a `std::string` can't be passed by value to Rust.
diff --git a/src/android/interoperability/java.md b/src/android/interoperability/java.md index dde7d7a..0841a65 100644 --- a/src/android/interoperability/java.md +++ b/src/android/interoperability/java.md @@ -1,8 +1,9 @@ # Interoperability with Java -Java can load shared objects via [Java Native Interface -(JNI)](https://en.wikipedia.org/wiki/Java_Native_Interface). The [`jni` -crate](https://docs.rs/jni/) allows you to create a compatible library. +Java can load shared objects via +[Java Native Interface (JNI)](https://en.wikipedia.org/wiki/Java_Native_Interface). +The [`jni` crate](https://docs.rs/jni/) allows you to create a compatible +library. First, we create a Rust function to export to Java: diff --git a/src/android/interoperability/with-c.md b/src/android/interoperability/with-c.md index 152fa69..1f1083e 100644 --- a/src/android/interoperability/with-c.md +++ b/src/android/interoperability/with-c.md @@ -17,8 +17,8 @@ fn main() { } ``` -We already saw this in the [Safe FFI Wrapper -exercise](../../exercises/day-3/safe-ffi-wrapper.md). +We already saw this in the +[Safe FFI Wrapper exercise](../../exercises/day-3/safe-ffi-wrapper.md). > This assumes full knowledge of the target platform. Not recommended for > production. diff --git a/src/android/interoperability/with-c/bindgen/c-library.md b/src/android/interoperability/with-c/bindgen/c-library.md index 01ddb6d..53f16a9 100644 --- a/src/android/interoperability/with-c/bindgen/c-library.md +++ b/src/android/interoperability/with-c/bindgen/c-library.md @@ -17,4 +17,3 @@ _interoperability/c/libbirthday/libbirthday.c_: ```c {{#include c/libbirthday/libbirthday.c}} ``` - diff --git a/src/android/interoperability/with-c/bindgen/main.rs b/src/android/interoperability/with-c/bindgen/main.rs index 03d68b6..96e5799 100644 --- a/src/android/interoperability/with-c/bindgen/main.rs +++ b/src/android/interoperability/with-c/bindgen/main.rs @@ -19,10 +19,7 @@ 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, - }; + let card = card { name: name.as_ptr(), years: 42 }; // SAFETY: `print_card` is safe to call with a valid `card` pointer. unsafe { print_card(&card as *const card); diff --git a/src/android/interoperability/with-c/hand-written.md b/src/android/interoperability/with-c/hand-written.md index abf68e6..56f0f24 100644 --- a/src/android/interoperability/with-c/hand-written.md +++ b/src/android/interoperability/with-c/hand-written.md @@ -14,8 +14,8 @@ fn main() { } ``` -We already saw this in the [Safe FFI Wrapper -exercise](../../exercises/day-3/safe-ffi-wrapper.md). +We already saw this in the +[Safe FFI Wrapper exercise](../../exercises/day-3/safe-ffi-wrapper.md). > This assumes full knowledge of the target platform. Not recommended for > production. diff --git a/src/android/interoperability/with-c/rust.md b/src/android/interoperability/with-c/rust.md index 31dd12f..5a045df 100644 --- a/src/android/interoperability/with-c/rust.md +++ b/src/android/interoperability/with-c/rust.md @@ -34,7 +34,6 @@ _interoperability/rust/analyze/Android.bp_ {{#include rust/analyze/Android.bp}} ``` - Build, push, and run the binary on your device: ```shell @@ -43,7 +42,8 @@ Build, push, and run the binary on your device:
-`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol will just be the name of -the function. You can also use `#[export_name = "some_name"]` to specify whatever name you want. +`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol will +just be the name of the function. You can also use +`#[export_name = "some_name"]` to specify whatever name you want.
diff --git a/src/android/setup.md b/src/android/setup.md index cebba74..32d9d50 100644 --- a/src/android/setup.md +++ b/src/android/setup.md @@ -1,7 +1,7 @@ # Setup -We will be using a Cuttlefish Android Virtual Device to test our code. Make sure you -have access to one or create a new one with: +We will be using a Cuttlefish Android Virtual Device to test our code. Make sure +you have access to one or create a new one with: ```shell source build/envsetup.sh @@ -9,15 +9,18 @@ lunch aosp_cf_x86_64_phone-trunk_staging-userdebug acloud create ``` -Please see the [Android Developer -Codelab](https://source.android.com/docs/setup/start) for details. +Please see the +[Android Developer Codelab](https://source.android.com/docs/setup/start) for +details.
Key points: -- Cuttlefish is a reference Android device designed to work on generic Linux desktops. MacOS support is also planned. +- Cuttlefish is a reference Android device designed to work on generic Linux + desktops. MacOS support is also planned. -- The Cuttlefish system image maintains high fidelity to real devices, and is the ideal emulator to run many Rust use cases. +- The Cuttlefish system image maintains high fidelity to real devices, and is + the ideal emulator to run many Rust use cases.
diff --git a/src/async.md b/src/async.md index b838768..a031537 100644 --- a/src/async.md +++ b/src/async.md @@ -1,6 +1,7 @@ --- session: Afternoon --- + # Async Rust "Async" is a concurrency model where multiple tasks are executed concurrently by @@ -11,18 +12,18 @@ very low and operating systems provide primitives for efficiently identifying I/O that is able to proceed. Rust's asynchronous operation is based on "futures", which represent work that -may be completed in the future. Futures are "polled" until they signal that -they are complete. +may be completed in the future. Futures are "polled" until they signal that they +are complete. Futures are polled by an async runtime, and several different runtimes are available. ## Comparisons - * Python has a similar model in its `asyncio`. However, its `Future` type is - callback-based, and not polled. Async Python programs require a "loop", - similar to a runtime in Rust. +- Python has a similar model in its `asyncio`. However, its `Future` type is + callback-based, and not polled. Async Python programs require a "loop", + similar to a runtime in Rust. - * JavaScript's `Promise` is similar, but again callback-based. The language - runtime implements the event loop, so many of the details of Promise - resolution are hidden. +- JavaScript's `Promise` is similar, but again callback-based. The language + runtime implements the event loop, so many of the details of Promise + resolution are hidden. diff --git a/src/async/async-await.md b/src/async/async-await.md index 7906033..b80d19b 100644 --- a/src/async/async-await.md +++ b/src/async/async-await.md @@ -24,25 +24,25 @@ fn main() { Key points: -* Note that this is a simplified example to show the syntax. There is no long +- Note that this is a simplified example to show the syntax. There is no long running operation or any real concurrency in it! -* What is the return type of an async call? - * Use `let future: () = async_main(10);` in `main` to see the type. +- What is the return type of an async call? + - Use `let future: () = async_main(10);` in `main` to see the type. -* The "async" keyword is syntactic sugar. The compiler replaces the return type - with a future. +- The "async" keyword is syntactic sugar. The compiler replaces the return type + with a future. -* You cannot make `main` async, without additional instructions to the compiler +- You cannot make `main` async, without additional instructions to the compiler on how to use the returned future. -* You need an executor to run async code. `block_on` blocks the current thread - until the provided future has run to completion. +- You need an executor to run async code. `block_on` blocks the current thread + until the provided future has run to completion. -* `.await` asynchronously waits for the completion of another operation. Unlike +- `.await` asynchronously waits for the completion of another operation. Unlike `block_on`, `.await` doesn't block the current thread. -* `.await` can only be used inside an `async` function (or block; these are - introduced later). +- `.await` can only be used inside an `async` function (or block; these are + introduced later).
diff --git a/src/async/channels.md b/src/async/channels.md index 5a58361..301c0ab 100644 --- a/src/async/channels.md +++ b/src/async/channels.md @@ -32,18 +32,18 @@ async fn main() {
-* Change the channel size to `3` and see how it affects the execution. +- Change the channel size to `3` and see how it affects the execution. -* Overall, the interface is similar to the `sync` channels as seen in the +- Overall, the interface is similar to the `sync` channels as seen in the [morning class](concurrency/channels.md). -* Try removing the `std::mem::drop` call. What happens? Why? +- Try removing the `std::mem::drop` call. What happens? Why? -* The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that +- The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that implement both `sync` and `async` `send` and `recv`. This can be convenient for complex applications with both IO and heavy CPU processing tasks. -* What makes working with `async` channels preferable is the ability to combine +- What makes working with `async` channels preferable is the ability to combine them with other `future`s to combine them and create complex control flow.
diff --git a/src/async/control-flow/join.md b/src/async/control-flow/join.md index 4a93e5c..0d1015e 100644 --- a/src/async/control-flow/join.md +++ b/src/async/control-flow/join.md @@ -1,8 +1,8 @@ # Join -A join operation waits until all of a set of futures are ready, and -returns a collection of their results. This is similar to `Promise.all` in -JavaScript or `asyncio.gather` in Python. +A join operation waits until all of a set of futures are ready, and returns a +collection of their results. This is similar to `Promise.all` in JavaScript or +`asyncio.gather` in Python. ```rust,editable,compile_fail use anyhow::Result; @@ -35,16 +35,17 @@ async fn main() { Copy this example into your prepared `src/main.rs` and run it from there. -* For multiple futures of disjoint types, you can use `std::future::join!` but +- For multiple futures of disjoint types, you can use `std::future::join!` but you must know how many futures you will have at compile time. This is currently in the `futures` crate, soon to be stabilised in `std::future`. -* The risk of `join` is that one of the futures may never resolve, this would - cause your program to stall. +- The risk of `join` is that one of the futures may never resolve, this would + cause your program to stall. -* You can also combine `join_all` with `join!` for instance to join all requests +- You can also combine `join_all` with `join!` for instance to join all requests to an http service as well as a database query. Try adding a `tokio::time::sleep` to the future, using `futures::join!`. This is not a - timeout (that requires `select!`, explained in the next chapter), but demonstrates `join!`. + timeout (that requires `select!`, explained in the next chapter), but + demonstrates `join!`.
diff --git a/src/async/control-flow/select.md b/src/async/control-flow/select.md index 014d24a..61ff9cf 100644 --- a/src/async/control-flow/select.md +++ b/src/async/control-flow/select.md @@ -2,8 +2,8 @@ A select operation waits until any of a set of futures is ready, and responds to that future's result. In JavaScript, this is similar to `Promise.race`. In -Python, it compares to `asyncio.wait(task_set, -return_when=asyncio.FIRST_COMPLETED)`. +Python, it compares to +`asyncio.wait(task_set, return_when=asyncio.FIRST_COMPLETED)`. Similar to a match statement, the body of `select!` has a number of arms, each of the form `pattern = future => statement`. When the `future` is ready, the @@ -36,17 +36,11 @@ async fn main() { let (dog_sender, dog_receiver) = mpsc::channel(32); tokio::spawn(async move { sleep(Duration::from_millis(500)).await; - cat_sender - .send(String::from("Felix")) - .await - .expect("Failed to send cat."); + cat_sender.send(String::from("Felix")).await.expect("Failed to send cat."); }); tokio::spawn(async move { sleep(Duration::from_millis(50)).await; - dog_sender - .send(String::from("Rex")) - .await - .expect("Failed to send dog."); + dog_sender.send(String::from("Rex")).await.expect("Failed to send dog."); }); let winner = first_animal_to_finish_race(cat_receiver, dog_receiver) @@ -59,21 +53,21 @@ async fn main() {
-* In this example, we have a race between a cat and a dog. +- In this example, we have a race between a cat and a dog. `first_animal_to_finish_race` listens to both channels and will pick whichever - arrives first. Since the dog takes 50ms, it wins against the cat that - take 500ms. + arrives first. Since the dog takes 50ms, it wins against the cat that take + 500ms. -* You can use `oneshot` channels in this example as the channels are supposed to +- You can use `oneshot` channels in this example as the channels are supposed to receive only one `send`. -* Try adding a deadline to the race, demonstrating selecting different sorts of +- Try adding a deadline to the race, demonstrating selecting different sorts of futures. -* Note that `select!` drops unmatched branches, which cancels their futures. - It is easiest to use when every execution of `select!` creates new futures. +- Note that `select!` drops unmatched branches, which cancels their futures. It + is easiest to use when every execution of `select!` creates new futures. - * An alternative is to pass `&mut future` instead of the future itself, but - this can lead to issues, further discussed in the pinning slide. + - An alternative is to pass `&mut future` instead of the future itself, but + this can lead to issues, further discussed in the pinning slide.
diff --git a/src/async/futures.md b/src/async/futures.md index d9d4347..60b38b7 100644 --- a/src/async/futures.md +++ b/src/async/futures.md @@ -1,8 +1,8 @@ # Futures -[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) -is a trait, implemented by objects that represent an operation that may not be -complete yet. A future can be polled, and `poll` returns a +[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) is a trait, +implemented by objects that represent an operation that may not be complete yet. +A future can be polled, and `poll` returns a [`Poll`](https://doc.rust-lang.org/std/task/enum.Poll.html). ```rust @@ -29,16 +29,16 @@ pause until that Future is ready, and then evaluates to its output.
-* The `Future` and `Poll` types are implemented exactly as shown; click the +- The `Future` and `Poll` types are implemented exactly as shown; click the links to show the implementations in the docs. -* We will not get to `Pin` and `Context`, as we will focus on writing async +- We will not get to `Pin` and `Context`, as we will focus on writing async code, rather than building new async primitives. Briefly: - * `Context` allows a Future to schedule itself to be polled again when an + - `Context` allows a Future to schedule itself to be polled again when an event occurs. - * `Pin` ensures that the Future isn't moved in memory, so that pointers into + - `Pin` ensures that the Future isn't moved in memory, so that pointers into that future remain valid. This is required to allow references to remain valid after an `.await`. diff --git a/src/async/pitfalls.md b/src/async/pitfalls.md index b025ef5..924c9c1 100644 --- a/src/async/pitfalls.md +++ b/src/async/pitfalls.md @@ -1,6 +1,8 @@ # Pitfalls of async/await -Async / await provides convenient and efficient abstraction for concurrent asynchronous programming. However, the async/await model in Rust also comes with its share of pitfalls and footguns. We illustrate some of them in this chapter: +Async / await provides convenient and efficient abstraction for concurrent +asynchronous programming. However, the async/await model in Rust also comes with +its share of pitfalls and footguns. We illustrate some of them in this chapter: - [Blocking the Executor](pitfalls/blocking-executor.md) - [Pin](pitfalls/pin.md) diff --git a/src/async/pitfalls/async-traits.md b/src/async/pitfalls/async-traits.md index a4ea8a0..1b5d670 100644 --- a/src/async/pitfalls/async-traits.md +++ b/src/async/pitfalls/async-traits.md @@ -1,8 +1,10 @@ # Async Traits -Async methods in traits are not yet supported in the stable channel ([An experimental feature exists in nightly and should be stabilized in the mid term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-nightly.html)) +Async methods in traits are not yet supported in the stable channel +([An experimental feature exists in nightly and should be stabilized in the mid term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-nightly.html)) -The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) provides a workaround through a macro: +The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) +provides a workaround through a macro: ```rust,editable,compile_fail use async_trait::async_trait; @@ -25,7 +27,10 @@ impl Sleeper for FixedSleeper { } } -async fn run_all_sleepers_multiple_times(sleepers: Vec>, n_times: usize) { +async fn run_all_sleepers_multiple_times( + sleepers: Vec>, + n_times: usize, +) { for _ in 0..n_times { println!("running all sleepers.."); for sleeper in &sleepers { @@ -46,18 +51,18 @@ async fn main() { } ``` -
+
-* `async_trait` is easy to use, but note that it's using heap allocations to +- `async_trait` is easy to use, but note that it's using heap allocations to achieve this. This heap allocation has performance overhead. -* The challenges in language support for `async trait` are deep Rust and +- The challenges in language support for `async trait` are deep Rust and probably not worth describing in-depth. Niko Matsakis did a good job of - explaining them in [this - post](https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/) + explaining them in + [this post](https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/) if you are interested in digging deeper. -* Try creating a new sleeper struct that will sleep for a random amount of time +- Try creating a new sleeper struct that will sleep for a random amount of time and adding it to the Vec.
diff --git a/src/async/pitfalls/blocking-executor.md b/src/async/pitfalls/blocking-executor.md index cfbfb46..2ec6d1f 100644 --- a/src/async/pitfalls/blocking-executor.md +++ b/src/async/pitfalls/blocking-executor.md @@ -1,8 +1,8 @@ # Blocking the executor -Most async runtimes only allow IO tasks to run concurrently. -This means that CPU blocking tasks will block the executor and prevent other tasks from being executed. -An easy workaround is to use async equivalent methods where possible. +Most async runtimes only allow IO tasks to run concurrently. This means that CPU +blocking tasks will block the executor and prevent other tasks from being +executed. An easy workaround is to use async equivalent methods where possible. ```rust,editable,compile_fail use futures::future::join_all; @@ -26,25 +26,25 @@ async fn main() {
-* Run the code and see that the sleeps happen consecutively rather than +- Run the code and see that the sleeps happen consecutively rather than concurrently. -* The `"current_thread"` flavor puts all tasks on a single thread. This makes the - effect more obvious, but the bug is still present in the multi-threaded +- The `"current_thread"` flavor puts all tasks on a single thread. This makes + the effect more obvious, but the bug is still present in the multi-threaded flavor. -* Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result. +- Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result. -* Another fix would be to `tokio::task::spawn_blocking` which spawns an actual +- Another fix would be to `tokio::task::spawn_blocking` which spawns an actual thread and transforms its handle into a future without blocking the executor. -* You should not think of tasks as OS threads. They do not map 1 to 1 and most +- You should not think of tasks as OS threads. They do not map 1 to 1 and most executors will allow many tasks to run on a single OS thread. This is particularly problematic when interacting with other libraries via FFI, where that library might depend on thread-local storage or map to specific OS threads (e.g., CUDA). Prefer `tokio::task::spawn_blocking` in such situations. -* Use sync mutexes with care. Holding a mutex over an `.await` may cause another +- Use sync mutexes with care. Holding a mutex over an `.await` may cause another task to block, and that task may be running on the same thread.
diff --git a/src/async/pitfalls/cancellation.md b/src/async/pitfalls/cancellation.md index cf4aba1..6b18bf0 100644 --- a/src/async/pitfalls/cancellation.md +++ b/src/async/pitfalls/cancellation.md @@ -1,9 +1,9 @@ # Cancellation -Dropping a future implies it can never be polled again. This is called *cancellation* -and it can occur at any `await` point. Care is needed to ensure the system works -correctly even when futures are cancelled. For example, it shouldn't deadlock or -lose data. +Dropping a future implies it can never be polled again. This is called +_cancellation_ and it can occur at any `await` point. Care is needed to ensure +the system works correctly even when futures are cancelled. For example, it +shouldn't deadlock or lose data. ```rust,editable,compile_fail use std::io::{self, ErrorKind}; @@ -29,7 +29,7 @@ impl LinesReader { } } if bytes.is_empty() { - return Ok(None) + return Ok(None); } let s = String::from_utf8(bytes) .map_err(|_| io::Error::new(ErrorKind::InvalidData, "not UTF-8"))?; @@ -69,46 +69,49 @@ async fn main() -> std::io::Result<()> {
-* The compiler doesn't help with cancellation-safety. You need to read API +- The compiler doesn't help with cancellation-safety. You need to read API documentation and consider what state your `async fn` holds. -* Unlike `panic` and `?`, cancellation is part of normal control flow - (vs error-handling). +- Unlike `panic` and `?`, cancellation is part of normal control flow (vs + error-handling). -* The example loses parts of the string. +- The example loses parts of the string. - * Whenever the `tick()` branch finishes first, `next()` and its `buf` are dropped. + - Whenever the `tick()` branch finishes first, `next()` and its `buf` are + dropped. - * `LinesReader` can be made cancellation-safe by making `buf` part of the struct: - ```rust,compile_fail - struct LinesReader { - stream: DuplexStream, - bytes: Vec, - buf: [u8; 1], - } + - `LinesReader` can be made cancellation-safe by making `buf` part of the + struct: + ```rust,compile_fail + struct LinesReader { + stream: DuplexStream, + bytes: Vec, + buf: [u8; 1], + } - impl LinesReader { - fn new(stream: DuplexStream) -> Self { - Self { stream, bytes: Vec::new(), buf: [0] } - } - async fn next(&mut self) -> io::Result> { - // prefix buf and bytes with self. - // ... - let raw = std::mem::take(&mut self.bytes); - let s = String::from_utf8(raw) - // ... - } + impl LinesReader { + fn new(stream: DuplexStream) -> Self { + Self { stream, bytes: Vec::new(), buf: [0] } + } + async fn next(&mut self) -> io::Result> { + // prefix buf and bytes with self. + // ... + let raw = std::mem::take(&mut self.bytes); + let s = String::from_utf8(raw) + // ... } - ``` + } + ``` -* [`Interval::tick`](https://docs.rs/tokio/latest/tokio/time/struct.Interval.html#method.tick) - is cancellation-safe because it keeps track of whether a tick has been 'delivered'. +- [`Interval::tick`](https://docs.rs/tokio/latest/tokio/time/struct.Interval.html#method.tick) + is cancellation-safe because it keeps track of whether a tick has been + 'delivered'. -* [`AsyncReadExt::read`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.read) +- [`AsyncReadExt::read`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncReadExt.html#method.read) is cancellation-safe because it either returns or doesn't read data. -* [`AsyncBufReadExt::read_line`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncBufReadExt.html#method.read_line) - is similar to the example and *isn't* cancellation-safe. See its documentation +- [`AsyncBufReadExt::read_line`](https://docs.rs/tokio/latest/tokio/io/trait.AsyncBufReadExt.html#method.read_line) + is similar to the example and _isn't_ cancellation-safe. See its documentation for details and alternatives.
diff --git a/src/async/pitfalls/pin.md b/src/async/pitfalls/pin.md index a6f85b7..24e91d5 100644 --- a/src/async/pitfalls/pin.md +++ b/src/async/pitfalls/pin.md @@ -1,9 +1,9 @@ # `Pin` When you await a future, all local variables (that would ordinarily be stored on -a stack frame) are instead stored in the Future for the current async block. If your -future has pointers to data on the stack, those pointers might get invalidated. -This is unsafe. +a stack frame) are instead stored in the Future for the current async block. If +your future has pointers to data on the stack, those pointers might get +invalidated. This is unsafe. Therefore, you must guarantee that the addresses your future points to don't change. That is why we need to "pin" futures. Using the same future repeatedly @@ -43,10 +43,7 @@ async fn worker(mut work_queue: mpsc::Receiver) { async fn do_work(work_queue: &mpsc::Sender, input: u32) -> u32 { let (tx, rx) = oneshot::channel(); work_queue - .send(Work { - input, - respond_on: tx, - }) + .send(Work { input, respond_on: tx }) .await .expect("failed to send on work queue"); rx.await.expect("failed waiting for response") @@ -65,48 +62,49 @@ async fn main() {
-* You may recognize this as an example of the actor pattern. Actors - typically call `select!` in a loop. +- You may recognize this as an example of the actor pattern. Actors typically + call `select!` in a loop. -* This serves as a summation of a few of the previous lessons, so take your time +- This serves as a summation of a few of the previous lessons, so take your time with it. - * Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` - to the `select!`. This will never execute. Why? + - Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` to + the `select!`. This will never execute. Why? - * Instead, add a `timeout_fut` containing that future outside of the `loop`: + - Instead, add a `timeout_fut` containing that future outside of the `loop`: - ```rust,compile_fail - let mut timeout_fut = sleep(Duration::from_millis(100)); - loop { - select! { - .., - _ = timeout_fut => { println!(..); }, - } + ```rust,compile_fail + let mut timeout_fut = sleep(Duration::from_millis(100)); + loop { + select! { + .., + _ = timeout_fut => { println!(..); }, } - ``` - * This still doesn't work. Follow the compiler errors, adding `&mut` to the - `timeout_fut` in the `select!` to work around the move, then using - `Box::pin`: - - ```rust,compile_fail - let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100))); - loop { - select! { - .., - _ = &mut timeout_fut => { println!(..); }, - } + } + ``` + - This still doesn't work. Follow the compiler errors, adding `&mut` to the + `timeout_fut` in the `select!` to work around the move, then using + `Box::pin`: + + ```rust,compile_fail + let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100))); + loop { + select! { + .., + _ = &mut timeout_fut => { println!(..); }, } - ``` + } + ``` - * This compiles, but once the timeout expires it is `Poll::Ready` on every - iteration (a fused future would help with this). Update to reset - `timeout_fut` every time it expires. + - This compiles, but once the timeout expires it is `Poll::Ready` on every + iteration (a fused future would help with this). Update to reset + `timeout_fut` every time it expires. -* Box allocates on the heap. In some cases, `std::pin::pin!` (only recently +- Box allocates on the heap. In some cases, `std::pin::pin!` (only recently stabilized, with older code often using `tokio::pin!`) is also an option, but that is difficult to use for a future that is reassigned. -* Another alternative is to not use `pin` at all but spawn another task that will send to a `oneshot` channel every 100ms. +- Another alternative is to not use `pin` at all but spawn another task that + will send to a `oneshot` channel every 100ms.
diff --git a/src/async/runtimes.md b/src/async/runtimes.md index 9d2888a..6b03541 100644 --- a/src/async/runtimes.md +++ b/src/async/runtimes.md @@ -1,15 +1,15 @@ # Runtimes -A *runtime* provides support for performing operations asynchronously (a -*reactor*) and is responsible for executing futures (an *executor*). Rust does not have a -"built-in" runtime, but several options are available: +A _runtime_ provides support for performing operations asynchronously (a +_reactor_) and is responsible for executing futures (an _executor_). Rust does +not have a "built-in" runtime, but several options are available: - * [Tokio](https://tokio.rs/): performant, with a well-developed ecosystem of - functionality like [Hyper](https://hyper.rs/) for HTTP or - [Tonic](https://github.com/hyperium/tonic) for gRPC. - * [async-std](https://async.rs/): aims to be a "std for async", and includes a - basic runtime in `async::task`. - * [smol](https://docs.rs/smol/latest/smol/): simple and lightweight +- [Tokio](https://tokio.rs/): performant, with a well-developed ecosystem of + functionality like [Hyper](https://hyper.rs/) for HTTP or + [Tonic](https://github.com/hyperium/tonic) for gRPC. +- [async-std](https://async.rs/): aims to be a "std for async", and includes a + basic runtime in `async::task`. +- [smol](https://docs.rs/smol/latest/smol/): simple and lightweight Several larger applications have their own runtimes. For example, [Fuchsia](https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/src/lib/fuchsia-async/src/lib.rs) @@ -17,11 +17,11 @@ already has one.
-* Note that of the listed runtimes, only Tokio is supported in the Rust +- Note that of the listed runtimes, only Tokio is supported in the Rust playground. The playground also does not permit any I/O, so most interesting async things can't run in the playground. -* Futures are "inert" in that they do not do anything (not even start an I/O +- Futures are "inert" in that they do not do anything (not even start an I/O operation) unless there is an executor polling them. This differs from JS Promises, for example, which will run to completion even if they are never used. diff --git a/src/async/runtimes/tokio.md b/src/async/runtimes/tokio.md index c9dfbd4..73a7bc1 100644 --- a/src/async/runtimes/tokio.md +++ b/src/async/runtimes/tokio.md @@ -1,11 +1,10 @@ # Tokio +Tokio provides: -Tokio provides: - -* A multi-threaded runtime for executing asynchronous code. -* An asynchronous version of the standard library. -* A large ecosystem of libraries. +- A multi-threaded runtime for executing asynchronous code. +- An asynchronous version of the standard library. +- A large ecosystem of libraries. ```rust,editable,compile_fail use tokio::time; @@ -30,20 +29,20 @@ async fn main() {
-* With the `tokio::main` macro we can now make `main` async. +- With the `tokio::main` macro we can now make `main` async. -* The `spawn` function creates a new, concurrent "task". +- The `spawn` function creates a new, concurrent "task". -* Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`. +- Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`. **Further exploration:** -* Why does `count_to` not (usually) get to 10? This is an example of async +- Why does `count_to` not (usually) get to 10? This is an example of async cancellation. `tokio::spawn` returns a handle which can be awaited to wait until it finishes. -* Try `count_to(10).await` instead of spawning. +- Try `count_to(10).await` instead of spawning. -* Try awaiting the task returned from `tokio::spawn`. +- Try awaiting the task returned from `tokio::spawn`.
diff --git a/src/async/tasks.md b/src/async/tasks.md index 7dd39c6..78b99de 100644 --- a/src/async/tasks.md +++ b/src/async/tasks.md @@ -14,7 +14,7 @@ use tokio::net::TcpListener; #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:6142").await?; - println!("listening on port 6142"); + println!("listening on port 6142"); loop { let (mut socket, addr) = listener.accept().await?; @@ -51,15 +51,18 @@ async fn main() -> io::Result<()> { Copy this example into your prepared `src/main.rs` and run it from there. -Try connecting to it with a TCP connection tool like [nc](https://www.unix.com/man-page/linux/1/nc/) or [telnet](https://www.unix.com/man-page/linux/1/telnet/). +Try connecting to it with a TCP connection tool like +[nc](https://www.unix.com/man-page/linux/1/nc/) or +[telnet](https://www.unix.com/man-page/linux/1/telnet/). -* Ask students to visualize what the state of the example server would be with a +- Ask students to visualize what the state of the example server would be with a few connected clients. What tasks exist? What are their Futures? -* This is the first time we've seen an `async` block. This is similar to a +- This is the first time we've seen an `async` block. This is similar to a closure, but does not take any arguments. Its return value is a Future, - similar to an `async fn`. + similar to an `async fn`. -* Refactor the async block into a function, and improve the error handling using `?`. +- Refactor the async block into a function, and improve the error handling using + `?`.
diff --git a/src/bare-metal.md b/src/bare-metal.md index e6479ed..f9101cd 100644 --- a/src/bare-metal.md +++ b/src/bare-metal.md @@ -2,27 +2,32 @@ course: Bare Metal session: Morning --- + # Welcome to Bare Metal Rust -This is a standalone one-day course about bare-metal Rust, aimed at people who are familiar with the -basics of Rust (perhaps from completing the Comprehensive Rust course), and ideally also have some -experience with bare-metal programming in some other language such as C. +This is a standalone one-day course about bare-metal Rust, aimed at people who +are familiar with the basics of Rust (perhaps from completing the Comprehensive +Rust course), and ideally also have some experience with bare-metal programming +in some other language such as C. -Today we will talk about 'bare-metal' Rust: running Rust code without an OS underneath us. This will -be divided into several parts: +Today we will talk about 'bare-metal' Rust: running Rust code without an OS +underneath us. This will be divided into several parts: - What is `no_std` Rust? - Writing firmware for microcontrollers. - Writing bootloader / kernel code for application processors. - Some useful crates for bare-metal Rust development. -For the microcontroller part of the course we will use the [BBC micro:bit](https://microbit.org/) v2 -as an example. It's a [development board](https://tech.microbit.org/hardware/) based on the Nordic -nRF51822 microcontroller with some LEDs and buttons, an I2C-connected accelerometer and compass, and -an on-board SWD debugger. +For the microcontroller part of the course we will use the +[BBC micro:bit](https://microbit.org/) v2 as an example. It's a +[development board](https://tech.microbit.org/hardware/) based on the Nordic +nRF51822 microcontroller with some LEDs and buttons, an I2C-connected +accelerometer and compass, and an on-board SWD debugger. To get started, install some tools we'll need later. On gLinux or Debian: + + ```bash sudo apt install gcc-aarch64-linux-gnu gdb-multiarch libudev-dev picocom pkg-config qemu-system-arm rustup update @@ -32,7 +37,9 @@ cargo install cargo-binutils cargo-embed ``` And give users in the `plugdev` group access to the micro:bit programmer: + + ```bash echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="0d28", MODE="0664", GROUP="plugdev"' |\ sudo tee /etc/udev/rules.d/50-microbit.rules @@ -40,7 +47,9 @@ sudo udevadm control --reload-rules ``` On MacOS: + + ```bash xcode-select --install brew install gdb picocom qemu diff --git a/src/bare-metal/alloc-example/src/main.rs b/src/bare-metal/alloc-example/src/main.rs index 7ab8ba5..5a86a4f 100644 --- a/src/bare-metal/alloc-example/src/main.rs +++ b/src/bare-metal/alloc-example/src/main.rs @@ -32,9 +32,7 @@ pub fn entry() { // Safe because `HEAP` is only used here and `entry` is only called once. unsafe { // Give the allocator some memory to allocate. - HEAP_ALLOCATOR - .lock() - .init(HEAP.as_mut_ptr() as usize, HEAP.len()); + HEAP_ALLOCATOR.lock().init(HEAP.as_mut_ptr() as usize, HEAP.len()); } // Now we can do things that require heap allocation. diff --git a/src/bare-metal/alloc.md b/src/bare-metal/alloc.md index e600b79..91dac1a 100644 --- a/src/bare-metal/alloc.md +++ b/src/bare-metal/alloc.md @@ -9,14 +9,16 @@ To use `alloc` you must implement a
-* `buddy_system_allocator` is a third-party crate implementing a basic buddy system allocator. Other - crates are available, or you can write your own or hook into your existing allocator. -* The const parameter of `LockedHeap` is the max order of the allocator; i.e. in this case it can - allocate regions of up to 2**32 bytes. -* If any crate in your dependency tree depends on `alloc` then you must have exactly one global - allocator defined in your binary. Usually this is done in the top-level binary crate. -* `extern crate panic_halt as _` is necessary to ensure that the `panic_halt` crate is linked in so - we get its panic handler. -* This example will build but not run, as it doesn't have an entry point. +- `buddy_system_allocator` is a third-party crate implementing a basic buddy + system allocator. Other crates are available, or you can write your own or + hook into your existing allocator. +- The const parameter of `LockedHeap` is the max order of the allocator; i.e. in + this case it can allocate regions of up to 2**32 bytes. +- If any crate in your dependency tree depends on `alloc` then you must have + exactly one global allocator defined in your binary. Usually this is done in + the top-level binary crate. +- `extern crate panic_halt as _` is necessary to ensure that the `panic_halt` + crate is linked in so we get its panic handler. +- This example will build but not run, as it doesn't have an entry point.
diff --git a/src/bare-metal/android.md b/src/bare-metal/android.md index 89c95d5..c581f0e 100644 --- a/src/bare-metal/android.md +++ b/src/bare-metal/android.md @@ -1,9 +1,12 @@ # Android -To build a bare-metal Rust binary in AOSP, you need to use a `rust_ffi_static` Soong rule to build -your Rust code, then a `cc_binary` with a linker script to produce the binary itself, and then a -`raw_binary` to convert the ELF to a raw binary ready to be run. +To build a bare-metal Rust binary in AOSP, you need to use a `rust_ffi_static` +Soong rule to build your Rust code, then a `cc_binary` with a linker script to +produce the binary itself, and then a `raw_binary` to convert the ELF to a raw +binary ready to be run. + + ```soong rust_ffi_static { name: "libvmbase_example", diff --git a/src/bare-metal/android/vmbase.md b/src/bare-metal/android/vmbase.md index 12bc288..417c4da 100644 --- a/src/bare-metal/android/vmbase.md +++ b/src/bare-metal/android/vmbase.md @@ -1,8 +1,11 @@ # vmbase -For VMs running under crosvm on aarch64, the [vmbase][1] library provides a linker script and useful -defaults for the build rules, along with an entry point, UART console logging and more. +For VMs running under crosvm on aarch64, the [vmbase][1] library provides a +linker script and useful defaults for the build rules, along with an entry +point, UART console logging and more. + + ```rust,compile_fail #![no_main] #![no_std] @@ -18,9 +21,10 @@ pub fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) {
-* The `main!` macro marks your main function, to be called from the `vmbase` entry point. -* The `vmbase` entry point handles console initialisation, and issues a PSCI_SYSTEM_OFF to shutdown - the VM if your main function returns. +- The `main!` macro marks your main function, to be called from the `vmbase` + entry point. +- The `vmbase` entry point handles console initialisation, and issues a + PSCI_SYSTEM_OFF to shutdown the VM if your main function returns.
diff --git a/src/bare-metal/aps.md b/src/bare-metal/aps.md index ace7c62..82ebf7f 100644 --- a/src/bare-metal/aps.md +++ b/src/bare-metal/aps.md @@ -1,18 +1,21 @@ --- session: Afternoon --- + # Application processors -So far we've talked about microcontrollers, such as the Arm Cortex-M series. Now let's try writing -something for Cortex-A. For simplicity we'll just work with QEMU's aarch64 +So far we've talked about microcontrollers, such as the Arm Cortex-M series. Now +let's try writing something for Cortex-A. For simplicity we'll just work with +QEMU's aarch64 ['virt'](https://qemu-project.gitlab.io/qemu/system/arm/virt.html) board.
-* Broadly speaking, microcontrollers don't have an MMU or multiple levels of privilege (exception - levels on Arm CPUs, rings on x86), while application processors do. -* QEMU supports emulating various different machines or board models for each architecture. The - 'virt' board doesn't correspond to any particular real hardware, but is designed purely for - virtual machines. +- Broadly speaking, microcontrollers don't have an MMU or multiple levels of + privilege (exception levels on Arm CPUs, rings on x86), while application + processors do. +- QEMU supports emulating various different machines or board models for each + architecture. The 'virt' board doesn't correspond to any particular real + hardware, but is designed purely for virtual machines.
diff --git a/src/bare-metal/aps/better-uart.md b/src/bare-metal/aps/better-uart.md index 99ceb51..f87fca7 100644 --- a/src/bare-metal/aps/better-uart.md +++ b/src/bare-metal/aps/better-uart.md @@ -1,8 +1,8 @@ # A better UART driver -The PL011 actually has [a bunch more registers][1], and adding offsets to construct pointers to access -them is error-prone and hard to read. Plus, some of them are bit fields which would be nice to -access in a structured way. +The PL011 actually has [a bunch more registers][1], and adding offsets to +construct pointers to access them is error-prone and hard to read. Plus, some of +them are bit fields which would be nice to access in a structured way. | Offset | Register name | Width | | ------ | ------------- | ----- | diff --git a/src/bare-metal/aps/better-uart/bitflags.md b/src/bare-metal/aps/better-uart/bitflags.md index 0ee6c0c..891cd2e 100644 --- a/src/bare-metal/aps/better-uart/bitflags.md +++ b/src/bare-metal/aps/better-uart/bitflags.md @@ -1,6 +1,7 @@ # Bitflags -The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for working with bitflags. +The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for working +with bitflags. ```rust,editable,compile_fail {{#include ../examples/src/pl011.rs:Flags}} @@ -8,7 +9,7 @@ The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for working
-* The `bitflags!` macro creates a newtype something like `Flags(u16)`, along with a bunch of method - implementations to get and set flags. +- The `bitflags!` macro creates a newtype something like `Flags(u16)`, along + with a bunch of method implementations to get and set flags.
diff --git a/src/bare-metal/aps/better-uart/driver.md b/src/bare-metal/aps/better-uart/driver.md index 28bad72..64c432e 100644 --- a/src/bare-metal/aps/better-uart/driver.md +++ b/src/bare-metal/aps/better-uart/driver.md @@ -8,7 +8,7 @@ Now let's use the new `Registers` struct in our driver.
-* Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual fields without creating - an intermediate reference, which would be unsound. +- Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual + fields without creating an intermediate reference, which would be unsound.
diff --git a/src/bare-metal/aps/better-uart/registers.md b/src/bare-metal/aps/better-uart/registers.md index 3cd8d33..48f5e5b 100644 --- a/src/bare-metal/aps/better-uart/registers.md +++ b/src/bare-metal/aps/better-uart/registers.md @@ -1,16 +1,19 @@ # Multiple registers We can use a struct to represent the memory layout of the UART's registers. + + ```rust,editable,compile_fail {{#include ../examples/src/pl011.rs:Registers}} ```
-* [`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-representation) tells - the compiler to lay the struct fields out in order, following the same rules as C. This is - necessary for our struct to have a predictable layout, as default Rust representation allows the - compiler to (among other things) reorder fields however it sees fit. +- [`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-representation) + tells the compiler to lay the struct fields out in order, following the same + rules as C. This is necessary for our struct to have a predictable layout, as + default Rust representation allows the compiler to (among other things) + reorder fields however it sees fit.
diff --git a/src/bare-metal/aps/better-uart/using.md b/src/bare-metal/aps/better-uart/using.md index 5089224..159c8e3 100644 --- a/src/bare-metal/aps/better-uart/using.md +++ b/src/bare-metal/aps/better-uart/using.md @@ -1,7 +1,7 @@ # Using it -Let's write a small program using our driver to write to the serial console, and echo incoming -bytes. +Let's write a small program using our driver to write to the serial console, and +echo incoming bytes. ```rust,editable,compile_fail {{#include ../examples/src/main_improved.rs:main}} @@ -9,8 +9,9 @@ bytes.
-* As in the [inline assembly](../inline-assembly.md) example, this `main` function is called from our - entry point code in `entry.S`. See the speaker notes there for details. -* Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`. +- As in the [inline assembly](../inline-assembly.md) example, this `main` + function is called from our entry point code in `entry.S`. See the speaker + notes there for details. +- Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/aps/entry-point.md b/src/bare-metal/aps/entry-point.md index b40005d..783e73d 100644 --- a/src/bare-metal/aps/entry-point.md +++ b/src/bare-metal/aps/entry-point.md @@ -8,28 +8,36 @@ Before we can start running Rust code, we need to do some initialisation.
-* This is the same as it would be for C: initialising the processor state, zeroing the BSS, and - setting up the stack pointer. - * The BSS (block starting symbol, for historical reasons) is the part of the object file which - containing statically allocated variables which are initialised to zero. They are omitted from - the image, to avoid wasting space on zeroes. The compiler assumes that the loader will take care - of zeroing them. -* The BSS may already be zeroed, depending on how memory is initialised and the image is loaded, but - we zero it to be sure. -* We need to enable the MMU and cache before reading or writing any memory. If we don't: - * Unaligned accesses will fault. We build the Rust code for the `aarch64-unknown-none` target - which sets `+strict-align` to prevent the compiler generating unaligned accesses, so it should - be fine in this case, but this is not necessarily the case in general. - * If it were running in a VM, this can lead to cache coherency issues. The problem is that the VM - is accessing memory directly with the cache disabled, while the host has cacheable aliases to the - same memory. Even if the host doesn't explicitly access the memory, speculative accesses can - lead to cache fills, and then changes from one or the other will get lost when the cache is - cleaned or the VM enables the cache. (Cache is keyed by physical address, not VA or IPA.) -* For simplicity, we just use a hardcoded pagetable (see `idmap.S`) which identity maps the first 1 - GiB of address space for devices, the next 1 GiB for DRAM, and another 1 GiB higher up for more - devices. This matches the memory layout that QEMU uses. -* We also set up the exception vector (`vbar_el1`), which we'll see more about later. -* All examples this afternoon assume we will be running at exception level 1 (EL1). If you need to - run at a different exception level you'll need to modify `entry.S` accordingly. +- This is the same as it would be for C: initialising the processor state, + zeroing the BSS, and setting up the stack pointer. + - The BSS (block starting symbol, for historical reasons) is the part of the + object file which containing statically allocated variables which are + initialised to zero. They are omitted from the image, to avoid wasting space + on zeroes. The compiler assumes that the loader will take care of zeroing + them. +- The BSS may already be zeroed, depending on how memory is initialised and the + image is loaded, but we zero it to be sure. +- We need to enable the MMU and cache before reading or writing any memory. If + we don't: + - Unaligned accesses will fault. We build the Rust code for the + `aarch64-unknown-none` target which sets `+strict-align` to prevent the + compiler generating unaligned accesses, so it should be fine in this case, + but this is not necessarily the case in general. + - If it were running in a VM, this can lead to cache coherency issues. The + problem is that the VM is accessing memory directly with the cache disabled, + while the host has cacheable aliases to the same memory. Even if the host + doesn't explicitly access the memory, speculative accesses can lead to cache + fills, and then changes from one or the other will get lost when the cache + is cleaned or the VM enables the cache. (Cache is keyed by physical address, + not VA or IPA.) +- For simplicity, we just use a hardcoded pagetable (see `idmap.S`) which + identity maps the first 1 GiB of address space for devices, the next 1 GiB for + DRAM, and another 1 GiB higher up for more devices. This matches the memory + layout that QEMU uses. +- We also set up the exception vector (`vbar_el1`), which we'll see more about + later. +- All examples this afternoon assume we will be running at exception level 1 + (EL1). If you need to run at a different exception level you'll need to modify + `entry.S` accordingly.
diff --git a/src/bare-metal/aps/examples/src/logger.rs b/src/bare-metal/aps/examples/src/logger.rs index 8151949..e27ee2b 100644 --- a/src/bare-metal/aps/examples/src/logger.rs +++ b/src/bare-metal/aps/examples/src/logger.rs @@ -18,9 +18,7 @@ use core::fmt::Write; use log::{LevelFilter, Log, Metadata, Record, SetLoggerError}; use spin::mutex::SpinMutex; -static LOGGER: Logger = Logger { - uart: SpinMutex::new(None), -}; +static LOGGER: Logger = Logger { uart: SpinMutex::new(None) }; struct Logger { uart: SpinMutex>, diff --git a/src/bare-metal/aps/examples/src/pl011.rs b/src/bare-metal/aps/examples/src/pl011.rs index a633012..5074955 100644 --- a/src/bare-metal/aps/examples/src/pl011.rs +++ b/src/bare-metal/aps/examples/src/pl011.rs @@ -112,9 +112,7 @@ impl Uart { /// 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 u32) -> Self { - Self { - registers: base_address as *mut Registers, - } + Self { registers: base_address as *mut Registers } } /// Writes a single byte to the UART. @@ -133,7 +131,8 @@ impl Uart { while self.read_flag_register().contains(Flags::BUSY) {} } - /// Reads and returns a pending byte, or `None` if nothing has been received. + /// Reads and returns a pending byte, or `None` if nothing has been + /// received. pub fn read_byte(&self) -> Option { if self.read_flag_register().contains(Flags::RXFE) { None diff --git a/src/bare-metal/aps/exceptions.md b/src/bare-metal/aps/exceptions.md index e8bf4a9..916d952 100644 --- a/src/bare-metal/aps/exceptions.md +++ b/src/bare-metal/aps/exceptions.md @@ -1,26 +1,30 @@ # Exceptions -AArch64 defines an exception vector table with 16 entries, for 4 types of exceptions (synchronous, -IRQ, FIQ, SError) from 4 states (current EL with SP0, current EL with SPx, lower EL using AArch64, -lower EL using AArch32). We implement this in assembly to save volatile registers to the stack -before calling into Rust code: +AArch64 defines an exception vector table with 16 entries, for 4 types of +exceptions (synchronous, IRQ, FIQ, SError) from 4 states (current EL with SP0, +current EL with SPx, lower EL using AArch64, lower EL using AArch32). We +implement this in assembly to save volatile registers to the stack before +calling into Rust code: + + ```rust,editable,compile_fail {{#include examples/src/exceptions.rs:exceptions}} ```
-* EL is exception level; all our examples this afternoon run in EL1. -* For simplicity we aren't distinguishing between SP0 and SPx for the current EL exceptions, or - between AArch32 and AArch64 for the lower EL exceptions. -* For this example we just log the exception and power down, as we don't expect any of them to - actually happen. -* We can think of exception handlers and our main execution context more or less like different - threads. [`Send` and `Sync`][1] will control what we can share between them, just like with threads. - For example, if we want to share some value between exception handlers and the rest of the - program, and it's `Send` but not `Sync`, then we'll need to wrap it in something like a `Mutex` - and put it in a static. +- EL is exception level; all our examples this afternoon run in EL1. +- For simplicity we aren't distinguishing between SP0 and SPx for the current EL + exceptions, or between AArch32 and AArch64 for the lower EL exceptions. +- For this example we just log the exception and power down, as we don't expect + any of them to actually happen. +- We can think of exception handlers and our main execution context more or less + like different threads. [`Send` and `Sync`][1] will control what we can share + between them, just like with threads. For example, if we want to share some + value between exception handlers and the rest of the program, and it's `Send` + but not `Sync`, then we'll need to wrap it in something like a `Mutex` and put + it in a static.
diff --git a/src/bare-metal/aps/inline-assembly.md b/src/bare-metal/aps/inline-assembly.md index 0af641f..31336c4 100644 --- a/src/bare-metal/aps/inline-assembly.md +++ b/src/bare-metal/aps/inline-assembly.md @@ -1,30 +1,35 @@ # Inline assembly -Sometimes we need to use assembly to do things that aren't possible with Rust code. For example, -to make an HVC (hypervisor call) to tell the firmware to power off the system: +Sometimes we need to use assembly to do things that aren't possible with Rust +code. For example, to make an HVC (hypervisor call) to tell the firmware to +power off the system: ```rust,editable,compile_fail {{#include examples/src/main_psci.rs:main}} ``` -(If you actually want to do this, use the [`smccc`][1] crate which has wrappers for all these functions.) +(If you actually want to do this, use the [`smccc`][1] crate which has wrappers +for all these functions.)
-* PSCI is the Arm Power State Coordination Interface, a standard set of functions to manage system - and CPU power states, among other things. It is implemented by EL3 firmware and hypervisors on - many systems. -* The `0 => _` syntax means initialise the register to 0 before running the inline assembly code, - and ignore its contents afterwards. We need to use `inout` rather than `in` because the call could - potentially clobber the contents of the registers. -* This `main` function needs to be `#[no_mangle]` and `extern "C"` because it is called from our - entry point in `entry.S`. -* `_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally used by the bootloader - to pass things like a pointer to the device tree. According to the standard aarch64 calling - convention (which is what `extern "C"` specifies to use), registers `x0`–`x7` are used for the - first 8 arguments passed to a function, so `entry.S` doesn't need to do anything special except - make sure it doesn't change these registers. -* Run the example in QEMU with `make qemu_psci` under `src/bare-metal/aps/examples`. +- PSCI is the Arm Power State Coordination Interface, a standard set of + functions to manage system and CPU power states, among other things. It is + implemented by EL3 firmware and hypervisors on many systems. +- The `0 => _` syntax means initialise the register to 0 before running the + inline assembly code, and ignore its contents afterwards. We need to use + `inout` rather than `in` because the call could potentially clobber the + contents of the registers. +- This `main` function needs to be `#[no_mangle]` and `extern "C"` because it is + called from our entry point in `entry.S`. +- `_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally + used by the bootloader to pass things like a pointer to the device tree. + According to the standard aarch64 calling convention (which is what + `extern "C"` specifies to use), registers `x0`–`x7` are used for the first 8 + arguments passed to a function, so `entry.S` doesn't need to do anything + special except make sure it doesn't change these registers. +- Run the example in QEMU with `make qemu_psci` under + `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/aps/logging.md b/src/bare-metal/aps/logging.md index 8a72bab..0d11f62 100644 --- a/src/bare-metal/aps/logging.md +++ b/src/bare-metal/aps/logging.md @@ -1,7 +1,7 @@ # Logging -It would be nice to be able to use the logging macros from the [`log`][1] crate. We can do this by -implementing the `Log` trait. +It would be nice to be able to use the logging macros from the [`log`][1] crate. +We can do this by implementing the `Log` trait. ```rust,editable,compile_fail {{#include examples/src/logger.rs:main}} @@ -9,7 +9,8 @@ implementing the `Log` trait.
-* The unwrap in `log` is safe because we initialise `LOGGER` before calling `set_logger`. +- The unwrap in `log` is safe because we initialise `LOGGER` before calling + `set_logger`.
diff --git a/src/bare-metal/aps/logging/using.md b/src/bare-metal/aps/logging/using.md index a2e1500..0d559a2 100644 --- a/src/bare-metal/aps/logging/using.md +++ b/src/bare-metal/aps/logging/using.md @@ -8,7 +8,8 @@ We need to initialise the logger before we use it.
-* Note that our panic handler can now log details of panics. -* Run the example in QEMU with `make qemu_logger` under `src/bare-metal/aps/examples`. +- Note that our panic handler can now log details of panics. +- Run the example in QEMU with `make qemu_logger` under + `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/aps/mmio.md b/src/bare-metal/aps/mmio.md index 4c63731..47b81df 100644 --- a/src/bare-metal/aps/mmio.md +++ b/src/bare-metal/aps/mmio.md @@ -1,17 +1,21 @@ # Volatile memory access for MMIO - * Use `pointer::read_volatile` and `pointer::write_volatile`. - * Never hold a reference. - * `addr_of!` lets you get fields of structs without creating an intermediate reference. +- Use `pointer::read_volatile` and `pointer::write_volatile`. +- Never hold a reference. +- `addr_of!` lets you get fields of structs without creating an intermediate + reference.
- * Volatile access: read or write operations may have side-effects, so prevent the compiler or - hardware from reordering, duplicating or eliding them. - * Usually if you write and then read, e.g. via a mutable reference, the compiler may assume that - the value read is the same as the value just written, and not bother actually reading memory. - * Some existing crates for volatile access to hardware do hold references, but this is unsound. - Whenever a reference exist, the compiler may choose to dereference it. - * Use the `addr_of!` macro to get struct field pointers from a pointer to the struct. +- Volatile access: read or write operations may have side-effects, so prevent + the compiler or hardware from reordering, duplicating or eliding them. + - Usually if you write and then read, e.g. via a mutable reference, the + compiler may assume that the value read is the same as the value just + written, and not bother actually reading memory. +- Some existing crates for volatile access to hardware do hold references, but + this is unsound. Whenever a reference exist, the compiler may choose to + dereference it. +- Use the `addr_of!` macro to get struct field pointers from a pointer to the + struct.
diff --git a/src/bare-metal/aps/other-projects.md b/src/bare-metal/aps/other-projects.md index 6f02179..9f76955 100644 --- a/src/bare-metal/aps/other-projects.md +++ b/src/bare-metal/aps/other-projects.md @@ -1,29 +1,31 @@ # Other projects - * [oreboot](https://github.com/oreboot/oreboot) - * "coreboot without the C" - * Supports x86, aarch64 and RISC-V. - * Relies on LinuxBoot rather than having many drivers itself. - * [Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials) - * Initialisation, UART driver, simple bootloader, JTAG, exception levels, exception handling, - page tables - * Some dodginess around cache maintenance and initialisation in Rust, not necessarily a good - example to copy for production code. - * [`cargo-call-stack`](https://crates.io/crates/cargo-call-stack) - * Static analysis to determine maximum stack usage. +- [oreboot](https://github.com/oreboot/oreboot) + - "coreboot without the C" + - Supports x86, aarch64 and RISC-V. + - Relies on LinuxBoot rather than having many drivers itself. +- [Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials) + - Initialisation, UART driver, simple bootloader, JTAG, exception levels, + exception handling, page tables + - Some dodginess around cache maintenance and initialisation in Rust, not + necessarily a good example to copy for production code. +- [`cargo-call-stack`](https://crates.io/crates/cargo-call-stack) + - Static analysis to determine maximum stack usage.
-* The RaspberryPi OS tutorial runs Rust code before the MMU and caches are enabled. This will read - and write memory (e.g. the stack). However: - * Without the MMU and cache, unaligned accesses will fault. It builds with `aarch64-unknown-none` - which sets `+strict-align` to prevent the compiler generating unaligned accesses so it should be - alright, but this is not necessarily the case in general. - * If it were running in a VM, this can lead to cache coherency issues. The problem is that the VM - is accessing memory directly with the cache disabled, while the host has cacheable aliases to the - same memory. Even if the host doesn't explicitly access the memory, speculative accesses can - lead to cache fills, and then changes from one or the other will get lost. Again this is alright - in this particular case (running directly on the hardware with no hypervisor), but isn't a good - pattern in general. +- The RaspberryPi OS tutorial runs Rust code before the MMU and caches are + enabled. This will read and write memory (e.g. the stack). However: + - Without the MMU and cache, unaligned accesses will fault. It builds with + `aarch64-unknown-none` which sets `+strict-align` to prevent the compiler + generating unaligned accesses so it should be alright, but this is not + necessarily the case in general. + - If it were running in a VM, this can lead to cache coherency issues. The + problem is that the VM is accessing memory directly with the cache disabled, + while the host has cacheable aliases to the same memory. Even if the host + doesn't explicitly access the memory, speculative accesses can lead to cache + fills, and then changes from one or the other will get lost. Again this is + alright in this particular case (running directly on the hardware with no + hypervisor), but isn't a good pattern in general.
diff --git a/src/bare-metal/aps/uart.md b/src/bare-metal/aps/uart.md index 9c868bf..4d5ca72 100644 --- a/src/bare-metal/aps/uart.md +++ b/src/bare-metal/aps/uart.md @@ -8,16 +8,18 @@ The QEMU 'virt' machine has a [PL011][1] UART, so let's write a driver for that.
-* Note that `Uart::new` is unsafe while the other methods are safe. This is because as long as the - caller of `Uart::new` guarantees that its safety requirements are met (i.e. that there is only - ever one instance of the driver for a given UART, and nothing else aliasing its address space), - then it is always safe to call `write_byte` later because we can assume the necessary +- Note that `Uart::new` is unsafe while the other methods are safe. This is + because as long as the caller of `Uart::new` guarantees that its safety + requirements are met (i.e. that there is only ever one instance of the driver + for a given UART, and nothing else aliasing its address space), then it is + always safe to call `write_byte` later because we can assume the necessary preconditions. -* We could have done it the other way around (making `new` safe but `write_byte` unsafe), but that - would be much less convenient to use as every place that calls `write_byte` would need to reason - about the safety -* This is a common pattern for writing safe wrappers of unsafe code: moving the burden of proof for - soundness from a large number of places to a smaller number of places. +- We could have done it the other way around (making `new` safe but `write_byte` + unsafe), but that would be much less convenient to use as every place that + calls `write_byte` would need to reason about the safety +- This is a common pattern for writing safe wrappers of unsafe code: moving the + burden of proof for soundness from a large number of places to a smaller + number of places.
diff --git a/src/bare-metal/aps/uart/traits.md b/src/bare-metal/aps/uart/traits.md index 95b5f74..1f69e9f 100644 --- a/src/bare-metal/aps/uart/traits.md +++ b/src/bare-metal/aps/uart/traits.md @@ -1,6 +1,7 @@ # More traits -We derived the `Debug` trait. It would be useful to implement a few more traits too. +We derived the `Debug` trait. It would be useful to implement a few more traits +too. ```rust,editable,compile_fail {{#include ../examples/src/pl011_minimal.rs:Traits}} @@ -8,7 +9,9 @@ We derived the `Debug` trait. It would be useful to implement a few more traits
-* Implementing `Write` lets us use the `write!` and `writeln!` macros with our `Uart` type. -* Run the example in QEMU with `make qemu_minimal` under `src/bare-metal/aps/examples`. +- Implementing `Write` lets us use the `write!` and `writeln!` macros with our + `Uart` type. +- Run the example in QEMU with `make qemu_minimal` under + `src/bare-metal/aps/examples`.
diff --git a/src/bare-metal/microcontrollers.md b/src/bare-metal/microcontrollers.md index c41758c..a9b1b7e 100644 --- a/src/bare-metal/microcontrollers.md +++ b/src/bare-metal/microcontrollers.md @@ -1,17 +1,21 @@ # Microcontrollers -The `cortex_m_rt` crate provides (among other things) a reset handler for Cortex M microcontrollers. +The `cortex_m_rt` crate provides (among other things) a reset handler for Cortex +M microcontrollers. + + ```rust,editable,compile_fail {{#include microcontrollers/examples/src/bin/minimal.rs:Example}} ``` -Next we'll look at how to access peripherals, with increasing levels of abstraction. +Next we'll look at how to access peripherals, with increasing levels of +abstraction.
-* The `cortex_m_rt::entry` macro requires that the function have type `fn() -> !`, because returning - to the reset handler doesn't make sense. -* Run the example with `cargo embed --bin minimal` +- The `cortex_m_rt::entry` macro requires that the function have type + `fn() -> !`, because returning to the reset handler doesn't make sense. +- Run the example with `cargo embed --bin minimal`
diff --git a/src/bare-metal/microcontrollers/board-support.md b/src/bare-metal/microcontrollers/board-support.md index 07853eb..f99745e 100644 --- a/src/bare-metal/microcontrollers/board-support.md +++ b/src/bare-metal/microcontrollers/board-support.md @@ -1,18 +1,21 @@ # Board support crates -Board support crates provide a further level of wrapping for a specific board for convenience. +Board support crates provide a further level of wrapping for a specific board +for convenience. + + ```rust,editable,compile_fail {{#include examples/src/bin/board_support.rs:Example}} ```
- * In this case the board support crate is just providing more useful names, and a bit of - initialisation. - * The crate may also include drivers for some on-board devices outside of the microcontroller - itself. - * `microbit-v2` includes a simple driver for the LED matrix. +- In this case the board support crate is just providing more useful names, and + a bit of initialisation. +- The crate may also include drivers for some on-board devices outside of the + microcontroller itself. + - `microbit-v2` includes a simple driver for the LED matrix. Run the example with: diff --git a/src/bare-metal/microcontrollers/debugging.md b/src/bare-metal/microcontrollers/debugging.md index 7753a4b..349e091 100644 --- a/src/bare-metal/microcontrollers/debugging.md +++ b/src/bare-metal/microcontrollers/debugging.md @@ -1,7 +1,9 @@ # Debugging _Embed.toml_: + + ```toml [default.general] chip = "nrf52833_xxAA" @@ -11,7 +13,9 @@ enabled = true ``` In one terminal under `src/bare-metal/microcontrollers/examples/`: + + ```sh cargo embed --bin board_support debug ``` @@ -19,20 +23,27 @@ cargo embed --bin board_support debug In another terminal in the same directory: On gLinux or Debian: + + ```sh gdb-multiarch target/thumbv7em-none-eabihf/debug/board_support --eval-command="target remote :1337" ``` On MacOS: + + ```sh arm-none-eabi-gdb target/thumbv7em-none-eabihf/debug/board_support --eval-command="target remote :1337" ``` +
In GDB, try running: + + ```gdb b src/bin/board_support.rs:29 b src/bin/board_support.rs:30 diff --git a/src/bare-metal/microcontrollers/embedded-hal.md b/src/bare-metal/microcontrollers/embedded-hal.md index d1d325e..5e8c3da 100644 --- a/src/bare-metal/microcontrollers/embedded-hal.md +++ b/src/bare-metal/microcontrollers/embedded-hal.md @@ -1,23 +1,25 @@ # `embedded-hal` -The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a number of traits -covering common microcontroller peripherals. +The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a +number of traits covering common microcontroller peripherals. - * GPIO - * ADC - * I2C, SPI, UART, CAN - * RNG - * Timers - * Watchdogs +- GPIO +- ADC +- I2C, SPI, UART, CAN +- RNG +- Timers +- Watchdogs Other crates then implement -[drivers](https://github.com/rust-embedded/awesome-embedded-rust#driver-crates) in terms of these -traits, e.g. an accelerometer driver might need an I2C or SPI bus implementation. +[drivers](https://github.com/rust-embedded/awesome-embedded-rust#driver-crates) +in terms of these traits, e.g. an accelerometer driver might need an I2C or SPI +bus implementation.
- * There are implementations for many microcontrollers, as well as other platforms such as Linux on -Raspberry Pi. - * There is work in progress on an `async` version of `embedded-hal`, but it isn't stable yet. +- There are implementations for many microcontrollers, as well as other + platforms such as Linux on Raspberry Pi. +- There is work in progress on an `async` version of `embedded-hal`, but it + isn't stable yet.
diff --git a/src/bare-metal/microcontrollers/examples/src/bin/mmio.rs b/src/bare-metal/microcontrollers/examples/src/bin/mmio.rs index db973ea..f5882c6 100644 --- a/src/bare-metal/microcontrollers/examples/src/bin/mmio.rs +++ b/src/bare-metal/microcontrollers/examples/src/bin/mmio.rs @@ -47,10 +47,18 @@ fn main() -> ! { // no aliases exist. unsafe { pin_cnf_21.write_volatile( - DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | SENSE_DISABLED, + 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, + DIR_OUTPUT + | INPUT_DISCONNECT + | PULL_DISABLED + | DRIVE_S0S1 + | SENSE_DISABLED, ); } diff --git a/src/bare-metal/microcontrollers/examples/src/bin/typestate.rs b/src/bare-metal/microcontrollers/examples/src/bin/typestate.rs index 8ef87e4..f53761a 100644 --- a/src/bare-metal/microcontrollers/examples/src/bin/typestate.rs +++ b/src/bare-metal/microcontrollers/examples/src/bin/typestate.rs @@ -20,7 +20,8 @@ extern crate panic_halt as _; use cortex_m_rt::entry; use nrf52833_hal::gpio::p0::{self, P0_01, P0_02, P0_03}; use nrf52833_hal::gpio::{ - Disconnected, Floating, Input, Level, OpenDrain, OpenDrainConfig, Output, PushPull, + Disconnected, Floating, Input, Level, OpenDrain, OpenDrainConfig, Output, + PushPull, }; use nrf52833_hal::pac::Peripherals; use nrf52833_hal::prelude::*; @@ -46,7 +47,8 @@ fn main() -> ! { let _pin2: P0_02> = gpio0 .p0_02 .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, Level::Low); - let _pin3: P0_03> = gpio0.p0_03.into_push_pull_output(Level::Low); + let _pin3: P0_03> = + gpio0.p0_03.into_push_pull_output(Level::Low); loop {} } diff --git a/src/bare-metal/microcontrollers/hals.md b/src/bare-metal/microcontrollers/hals.md index 642e0ad..9b9b3d2 100644 --- a/src/bare-metal/microcontrollers/hals.md +++ b/src/bare-metal/microcontrollers/hals.md @@ -1,8 +1,9 @@ # HAL crates -[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-implementation-crates) for -many microcontrollers provide wrappers around various peripherals. These generally implement traits -from [`embedded-hal`](https://crates.io/crates/embedded-hal). +[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-implementation-crates) +for many microcontrollers provide wrappers around various peripherals. These +generally implement traits from +[`embedded-hal`](https://crates.io/crates/embedded-hal). ```rust,editable,compile_fail {{#include examples/src/bin/hal.rs:Example}} @@ -10,9 +11,9 @@ from [`embedded-hal`](https://crates.io/crates/embedded-hal).
- * `set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait. - * HAL crates exist for many Cortex-M and RISC-V devices, including various STM32, GD32, nRF, NXP, - MSP430, AVR and PIC microcontrollers. +- `set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait. +- HAL crates exist for many Cortex-M and RISC-V devices, including various + STM32, GD32, nRF, NXP, MSP430, AVR and PIC microcontrollers. Run the example with: diff --git a/src/bare-metal/microcontrollers/mmio.md b/src/bare-metal/microcontrollers/mmio.md index 57f3711..426083f 100644 --- a/src/bare-metal/microcontrollers/mmio.md +++ b/src/bare-metal/microcontrollers/mmio.md @@ -1,7 +1,7 @@ # Raw MMIO -Most microcontrollers access peripherals via memory-mapped IO. Let's try turning on an LED on our -micro:bit: +Most microcontrollers access peripherals via memory-mapped IO. Let's try turning +on an LED on our micro:bit: ```rust,editable,compile_fail {{#include examples/src/bin/mmio.rs:Example}} @@ -9,7 +9,8 @@ micro:bit:
-* GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 to the first row. +- GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 + to the first row. Run the example with: diff --git a/src/bare-metal/microcontrollers/other-projects.md b/src/bare-metal/microcontrollers/other-projects.md index d653c93..8434b02 100644 --- a/src/bare-metal/microcontrollers/other-projects.md +++ b/src/bare-metal/microcontrollers/other-projects.md @@ -1,26 +1,29 @@ # Other projects - * [RTIC](https://rtic.rs/) - * "Real-Time Interrupt-driven Concurrency" - * Shared resource management, message passing, task scheduling, timer queue - * [Embassy](https://embassy.dev/) - * `async` executors with priorities, timers, networking, USB - * [TockOS](https://www.tockos.org/documentation/getting-started) - * Security-focused RTOS with preemptive scheduling and Memory Protection Unit support - * [Hubris](https://hubris.oxide.computer/) - * Microkernel RTOS from Oxide Computer Company with memory protection, unprivileged drivers, IPC - * [Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust) - * Some platforms have `std` implementations, e.g. - [esp-idf](https://esp-rs.github.io/book/overview/using-the-standard-library.html). +- [RTIC](https://rtic.rs/) + - "Real-Time Interrupt-driven Concurrency" + - Shared resource management, message passing, task scheduling, timer queue +- [Embassy](https://embassy.dev/) + - `async` executors with priorities, timers, networking, USB +- [TockOS](https://www.tockos.org/documentation/getting-started) + - Security-focused RTOS with preemptive scheduling and Memory Protection Unit + support +- [Hubris](https://hubris.oxide.computer/) + - Microkernel RTOS from Oxide Computer Company with memory protection, + unprivileged drivers, IPC +- [Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust) +- Some platforms have `std` implementations, e.g. + [esp-idf](https://esp-rs.github.io/book/overview/using-the-standard-library.html).
- * RTIC can be considered either an RTOS or a concurrency framework. - * It doesn't include any HALs. - * It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for scheduling rather than a - proper kernel. - * Cortex-M only. - * Google uses TockOS on the Haven microcontroller for Titan security keys. - * FreeRTOS is mostly written in C, but there are Rust bindings for writing applications. +- RTIC can be considered either an RTOS or a concurrency framework. + - It doesn't include any HALs. + - It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for + scheduling rather than a proper kernel. + - Cortex-M only. +- Google uses TockOS on the Haven microcontroller for Titan security keys. +- FreeRTOS is mostly written in C, but there are Rust bindings for writing + applications.
diff --git a/src/bare-metal/microcontrollers/pacs.md b/src/bare-metal/microcontrollers/pacs.md index 86e0b0d..2ecb30f 100644 --- a/src/bare-metal/microcontrollers/pacs.md +++ b/src/bare-metal/microcontrollers/pacs.md @@ -1,8 +1,8 @@ # Peripheral Access Crates -[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust wrappers for -memory-mapped peripherals from [CMSIS-SVD](https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html) -files. +[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust +wrappers for memory-mapped peripherals from +[CMSIS-SVD](https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html) files. ```rust,editable,compile_fail {{#include examples/src/bin/pac.rs:Example}} @@ -10,15 +10,17 @@ files.
-* SVD (System View Description) files are XML files typically provided by silicon vendors which - describe the memory map of the device. - * They are organised by peripheral, register, field and value, with names, descriptions, addresses - and so on. - * SVD files are often buggy and incomplete, so there are various projects which patch the - mistakes, add missing details, and publish the generated crates. -* `cortex-m-rt` provides the vector table, among other things. -* If you `cargo install cargo-binutils` then you can run - `cargo objdump --bin pac -- -d --no-show-raw-insn` to see the resulting binary. +- SVD (System View Description) files are XML files typically provided by + silicon vendors which describe the memory map of the device. + - They are organised by peripheral, register, field and value, with names, + descriptions, addresses and so on. + - SVD files are often buggy and incomplete, so there are various projects + which patch the mistakes, add missing details, and publish the generated + crates. +- `cortex-m-rt` provides the vector table, among other things. +- If you `cargo install cargo-binutils` then you can run + `cargo objdump --bin pac -- -d --no-show-raw-insn` to see the resulting + binary. Run the example with: diff --git a/src/bare-metal/microcontrollers/probe-rs.md b/src/bare-metal/microcontrollers/probe-rs.md index 1633139..1d99535 100644 --- a/src/bare-metal/microcontrollers/probe-rs.md +++ b/src/bare-metal/microcontrollers/probe-rs.md @@ -1,11 +1,11 @@ # `probe-rs` and `cargo-embed` -[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, like OpenOCD but better -integrated. +[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, like +OpenOCD but better integrated. -* SWD (Serial Wire Debug) and JTAG via CMSIS-DAP, ST-Link and J-Link probes -* GDB stub and Microsoft DAP (Debug Adapter Protocol) server -* Cargo integration +- SWD (Serial Wire Debug) and JTAG via CMSIS-DAP, ST-Link and J-Link probes +- GDB stub and Microsoft DAP (Debug Adapter Protocol) server +- Cargo integration `cargo-embed` is a cargo subcommand to build and flash binaries, log RTT (Real Time Transfers) output and connect GDB. It's configured by an `Embed.toml` file @@ -13,17 +13,22 @@ in your project directory.
-* [CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is an Arm standard - protocol over USB for an in-circuit debugger to access the CoreSight Debug Access Port of various - Arm Cortex processors. It's what the on-board debugger on the BBC micro:bit uses. -* ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link is a range from - SEGGER. -* The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin Serial Wire Debug. -* probe-rs is a library which you can integrate into your own tools if you want to. -* The [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) lets - VSCode and other IDEs debug code running on any supported microcontroller. -* cargo-embed is a binary built using the probe-rs library. -* RTT (Real Time Transfers) is a mechanism to transfer data between the debug host and the target - through a number of ringbuffers. +- [CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is an + Arm standard protocol over USB for an in-circuit debugger to access the + CoreSight Debug Access Port of various Arm Cortex processors. It's what the + on-board debugger on the BBC micro:bit uses. +- ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link is + a range from SEGGER. +- The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin Serial + Wire Debug. +- probe-rs is a library which you can integrate into your own tools if you want + to. +- The + [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) + lets VSCode and other IDEs debug code running on any supported + microcontroller. +- cargo-embed is a binary built using the probe-rs library. +- RTT (Real Time Transfers) is a mechanism to transfer data between the debug + host and the target through a number of ringbuffers.
diff --git a/src/bare-metal/microcontrollers/type-state.md b/src/bare-metal/microcontrollers/type-state.md index 5829b17..0ed4edf 100644 --- a/src/bare-metal/microcontrollers/type-state.md +++ b/src/bare-metal/microcontrollers/type-state.md @@ -6,15 +6,17 @@
- * Pins don't implement `Copy` or `Clone`, so only one instance of each can exist. Once a pin is - moved out of the port struct nobody else can take it. - * Changing the configuration of a pin consumes the old pin instance, so you can’t keep use the old - instance afterwards. - * The type of a value indicates the state that it is in: e.g. in this case, the configuration state - of a GPIO pin. This encodes the state machine into the type system, and ensures that you don't - try to use a pin in a certain way without properly configuring it first. Illegal state - transitions are caught at compile time. - * You can call `is_high` on an input pin and `set_high` on an output pin, but not vice-versa. - * Many HAL crates follow this pattern. +- Pins don't implement `Copy` or `Clone`, so only one instance of each can + exist. Once a pin is moved out of the port struct nobody else can take it. +- Changing the configuration of a pin consumes the old pin instance, so you + can’t keep use the old instance afterwards. +- The type of a value indicates the state that it is in: e.g. in this case, the + configuration state of a GPIO pin. This encodes the state machine into the + type system, and ensures that you don't try to use a pin in a certain way + without properly configuring it first. Illegal state transitions are caught at + compile time. +- You can call `is_high` on an input pin and `set_high` on an output pin, but + not vice-versa. +- Many HAL crates follow this pattern.
diff --git a/src/bare-metal/minimal.md b/src/bare-metal/minimal.md index a4e00dd..c257d23 100644 --- a/src/bare-metal/minimal.md +++ b/src/bare-metal/minimal.md @@ -1,5 +1,7 @@ # A minimal `no_std` program + + ```rust,editable,compile_fail #![no_main] #![no_std] @@ -14,13 +16,13 @@ fn panic(_panic: &PanicInfo) -> ! {
-* This will compile to an empty binary. -* `std` provides a panic handler; without it we must provide our own. -* It can also be provided by another crate, such as `panic-halt`. -* Depending on the target, you may need to compile with `panic = "abort"` to avoid an error about - `eh_personality`. -* Note that there is no `main` or any other entry point; it's up to you to define your own entry - point. This will typically involve a linker script and some assembly code to set things up ready - for Rust code to run. +- This will compile to an empty binary. +- `std` provides a panic handler; without it we must provide our own. +- It can also be provided by another crate, such as `panic-halt`. +- Depending on the target, you may need to compile with `panic = "abort"` to + avoid an error about `eh_personality`. +- Note that there is no `main` or any other entry point; it's up to you to + define your own entry point. This will typically involve a linker script and + some assembly code to set things up ready for Rust code to run.
diff --git a/src/bare-metal/no_std.md b/src/bare-metal/no_std.md index 9ea4d5d..4f984e7 100644 --- a/src/bare-metal/no_std.md +++ b/src/bare-metal/no_std.md @@ -3,7 +3,7 @@ @@ -21,37 +21,37 @@ @@ -59,7 +59,7 @@
-* `HashMap` depends on RNG. -* `std` re-exports the contents of both `core` and `alloc`. +- `HashMap` depends on RNG. +- `std` re-exports the contents of both `core` and `alloc`.
diff --git a/src/bare-metal/useful-crates.md b/src/bare-metal/useful-crates.md index d544efe..3930177 100644 --- a/src/bare-metal/useful-crates.md +++ b/src/bare-metal/useful-crates.md @@ -1,3 +1,4 @@ # Useful crates -We'll go over a few crates which solve some common problems in bare-metal programming. +We'll go over a few crates which solve some common problems in bare-metal +programming. diff --git a/src/bare-metal/useful-crates/aarch64-paging.md b/src/bare-metal/useful-crates/aarch64-paging.md index 1d80978..dbf5f4c 100644 --- a/src/bare-metal/useful-crates/aarch64-paging.md +++ b/src/bare-metal/useful-crates/aarch64-paging.md @@ -1,7 +1,7 @@ # `aarch64-paging` -The [`aarch64-paging`][1] crate lets you create page tables according to the AArch64 Virtual Memory -System Architecture. +The [`aarch64-paging`][1] crate lets you create page tables according to the +AArch64 Virtual Memory System Architecture. ```rust,editable,compile_fail use aarch64_paging::{ @@ -25,10 +25,11 @@ idmap.activate();
-* For now it only supports EL1, but support for other exception levels should be straightforward to - add. -* This is used in Android for the [Protected VM Firmware][2]. -* There's no easy way to run this example, as it needs to run on real hardware or under QEMU. +- For now it only supports EL1, but support for other exception levels should be + straightforward to add. +- This is used in Android for the [Protected VM Firmware][2]. +- There's no easy way to run this example, as it needs to run on real hardware + or under QEMU.
diff --git a/src/bare-metal/useful-crates/buddy_system_allocator.md b/src/bare-metal/useful-crates/buddy_system_allocator.md index 588d7ab..9d34911 100644 --- a/src/bare-metal/useful-crates/buddy_system_allocator.md +++ b/src/bare-metal/useful-crates/buddy_system_allocator.md @@ -1,19 +1,23 @@ # `buddy_system_allocator` -[`buddy_system_allocator`][1] is a third-party crate implementing a basic buddy system allocator. -It can be used both for [`LockedHeap`][2] implementing [`GlobalAlloc`][3] so you can use the -standard `alloc` crate (as we saw [before][4]), or for allocating other address space. For example, -we might want to allocate MMIO space for PCI BARs: +[`buddy_system_allocator`][1] is a third-party crate implementing a basic buddy +system allocator. It can be used both for [`LockedHeap`][2] implementing +[`GlobalAlloc`][3] so you can use the standard `alloc` crate (as we saw +[before][4]), or for allocating other address space. For example, we might want +to allocate MMIO space for PCI BARs: + + ```rust,editable,compile_fail {{#include allocator-example/src/main.rs:main}} ```
-* PCI BARs always have alignment equal to their size. -* Run the example with `cargo run` under `src/bare-metal/useful-crates/allocator-example/`. (It won't - run in the Playground because of the crate dependency.) +- PCI BARs always have alignment equal to their size. +- Run the example with `cargo run` under + `src/bare-metal/useful-crates/allocator-example/`. (It won't run in the + Playground because of the crate dependency.)
diff --git a/src/bare-metal/useful-crates/spin.md b/src/bare-metal/useful-crates/spin.md index 59e02e5..19b83ba 100644 --- a/src/bare-metal/useful-crates/spin.md +++ b/src/bare-metal/useful-crates/spin.md @@ -1,11 +1,14 @@ # `spin` -`std::sync::Mutex` and the other synchronisation primitives from `std::sync` are not available in -`core` or `alloc`. How can we manage synchronisation or interior mutability, such as for sharing -state between different CPUs? +`std::sync::Mutex` and the other synchronisation primitives from `std::sync` are +not available in `core` or `alloc`. How can we manage synchronisation or +interior mutability, such as for sharing state between different CPUs? + +The [`spin`][1] crate provides spinlock-based equivalents of many of these +primitives. -The [`spin`][1] crate provides spinlock-based equivalents of many of these primitives. + ```rust,editable,compile_fail use spin::mutex::SpinMutex; @@ -20,12 +23,12 @@ fn main() {
-* Be careful to avoid deadlock if you take locks in interrupt handlers. -* `spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, `Barrier` and `Once` - from `std::sync`; and `Lazy` for lazy initialisation. -* The [`once_cell`][2] crate also has some useful types for late initialisation with a slightly - different approach to `spin::once::Once`. -* The Rust Playground includes `spin`, so this example will run fine inline. +- Be careful to avoid deadlock if you take locks in interrupt handlers. +- `spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, + `Barrier` and `Once` from `std::sync`; and `Lazy` for lazy initialisation. +- The [`once_cell`][2] crate also has some useful types for late initialisation + with a slightly different approach to `spin::once::Once`. +- The Rust Playground includes `spin`, so this example will run fine inline.
diff --git a/src/bare-metal/useful-crates/tinyvec.md b/src/bare-metal/useful-crates/tinyvec.md index 021c532..9a96f2a 100644 --- a/src/bare-metal/useful-crates/tinyvec.md +++ b/src/bare-metal/useful-crates/tinyvec.md @@ -1,10 +1,12 @@ # `tinyvec` -Sometimes you want something which can be resized like a `Vec`, but without heap allocation. -[`tinyvec`][1] provides this: a vector backed by an array or slice, which could be statically -allocated or on the stack, which keeps track of how many elements are used and panics if you try to -use more than are allocated. +Sometimes you want something which can be resized like a `Vec`, but without heap +allocation. [`tinyvec`][1] provides this: a vector backed by an array or slice, +which could be statically allocated or on the stack, which keeps track of how +many elements are used and panics if you try to use more than are allocated. + + ```rust,editable,compile_fail use tinyvec::{array_vec, ArrayVec}; @@ -20,8 +22,9 @@ fn main() {
-* `tinyvec` requires that the element type implement `Default` for initialisation. -* The Rust Playground includes `tinyvec`, so this example will run fine inline. +- `tinyvec` requires that the element type implement `Default` for + initialisation. +- The Rust Playground includes `tinyvec`, so this example will run fine inline.
diff --git a/src/bare-metal/useful-crates/zerocopy.md b/src/bare-metal/useful-crates/zerocopy.md index a081e0a..c008fe6 100644 --- a/src/bare-metal/useful-crates/zerocopy.md +++ b/src/bare-metal/useful-crates/zerocopy.md @@ -1,24 +1,29 @@ # `zerocopy` -The [`zerocopy`][1] crate (from Fuchsia) provides traits and macros for safely converting between -byte sequences and other types. +The [`zerocopy`][1] crate (from Fuchsia) provides traits and macros for safely +converting between byte sequences and other types. + + ```rust,editable,compile_fail {{#include zerocopy-example/src/main.rs:main}} ``` -This is not suitable for MMIO (as it doesn't use volatile reads and writes), but can be useful for -working with structures shared with hardware e.g. by DMA, or sent over some external interface. +This is not suitable for MMIO (as it doesn't use volatile reads and writes), but +can be useful for working with structures shared with hardware e.g. by DMA, or +sent over some external interface.
-* `FromBytes` can be implemented for types for which any byte pattern is valid, and so can safely be - converted from an untrusted sequence of bytes. -* Attempting to derive `FromBytes` for these types would fail, because `RequestType` doesn't use all - possible u32 values as discriminants, so not all byte patterns are valid. -* `zerocopy::byteorder` has types for byte-order aware numeric primitives. -* Run the example with `cargo run` under `src/bare-metal/useful-crates/zerocopy-example/`. (It won't - run in the Playground because of the crate dependency.) +- `FromBytes` can be implemented for types for which any byte pattern is valid, + and so can safely be converted from an untrusted sequence of bytes. +- Attempting to derive `FromBytes` for these types would fail, because + `RequestType` doesn't use all possible u32 values as discriminants, so not all + byte patterns are valid. +- `zerocopy::byteorder` has types for byte-order aware numeric primitives. +- Run the example with `cargo run` under + `src/bare-metal/useful-crates/zerocopy-example/`. (It won't run in the + Playground because of the crate dependency.)
diff --git a/src/borrowing/borrowck.md b/src/borrowing/borrowck.md index 306fa6a..d84fe22 100644 --- a/src/borrowing/borrowck.md +++ b/src/borrowing/borrowck.md @@ -4,12 +4,14 @@ minutes: 10 # Borrow Checking -Rust's _borrow checker_ puts constraints on the ways you can borrow values. For a given value, at any time: +Rust's _borrow checker_ puts constraints on the ways you can borrow values. For +a given value, at any time: -* You can have one or more shared references to the value, _or_ -* You can have exactly one exclusive reference to the value. +- You can have one or more shared references to the value, _or_ +- You can have exactly one exclusive reference to the value. + ```rust,editable,compile_fail fn main() { let mut a: i32 = 10; @@ -27,11 +29,22 @@ fn main() {
-* Note that the requirement is that conflicting references not _exist_ at the same point. It does not matter where the reference is dereferenced. -* The above code does not compile because `a` is borrowed as mutable (through `c`) and as immutable (through `b`) at the same time. -* Move the `println!` statement for `b` before the scope that introduces `c` to make the code compile. -* After that change, the compiler realizes that `b` is only ever used before the new mutable borrow of `a` through `c`. This is a feature of the borrow checker called "non-lexical lifetimes". -* The exclusive reference constraint is quite strong. Rust uses it to ensure that data races do not occur. Rust also _relies_ on this constraint to optimize code. For example, a value behind a shared reference can be safely cached in a register for the lifetime of that reference. -* The borrow checker is designed to accommodate many common patterns, such as taking exclusive references to different fields in a struct at the same time. But, there are some situations where it doesn't quite "get it" and this often results in "fighting with the borrow checker." +- Note that the requirement is that conflicting references not _exist_ at the + same point. It does not matter where the reference is dereferenced. +- The above code does not compile because `a` is borrowed as mutable (through + `c`) and as immutable (through `b`) at the same time. +- Move the `println!` statement for `b` before the scope that introduces `c` to + make the code compile. +- After that change, the compiler realizes that `b` is only ever used before the + new mutable borrow of `a` through `c`. This is a feature of the borrow checker + called "non-lexical lifetimes". +- The exclusive reference constraint is quite strong. Rust uses it to ensure + that data races do not occur. Rust also _relies_ on this constraint to + optimize code. For example, a value behind a shared reference can be safely + cached in a register for the lifetime of that reference. +- The borrow checker is designed to accommodate many common patterns, such as + taking exclusive references to different fields in a struct at the same time. + But, there are some situations where it doesn't quite "get it" and this often + results in "fighting with the borrow checker."
diff --git a/src/borrowing/interior-mutability.md b/src/borrowing/interior-mutability.md index 9226680..a229bfd 100644 --- a/src/borrowing/interior-mutability.md +++ b/src/borrowing/interior-mutability.md @@ -5,6 +5,7 @@ minutes: 10 + # Interior Mutability Rust provides a few safe means of modifying a value given only a shared @@ -15,7 +16,7 @@ checks. [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html) and [`RefCell`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) implement -what Rust calls *interior mutability:* mutation of values in an immutable +what Rust calls _interior mutability:_ mutation of values in an immutable context. `Cell` is typically used for simple types, as it requires copying or moving @@ -57,9 +58,17 @@ fn main() {
-* If we were using `Cell` instead of `RefCell` in this example, we would have to move the `Node` out of the `Rc` to push children, then move it back in. This is safe because there's always one, un-referenced value in the cell, but it's not ergonomic. -* To do anything with a Node, you must call a `RefCell` method, usually `borrow` or `borrow_mut`. -* Demonstrate that reference loops can be created by adding `root` to `subtree.children` (don't try to print it!). -* To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments `self.value` and calls the same method on its children. This will panic in the presence of the reference loop, with `thread 'main' panicked at 'already borrowed: BorrowMutError'`. +- If we were using `Cell` instead of `RefCell` in this example, we would have to + move the `Node` out of the `Rc` to push children, then move it back in. This + is safe because there's always one, un-referenced value in the cell, but it's + not ergonomic. +- To do anything with a Node, you must call a `RefCell` method, usually `borrow` + or `borrow_mut`. +- Demonstrate that reference loops can be created by adding `root` to + `subtree.children` (don't try to print it!). +- To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments + `self.value` and calls the same method on its children. This will panic in the + presence of the reference loop, with + `thread 'main' panicked at 'already borrowed: BorrowMutError'`.
diff --git a/src/borrowing/shared.md b/src/borrowing/shared.md index f21ed4a..68a8aa5 100644 --- a/src/borrowing/shared.md +++ b/src/borrowing/shared.md @@ -4,10 +4,11 @@ minutes: 10 # Borrowing a Value -As we saw before, instead of transferring ownership when calling a function, -you can let a function _borrow_ the value: +As we saw before, instead of transferring ownership when calling a function, you +can let a function _borrow_ the value: + ```rust,editable #[derive(Debug)] struct Point(i32, i32); @@ -24,8 +25,8 @@ fn main() { } ``` -* The `add` function _borrows_ two points and returns a new point. -* The caller retains ownership of the inputs. +- The `add` function _borrows_ two points and returns a new point. +- The caller retains ownership of the inputs.
@@ -36,7 +37,12 @@ slightly to include function arguments and return values. Notes on stack returns: -* Demonstrate that the return from `add` is cheap because the compiler can eliminate the copy operation. Change the above code to print stack addresses and run it on the [Playground] or look at the assembly in [Godbolt](https://rust.godbolt.org/). In the "DEBUG" optimization level, the addresses should change, while they stay the same when changing to the "RELEASE" setting: +- Demonstrate that the return from `add` is cheap because the compiler can + eliminate the copy operation. Change the above code to print stack addresses + and run it on the [Playground] or look at the assembly in + [Godbolt](https://rust.godbolt.org/). In the "DEBUG" optimization level, the + addresses should change, while they stay the same when changing to the + "RELEASE" setting: ```rust,editable @@ -57,8 +63,11 @@ Notes on stack returns: println!("{p1:?} + {p2:?} = {p3:?}"); } ``` -* The Rust compiler can do return value optimization (RVO). -* In C++, copy elision has to be defined in the language specification because constructors can have side effects. In Rust, this is not an issue at all. If RVO did not happen, Rust will always perform a simple and efficient `memcpy` copy. +- The Rust compiler can do return value optimization (RVO). +- In C++, copy elision has to be defined in the language specification because + constructors can have side effects. In Rust, this is not an issue at all. If + RVO did not happen, Rust will always perform a simple and efficient `memcpy` + copy.
diff --git a/src/cargo.md b/src/cargo.md index 763d115..206633b 100644 --- a/src/cargo.md +++ b/src/cargo.md @@ -1,25 +1,34 @@ # Using Cargo -When you start reading about Rust, you will soon meet [Cargo](https://doc.rust-lang.org/cargo/), the standard tool -used in the Rust ecosystem to build and run Rust applications. Here we want to -give a brief overview of what Cargo is and how it fits into the wider ecosystem -and how it fits into this training. +When you start reading about Rust, you will soon meet +[Cargo](https://doc.rust-lang.org/cargo/), the standard tool used in the Rust +ecosystem to build and run Rust applications. Here we want to give a brief +overview of what Cargo is and how it fits into the wider ecosystem and how it +fits into this training. ## Installation > **Please follow the instructions on .** -This will give you the Cargo build tool (`cargo`) and the Rust compiler (`rustc`). You will also get `rustup`, a command line utility that you can use to install to different compiler versions. +This will give you the Cargo build tool (`cargo`) and the Rust compiler +(`rustc`). You will also get `rustup`, a command line utility that you can use +to install to different compiler versions. -After installing Rust, you should configure your editor or IDE to work with Rust. Most editors do this by talking to [rust-analyzer], which provides auto-completion and jump-to-definition functionality for [VS Code], [Emacs], [Vim/Neovim], and many others. There is also a different IDE available called [RustRover]. +After installing Rust, you should configure your editor or IDE to work with +Rust. Most editors do this by talking to [rust-analyzer], which provides +auto-completion and jump-to-definition functionality for [VS Code], [Emacs], +[Vim/Neovim], and many others. There is also a different IDE available called +[RustRover].
-* On Debian/Ubuntu, you can also install Cargo, the Rust source and the [Rust formatter] via `apt`. However, this gets you an outdated rust version and may lead to unexpected behavior. The command would be: +- On Debian/Ubuntu, you can also install Cargo, the Rust source and the + [Rust formatter] via `apt`. However, this gets you an outdated rust version + and may lead to unexpected behavior. The command would be: - ```shell - sudo apt install cargo rust-src rustfmt - ``` + ```shell + sudo apt install cargo rust-src rustfmt + ```
diff --git a/src/cargo/code-samples.md b/src/cargo/code-samples.md index 95fca6d..02ab93a 100644 --- a/src/cargo/code-samples.md +++ b/src/cargo/code-samples.md @@ -21,15 +21,14 @@ text box.
-Most code samples are editable like shown above. A few code samples -are not editable for various reasons: +Most code samples are editable like shown above. A few code samples are not +editable for various reasons: -* The embedded playgrounds cannot execute unit tests. Copy-paste the - code and open it in the real Playground to demonstrate unit tests. +- The embedded playgrounds cannot execute unit tests. Copy-paste the code and + open it in the real Playground to demonstrate unit tests. -* The embedded playgrounds lose their state the moment you navigate - away from the page! This is the reason that the students should - solve the exercises using a local Rust installation or via the - Playground. +- The embedded playgrounds lose their state the moment you navigate away from + the page! This is the reason that the students should solve the exercises + using a local Rust installation or via the Playground.
diff --git a/src/cargo/running-locally.md b/src/cargo/running-locally.md index 55d5267..78898ad 100644 --- a/src/cargo/running-locally.md +++ b/src/cargo/running-locally.md @@ -1,9 +1,10 @@ # Running Code Locally with Cargo If you want to experiment with the code on your own system, then you will need -to first install Rust. Do this by following the [instructions in the Rust -Book][1]. This should give you a working `rustc` and `cargo`. At the time of -writing, the latest stable Rust release has these version numbers: +to first install Rust. Do this by following the +[instructions in the Rust Book][1]. This should give you a working `rustc` and +`cargo`. At the time of writing, the latest stable Rust release has these +version numbers: ```shell % rustc --version @@ -14,47 +15,47 @@ cargo 1.69.0 (6e9a83356 2023-04-12) You can use any later version too since Rust maintains backwards compatibility. -With this in place, follow these steps to build a Rust binary from one -of the examples in this training: +With this in place, follow these steps to build a Rust binary from one of the +examples in this training: 1. Click the "Copy to clipboard" button on the example you want to copy. 2. Use `cargo new exercise` to create a new `exercise/` directory for your code: - ```shell - $ cargo new exercise - Created binary (application) `exercise` package - ``` + ```shell + $ cargo new exercise + Created binary (application) `exercise` package + ``` 3. Navigate into `exercise/` and use `cargo run` to build and run your binary: - ```shell - $ cd exercise - $ cargo run - Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) - Finished dev [unoptimized + debuginfo] target(s) in 0.75s - Running `target/debug/exercise` - Hello, world! - ``` + ```shell + $ cd exercise + $ cargo run + Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) + Finished dev [unoptimized + debuginfo] target(s) in 0.75s + Running `target/debug/exercise` + Hello, world! + ``` 4. Replace the boiler-plate code in `src/main.rs` with your own code. For example, using the example on the previous page, make `src/main.rs` look like - ```rust - fn main() { - println!("Edit me!"); - } - ``` + ```rust + fn main() { + println!("Edit me!"); + } + ``` 5. Use `cargo run` to build and run your updated binary: - ```shell - $ cargo run - Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) - Finished dev [unoptimized + debuginfo] target(s) in 0.24s - Running `target/debug/exercise` - Edit me! - ``` + ```shell + $ cargo run + Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) + Finished dev [unoptimized + debuginfo] target(s) in 0.24s + Running `target/debug/exercise` + Edit me! + ``` 6. Use `cargo check` to quickly check your project for errors, use `cargo build` to compile it without running it. You will find the output in `target/debug/` @@ -69,8 +70,8 @@ of the examples in this training:
-Try to encourage the class participants to install Cargo and use a -local editor. It will make their life easier since they will have a -normal development environment. +Try to encourage the class participants to install Cargo and use a local editor. +It will make their life easier since they will have a normal development +environment.
diff --git a/src/cargo/rust-ecosystem.md b/src/cargo/rust-ecosystem.md index 21b4240..c193a5a 100644 --- a/src/cargo/rust-ecosystem.md +++ b/src/cargo/rust-ecosystem.md @@ -2,15 +2,15 @@ The Rust ecosystem consists of a number of tools, of which the main ones are: -* `rustc`: the Rust compiler which turns `.rs` files into binaries and other +- `rustc`: the Rust compiler which turns `.rs` files into binaries and other intermediate formats. -* `cargo`: the Rust dependency manager and build tool. Cargo knows how to - download dependencies, usually hosted on , and it will pass them to - `rustc` when building your project. Cargo also comes with a built-in test - runner which is used to execute unit tests. +- `cargo`: the Rust dependency manager and build tool. Cargo knows how to + download dependencies, usually hosted on , and it will pass + them to `rustc` when building your project. Cargo also comes with a built-in + test runner which is used to execute unit tests. -* `rustup`: the Rust toolchain installer and updater. This tool is used to +- `rustup`: the Rust toolchain installer and updater. This tool is used to install and update `rustc` and `cargo` when new versions of Rust are released. In addition, `rustup` can also download documentation for the standard library. You can have multiple versions of Rust installed at once and `rustup` @@ -20,52 +20,51 @@ The Rust ecosystem consists of a number of tools, of which the main ones are: Key points: -* Rust has a rapid release schedule with a new release coming out - every six weeks. New releases maintain backwards compatibility with - old releases --- plus they enable new functionality. +- Rust has a rapid release schedule with a new release coming out every six + weeks. New releases maintain backwards compatibility with old releases --- + plus they enable new functionality. -* There are three release channels: "stable", "beta", and "nightly". +- There are three release channels: "stable", "beta", and "nightly". -* New features are being tested on "nightly", "beta" is what becomes - "stable" every six weeks. +- New features are being tested on "nightly", "beta" is what becomes "stable" + every six weeks. -* Dependencies can also be resolved from alternative [registries], git, folders, and more. +- Dependencies can also be resolved from alternative [registries], git, folders, + and more. -* Rust also has [editions]: the current edition is Rust 2021. Previous - editions were Rust 2015 and Rust 2018. +- Rust also has [editions]: the current edition is Rust 2021. Previous editions + were Rust 2015 and Rust 2018. - * The editions are allowed to make backwards incompatible changes to - the language. + - The editions are allowed to make backwards incompatible changes to the + language. - * To prevent breaking code, editions are opt-in: you select the - edition for your crate via the `Cargo.toml` file. + - To prevent breaking code, editions are opt-in: you select the edition for + your crate via the `Cargo.toml` file. - * To avoid splitting the ecosystem, Rust compilers can mix code - written for different editions. + - To avoid splitting the ecosystem, Rust compilers can mix code written for + different editions. - * Mention that it is quite rare to ever use the compiler directly not through `cargo` (most users never do). + - Mention that it is quite rare to ever use the compiler directly not through + `cargo` (most users never do). - * It might be worth alluding that Cargo itself is an extremely powerful and comprehensive tool. It is capable of many advanced features including but not limited to: - * Project/package structure - * [workspaces] - * Dev Dependencies and Runtime Dependency management/caching - * [build scripting] - * [global installation] - * It is also extensible with sub command plugins as well (such as [cargo clippy]). - * Read more from the [official Cargo Book] + - It might be worth alluding that Cargo itself is an extremely powerful and + comprehensive tool. It is capable of many advanced features including but + not limited to: + - Project/package structure + - [workspaces] + - Dev Dependencies and Runtime Dependency management/caching + - [build scripting] + - [global installation] + - It is also extensible with sub command plugins as well (such as + [cargo clippy]). + - Read more from the [official Cargo Book] [editions]: https://doc.rust-lang.org/edition-guide/ - [workspaces]: https://doc.rust-lang.org/cargo/reference/workspaces.html - [build scripting]: https://doc.rust-lang.org/cargo/reference/build-scripts.html - [global installation]: https://doc.rust-lang.org/cargo/commands/cargo-install.html - [cargo clippy]: https://github.com/rust-lang/rust-clippy - [official Cargo Book]: https://doc.rust-lang.org/cargo/ - [registries]: https://doc.rust-lang.org/cargo/reference/registries.html diff --git a/src/chromium.md b/src/chromium.md index 362c220..442db00 100644 --- a/src/chromium.md +++ b/src/chromium.md @@ -2,12 +2,13 @@ course: Chromium session: Chromium --- + # Welcome to Rust in Chromium Rust is supported for third-party libraries in Chromium, with first-party glue code to connect between Rust and existing Chromium C++ code. -> Today, we'll call into Rust to do something silly with strings. If you've -> got a corner of the code where you're displaying a UTF8 string to the user, -> feel free to follow this recipe in your part of the codebase instead of -> the exact part we talk about. +> Today, we'll call into Rust to do something silly with strings. If you've got +> a corner of the code where you're displaying a UTF8 string to the user, feel +> free to follow this recipe in your part of the codebase instead of the exact +> part we talk about. diff --git a/src/chromium/adding-third-party-crates.md b/src/chromium/adding-third-party-crates.md index f2f57ee..afa7164 100644 --- a/src/chromium/adding-third-party-crates.md +++ b/src/chromium/adding-third-party-crates.md @@ -1,26 +1,26 @@ # Adding Third Party Crates -Rust libraries are called "crates" and are found at [crates.io][0]. It's *very -easy* for Rust crates to depend upon one another. So they do! +Rust libraries are called "crates" and are found at [crates.io][0]. It's _very +easy_ for Rust crates to depend upon one another. So they do! -| Property | C++ library | Rust crate | -| --- | --- | --- | -| Build system | Lots | Consistent: `Cargo.toml` | -| Typical library size | Large-ish | Small | -| Transitive dependencies | Few | Lots | +| Property | C++ library | Rust crate | +| ----------------------- | ----------- | ------------------------ | +| Build system | Lots | Consistent: `Cargo.toml` | +| Typical library size | Large-ish | Small | +| Transitive dependencies | Few | Lots | For a Chromium engineer, this has pros and cons: -* All crates use a common build system so we can automate their inclusion into +- All crates use a common build system so we can automate their inclusion into Chromium... -* ... but, crates typically have transitive dependencies, so you will - likely have to bring in multiple libraries. +- ... but, crates typically have transitive dependencies, so you will likely + have to bring in multiple libraries. We'll discuss: -* How to put a crate in the Chromium source code tree -* How to make `gn` build rules for it -* How to audit its source code for sufficient safety. +- How to put a crate in the Chromium source code tree +- How to make `gn` build rules for it +- How to audit its source code for sufficient safety. [0]: https://crates.io diff --git a/src/chromium/adding-third-party-crates/checking-in.md b/src/chromium/adding-third-party-crates/checking-in.md index a7515fa..481938e 100644 --- a/src/chromium/adding-third-party-crates/checking-in.md +++ b/src/chromium/adding-third-party-crates/checking-in.md @@ -1,21 +1,23 @@ # Checking Crates into Chromium Source Code `git status` should reveal: -* Crate code in `//third_party/rust/chromium_crates_io` -* Metadata (`BUILD.gn` and `README.chromium`) in `//third_party/rust//` + +- Crate code in `//third_party/rust/chromium_crates_io` +- Metadata (`BUILD.gn` and `README.chromium`) in + `//third_party/rust//` Please also add an `OWNERS` file in the latter location. -You should land all this, along with your `Cargo.toml` and `gnrt_config.toml` changes, into -the Chromium repo. +You should land all this, along with your `Cargo.toml` and `gnrt_config.toml` +changes, into the Chromium repo. **Important**: you need to use `git add -f` because otherwise `.gitignore` files may result in some files being skipped. As you do so, you might find presubmit checks fail because of non-inclusive -language. This is because Rust crate data tends to include names of git branches, -and many projects still use non-inclusive terminology there. So you may need -to run: +language. This is because Rust crate data tends to include names of git +branches, and many projects still use non-inclusive terminology there. So you +may need to run: ```shell infra/update_inclusive_language_presubmit_exempt_dirs.sh > infra/inclusive_language_presubmit_exempt_dirs.txt diff --git a/src/chromium/adding-third-party-crates/configuring-cargo-toml.md b/src/chromium/adding-third-party-crates/configuring-cargo-toml.md index ad43cae..c55274b 100644 --- a/src/chromium/adding-third-party-crates/configuring-cargo-toml.md +++ b/src/chromium/adding-third-party-crates/configuring-cargo-toml.md @@ -1,7 +1,7 @@ # Configuring the `Cargo.toml` file to add crates -Chromium has a single set of centrally-managed direct crate dependencies. -These are managed through a single [`Cargo.toml`][0]: +Chromium has a single set of centrally-managed direct crate dependencies. These +are managed through a single [`Cargo.toml`][0]: ```toml [dependencies] @@ -11,13 +11,12 @@ cxx = "1" # lots more... ``` -As with any other `Cargo.toml`, you can specify [more details about -the dependencies][1] --- most commonly, you'll want to specify the `features` that -you wish to enable in the crate. +As with any other `Cargo.toml`, you can specify +[more details about the dependencies][1] --- most commonly, you'll want to +specify the `features` that you wish to enable in the crate. When adding a crate to Chromium, you'll often need to provide some extra information in an additional file, `gnrt_config.toml`, which we'll meet next. - [0]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/rust/chromium_crates_io/Cargo.toml [1]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html diff --git a/src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md b/src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md index 6649786..60a427b 100644 --- a/src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +++ b/src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md @@ -1,10 +1,9 @@ # Configuring `gnrt_config.toml` -Alongside `Cargo.toml` is [`gnrt_config.toml`][0]. This contains Chromium-specific -extensions to crate handling. +Alongside `Cargo.toml` is [`gnrt_config.toml`][0]. This contains +Chromium-specific extensions to crate handling. -If you add a new crate, you should specify at least the `group`. -This is one of: +If you add a new crate, you should specify at least the `group`. This is one of: ```toml # 'safe': The library satisfies the rule-of-2 and can be used in any process. @@ -20,10 +19,10 @@ For instance, group = 'test' # only used in test code ``` -Depending on the crate source code layout, you may also need to use this -file to specify where its `LICENSE` file(s) can be found. +Depending on the crate source code layout, you may also need to use this file to +specify where its `LICENSE` file(s) can be found. -Later, we'll see some other things you will need to configure in this file -to resolve problems. +Later, we'll see some other things you will need to configure in this file to +resolve problems. -[0]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/rust/chromium_crates_io/gnrt_config.toml \ No newline at end of file +[0]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/rust/chromium_crates_io/gnrt_config.toml diff --git a/src/chromium/adding-third-party-crates/depending-on-a-crate.md b/src/chromium/adding-third-party-crates/depending-on-a-crate.md index 07eae92..d431aa1 100644 --- a/src/chromium/adding-third-party-crates/depending-on-a-crate.md +++ b/src/chromium/adding-third-party-crates/depending-on-a-crate.md @@ -1,8 +1,8 @@ # Depending on a Crate -Once you've added a third-party crate and generated build rules, -depending on a crate is simple. Find your `rust_static_library` target, -and add a `dep` on the `:lib` target within your crate. +Once you've added a third-party crate and generated build rules, depending on a +crate is simple. Find your `rust_static_library` target, and add a `dep` on the +`:lib` target within your crate. Specifically, diff --git a/src/chromium/adding-third-party-crates/downloading-crates.md b/src/chromium/adding-third-party-crates/downloading-crates.md index 64ad69a..d130668 100644 --- a/src/chromium/adding-third-party-crates/downloading-crates.md +++ b/src/chromium/adding-third-party-crates/downloading-crates.md @@ -10,20 +10,19 @@ cd chromium/src vpython3 tools/crates/run_gnrt.py -- vendor ``` -> Although the `gnrt` tool is part of the Chromium source code, -> by running this command you will be downloading and running its dependencies -> from `crates.io`. See [the earlier section][0] discussing this security -> decision. +> Although the `gnrt` tool is part of the Chromium source code, by running this +> command you will be downloading and running its dependencies from `crates.io`. +> See [the earlier section][0] discussing this security decision. This `vendor` command may download: -* Your crate -* Direct and transitive dependencies -* New versions of other crates, as required by `cargo` to resolve - the complete set of crates required by Chromium. + +- Your crate +- Direct and transitive dependencies +- New versions of other crates, as required by `cargo` to resolve the complete + set of crates required by Chromium. Chromium maintains patches for some crates, kept in `//third_party/rust/chromium_crates_io/patches`. These will be reapplied automatically, but if patching fails you may need to take manual action. - -[0]: ../cargo.md \ No newline at end of file +[0]: ../cargo.md diff --git a/src/chromium/adding-third-party-crates/generating-gn-build-rules.md b/src/chromium/adding-third-party-crates/generating-gn-build-rules.md index f81092f..bf3857e 100644 --- a/src/chromium/adding-third-party-crates/generating-gn-build-rules.md +++ b/src/chromium/adding-third-party-crates/generating-gn-build-rules.md @@ -8,9 +8,11 @@ vpython3 tools/crates/run_gnrt.py -- gen Now run `git status`. You should find: -* At least one new crate source code in `third_party/rust/chromium_crates_io/vendor` -* At least one new `BUILD.gn` in `third_party/rust//v` -* An appropriate `README.chromium` +- At least one new crate source code in + `third_party/rust/chromium_crates_io/vendor` +- At least one new `BUILD.gn` in + `third_party/rust//v` +- An appropriate `README.chromium` The "major semver version" is a [Rust "semver" version number][0]. @@ -18,9 +20,9 @@ Take a close look, especially at the things generated in `third_party/rust`.
-Talk a little about semver --- and specifically the way that in Chromium -it's to allow multiple incompatible versions of a crate, which is discouraged -but sometimes necessary in the Cargo ecosystem. +Talk a little about semver --- and specifically the way that in Chromium it's to +allow multiple incompatible versions of a crate, which is discouraged but +sometimes necessary in the Cargo ecosystem. diff --git a/src/chromium/adding-third-party-crates/keeping-up-to-date.md b/src/chromium/adding-third-party-crates/keeping-up-to-date.md index 9d6cce2..c2c1ee6 100644 --- a/src/chromium/adding-third-party-crates/keeping-up-to-date.md +++ b/src/chromium/adding-third-party-crates/keeping-up-to-date.md @@ -1,8 +1,8 @@ # Keeping Crates Up to Date As the OWNER of any third party Chromium dependency, you are -[expected to keep it up to date with any security fixes][0]. It is hoped -that we will soon automate this for Rust crates, but for now, it's still -your responsibility just as it is for any other third party dependency. +[expected to keep it up to date with any security fixes][0]. It is hoped that we +will soon automate this for Rust crates, but for now, it's still your +responsibility just as it is for any other third party dependency. -[0]: https://chromium.googlesource.com/chromium/src/+/main/docs/adding_to_third_party.md#add-owners \ No newline at end of file +[0]: https://chromium.googlesource.com/chromium/src/+/main/docs/adding_to_third_party.md#add-owners diff --git a/src/chromium/adding-third-party-crates/resolving-problems.md b/src/chromium/adding-third-party-crates/resolving-problems.md index 5d81ce6..5b10c4c 100644 --- a/src/chromium/adding-third-party-crates/resolving-problems.md +++ b/src/chromium/adding-third-party-crates/resolving-problems.md @@ -1,19 +1,19 @@ # Resolving Problems -If your build fails, it may be because of a `build.rs`: programs which do arbitrary -things at build time. This is fundamentally at odds with the design of `gn` -and `ninja` which aim for static, deterministic, build rules to maximize +If your build fails, it may be because of a `build.rs`: programs which do +arbitrary things at build time. This is fundamentally at odds with the design of +`gn` and `ninja` which aim for static, deterministic, build rules to maximize parallelism and repeatability of builds. Some `build.rs` actions are automatically supported; others require action: -| build script effect | Supported by our gn templates | Work required by you | -|-----|-----|-----| -| Checking rustc version to configure features on and off | Yes | None | -| Checking platform or CPU to configure features on and off | Yes | None | -| Generating code | Yes | Yes - specify in `gnrt_config.toml` | -| Building C/C++ | No | Patch around it | -| Arbitrary other actions | No | Patch around it | +| build script effect | Supported by our gn templates | Work required by you | +| --------------------------------------------------------- | ----------------------------- | ----------------------------------- | +| Checking rustc version to configure features on and off | Yes | None | +| Checking platform or CPU to configure features on and off | Yes | None | +| Generating code | Yes | Yes - specify in `gnrt_config.toml` | +| Building C/C++ | No | Patch around it | +| Arbitrary other actions | No | Patch around it | Fortunately, most crates don't contain a build script, and fortunately, most build scripts only do the top two actions. diff --git a/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md b/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md index b2d95ed..a2fda2b 100644 --- a/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md +++ b/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md @@ -4,19 +4,18 @@ If `ninja` complains about missing files, check the `build.rs` to see if it writes source code files. If so, modify [`gnrt_config.toml`][1] to add `build-script-outputs` to the -crate. If this is a transitive dependency, that is, one on which Chromium -code should not directly depend, also add `allow-first-party-usage=false`. -There are several examples already in that file: +crate. If this is a transitive dependency, that is, one on which Chromium code +should not directly depend, also add `allow-first-party-usage=false`. There are +several examples already in that file: ```toml [crate.unicode-linebreak] allow-first-party-usage = false -build-script-outputs = [ "tables.rs" ] +build-script-outputs = ["tables.rs"] ``` Now rerun [`gnrt.py -- gen`][2] to regenerate `BUILD.gn` files to inform ninja that this particular output file is input to subsequent build steps. - [1]: ../configuring-gnrt-config-toml.md -[2]: ../generating-gn-build-rules.md \ No newline at end of file +[2]: ../generating-gn-build-rules.md diff --git a/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md b/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md index ed9adcc..e2b2e25 100644 --- a/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +++ b/src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md @@ -1,19 +1,19 @@ # Build Scripts Which Build C++ or Take Arbitrary Actions -Some crates use the [`cc`][1] crate to build and link C/C++ libraries. -Other crates parse C/C++ using [`bindgen`][2] within their build scripts. -These actions can't be supported in a Chromium context --- our gn, ninja -and LLVM build system is very specific in expressing relationships between -build actions. +Some crates use the [`cc`][1] crate to build and link C/C++ libraries. Other +crates parse C/C++ using [`bindgen`][2] within their build scripts. These +actions can't be supported in a Chromium context --- our gn, ninja and LLVM +build system is very specific in expressing relationships between build actions. So, your options are: -* Avoid these crates -* Apply a patch to the crate. +- Avoid these crates +- Apply a patch to the crate. -Patches should be kept in `third_party/rust/chromium_crates_io/patches/` - -see for example the [patches against the `cxx` crate][3] - and will be applied -automatically by `gnrt` each time it upgrades the crate. +Patches should be kept in +`third_party/rust/chromium_crates_io/patches/` - see for example the +[patches against the `cxx` crate][3] - and will be applied automatically by +`gnrt` each time it upgrades the crate. [1]: https://crates.io/crates/cc [2]: https://crates.io/crates/bindgen diff --git a/src/chromium/adding-third-party-crates/reviews-and-audits.md b/src/chromium/adding-third-party-crates/reviews-and-audits.md index 26b9252..b2d548b 100644 --- a/src/chromium/adding-third-party-crates/reviews-and-audits.md +++ b/src/chromium/adding-third-party-crates/reviews-and-audits.md @@ -1,28 +1,28 @@ # Auditing Third Party Crates Adding new libraries is subject to Chromium's standard [policies][0], but of -course also subject to security review. As you may be bringing in not just a single -crate but also transitive dependencies, there may be a lot of code to review. -On the other hand, safe Rust code can have limited negative side effects. -How should you review it? +course also subject to security review. As you may be bringing in not just a +single crate but also transitive dependencies, there may be a lot of code to +review. On the other hand, safe Rust code can have limited negative side +effects. How should you review it? Over time Chromium aims to move to a process based around [cargo vet][1]. Meanwhile, for each new crate addition, we are checking for the following: -* Understand why each crate is used. What's the relationship between crates? - If the build system for each crate contains a `build.rs` or procedural - macros, work out what they're for. Are they compatible with the way - Chromium is normally built? -* Check each crate seems to be reasonably well maintained -* Use `cd third-party/rust/chromium_crates_io; cargo audit` to check for - known vulnerabilities (first you'll need to `cargo install cargo-audit`, - which ironically involves downloading lots of dependencies from the internet[2]) -* Ensure any `unsafe` code is good enough for the [Rule of Two][3] -* Check for any use of `fs` or `net` APIs -* Read all the code at a sufficient level to look for anything out of place - that might have been maliciously inserted. (You can't realistically aim - for 100% perfection here: there's often just too much code.) +- Understand why each crate is used. What's the relationship between crates? If + the build system for each crate contains a `build.rs` or procedural macros, + work out what they're for. Are they compatible with the way Chromium is + normally built? +- Check each crate seems to be reasonably well maintained +- Use `cd third-party/rust/chromium_crates_io; cargo audit` to check for known + vulnerabilities (first you'll need to `cargo install cargo-audit`, which + ironically involves downloading lots of dependencies from the internet[2]) +- Ensure any `unsafe` code is good enough for the [Rule of Two][3] +- Check for any use of `fs` or `net` APIs +- Read all the code at a sufficient level to look for anything out of place that + might have been maliciously inserted. (You can't realistically aim for 100% + perfection here: there's often just too much code.) These are just guidelines --- work with reviewers from `security@chromium.org` to work out the right way to become confident of the crate. diff --git a/src/chromium/build-rules.md b/src/chromium/build-rules.md index 8b31ffa..79f7bc7 100644 --- a/src/chromium/build-rules.md +++ b/src/chromium/build-rules.md @@ -1,7 +1,8 @@ # Build rules Rust code is usually built using `cargo`. Chromium builds with `gn` and `ninja` -for efficiency --- its static rules allow maximum parallelism. Rust is no exception. +for efficiency --- its static rules allow maximum parallelism. Rust is no +exception. ## Adding Rust code to Chromium @@ -16,24 +17,24 @@ rust_static_library("my_rust_lib") { } ``` -You can also add `deps` on other Rust targets. Later we'll use this to -depend upon third party code. +You can also add `deps` on other Rust targets. Later we'll use this to depend +upon third party code.
-You must specify _both_ the crate root, _and_ a full list of sources. -The `crate_root` is the file given to the Rust compiler representing the root -file of the compilation unit --- typically `lib.rs`. `sources` is a complete -list of all source files which `ninja` needs in order to determine when rebuilds -are necessary. +You must specify _both_ the crate root, _and_ a full list of sources. The +`crate_root` is the file given to the Rust compiler representing the root file +of the compilation unit --- typically `lib.rs`. `sources` is a complete list of +all source files which `ninja` needs in order to determine when rebuilds are +necessary. -(There's no such thing as a Rust `source_set`, because in Rust, an entire -crate is a compilation unit. A `static_library` is the smallest unit.) +(There's no such thing as a Rust `source_set`, because in Rust, an entire crate +is a compilation unit. A `static_library` is the smallest unit.) Students might be wondering why we need a gn template, rather than using -[gn's built-in support for Rust static libraries][0]. -The answer is that this template provides support for CXX interop, Rust features, -and unit tests, some of which we'll use later. +[gn's built-in support for Rust static libraries][0]. The answer is that this +template provides support for CXX interop, Rust features, and unit tests, some +of which we'll use later.
diff --git a/src/chromium/build-rules/depending.md b/src/chromium/build-rules/depending.md index e2dba5f..392c8df 100644 --- a/src/chromium/build-rules/depending.md +++ b/src/chromium/build-rules/depending.md @@ -19,4 +19,4 @@ component("preexisting_cpp") {
We'll see that this relationship only works if the Rust code exposes plain C APIs which can be called from C++, or if we use a C++/Rust interop tool. -
\ No newline at end of file +
diff --git a/src/chromium/build-rules/unsafe.md b/src/chromium/build-rules/unsafe.md index 85cf28a..190e123 100644 --- a/src/chromium/build-rules/unsafe.md +++ b/src/chromium/build-rules/unsafe.md @@ -1,8 +1,8 @@ # Including `unsafe` Rust Code Unsafe Rust code is forbidden in `rust_static_library` by default --- it won't -compile. If you need unsafe Rust code, add `allow_unsafe = true` to the -gn target. (Later in the course we'll see circumstances where this is necessary.) +compile. If you need unsafe Rust code, add `allow_unsafe = true` to the gn +target. (Later in the course we'll see circumstances where this is necessary.) ```gn import("//build/rust/rust_static_library.gni") @@ -15,3 +15,4 @@ rust_static_library("my_rust_lib") { ] allow_unsafe = true } +``` diff --git a/src/chromium/build-rules/vscode.md b/src/chromium/build-rules/vscode.md index b5d68d7..73363dc 100644 --- a/src/chromium/build-rules/vscode.md +++ b/src/chromium/build-rules/vscode.md @@ -1,34 +1,35 @@ # Visual Studio Code -Types are elided in Rust code, which makes a good IDE even more useful than -for C++. Visual Studio code works well for Rust in Chromium. To use it, +Types are elided in Rust code, which makes a good IDE even more useful than for +C++. Visual Studio code works well for Rust in Chromium. To use it, -* Ensure your VSCode has the `rust-analyzer` extension, not earlier forms - of Rust support -* `gn gen out/Debug --export-rust-project` (or equivalent for your output +- Ensure your VSCode has the `rust-analyzer` extension, not earlier forms of + Rust support +- `gn gen out/Debug --export-rust-project` (or equivalent for your output directory) -* `ln -s out/Debug/rust-project.json rust-project.json` +- `ln -s out/Debug/rust-project.json rust-project.json` Example screenshot from VSCode
-A demo of some of the code annotation and exploration features of rust-analyzer might be -beneficial if the audience are naturally skeptical of IDEs. +A demo of some of the code annotation and exploration features of rust-analyzer +might be beneficial if the audience are naturally skeptical of IDEs. The following steps may help with the demo (but feel free to instead use a piece of Chromium-related Rust that you are most familiar with): -* Open `components/qr_code_generator/qr_code_generator_ffi_glue.rs` -* Place the cursor over the `QrCode::new` call (around line 26) in +- Open `components/qr_code_generator/qr_code_generator_ffi_glue.rs` +- Place the cursor over the `QrCode::new` call (around line 26) in `qr_code_generator_ffi_glue.rs -* Demo **show documentation** (typical bindings: vscode = ctrl k i; vim/CoC = K). -* Demo **go to definition** (typical bindings: vscode = F12; vim/CoC = g d). +- Demo **show documentation** (typical bindings: vscode = ctrl k i; vim/CoC = + K). +- Demo **go to definition** (typical bindings: vscode = F12; vim/CoC = g d). (This will take you to `//third_party/rust/.../qr_code-.../src/lib.rs`.) -* Demo **outline** and navigate to the `QrCode::with_bits` method (around line +- Demo **outline** and navigate to the `QrCode::with_bits` method (around line 164; the outline is in the file explorer pane in vscode; typical vim/CoC bindings = space o) -* Demo **type annotations** (there are quote a few nice examples in the +- Demo **type annotations** (there are quote a few nice examples in the `QrCode::with_bits` method) It may be worth pointing out that `gn gen ... --export-rust-project` will need diff --git a/src/chromium/cargo.md b/src/chromium/cargo.md index 8460727..c0bd7c6 100644 --- a/src/chromium/cargo.md +++ b/src/chromium/cargo.md @@ -5,59 +5,61 @@ Chromium is built using `gn` and `ninja` and a curated set of dependencies. When writing code in Rust, your choices are: -* Use `gn` and `ninja` with the help of the templates from `//build/rust/*.gni` - (e.g. `rust_static_library` that we'll meet later). - This uses Chromium's audited toolchain and crates. -* Use `cargo`, but [restrict yourself to Chromium's audited toolchain and crates][0] -* Use `cargo`, trusting a [toolchain][1] and/or [crates downloaded from the internet][2] +- Use `gn` and `ninja` with the help of the templates from `//build/rust/*.gni` + (e.g. `rust_static_library` that we'll meet later). This uses Chromium's + audited toolchain and crates. +- Use `cargo`, but + [restrict yourself to Chromium's audited toolchain and crates][0] +- Use `cargo`, trusting a [toolchain][1] and/or + [crates downloaded from the internet][2] From here on we'll be focusing on `gn` and `ninja`, because this is how Rust -code can be built into the Chromium browser. At the same time, Cargo is an +code can be built into the Chromium browser. At the same time, Cargo is an important part of the Rust ecosystem and you should keep it in your toolbox. ## Mini exercise Split into small groups and: -* Brainstorm scenarios where `cargo` may offer an advantage - and assess the risk profile of these scenarios. -* Discuss which tools, libraries, and groups of people need to be trusted - when using `gn` and `ninja`, offline `cargo`, etc. +- Brainstorm scenarios where `cargo` may offer an advantage and assess the risk + profile of these scenarios. +- Discuss which tools, libraries, and groups of people need to be trusted when + using `gn` and `ninja`, offline `cargo`, etc.
Ask students to avoid peeking at the speaker notes before completing the -exercise. Assuming folks taking the course are physically together, ask them to +exercise. Assuming folks taking the course are physically together, ask them to discuss in small groups of 3-4 people. Notes/hints related to the first part of the exercise ("scenarios where Cargo may offer an advantage"): -* It's fantastic that when writing a tool, or prototyping a part of Chromium, - one has access to the rich ecosystem of crates.io libraries. There is a - crate for almost anything and they are usually quite pleasant to use. - (`clap` for command-line parsing, `serde` for serializing/deserializing - to/from various formats, `itertools` for working with iterators, etc.). +- It's fantastic that when writing a tool, or prototyping a part of Chromium, + one has access to the rich ecosystem of crates.io libraries. There is a crate + for almost anything and they are usually quite pleasant to use. (`clap` for + command-line parsing, `serde` for serializing/deserializing to/from various + formats, `itertools` for working with iterators, etc.). - `cargo` makes it easy to try a library (just add a single line to `Cargo.toml` and start writing code) - - It may be worth comparing how CPAN helped make `perl` a popular choice. - Or comparing with `python` + `pip`. + - It may be worth comparing how CPAN helped make `perl` a popular choice. Or + comparing with `python` + `pip`. -* Development experience is made really nice not only by core Rust tools (e.g. +- Development experience is made really nice not only by core Rust tools (e.g. using `rustup` to switch to a different `rustc` version when testing a crate that needs to work on nightly, current stable, and older stable) but also by an ecosystem of third-party tools (e.g. Mozilla provides `cargo vet` for - streamlining and sharing security audits; `criterion` crate gives a + streamlining and sharing security audits; `criterion` crate gives a streamlined way to run benchmarks). - `cargo` makes it easy to add a tool via `cargo install --locked cargo-vet`. - It may be worth comparing with Chrome Extensions or VScode extensions. -* Broad, generic examples of projects where `cargo` may be the right choice: +- Broad, generic examples of projects where `cargo` may be the right choice: - Perhaps surprisingly, Rust is becoming increasingly popular in the industry - for writing command line tools. The breadth and ergonomics of libraries is + for writing command line tools. The breadth and ergonomics of libraries is comparable to Python, while being more robust (thanks to the rich typesystem) and running faster (as a compiled, rather than interpreted language). @@ -66,7 +68,7 @@ may offer an advantage"): used outside of Chromium (e.g. in Bazel or Android/Soong build environments) should probably use Cargo. -* Examples of Chromium-related projects that are `cargo`-based: +- Examples of Chromium-related projects that are `cargo`-based: - `serde_json_lenient` (experimented with in other parts of Google which resulted in PRs with performance improvements) - Fontations libraries like `font-types` @@ -82,18 +84,18 @@ may offer an advantage"): Students may identify the following items as being implicitly or explicitly trusted: -* `rustc` (the Rust compiler) which in turn depends on the LLVM libraries, the +- `rustc` (the Rust compiler) which in turn depends on the LLVM libraries, the Clang compiler, the `rustc` sources (fetched from GitHub, reviewed by Rust compiler team), binary Rust compiler downloaded for bootstrapping -* `rustup` (it may be worth pointing out that `rustup` is developed under the +- `rustup` (it may be worth pointing out that `rustup` is developed under the umbrella of the https://github.com/rust-lang/ organization - same as `rustc`) -* `cargo`, `rustfmt`, etc. -* Various internal infrastructure (bots that build `rustc`, system for +- `cargo`, `rustfmt`, etc. +- Various internal infrastructure (bots that build `rustc`, system for distributing the prebuilt toolchain to Chromium engineers, etc.) -* Cargo tools like `cargo audit`, `cargo vet`, etc. -* Rust libraries vendored into `//third_party/rust` (audited by +- Cargo tools like `cargo audit`, `cargo vet`, etc. +- Rust libraries vendored into `//third_party/rust` (audited by security@chromium.org) -* Other Rust libraries (some niche, some quite popular and commonly used) +- Other Rust libraries (some niche, some quite popular and commonly used)
diff --git a/src/chromium/interoperability-with-cpp.md b/src/chromium/interoperability-with-cpp.md index 36bf0ad..7940b09 100644 --- a/src/chromium/interoperability-with-cpp.md +++ b/src/chromium/interoperability-with-cpp.md @@ -11,40 +11,36 @@ functions and types in both Rust and C++. See the [CXX tutorial][1] for a full example of using this. - [1]: https://cxx.rs/tutorial.html [2]: https://cxx.rs/bindings.html -
-Talk through the diagram. Explain that behind the scenes, this is doing -just the same as you previously did. Point out that automating the process has -the following benefits: - -* The tool guarantees that the C++ and Rust sides match - (e.g. you get compile errors if the `#[cxx::bridge]` doesn't match the actual - C++ or Rust definitions, but with out-of-sync manual bindings you'd get - Undefined Behavior) -* The tool automates generation of FFI thunks (small, C-ABI-compatible, free - functions) for non-C features - (e.g. enabling FFI calls into Rust or C++ methods; - manual bindings would require authoring such top-level, free functions - manually) -* The tool and the library can handle a set of core types - for example: - - `&[T]` can be passed across the FFI boundary, even though it doesn't - guarantee any particular ABI or memory layout. With manual bindings - `std::span` / `&[T]` have to be manually destructured and rebuilt out - of a pointer and length - this is error-prone given that each language - represents empty slices slightly differently) - - Smart pointers like `std::unique_ptr`, - `std::shared_ptr`, and/or `Box` are natively supported. With manual - bindings, one would have to pass C-ABI-compatible raw pointers, which - would increase lifetime and memory-safety risks. - - `rust::String` and `CxxString` types understand and maintain differences - in string representation across the languages (e.g. `rust::String::lossy` - can build a Rust string from non-UTF8 input and `rust::String::c_str` - can NUL-terminate a string). +Talk through the diagram. Explain that behind the scenes, this is doing just the +same as you previously did. Point out that automating the process has the +following benefits: + +- The tool guarantees that the C++ and Rust sides match (e.g. you get compile + errors if the `#[cxx::bridge]` doesn't match the actual C++ or Rust + definitions, but with out-of-sync manual bindings you'd get Undefined + Behavior) +- The tool automates generation of FFI thunks (small, C-ABI-compatible, free + functions) for non-C features (e.g. enabling FFI calls into Rust or C++ + methods; manual bindings would require authoring such top-level, free + functions manually) +- The tool and the library can handle a set of core types - for example: + - `&[T]` can be passed across the FFI boundary, even though it doesn't + guarantee any particular ABI or memory layout. With manual bindings + `std::span` / `&[T]` have to be manually destructured and rebuilt out of + a pointer and length - this is error-prone given that each language + represents empty slices slightly differently) + - Smart pointers like `std::unique_ptr`, `std::shared_ptr`, and/or `Box` + are natively supported. With manual bindings, one would have to pass + C-ABI-compatible raw pointers, which would increase lifetime and + memory-safety risks. + - `rust::String` and `CxxString` types understand and maintain differences in + string representation across the languages (e.g. `rust::String::lossy` can + build a Rust string from non-UTF8 input and `rust::String::c_str` can + NUL-terminate a string).
- diff --git a/src/chromium/interoperability-with-cpp/error-handling-png.md b/src/chromium/interoperability-with-cpp/error-handling-png.md index c8f350c..81895de 100644 --- a/src/chromium/interoperability-with-cpp/error-handling-png.md +++ b/src/chromium/interoperability-with-cpp/error-handling-png.md @@ -7,7 +7,8 @@ result cannot be passed across the FFI boundary: #[cxx::bridge(namespace = "gfx::rust_bindings")] mod ffi { extern "Rust" { - /// This returns an FFI-friendly equivalent of `Result, ()>`. + /// This returns an FFI-friendly equivalent of `Result, + /// ()>`. fn new_png_reader<'a>(input: &'a [u8]) -> Box>; /// C++ bindings for the `crate::png::ResultOfPngReader` type. @@ -29,15 +30,14 @@ mod ffi {
`PngReader` and `ResultOfPngReader` are Rust types --- objects of these types -cannot cross the FFI boundary without indirection of a `Box`. We can't have +cannot cross the FFI boundary without indirection of a `Box`. We can't have an `out_parameter: &mut PngReader`, because CXX doesn't allow C++ to store Rust objects by value. This example illustrates that even though CXX doesn't support arbitrary generics nor templates, we can still pass them across the FFI boundary by manually -specializing / monomorphizing them into a non-generic type. In the example +specializing / monomorphizing them into a non-generic type. In the example `ResultOfPngReader` is a non-generic type that forwards into appropriate methods of `Result` (e.g. into `is_err`, `unwrap`, and/or `as_mut`).
- diff --git a/src/chromium/interoperability-with-cpp/error-handling-qr.md b/src/chromium/interoperability-with-cpp/error-handling-qr.md index d741850..cecf573 100644 --- a/src/chromium/interoperability-with-cpp/error-handling-qr.md +++ b/src/chromium/interoperability-with-cpp/error-handling-qr.md @@ -20,12 +20,12 @@ mod ffi {
-Students may be curious about the semantics of the `out_qr_size` output. This -is not the size of the vector, but the size of the QR code (and admittedly it is -a bit redundant - this is the square root of the size of the vector). +Students may be curious about the semantics of the `out_qr_size` output. This is +not the size of the vector, but the size of the QR code (and admittedly it is a +bit redundant - this is the square root of the size of the vector). It may be worth pointing out the importance of initializing `out_qr_size` before -calling into the Rust function. Creation of a Rust reference that points to +calling into the Rust function. Creation of a Rust reference that points to uninitialized memory results in Undefined Behavior (unlike in C++, when only the act of dereferencing such memory results in UB). @@ -36,4 +36,3 @@ Rust data, because it may contain self-referential pointers.
[0]: https://source.chromium.org/chromium/chromium/src/+/main:components/qr_code_generator/qr_code_generator_ffi_glue.rs;l=13-18;drc=7bf1b75b910ca430501b9c6a74c1d18a0223ecca - diff --git a/src/chromium/interoperability-with-cpp/error-handling.md b/src/chromium/interoperability-with-cpp/error-handling.md index 3f7fe22..00bcba5 100644 --- a/src/chromium/interoperability-with-cpp/error-handling.md +++ b/src/chromium/interoperability-with-cpp/error-handling.md @@ -3,20 +3,20 @@ CXX's [support for `Result`][0] relies on C++ exceptions, so we can't use that in Chromium. Alternatives: -* The `T` part of `Result` can be: - - Returned via out parameters (e.g. via `&mut T`). This requires that `T` - can be passed across the FFI boundary - for example `T` has to be: - - A primitive type (like `u32` or `usize`) - - A type natively supported by `cxx` (like `UniquePtr`) that has a - suitable default value to use in a failure case (*unlike* `Box`). - - Retained on the Rust side, and exposed via reference. This may be needed - when `T` is a Rust type, which cannot be passed across the FFI boundary, - and cannot be stored in `UniquePtr`. +- The `T` part of `Result` can be: + - Returned via out parameters (e.g. via `&mut T`). This requires that `T` can + be passed across the FFI boundary - for example `T` has to be: + - A primitive type (like `u32` or `usize`) + - A type natively supported by `cxx` (like `UniquePtr`) that has a + suitable default value to use in a failure case (_unlike_ `Box`). + - Retained on the Rust side, and exposed via reference. This may be needed + when `T` is a Rust type, which cannot be passed across the FFI boundary, and + cannot be stored in `UniquePtr`. -* The `E` part of `Result` can be: - - Returned as a boolean (e.g. `true` representing success, and `false` - representing failure) - - Preserving error details is in theory possible, but so far hasn't been - needed in practice. +- The `E` part of `Result` can be: + - Returned as a boolean (e.g. `true` representing success, and `false` + representing failure) + - Preserving error details is in theory possible, but so far hasn't been + needed in practice. [0]: https://cxx.rs/binding/result.html diff --git a/src/chromium/interoperability-with-cpp/example-bindings.md b/src/chromium/interoperability-with-cpp/example-bindings.md index cf0a01e..006eb9b 100644 --- a/src/chromium/interoperability-with-cpp/example-bindings.md +++ b/src/chromium/interoperability-with-cpp/example-bindings.md @@ -11,14 +11,14 @@ modules inside `.rs` source code. Point out: -* Although this looks like a regular Rust `mod`, the `#[cxx::bridge]` - procedural macro does complex things to it. The generated code is quite - a bit more sophisticated - though this does still result in a `mod` called - `ffi` in your code. -* Native support for C++'s `std::unique_ptr` in Rust -* Native support for Rust slices in C++ -* Calls from C++ to Rust, and Rust types (in the top part) -* Calls from Rust to C++, and C++ types (in the bottom part) +- Although this looks like a regular Rust `mod`, the `#[cxx::bridge]` procedural + macro does complex things to it. The generated code is quite a bit more + sophisticated - though this does still result in a `mod` called `ffi` in your + code. +- Native support for C++'s `std::unique_ptr` in Rust +- Native support for Rust slices in C++ +- Calls from C++ to Rust, and Rust types (in the top part) +- Calls from Rust to C++, and C++ types (in the bottom part) **Common misconception**: It _looks_ like a C++ header is being parsed by Rust, but this is misleading. This header is never interpreted by Rust, but simply diff --git a/src/chromium/interoperability-with-cpp/limitations-of-cxx.md b/src/chromium/interoperability-with-cpp/limitations-of-cxx.md index 04e251c..031e5c7 100644 --- a/src/chromium/interoperability-with-cpp/limitations-of-cxx.md +++ b/src/chromium/interoperability-with-cpp/limitations-of-cxx.md @@ -4,18 +4,18 @@ By far the most useful page when using CXX is the [type reference][1]. CXX fundamentally suits cases where: -* Your Rust-C++ interface is sufficiently simple that you can declare all of it. -* You're using only the types natively supported by CXX already, for example +- Your Rust-C++ interface is sufficiently simple that you can declare all of it. +- You're using only the types natively supported by CXX already, for example `std::unique_ptr`, `std::string`, `&[u8]` etc. -It has many limitations --- for example lack of support for Rust's `Option` type. +It has many limitations --- for example lack of support for Rust's `Option` +type. These limitations constrain us to using Rust in Chromium only for well isolated -"leaf nodes" rather than for arbitrary Rust-C++ interop. When considering -a use-case for Rust in Chromium, a good starting point is to draft the CXX +"leaf nodes" rather than for arbitrary Rust-C++ interop. When considering a +use-case for Rust in Chromium, a good starting point is to draft the CXX bindings for the language boundary to see if it appears simple enough. - [1]: https://cxx.rs/bindings.html
@@ -25,7 +25,7 @@ reason to restrict Rust to use in leaf nodes. You should also discuss some of the other sticky points with CXX, for example: -* Its error handling is based around C++ exceptions (given on the next slide) -* Function pointers are awkward to use. +- Its error handling is based around C++ exceptions (given on the next slide) +- Function pointers are awkward to use.
diff --git a/src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md b/src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md index eb0dec8..a932a78 100644 --- a/src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +++ b/src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md @@ -19,8 +19,8 @@ C++ headers will be generated at a sensible location, so you can just #include "ui/base/my_rust_file.rs.h" ``` -You will find some utility functions in `//base` to convert to/from Chromium -C++ types to CXX Rust types --- for example [`SpanToRustSlice`][0]. +You will find some utility functions in `//base` to convert to/from Chromium C++ +types to CXX Rust types --- for example [`SpanToRustSlice`][0].
@@ -29,16 +29,16 @@ Students may ask --- why do we still need `allow_unsafe = true`? The broad answer is that no C/C++ code is "safe" by the normal Rust standards. Calling back and forth to C/C++ from Rust may do arbitrary things to memory, and compromise the safety of Rust's own data layouts. Presence of _too many_ -`unsafe` keywords in C/C++ interop can harm the signal-to-noise ratio of -such a keyword, and is [controversial][1], but strictly, bringing any foreign -code into a Rust binary can cause unexpected behavior from Rust's perspective. +`unsafe` keywords in C/C++ interop can harm the signal-to-noise ratio of such a +keyword, and is [controversial][1], but strictly, bringing any foreign code into +a Rust binary can cause unexpected behavior from Rust's perspective. -The narrow answer lies in the diagram at the top of [this page][2] --- behind the -scenes, CXX generates Rust `unsafe` and `extern "C"` functions just like -we did manually in the previous section. +The narrow answer lies in the diagram at the top of [this page][2] --- behind +the scenes, CXX generates Rust `unsafe` and `extern "C"` functions just like we +did manually in the previous section.
[0]: https://source.chromium.org/chromium/chromium/src/+/main:base/containers/span_rust.h;l=21 [1]: https://steveklabnik.com/writing/the-cxx-debate -[2]: ../interoperability-with-cpp.md \ No newline at end of file +[2]: ../interoperability-with-cpp.md diff --git a/src/chromium/policy.md b/src/chromium/policy.md index 8cd0960..a08c5a9 100644 --- a/src/chromium/policy.md +++ b/src/chromium/policy.md @@ -1,9 +1,11 @@ # Chromium Rust policy -Chromium does not yet allow first-party Rust except in rare cases as approved -by Chromium's [Area Tech Leads](https://source.chromium.org/chromium/chromium/src/+/main:ATL_OWNERS). +Chromium does not yet allow first-party Rust except in rare cases as approved by +Chromium's +[Area Tech Leads](https://source.chromium.org/chromium/chromium/src/+/main:ATL_OWNERS). -Chromium's policy on third party libraries is outlined [here](https://chromium.googlesource.com/chromium/src/+/main/docs/adding_to_third_party.md#rust) - +Chromium's policy on third party libraries is outlined +[here](https://chromium.googlesource.com/chromium/src/+/main/docs/adding_to_third_party.md#rust) - Rust is allowed for third party libraries under various circumstances, including if they're the best option for performance or for security. @@ -25,13 +27,12 @@ all such libraries will require a small amount of first-party glue code. `- - - - - - - - - -' `- - - - - - - - - - - - - - - - - - - - - - -' ``` -> First-party Rust glue code for a particular third-party crate should -> normally be kept in `third_party/rust///wrapper`. +> First-party Rust glue code for a particular third-party crate should normally +> be kept in `third_party/rust///wrapper`. Because of this, today's course will be heavily focused on: -* Bringing in third-party Rust libraries ("crates") -* Writing glue code to be able to use those crates from Chromium C++. +- Bringing in third-party Rust libraries ("crates") +- Writing glue code to be able to use those crates from Chromium C++. If this policy changes over time, the course will evolve to keep up. - diff --git a/src/chromium/setup.md b/src/chromium/setup.md index e1dcaab..19215ef 100644 --- a/src/chromium/setup.md +++ b/src/chromium/setup.md @@ -10,10 +10,11 @@ autoninja -C out/Debug chrome out/Debug/chrome # or on Mac, out/Debug/Chromium.app/Contents/MacOS/Chromium ``` -(A component, debug build is recommended for quickest iteration time. This -is the default!) +(A component, debug build is recommended for quickest iteration time. This is +the default!) -See [How to build Chromium](https://www.chromium.org/developers/how-tos/get-the-code/) +See +[How to build Chromium](https://www.chromium.org/developers/how-tos/get-the-code/) if you aren't already at that point. Be warned: setting up to build Chromium takes time. @@ -22,6 +23,6 @@ It's also recommended that you have Visual Studio code installed. # About the exercises This part of the course has a series of exercises which build on each other. -We'll be doing them spread throughout the course instead of just at the end. -If you don't have time to complete a certain part, don't worry: you can -catch up in the next slot. +We'll be doing them spread throughout the course instead of just at the end. If +you don't have time to complete a certain part, don't worry: you can catch up in +the next slot. diff --git a/src/chromium/testing.md b/src/chromium/testing.md index 103a372..a57e236 100644 --- a/src/chromium/testing.md +++ b/src/chromium/testing.md @@ -1,14 +1,16 @@ # Testing Rust community typically authors unit tests in a module placed in the same -source file as the code being tested. This was covered -[earlier](../testing.md) in the course and looks like this: +source file as the code being tested. This was covered [earlier](../testing.md) +in the course and looks like this: ```rust #[cfg(test)] mod tests { #[test] - fn my_test() { todo!() } + fn my_test() { + todo!() + } } ``` @@ -19,33 +21,32 @@ configuration). This results in the following options for testing Rust code in Chromium: -* Native Rust tests (i.e. `#[test]`). - Discouraged outside of `//third_party/rust`. -* `gtest` tests authored in C++ and exercising Rust via FFI calls. Sufficient +- Native Rust tests (i.e. `#[test]`). Discouraged outside of + `//third_party/rust`. +- `gtest` tests authored in C++ and exercising Rust via FFI calls. Sufficient when Rust code is just a thin FFI layer and the existing unit tests provide sufficient coverage for the feature. -* `gtest` tests authored in Rust and using the crate under test through its - public API (using `pub mod for_testing { ... }` if needed). This is the +- `gtest` tests authored in Rust and using the crate under test through its + public API (using `pub mod for_testing { ... }` if needed). This is the subject of the next few slides.
Mention that native Rust tests of third-party crates should eventually be -exercised by Chromium bots. (Such testing is needed rarely --- only after -adding or updating third-party crates.) +exercised by Chromium bots. (Such testing is needed rarely --- only after adding +or updating third-party crates.) Some examples may help illustrate when C++ `gtest` vs Rust `gtest` should be used: -* QR has very little functionality in the first-party Rust layer (it's just a - thin FFI glue) and therefore uses the existing C++ unit tests for testing - both the C++ and the Rust implementation (parameterizing the tests so they - enable or disable Rust using a `ScopedFeatureList`). +- QR has very little functionality in the first-party Rust layer (it's just a + thin FFI glue) and therefore uses the existing C++ unit tests for testing both + the C++ and the Rust implementation (parameterizing the tests so they enable + or disable Rust using a `ScopedFeatureList`). -* Hypothetical/WIP PNG integration may need to implement memory-safe - implementation of pixel transformations that are provided by `libpng` - but missing in the `png` crate - e.g. RGBA => BGRA, or gamma correction. - Such functionality may benefit from separate tests authored in Rust. +- Hypothetical/WIP PNG integration may need to implement memory-safe + implementation of pixel transformations that are provided by `libpng` but + missing in the `png` crate - e.g. RGBA => BGRA, or gamma correction. Such + functionality may benefit from separate tests authored in Rust.
- diff --git a/src/chromium/testing/chromium-import-macro.md b/src/chromium/testing/chromium-import-macro.md index bfdff61..ec3e6e4 100644 --- a/src/chromium/testing/chromium-import-macro.md +++ b/src/chromium/testing/chromium-import-macro.md @@ -1,7 +1,7 @@ # `chromium::import!` Macro After adding `:my_rust_lib` to GN `deps`, we still need to learn how to import -and use `my_rust_lib` from `my_rust_lib_unittest.rs`. We haven't provided an +and use `my_rust_lib` from `my_rust_lib_unittest.rs`. We haven't provided an explicit `crate_name` for `my_rust_lib` so its crate name is computed based on the full target path and name. Fortunately we can avoid working with such an unwieldy name by using the `chromium::import!` macro from the @@ -29,12 +29,11 @@ macro.
`rust_static_library` supports specifying an explicit name via `crate_name` -property, but doing this is discouraged. And it is discouraged because -the crate name has to be globally unique. crates.io guarantees uniqueness -of its crate names so `cargo_crate` GN targets (generated by the `gnrt` -tool covered in a later section) use short crate names. +property, but doing this is discouraged. And it is discouraged because the crate +name has to be globally unique. crates.io guarantees uniqueness of its crate +names so `cargo_crate` GN targets (generated by the `gnrt` tool covered in a +later section) use short crate names.
- [0]: https://source.chromium.org/chromium/chromium/src/+/main:build/rust/chromium_prelude/chromium_prelude.rs?q=f:chromium_prelude.rs%20pub.use.*%5Cbimport%5Cb;%20-f:third_party&ss=chromium%2Fchromium%2Fsrc diff --git a/src/chromium/testing/rust-gtest-interop.md b/src/chromium/testing/rust-gtest-interop.md index e2a942d..e8ac7bc 100644 --- a/src/chromium/testing/rust-gtest-interop.md +++ b/src/chromium/testing/rust-gtest-interop.md @@ -2,10 +2,10 @@ The [`rust_gtest_interop`][0] library provides a way to: -* Use a Rust function as a `gtest` testcase - (using the `#[gtest(...)]` attribute) -* Use `expect_eq!` and similar macros (similar to `assert_eq!` but not - panicking and not terminating the test when the assertion fails). +- Use a Rust function as a `gtest` testcase (using the `#[gtest(...)]` + attribute) +- Use `expect_eq!` and similar macros (similar to `assert_eq!` but not panicking + and not terminating the test when the assertion fails). Example: diff --git a/src/concurrency.md b/src/concurrency.md index 4567d51..de68097 100644 --- a/src/concurrency.md +++ b/src/concurrency.md @@ -2,6 +2,7 @@ course: Concurrency session: Morning --- + # Welcome to Concurrency in Rust Rust has full support for concurrency using OS threads with mutexes and diff --git a/src/concurrency/channels.md b/src/concurrency/channels.md index 09ebb30..b9c8603 100644 --- a/src/concurrency/channels.md +++ b/src/concurrency/channels.md @@ -23,9 +23,10 @@ fn main() {
-* `mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` implement `Clone` (so - you can make multiple producers) but `Receiver` does not. -* `send()` and `recv()` return `Result`. If they return `Err`, it means the counterpart `Sender` or - `Receiver` is dropped and the channel is closed. +- `mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` + implement `Clone` (so you can make multiple producers) but `Receiver` does + not. +- `send()` and `recv()` return `Result`. If they return `Err`, it means the + counterpart `Sender` or `Receiver` is dropped and the channel is closed.
diff --git a/src/concurrency/channels/bounded.md b/src/concurrency/channels/bounded.md index ca919ad..83eec86 100644 --- a/src/concurrency/channels/bounded.md +++ b/src/concurrency/channels/bounded.md @@ -27,9 +27,13 @@ fn main() { ```
- -* Calling `send` will block the current thread until there is space in the channel for the new message. The thread can be blocked indefinitely if there is nobody who reads from the channel. -* A call to `send` will abort with an error (that is why it returns `Result`) if the channel is closed. A channel is closed when the receiver is dropped. -* A bounded channel with a size of zero is called a "rendezvous channel". Every send will block the current thread until another thread calls `read`. - + +- Calling `send` will block the current thread until there is space in the + channel for the new message. The thread can be blocked indefinitely if there + is nobody who reads from the channel. +- A call to `send` will abort with an error (that is why it returns `Result`) if + the channel is closed. A channel is closed when the receiver is dropped. +- A bounded channel with a size of zero is called a "rendezvous channel". Every + send will block the current thread until another thread calls `read`. +
diff --git a/src/concurrency/scoped-threads.md b/src/concurrency/scoped-threads.md index 95680e0..911cb3f 100644 --- a/src/concurrency/scoped-threads.md +++ b/src/concurrency/scoped-threads.md @@ -36,8 +36,10 @@ fn main() { [1]: https://doc.rust-lang.org/std/thread/fn.scope.html
- -* The reason for that is that when the `thread::scope` function completes, all the threads are guaranteed to be joined, so they can return borrowed data. -* Normal Rust borrowing rules apply: you can either borrow mutably by one thread, or immutably by any number of threads. - + +- The reason for that is that when the `thread::scope` function completes, all + the threads are guaranteed to be joined, so they can return borrowed data. +- Normal Rust borrowing rules apply: you can either borrow mutably by one + thread, or immutably by any number of threads. +
diff --git a/src/concurrency/send-sync.md b/src/concurrency/send-sync.md index dd238f7..2883217 100644 --- a/src/concurrency/send-sync.md +++ b/src/concurrency/send-sync.md @@ -1,15 +1,16 @@ # `Send` and `Sync` -How does Rust know to forbid shared access across threads? The answer is in two traits: +How does Rust know to forbid shared access across threads? The answer is in two +traits: -* [`Send`][1]: a type `T` is `Send` if it is safe to move a `T` across a thread +- [`Send`][1]: a type `T` is `Send` if it is safe to move a `T` across a thread boundary. -* [`Sync`][2]: a type `T` is `Sync` if it is safe to move a `&T` across a thread +- [`Sync`][2]: a type `T` is `Sync` if it is safe to move a `&T` across a thread boundary. -`Send` and `Sync` are [unsafe traits][3]. The compiler will automatically derive them for your types -as long as they only contain `Send` and `Sync` types. You can also implement them manually when you -know it is valid. +`Send` and `Sync` are [unsafe traits][3]. The compiler will automatically derive +them for your types as long as they only contain `Send` and `Sync` types. You +can also implement them manually when you know it is valid. [1]: https://doc.rust-lang.org/std/marker/trait.Send.html [2]: https://doc.rust-lang.org/std/marker/trait.Sync.html @@ -17,7 +18,8 @@ know it is valid.
-* One can think of these traits as markers that the type has certain thread-safety properties. -* They can be used in the generic constraints as normal traits. - +- One can think of these traits as markers that the type has certain + thread-safety properties. +- They can be used in the generic constraints as normal traits. +
diff --git a/src/concurrency/send-sync/examples.md b/src/concurrency/send-sync/examples.md index 77f18b8..7fffa9b 100644 --- a/src/concurrency/send-sync/examples.md +++ b/src/concurrency/send-sync/examples.md @@ -4,12 +4,12 @@ Most types you come across are `Send + Sync`: -* `i8`, `f32`, `bool`, `char`, `&str`, ... -* `(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ... -* `String`, `Option`, `Vec`, `Box`, ... -* `Arc`: Explicitly thread-safe via atomic reference count. -* `Mutex`: Explicitly thread-safe via internal locking. -* `AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions. +- `i8`, `f32`, `bool`, `char`, `&str`, ... +- `(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ... +- `String`, `Option`, `Vec`, `Box`, ... +- `Arc`: Explicitly thread-safe via atomic reference count. +- `Mutex`: Explicitly thread-safe via internal locking. +- `AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions. The generic types are typically `Send + Sync` when the type parameters are `Send + Sync`. @@ -19,23 +19,23 @@ The generic types are typically `Send + Sync` when the type parameters are These types can be moved to other threads, but they're not thread-safe. Typically because of interior mutability: -* `mpsc::Sender` -* `mpsc::Receiver` -* `Cell` -* `RefCell` +- `mpsc::Sender` +- `mpsc::Receiver` +- `Cell` +- `RefCell` ## `!Send + Sync` These types are thread-safe, but they cannot be moved to another thread: -* `MutexGuard`: Uses OS level primitives which must be deallocated on the - thread which created them. +- `MutexGuard`: Uses OS level primitives which must be deallocated on + the thread which created them. ## `!Send + !Sync` These types are not thread-safe and cannot be moved to other threads: -* `Rc`: each `Rc` has a reference to an `RcBox`, which contains a +- `Rc`: each `Rc` has a reference to an `RcBox`, which contains a non-atomic reference count. -* `*const T`, `*mut T`: Rust assumes raw pointers may have special - concurrency considerations. +- `*const T`, `*mut T`: Rust assumes raw pointers may have special concurrency + considerations. diff --git a/src/concurrency/send-sync/sync.md b/src/concurrency/send-sync/sync.md index 75ca77e..ea490bc 100644 --- a/src/concurrency/send-sync/sync.md +++ b/src/concurrency/send-sync/sync.md @@ -11,8 +11,14 @@ More precisely, the definition is:
-This statement is essentially a shorthand way of saying that if a type is thread-safe for shared use, it is also thread-safe to pass references of it across threads. - -This is because if a type is Sync it means that it can be shared across multiple threads without the risk of data races or other synchronization issues, so it is safe to move it to another thread. A reference to the type is also safe to move to another thread, because the data it references can be accessed from any thread safely. +This statement is essentially a shorthand way of saying that if a type is +thread-safe for shared use, it is also thread-safe to pass references of it +across threads. + +This is because if a type is Sync it means that it can be shared across multiple +threads without the risk of data races or other synchronization issues, so it is +safe to move it to another thread. A reference to the type is also safe to move +to another thread, because the data it references can be accessed from any +thread safely.
diff --git a/src/concurrency/shared_state.md b/src/concurrency/shared_state.md index 73b5d10..de84078 100644 --- a/src/concurrency/shared_state.md +++ b/src/concurrency/shared_state.md @@ -3,9 +3,9 @@ Rust uses the type system to enforce synchronization of shared data. This is primarily done via two types: -* [`Arc`][1], atomic reference counted `T`: handles sharing between threads and - takes care to deallocate `T` when the last reference is dropped, -* [`Mutex`][2]: ensures mutually exclusive access to the `T` value. +- [`Arc`][1], atomic reference counted `T`: handles sharing between threads + and takes care to deallocate `T` when the last reference is dropped, +- [`Mutex`][2]: ensures mutually exclusive access to the `T` value. [1]: https://doc.rust-lang.org/std/sync/struct.Arc.html [2]: https://doc.rust-lang.org/std/sync/struct.Mutex.html diff --git a/src/concurrency/shared_state/arc.md b/src/concurrency/shared_state/arc.md index cdd82c5..9ec310f 100644 --- a/src/concurrency/shared_state/arc.md +++ b/src/concurrency/shared_state/arc.md @@ -3,8 +3,8 @@ [`Arc`][1] allows shared read-only access via `Arc::clone`: ```rust,editable -use std::thread; use std::sync::Arc; +use std::thread; fn main() { let v = Arc::new(vec![10, 20, 30]); @@ -26,13 +26,14 @@ fn main() {
-* `Arc` stands for "Atomic Reference Counted", a thread safe version of `Rc` that uses atomic - operations. -* `Arc` implements `Clone` whether or not `T` does. It implements `Send` and `Sync` if - and only if `T` implements them both. -* `Arc::clone()` has the cost of atomic operations that get executed, but after that the use of the - `T` is free. -* Beware of reference cycles, `Arc` does not use a garbage collector to detect them. - * `std::sync::Weak` can help. +- `Arc` stands for "Atomic Reference Counted", a thread safe version of `Rc` + that uses atomic operations. +- `Arc` implements `Clone` whether or not `T` does. It implements `Send` and + `Sync` if and only if `T` implements them both. +- `Arc::clone()` has the cost of atomic operations that get executed, but after + that the use of the `T` is free. +- Beware of reference cycles, `Arc` does not use a garbage collector to detect + them. + - `std::sync::Weak` can help.
diff --git a/src/concurrency/shared_state/example.md b/src/concurrency/shared_state/example.md index 0cbb1a7..2219b70 100644 --- a/src/concurrency/shared_state/example.md +++ b/src/concurrency/shared_state/example.md @@ -21,7 +21,7 @@ fn main() {
Possible solution: - + ```rust,editable use std::sync::{Arc, Mutex}; use std::thread; @@ -45,12 +45,16 @@ fn main() { println!("v: {v:?}"); } ``` - + Notable parts: -* `v` is wrapped in both `Arc` and `Mutex`, because their concerns are orthogonal. - * Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state between threads. -* `v: Arc<_>` needs to be cloned as `v2` before it can be moved into another thread. Note `move` was added to the lambda signature. -* Blocks are introduced to narrow the scope of the `LockGuard` as much as possible. +- `v` is wrapped in both `Arc` and `Mutex`, because their concerns are + orthogonal. + - Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state + between threads. +- `v: Arc<_>` needs to be cloned as `v2` before it can be moved into another + thread. Note `move` was added to the lambda signature. +- Blocks are introduced to narrow the scope of the `LockGuard` as much as + possible.
diff --git a/src/concurrency/shared_state/mutex.md b/src/concurrency/shared_state/mutex.md index 7bd2224..a5914bf 100644 --- a/src/concurrency/shared_state/mutex.md +++ b/src/concurrency/shared_state/mutex.md @@ -27,19 +27,22 @@ implementation. [3]: https://doc.rust-lang.org/std/sync/struct.Arc.html
- -* `Mutex` in Rust looks like a collection with just one element --- the protected data. - * It is not possible to forget to acquire the mutex before accessing the protected data. -* You can get an `&mut T` from an `&Mutex` by taking the lock. The `MutexGuard` ensures that the - `&mut T` doesn't outlive the lock being held. -* `Mutex` implements both `Send` and `Sync` iff (if and only if) `T` implements `Send`. -* A read-write lock counterpart: `RwLock`. -* Why does `lock()` return a `Result`? - * If the thread that held the `Mutex` panicked, the `Mutex` becomes "poisoned" to signal that - the data it protected might be in an inconsistent state. Calling `lock()` on a poisoned mutex - fails with a [`PoisonError`]. You can call `into_inner()` on the error to recover the data - regardless. - -[`PoisonError`]: https://doc.rust-lang.org/std/sync/struct.PoisonError.html - + +- `Mutex` in Rust looks like a collection with just one element --- the + protected data. + - It is not possible to forget to acquire the mutex before accessing the + protected data. +- You can get an `&mut T` from an `&Mutex` by taking the lock. The + `MutexGuard` ensures that the `&mut T` doesn't outlive the lock being held. +- `Mutex` implements both `Send` and `Sync` iff (if and only if) `T` + implements `Send`. +- A read-write lock counterpart: `RwLock`. +- Why does `lock()` return a `Result`? + - If the thread that held the `Mutex` panicked, the `Mutex` becomes "poisoned" + to signal that the data it protected might be in an inconsistent state. + Calling `lock()` on a poisoned mutex fails with a [`PoisonError`]. You can + call `into_inner()` on the error to recover the data regardless. + +[`PoisonError`]: https://doc.rust-lang.org/std/sync/struct.PoisonError.html +
diff --git a/src/concurrency/threads.md b/src/concurrency/threads.md index 53ae24b..2f7456a 100644 --- a/src/concurrency/threads.md +++ b/src/concurrency/threads.md @@ -21,23 +21,23 @@ fn main() { } ``` -* Threads are all daemon threads, the main thread does not wait for them. -* Thread panics are independent of each other. - * Panics can carry a payload, which can be unpacked with `downcast_ref`. +- Threads are all daemon threads, the main thread does not wait for them. +- Thread panics are independent of each other. + - Panics can carry a payload, which can be unpacked with `downcast_ref`.
Key points: -* Notice that the thread is stopped before it reaches 10 --- the main thread is +- Notice that the thread is stopped before it reaches 10 --- the main thread is not waiting. -* Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for +- Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for the thread to finish. -* Trigger a panic in the thread, notice how this doesn't affect `main`. +- Trigger a panic in the thread, notice how this doesn't affect `main`. -* Use the `Result` return value from `handle.join()` to get access to the panic +- Use the `Result` return value from `handle.join()` to get access to the panic payload. This is a good time to talk about [`Any`]. [`Any`]: https://doc.rust-lang.org/std/any/index.html diff --git a/src/control-flow-basics/blocks-and-scopes.md b/src/control-flow-basics/blocks-and-scopes.md index b965889..75007fb 100644 --- a/src/control-flow-basics/blocks-and-scopes.md +++ b/src/control-flow-basics/blocks-and-scopes.md @@ -6,9 +6,8 @@ minutes: 10 ## Blocks -A block in Rust contains a sequence of expressions. -Each block has a value and a type, -which are those of the last expression of the block: +A block in Rust contains a sequence of expressions. Each block has a value and a +type, which are those of the last expression of the block: ```rust,editable fn main() { @@ -49,10 +48,15 @@ fn main() {
-* You can show how the value of the block changes by changing the last line in the block. For instance, adding/removing a semicolon or using a `return`. -* Show that a variable's scope is limited by adding a `b` in the inner block in the last example, and then trying to access it outside that block. -* Shadowing is different from mutation, because after shadowing both variable's memory locations exist at the same time. Both are available under the same name, depending where you use it in the code. -* A shadowing variable can have a different type. -* Shadowing looks obscure at first, but is convenient for holding on to values after `.unwrap()`. +- You can show how the value of the block changes by changing the last line in + the block. For instance, adding/removing a semicolon or using a `return`. +- Show that a variable's scope is limited by adding a `b` in the inner block in + the last example, and then trying to access it outside that block. +- Shadowing is different from mutation, because after shadowing both variable's + memory locations exist at the same time. Both are available under the same + name, depending where you use it in the code. +- A shadowing variable can have a different type. +- Shadowing looks obscure at first, but is convenient for holding on to values + after `.unwrap()`.
diff --git a/src/control-flow-basics/break-continue.md b/src/control-flow-basics/break-continue.md index da77f5a..6cad37f 100644 --- a/src/control-flow-basics/break-continue.md +++ b/src/control-flow-basics/break-continue.md @@ -6,10 +6,11 @@ minutes: 5 If you want to exit any kind of loop early, use [`break`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-expressions). -For `loop`, this can take an optional expression that becomes the value of the `loop` expression. +For `loop`, this can take an optional expression that becomes the value of the +`loop` expression. -If you want to immediately start -the next iteration use [`continue`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions). +If you want to immediately start the next iteration use +[`continue`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions). ```rust,editable fn main() { @@ -51,9 +52,8 @@ In this case we break the outer loop after 3 iterations of the inner loop.
-* Note that `loop` is the only looping construct which returns a non-trivial +- Note that `loop` is the only looping construct which returns a non-trivial value. This is because it's guaranteed to be entered at least once (unlike `while` and `for` loops).
- diff --git a/src/control-flow-basics/conditionals.md b/src/control-flow-basics/conditionals.md index 7492f17..03bd50e 100644 --- a/src/control-flow-basics/conditionals.md +++ b/src/control-flow-basics/conditionals.md @@ -6,16 +6,16 @@ minutes: 5 Much of the Rust syntax will be familiar to you from C, C++ or Java: -* Blocks are delimited by curly braces. -* Line comments are started with `//`, block comments are delimited by `/* ... - */`. -* Keywords like `if` and `while` work the same. -* Variable assignment is done with `=`, comparison is done with `==`. +- Blocks are delimited by curly braces. +- Line comments are started with `//`, block comments are delimited by + `/* ... */`. +- Keywords like `if` and `while` work the same. +- Variable assignment is done with `=`, comparison is done with `==`. ## `if` expressions -You use [`if` -expressions](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-expressions) +You use +[`if` expressions](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-expressions) exactly like `if` statements in other languages: ```rust,editable @@ -34,22 +34,19 @@ fn main() { In addition, you can use `if` as an expression. The last expression of each block becomes the value of the `if` expression: - ```rust,editable fn main() { let x = 10; - let size = if x < 20 { - "small" - } else { - "large" - }; + let size = if x < 20 { "small" } else { "large" }; println!("number size: {}", size); } ```
-Because `if` is an expression and must have a particular type, both of its branch blocks must have the same type. Show what happens if you add `;` after `"small"` in the second example. +Because `if` is an expression and must have a particular type, both of its +branch blocks must have the same type. Show what happens if you add `;` after +`"small"` in the second example. When `if` is used in an expression, the expression must have a `;` to separate it from the next statement. Remove the `;` before `println!` to see the compiler diff --git a/src/control-flow-basics/exercise.md b/src/control-flow-basics/exercise.md index aba86b0..99b40c3 100644 --- a/src/control-flow-basics/exercise.md +++ b/src/control-flow-basics/exercise.md @@ -12,14 +12,15 @@ defined as follows, for an arbitrary n1 greater than zero: - If _ni_ is odd, then _ni+1 = 3 * ni + 1_. For example, beginning with _n1_ = 3: - * 3 is odd, so _n2_ = 3 * 3 + 1 = 10; - * 10 is even, so _n3_ = 10 / 2 = 5; - * 5 is odd, so _n4_ = 3 * 15 + 1 = 16; - * 16 is even, so _n5_ = 16 / 2 = 8; - * 8 is even, so _n6_ = 8 / 2 = 4; - * 4 is even, so _n7_ = 4 / 2 = 2; - * 2 is even, so _n8_ = 1; and - * the sequence terminates. + +- 3 is odd, so _n2_ = 3 * 3 + 1 = 10; +- 10 is even, so _n3_ = 10 / 2 = 5; +- 5 is odd, so _n4_ = 3 * 15 + 1 = 16; +- 16 is even, so _n5_ = 16 / 2 = 8; +- 8 is even, so _n6_ = 8 / 2 = 4; +- 4 is even, so _n7_ = 4 / 2 = 2; +- 2 is even, so _n8_ = 1; and +- the sequence terminates. Write a function to calculate the length of the collatz sequence for a given initial `n`. diff --git a/src/control-flow-basics/functions.md b/src/control-flow-basics/functions.md index 1c0f817..093337e 100644 --- a/src/control-flow-basics/functions.md +++ b/src/control-flow-basics/functions.md @@ -5,6 +5,7 @@ minutes: 3 # Functions + ```rust,editable fn gcd(a: u32, b: u32) -> u32 { if b > 0 { @@ -21,12 +22,18 @@ fn main() {
-* Declaration parameters are followed by a type (the reverse of some programming languages), then a return type. -* The last expression in a function body (or any block) becomes the return value. Simply omit the `;` at the end of the expression. - The `return` keyword can be used for early return, but the "bare value" form is idiomatic at the end of a function (refactor `gcd` to use a `return`). -* Some functions have no return value, and return the 'unit type', `()`. The compiler will infer this if the `-> ()` return type is omitted. -* Overloading is not supported -- each function has a single implementation. - * Always takes a fixed number of parameters. Default arguments are not supported. Macros can be used to support variadic functions. - * Always takes a single set of parameter types. These types can be generic, which will be covered later. +- Declaration parameters are followed by a type (the reverse of some programming + languages), then a return type. +- The last expression in a function body (or any block) becomes the return + value. Simply omit the `;` at the end of the expression. The `return` keyword + can be used for early return, but the "bare value" form is idiomatic at the + end of a function (refactor `gcd` to use a `return`). +- Some functions have no return value, and return the 'unit type', `()`. The + compiler will infer this if the `-> ()` return type is omitted. +- Overloading is not supported -- each function has a single implementation. + - Always takes a fixed number of parameters. Default arguments are not + supported. Macros can be used to support variadic functions. + - Always takes a single set of parameter types. These types can be generic, + which will be covered later.
diff --git a/src/control-flow-basics/loops.md b/src/control-flow-basics/loops.md index 40cb572..352c08a 100644 --- a/src/control-flow-basics/loops.md +++ b/src/control-flow-basics/loops.md @@ -8,7 +8,8 @@ There are three looping keywords in Rust: `while`, `loop`, and `for`: ## `while` -The [`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops) +The +[`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops) works much like in other languages, executing the loop body as long as the condition is true. @@ -55,7 +56,8 @@ fn main() {
-* We will discuss iteration later; for now, just stick to range expressions. -* Note that the `for` loop only iterates to `4`. Show the `1..=5` syntax for an inclusive range. +- We will discuss iteration later; for now, just stick to range expressions. +- Note that the `for` loop only iterates to `4`. Show the `1..=5` syntax for an + inclusive range.
diff --git a/src/control-flow-basics/macros.md b/src/control-flow-basics/macros.md index fc9624e..9528650 100644 --- a/src/control-flow-basics/macros.md +++ b/src/control-flow-basics/macros.md @@ -8,11 +8,15 @@ Macros are expanded into Rust code during compilation, and can take a variable number of arguments. They are distinguished by a `!` at the end. The Rust standard library includes an assortment of useful macros. -* `println!(format, ..)` prints a line to standard output, applying formatting described in [`std::fmt`](https://doc.rust-lang.org/std/fmt/index.html). -* `format!(format, ..)` works just like `println!` but returns the result as a string. -* `dbg!(expression)` logs the value of the expression and returns it. -* `todo!()` marks a bit of code as not-yet-implemented. If executed, it will panic. -* `unreachable!()` marks a bit of code as unreachable. If executed, it will panic. +- `println!(format, ..)` prints a line to standard output, applying formatting + described in [`std::fmt`](https://doc.rust-lang.org/std/fmt/index.html). +- `format!(format, ..)` works just like `println!` but returns the result as a + string. +- `dbg!(expression)` logs the value of the expression and returns it. +- `todo!()` marks a bit of code as not-yet-implemented. If executed, it will + panic. +- `unreachable!()` marks a bit of code as unreachable. If executed, it will + panic. ```rust,editable fn factorial(n: u32) -> u32 { @@ -39,7 +43,7 @@ The takeaway from this section is that these common conveniences exist, and how to use them. Why they are defined as macros, and what they expand to, is not especially critical. -The course does not cover defining macros, but a later section will describe -use of derive macros. +The course does not cover defining macros, but a later section will describe use +of derive macros.
diff --git a/src/credits.md b/src/credits.md index 99475f0..8b9568e 100644 --- a/src/credits.md +++ b/src/credits.md @@ -11,15 +11,15 @@ details. ## Rust by Example -Some examples and exercises have been copied and adapted from [Rust by -Example](https://doc.rust-lang.org/rust-by-example/). Please see the +Some examples and exercises have been copied and adapted from +[Rust by Example](https://doc.rust-lang.org/rust-by-example/). Please see the `third_party/rust-by-example/` directory for details, including the license terms. ## Rust on Exercism -Some exercises have been copied and adapted from [Rust on -Exercism](https://exercism.org/tracks/rust). Please see the +Some exercises have been copied and adapted from +[Rust on Exercism](https://exercism.org/tracks/rust). Please see the `third_party/rust-on-exercism/` directory for details, including the license terms. diff --git a/src/error-handling/Cargo.toml b/src/error-handling/Cargo.toml index 398fe3c..90e7f11 100644 --- a/src/error-handling/Cargo.toml +++ b/src/error-handling/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" publish = false [dependencies] -thiserror = "*" anyhow = "*" +thiserror = "*" [[bin]] name = "parser" diff --git a/src/error-handling/error.md b/src/error-handling/error.md index 7af80f2..d8cf4e6 100644 --- a/src/error-handling/error.md +++ b/src/error-handling/error.md @@ -5,8 +5,8 @@ minutes: 5 # Dynamic Error Types Sometimes we want to allow any type of error to be returned without writing our -own enum covering all the different possibilities. The `std::error::Error` -trait makes it easy to create a trait object that can contain any error. +own enum covering all the different possibilities. The `std::error::Error` trait +makes it easy to create a trait object that can contain any error. ```rust,editable use std::error::Error; @@ -34,9 +34,10 @@ fn main() { The `read_count` function can return `std::io::Error` (from file operations) or `std::num::ParseIntError` (from `String::parse`). -Boxing errors saves on code, but gives up the ability to cleanly handle different error cases differently in -the program. As such it's generally not a good idea to use `Box` in the public API of a -library, but it can be a good option in a program where you just want to display the error message +Boxing errors saves on code, but gives up the ability to cleanly handle +different error cases differently in the program. As such it's generally not a +good idea to use `Box` in the public API of a library, but it can be +a good option in a program where you just want to display the error message somewhere. Make sure to implement the `std::error::Error` trait when defining a custom diff --git a/src/error-handling/exercise.rs b/src/error-handling/exercise.rs index adcfa01..6b45111 100644 --- a/src/error-handling/exercise.rs +++ b/src/error-handling/exercise.rs @@ -101,7 +101,9 @@ enum ParserError { fn parse(input: &str) -> Result { let mut tokens = tokenize(input); - fn parse_expr<'a>(tokens: &mut Tokenizer<'a>) -> Result { + fn parse_expr<'a>( + tokens: &mut Tokenizer<'a>, + ) -> Result { let tok = tokens.next().ok_or(ParserError::UnexpectedEOF)??; let expr = match tok { Token::Number(num) => { @@ -114,9 +116,11 @@ fn parse(input: &str) -> Result { // Look ahead to parse a binary operation if present. Ok(match tokens.next() { None => expr, - Some(Ok(Token::Operator(op))) => { - Expression::Operation(Box::new(expr), op, Box::new(parse_expr(tokens)?)) - } + Some(Ok(Token::Operator(op))) => Expression::Operation( + Box::new(expr), + op, + Box::new(parse_expr(tokens)?), + ), Some(Err(e)) => return Err(e.into()), Some(Ok(tok)) => return Err(ParserError::UnexpectedToken(tok)), }) @@ -187,9 +191,11 @@ fn parse(input: &str) -> Expression { // Look ahead to parse a binary operation if present. match tokens.next() { None => expr, - Some(Token::Operator(op)) => { - Expression::Operation(Box::new(expr), op, Box::new(parse_expr(tokens))) - } + Some(Token::Operator(op)) => Expression::Operation( + Box::new(expr), + op, + Box::new(parse_expr(tokens)), + ), Some(tok) => panic!("Unexpected token {tok:?}"), } } diff --git a/src/error-handling/panics.md b/src/error-handling/panics.md index ee398f9..980569e 100644 --- a/src/error-handling/panics.md +++ b/src/error-handling/panics.md @@ -15,13 +15,14 @@ fn main() { } ``` -* Panics are for unrecoverable and unexpected errors. - * Panics are symptoms of bugs in the program. - * Runtime failures like failed bounds checks can panic - * Assertions (such as `assert!`) panic on failure - * Purpose-specific panics can use the `panic!` macro. -* A panic will "unwind" the stack, dropping values just as if the functions had returned. -* Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable. +- Panics are for unrecoverable and unexpected errors. + - Panics are symptoms of bugs in the program. + - Runtime failures like failed bounds checks can panic + - Assertions (such as `assert!`) panic on failure + - Purpose-specific panics can use the `panic!` macro. +- A panic will "unwind" the stack, dropping values just as if the functions had + returned. +- Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable.
@@ -31,9 +32,7 @@ By default, a panic will cause the stack to unwind. The unwinding can be caught: use std::panic; fn main() { - let result = panic::catch_unwind(|| { - "No problem here!" - }); + let result = panic::catch_unwind(|| "No problem here!"); println!("{result:?}"); let result = panic::catch_unwind(|| { @@ -43,7 +42,8 @@ fn main() { } ``` -- Catching is unusual; do not attempt to implement exceptions with `catch_unwind`! +- Catching is unusual; do not attempt to implement exceptions with + `catch_unwind`! - This can be useful in servers which should keep running even if a single request crashes. - This does not work if `panic = 'abort'` is set in your `Cargo.toml`. diff --git a/src/error-handling/solution.md b/src/error-handling/solution.md index 81412e7..2dc2bc5 100644 --- a/src/error-handling/solution.md +++ b/src/error-handling/solution.md @@ -1,6 +1,7 @@ # Solution + ```rust,editable,compile_fail {{#include exercise.rs:solution}} ``` diff --git a/src/error-handling/thiserror-and-anyhow.md b/src/error-handling/thiserror-and-anyhow.md index e3bc952..224df09 100644 --- a/src/error-handling/thiserror-and-anyhow.md +++ b/src/error-handling/thiserror-and-anyhow.md @@ -2,16 +2,18 @@ minutes: 5 --- -# `thiserror` and `anyhow` +# `thiserror` and `anyhow` -The [`thiserror`](https://docs.rs/thiserror/) and [`anyhow`](https://docs.rs/anyhow/) -crates are widely used to simplify error handling. `thiserror` helps -create custom error types that implement `From`. `anyhow` helps with error -handling in functions, including adding contextual information to your errors. +The [`thiserror`](https://docs.rs/thiserror/) and +[`anyhow`](https://docs.rs/anyhow/) crates are widely used to simplify error +handling. `thiserror` helps create custom error types that implement `From`. +`anyhow` helps with error handling in functions, including adding contextual +information to your errors. ```rust,editable,compile_fail use anyhow::{bail, Context, Result}; -use std::{fs, io::Read}; +use std::fs; +use std::io::Read; use thiserror::Error; #[derive(Clone, Debug, Eq, Error, PartialEq)] @@ -34,7 +36,7 @@ fn main() { //fs::write("config.dat", "").unwrap(); match read_username("config.dat") { Ok(username) => println!("Username: {username}"), - Err(err) => println!("Error: {err:?}"), + Err(err) => println!("Error: {err:?}"), } } ``` @@ -43,20 +45,23 @@ fn main() { ## `thiserror` -* The `Error` derive macro is provided by `thiserror`, and has lots of useful +- The `Error` derive macro is provided by `thiserror`, and has lots of useful attributes to help define error types in a compact way. -* The `std::error::Error` trait is derived automatically. -* The message from `#[error]` is used to derive the `Display` trait. +- The `std::error::Error` trait is derived automatically. +- The message from `#[error]` is used to derive the `Display` trait. ## `anyhow` -* `anyhow::Error` is essentially a wrapper around `Box`. As such it's again generally not - a good choice for the public API of a library, but is widely used in applications. -* `anyhow::Result` is a type alias for `Result`. -* Actual error type inside of it can be extracted for examination if necessary. -* Functionality provided by `anyhow::Result` may be familiar to Go developers, as it provides - similar usage patterns and ergonomics to `(T, error)` from Go. -* `anyhow::Context` is a trait implemented for the standard `Result` and `Option` types. - `use anyhow::Context` is necessary to enable `.context()` and `.with_context()` on those types. +- `anyhow::Error` is essentially a wrapper around `Box`. As such it's + again generally not a good choice for the public API of a library, but is + widely used in applications. +- `anyhow::Result` is a type alias for `Result`. +- Actual error type inside of it can be extracted for examination if necessary. +- Functionality provided by `anyhow::Result` may be familiar to Go + developers, as it provides similar usage patterns and ergonomics to + `(T, error)` from Go. +- `anyhow::Context` is a trait implemented for the standard `Result` and + `Option` types. `use anyhow::Context` is necessary to enable `.context()` and + `.with_context()` on those types.
diff --git a/src/error-handling/try-conversions.md b/src/error-handling/try-conversions.md index 94041da..ea804f1 100644 --- a/src/error-handling/try-conversions.md +++ b/src/error-handling/try-conversions.md @@ -4,7 +4,8 @@ minutes: 5 # Try Conversions -The effective expansion of `?` is a little more complicated than previously indicated: +The effective expansion of `?` is a little more complicated than previously +indicated: ```rust,ignore expression? @@ -43,7 +44,7 @@ impl Display for ReadUsernameError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::IoError(e) => write!(f, "IO error: {e}"), - Self::EmptyUsername(filename) => write!(f, "Found no username in {filename}"), + Self::EmptyUsername(path) => write!(f, "Found no username in {path}"), } } } @@ -73,13 +74,13 @@ fn main() {
The `?` operator must return a value compatible with the return type of the -function. For `Result`, it means that the error types have to be compatible. -A function that returns `Result` can only use `?` on a value of +function. For `Result`, it means that the error types have to be compatible. A +function that returns `Result` can only use `?` on a value of type `Result` if `ErrorOuter` and `ErrorInner` are the same type or if `ErrorOuter` implements `From`. -A common alternative to a `From` implementation is `Result::map_err`, -especially when the conversion only happens in one place. +A common alternative to a `From` implementation is `Result::map_err`, especially +when the conversion only happens in one place. There is no compatibility requirement for `Option`. A function returning `Option` can use the `?` operator on `Option` for arbitrary `T` and `U` diff --git a/src/error-handling/try.md b/src/error-handling/try.md index 93744af..8bff82e 100644 --- a/src/error-handling/try.md +++ b/src/error-handling/try.md @@ -5,7 +5,7 @@ minutes: 5 # Try Operator Runtime errors like connection-refused or file-not-found are handled with the -`Result` type, but matching this type on every call can be cumbersome. The +`Result` type, but matching this type on every call can be cumbersome. The try-operator `?` is used to return errors to the caller. It lets you turn the common @@ -25,8 +25,8 @@ some_expression? We can use this to simplify our error handling code: ```rust,editable -use std::{fs, io}; use std::io::Read; +use std::{fs, io}; fn read_username(path: &str) -> Result { let username_file_result = fs::File::open(path); @@ -55,8 +55,12 @@ Simplify the `read_username` function to use `?`. Key points: -* The `username` variable can be either `Ok(string)` or `Err(error)`. -* Use the `fs::write` call to test out the different scenarios: no file, empty file, file with username. -* Note that `main` can return a `Result<(), E>` as long as it implements `std::process:Termination`. In practice, this means that `E` implements `Debug`. The executable will print the `Err` variant and return a nonzero exit status on error. +- The `username` variable can be either `Ok(string)` or `Err(error)`. +- Use the `fs::write` call to test out the different scenarios: no file, empty + file, file with username. +- Note that `main` can return a `Result<(), E>` as long as it implements + `std::process:Termination`. In practice, this means that `E` implements + `Debug`. The executable will print the `Err` variant and return a nonzero exit + status on error.
diff --git a/src/exercises/android/morning.md b/src/exercises/android/morning.md index b339b3b..026a278 100644 --- a/src/exercises/android/morning.md +++ b/src/exercises/android/morning.md @@ -3,9 +3,9 @@ This is a group exercise: We will look at one of the projects you work with and try to integrate some Rust into it. Some suggestions: -* Call your AIDL service with a client written in Rust. +- Call your AIDL service with a client written in Rust. -* Move a function from your project to Rust and call it. +- Move a function from your project to Rust and call it.
diff --git a/src/exercises/bare-metal/compass.md b/src/exercises/bare-metal/compass.md index c28c8b4..d03f4ce 100644 --- a/src/exercises/bare-metal/compass.md +++ b/src/exercises/bare-metal/compass.md @@ -1,27 +1,30 @@ # Compass -We will read the direction from an I2C compass, and log the readings to a serial port. If you have -time, try displaying it on the LEDs somehow too, or use the buttons somehow. +We will read the direction from an I2C compass, and log the readings to a serial +port. If you have time, try displaying it on the LEDs somehow too, or use the +buttons somehow. Hints: -- Check the documentation for the [`lsm303agr`](https://docs.rs/lsm303agr/latest/lsm303agr/) and - [`microbit-v2`](https://docs.rs/microbit-v2/latest/microbit/) crates, as well as the - [micro:bit hardware](https://tech.microbit.org/hardware/). +- Check the documentation for the + [`lsm303agr`](https://docs.rs/lsm303agr/latest/lsm303agr/) and + [`microbit-v2`](https://docs.rs/microbit-v2/latest/microbit/) crates, as well + as the [micro:bit hardware](https://tech.microbit.org/hardware/). - The LSM303AGR Inertial Measurement Unit is connected to the internal I2C bus. - TWI is another name for I2C, so the I2C master peripheral is called TWIM. -- The LSM303AGR driver needs something implementing the `embedded_hal::blocking::i2c::WriteRead` - trait. The - [`microbit::hal::Twim`](https://docs.rs/microbit-v2/latest/microbit/hal/struct.Twim.html) struct - implements this. -- You have a [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/struct.Board.html) +- The LSM303AGR driver needs something implementing the + `embedded_hal::blocking::i2c::WriteRead` trait. The + [`microbit::hal::Twim`](https://docs.rs/microbit-v2/latest/microbit/hal/struct.Twim.html) + struct implements this. +- You have a + [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/struct.Board.html) struct with fields for the various pins and peripherals. - You can also look at the - [nRF52833 datasheet](https://infocenter.nordicsemi.com/pdf/nRF52833_PS_v1.5.pdf) if you want, but - it shouldn't be necessary for this exercise. + [nRF52833 datasheet](https://infocenter.nordicsemi.com/pdf/nRF52833_PS_v1.5.pdf) + if you want, but it shouldn't be necessary for this exercise. -Download the [exercise template](../../comprehensive-rust-exercises.zip) and look in the `compass` -directory for the following files. +Download the [exercise template](../../comprehensive-rust-exercises.zip) and +look in the `compass` directory for the following files. _src/main.rs_: @@ -44,6 +47,7 @@ _Cargo.toml_ (you shouldn't need to change this): + ```toml {{#include compass/Cargo.toml}} ``` @@ -52,6 +56,7 @@ _Embed.toml_ (you shouldn't need to change this): + ```toml {{#include compass/Embed.toml}} ``` @@ -60,18 +65,23 @@ _.cargo/config.toml_ (you shouldn't need to change this): + ```toml {{#include compass/.cargo/config.toml}} ``` See the serial output on Linux with: + + ```sh picocom --baud 115200 --imap lfcrlf /dev/ttyACM0 ``` Or on Mac OS something like (the device name may be slightly different): + + ```sh picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502 ``` diff --git a/src/exercises/bare-metal/compass/src/main.rs b/src/exercises/bare-metal/compass/src/main.rs index 31fc864..05ef032 100644 --- a/src/exercises/bare-metal/compass/src/main.rs +++ b/src/exercises/bare-metal/compass/src/main.rs @@ -91,8 +91,10 @@ fn main() -> ! { let mut image = [[0; 5]; 5]; let (x, y) = match mode { Mode::Compass => ( - scale(-compass_reading.x, -COMPASS_SCALE, COMPASS_SCALE, 0, 4) as usize, - scale(compass_reading.y, -COMPASS_SCALE, COMPASS_SCALE, 0, 4) as usize, + scale(-compass_reading.x, -COMPASS_SCALE, COMPASS_SCALE, 0, 4) + as usize, + scale(compass_reading.y, -COMPASS_SCALE, COMPASS_SCALE, 0, 4) + as usize, ), Mode::Accelerometer => ( scale( @@ -114,7 +116,8 @@ fn main() -> ! { 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 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(); @@ -145,11 +148,7 @@ impl Mode { 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; - cap( - min_out + range_out * (value - min_in) / range_in, - min_out, - max_out, - ) + cap(min_out + range_out * (value - min_in) / range_in, min_out, max_out) } fn cap(value: i32, min_value: i32, max_value: i32) -> i32 { diff --git a/src/exercises/bare-metal/morning.md b/src/exercises/bare-metal/morning.md index e4c01bc..1549aaa 100644 --- a/src/exercises/bare-metal/morning.md +++ b/src/exercises/bare-metal/morning.md @@ -1,6 +1,7 @@ # Exercises -We will read the direction from an I2C compass, and log the readings to a serial port. +We will read the direction from an I2C compass, and log the readings to a serial +port.
diff --git a/src/exercises/bare-metal/rtc.md b/src/exercises/bare-metal/rtc.md index cdd51bf..f92acec 100644 --- a/src/exercises/bare-metal/rtc.md +++ b/src/exercises/bare-metal/rtc.md @@ -1,20 +1,23 @@ # RTC driver -The QEMU aarch64 virt machine has a [PL031][1] real-time clock at 0x9010000. For this exercise, you -should write a driver for it. - -1. Use it to print the current time to the serial console. You can use the [`chrono`][2] crate for - date/time formatting. -2. Use the match register and raw interrupt status to busy-wait until a given time, e.g. 3 seconds - in the future. (Call [`core::hint::spin_loop`][3] inside the loop.) -3. _Extension if you have time:_ Enable and handle the interrupt generated by the RTC match. You can - use the driver provided in the [`arm-gic`][4] crate to configure the Arm Generic Interrupt Controller. +The QEMU aarch64 virt machine has a [PL031][1] real-time clock at 0x9010000. For +this exercise, you should write a driver for it. + +1. Use it to print the current time to the serial console. You can use the + [`chrono`][2] crate for date/time formatting. +2. Use the match register and raw interrupt status to busy-wait until a given + time, e.g. 3 seconds in the future. (Call [`core::hint::spin_loop`][3] inside + the loop.) +3. _Extension if you have time:_ Enable and handle the interrupt generated by + the RTC match. You can use the driver provided in the [`arm-gic`][4] crate to + configure the Arm Generic Interrupt Controller. - Use the RTC interrupt, which is wired to the GIC as `IntId::spi(2)`. - - Once the interrupt is enabled, you can put the core to sleep via `arm_gic::wfi()`, which will cause the core to sleep until it receives an interrupt. - + - Once the interrupt is enabled, you can put the core to sleep via + `arm_gic::wfi()`, which will cause the core to sleep until it receives an + interrupt. -Download the [exercise template](../../comprehensive-rust-exercises.zip) and look in the `rtc` -directory for the following files. +Download the [exercise template](../../comprehensive-rust-exercises.zip) and +look in the `rtc` directory for the following files. _src/main.rs_: @@ -34,7 +37,8 @@ _src/main.rs_: {{#include rtc/src/main.rs:main_end}} ``` -_src/exceptions.rs_ (you should only need to change this for the 3rd part of the exercise): +_src/exceptions.rs_ (you should only need to change this for the 3rd part of the +exercise): @@ -62,6 +66,7 @@ _Cargo.toml_ (you shouldn't need to change this): + ```toml {{#include rtc/Cargo.toml}} ``` @@ -118,6 +123,7 @@ _.cargo/config.toml_ (you shouldn't need to change this): + ```toml {{#include rtc/.cargo/config.toml}} ``` diff --git a/src/exercises/bare-metal/rtc/src/exceptions.rs b/src/exercises/bare-metal/rtc/src/exceptions.rs index 9dd3c7e..80f2a5b 100644 --- a/src/exercises/bare-metal/rtc/src/exceptions.rs +++ b/src/exercises/bare-metal/rtc/src/exceptions.rs @@ -26,7 +26,8 @@ extern "C" fn sync_exception_current(_elr: u64, _spsr: u64) { #[no_mangle] extern "C" fn irq_current(_elr: u64, _spsr: u64) { trace!("irq_current"); - let intid = GicV3::get_and_acknowledge_interrupt().expect("No pending interrupt"); + let intid = + GicV3::get_and_acknowledge_interrupt().expect("No pending interrupt"); info!("IRQ {intid:?}"); } diff --git a/src/exercises/bare-metal/rtc/src/logger.rs b/src/exercises/bare-metal/rtc/src/logger.rs index 8151949..e27ee2b 100644 --- a/src/exercises/bare-metal/rtc/src/logger.rs +++ b/src/exercises/bare-metal/rtc/src/logger.rs @@ -18,9 +18,7 @@ use core::fmt::Write; use log::{LevelFilter, Log, Metadata, Record, SetLoggerError}; use spin::mutex::SpinMutex; -static LOGGER: Logger = Logger { - uart: SpinMutex::new(None), -}; +static LOGGER: Logger = Logger { uart: SpinMutex::new(None) }; struct Logger { uart: SpinMutex>, diff --git a/src/exercises/bare-metal/rtc/src/main.rs b/src/exercises/bare-metal/rtc/src/main.rs index 029868c..3dd179f 100644 --- a/src/exercises/bare-metal/rtc/src/main.rs +++ b/src/exercises/bare-metal/rtc/src/main.rs @@ -82,10 +82,7 @@ extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) { // Wait for 3 seconds, without interrupts. let target = timestamp + 3; rtc.set_match(target); - info!( - "Waiting for {}", - Utc.timestamp_opt(target.into(), 0).unwrap() - ); + info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap()); trace!( "matched={}, interrupt_pending={}", rtc.matched(), @@ -103,10 +100,7 @@ extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) { // Wait another 3 seconds for an interrupt. let target = timestamp + 6; - info!( - "Waiting for {}", - Utc.timestamp_opt(target.into(), 0).unwrap() - ); + info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap()); rtc.set_match(target); rtc.clear_interrupt(); rtc.enable_interrupt(true); diff --git a/src/exercises/bare-metal/rtc/src/pl011.rs b/src/exercises/bare-metal/rtc/src/pl011.rs index 6c8467f..d268402 100644 --- a/src/exercises/bare-metal/rtc/src/pl011.rs +++ b/src/exercises/bare-metal/rtc/src/pl011.rs @@ -114,9 +114,7 @@ impl Uart { /// 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 u32) -> Self { - Self { - registers: base_address as *mut Registers, - } + Self { registers: base_address as *mut Registers } } /// Writes a single byte to the UART. @@ -135,7 +133,8 @@ impl Uart { while self.read_flag_register().contains(Flags::BUSY) {} } - /// Reads and returns a pending byte, or `None` if nothing has been received. + /// Reads and returns a pending byte, or `None` if nothing has been + /// received. pub fn read_byte(&self) -> Option { if self.read_flag_register().contains(Flags::RXFE) { None diff --git a/src/exercises/bare-metal/rtc/src/pl031.rs b/src/exercises/bare-metal/rtc/src/pl031.rs index acd4f75..14e768f 100644 --- a/src/exercises/bare-metal/rtc/src/pl031.rs +++ b/src/exercises/bare-metal/rtc/src/pl031.rs @@ -56,9 +56,7 @@ impl Rtc { /// PL031 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 u32) -> Self { - Self { - registers: base_address as *mut Registers, - } + Self { registers: base_address as *mut Registers } } /// Reads the current RTC value. diff --git a/src/exercises/chromium/bringing-it-together.md b/src/exercises/chromium/bringing-it-together.md index 77b61be..128f5bc 100644 --- a/src/exercises/chromium/bringing-it-together.md +++ b/src/exercises/chromium/bringing-it-together.md @@ -5,52 +5,51 @@ together everything you already learned. ## The Brief from Product Management -A community of pixies has been discovered living in a remote rainforest. -It's important that we get Chromium for Pixies delivered to them as soon -as possible. +A community of pixies has been discovered living in a remote rainforest. It's +important that we get Chromium for Pixies delivered to them as soon as possible. The requirement is to translate all Chromium's UI strings into Pixie language. -There's not time to wait for proper translations, but fortunately pixie -language is very close to English, and it turns out there's a Rust crate -which does the translation. +There's not time to wait for proper translations, but fortunately pixie language +is very close to English, and it turns out there's a Rust crate which does the +translation. In fact, you already [imported that crate in the previous exercise][0]. -(Obviously, real translations of Chrome require incredible care and -diligence. Don't ship this!) +(Obviously, real translations of Chrome require incredible care and diligence. +Don't ship this!) ## Steps -Modify `ResourceBundle::MaybeMangleLocalizedString` so that it uwuifies -all strings before display. In this special build of Chromium, it should -always do this irrespective of the setting of `mangle_localized_strings_`. +Modify `ResourceBundle::MaybeMangleLocalizedString` so that it uwuifies all +strings before display. In this special build of Chromium, it should always do +this irrespective of the setting of `mangle_localized_strings_`. -If you've done everything right across all these exercises, congratulations, -you should have created Chrome for pixies! +If you've done everything right across all these exercises, congratulations, you +should have created Chrome for pixies! Chromium UI screenshot with uwu language
Students will likely need some hints here. Hints include: -* UTF16 vs UTF8. Students should be aware that Rust strings are always - UTF8, and will probably decide that it's better to do the conversion - on the C++ side using `base::UTF16ToUTF8` and back again. -* If students decide to do the conversion on the Rust side, they'll need to - consider [`String::from_utf16`][1], consider error handling, and - consider which [CXX supported types can transfer a lot of u16s][2]. -* Students may design the C++/Rust boundary in several different ways, - e.g. taking and returning strings by value, or taking a mutable reference - to a string. If a mutable reference is used, CXX will likely - tell the student that they need to use [`Pin`][3]. You may need to explain - what `Pin` does, and then explain why CXX needs it for mutable references - to C++ data: the answer is that C++ data can't be moved around like Rust - data, because it may contain self-referential pointers. -* The C++ target containing `ResourceBundle::MaybeMangleLocalizedString` - will need to depend on a `rust_static_library` target. The student - probably already did this. -* The `rust_static_library` target will need to depend on +- UTF16 vs UTF8. Students should be aware that Rust strings are always UTF8, and + will probably decide that it's better to do the conversion on the C++ side + using `base::UTF16ToUTF8` and back again. +- If students decide to do the conversion on the Rust side, they'll need to + consider [`String::from_utf16`][1], consider error handling, and consider + which [CXX supported types can transfer a lot of u16s][2]. +- Students may design the C++/Rust boundary in several different ways, e.g. + taking and returning strings by value, or taking a mutable reference to a + string. If a mutable reference is used, CXX will likely tell the student that + they need to use [`Pin`][3]. You may need to explain what `Pin` does, and then + explain why CXX needs it for mutable references to C++ data: the answer is + that C++ data can't be moved around like Rust data, because it may contain + self-referential pointers. +- The C++ target containing `ResourceBundle::MaybeMangleLocalizedString` will + need to depend on a `rust_static_library` target. The student probably already + did this. +- The `rust_static_library` target will need to depend on `//third_party/rust/uwuify/v0_2:lib`.
diff --git a/src/exercises/chromium/build-rules.md b/src/exercises/chromium/build-rules.md index 2863cba..50e9bab 100644 --- a/src/exercises/chromium/build-rules.md +++ b/src/exercises/chromium/build-rules.md @@ -1,6 +1,7 @@ # Build rules exercise -In your Chromium build, add a new Rust target to `//ui/base/BUILD.gn` containing: +In your Chromium build, add a new Rust target to `//ui/base/BUILD.gn` +containing: ```rust #[no_mangle] @@ -8,32 +9,33 @@ pub extern "C" fn hello_from_rust() { println!("Hello from Rust!") } ``` -**Important**: note that `no_mangle` here is considered a type of unsafety -by the Rust compiler, so you'll need to to allow unsafe code in your -`gn` target. -Add this new Rust target as a dependency of `//ui/base:base`. -Declare this function at the top of `ui/base/resource/resource_bundle.cc` -(later, we'll see how this can be automated by bindings generation tools): +**Important**: note that `no_mangle` here is considered a type of unsafety by +the Rust compiler, so you'll need to to allow unsafe code in your `gn` target. + +Add this new Rust target as a dependency of `//ui/base:base`. Declare this +function at the top of `ui/base/resource/resource_bundle.cc` (later, we'll see +how this can be automated by bindings generation tools): + ```cpp extern "C" void hello_from_rust(); ``` -Call this function from somewhere in `ui/base/resource/resource_bundle.cc` - -we suggest the top of `ResourceBundle::MaybeMangleLocalizedString`. -Build and run Chromium, and ensure that "Hello from Rust!" is printed lots of times. +Call this function from somewhere in `ui/base/resource/resource_bundle.cc` - we +suggest the top of `ResourceBundle::MaybeMangleLocalizedString`. Build and run +Chromium, and ensure that "Hello from Rust!" is printed lots of times. -If you use VSCode, now set up Rust to work well in VSCode. It will be useful -in subsequent exercises. If you've succeeded, you will be able to use -right-click "Go to definition" on `println!`. +If you use VSCode, now set up Rust to work well in VSCode. It will be useful in +subsequent exercises. If you've succeeded, you will be able to use right-click +"Go to definition" on `println!`. ## Where to find help -* The options available to the [`rust_static_library` gn template][0] -* Information about [`#[no_mangle]`][1] -* Information about [`extern "C"`][2] -* Information about gn's [`--export-rust-project`][3] switch -* [How to install rust-analyzer in VSCode][4] +- The options available to the [`rust_static_library` gn template][0] +- Information about [`#[no_mangle]`][1] +- Information about [`extern "C"`][2] +- Information about gn's [`--export-rust-project`][3] switch +- [How to install rust-analyzer in VSCode][4]
It's really important that students get this running, because future exercises @@ -49,10 +51,11 @@ that the right one is called. If you need a pure Rust executable, you can also do that using the `rust_executable` gn template. +
[0]: https://source.chromium.org/chromium/chromium/src/+/main:build/rust/rust_static_library.gni;l=16 [1]: https://doc.rust-lang.org/beta/reference/abi.html#the-no_mangle-attribute [2]: https://doc.rust-lang.org/std/keyword.extern.html [3]: https://gn.googlesource.com/gn/+/main/docs/reference.md#compilation-database -[4]: https://code.visualstudio.com/docs/languages/rust \ No newline at end of file +[4]: https://code.visualstudio.com/docs/languages/rust diff --git a/src/exercises/chromium/interoperability-with-cpp.md b/src/exercises/chromium/interoperability-with-cpp.md index 9d28992..de8f0bc 100644 --- a/src/exercises/chromium/interoperability-with-cpp.md +++ b/src/exercises/chromium/interoperability-with-cpp.md @@ -2,70 +2,70 @@ ## Part one -* In the Rust file you previously created, add a `#[cxx::bridge]` which specifies a single function, - to be called from C++, called `hello_from_rust`, taking no parameters and returning - no value. -* Modify your previous `hello_from_rust` function to remove `extern "C"` and `#[no_mangle]`. - This is now just a standard Rust function. -* Modify your `gn` target to build these bindings. -* In your C++ code, remove the forward-declaration of `hello_from_rust`. Instead, include - the generated header file. -* Build and run! +- In the Rust file you previously created, add a `#[cxx::bridge]` which + specifies a single function, to be called from C++, called `hello_from_rust`, + taking no parameters and returning no value. +- Modify your previous `hello_from_rust` function to remove `extern "C"` and + `#[no_mangle]`. This is now just a standard Rust function. +- Modify your `gn` target to build these bindings. +- In your C++ code, remove the forward-declaration of `hello_from_rust`. + Instead, include the generated header file. +- Build and run! ## Part two -It's a good idea to play with CXX a little. It helps you think about how flexible -Rust in Chromium actually is. +It's a good idea to play with CXX a little. It helps you think about how +flexible Rust in Chromium actually is. Some things to try: -* Call back into C++ from Rust. You will need: - * An additional header file which you can `include!` from your `cxx::bridge`. +- Call back into C++ from Rust. You will need: + - An additional header file which you can `include!` from your `cxx::bridge`. You'll need to declare your C++ function in that new header file. - * An `unsafe` block to call such a function, or alternatively specify the `unsafe` - keyword in your `#[cxx::bridge]` [as described here][0]. - * You may also need to `#include "third_party/rust/cxx/v1/crate/include/cxx.h"` -* Pass a C++ string from C++ into Rust. -* Pass a reference to a C++ object into Rust. -* Intentionally get the Rust function signatures mismatched from the `#[cxx::bridge]`, - and get used to the errors you see. -* Intentionally get the C++ function signatures mismatched from the `#[cxx::bridge]`, - and get used to the errors you see. -* Pass a `std::unique_ptr` of some type from C++ into Rust, so that Rust - can own some C++ object. -* Create a Rust object and pass it into C++, so that C++ owns it. (Hint: - you need a `Box`). -* Declare some methods on a C++ type. Call them from Rust. -* Declare some methods on a Rust type. Call them from C++. + - An `unsafe` block to call such a function, or alternatively specify the + `unsafe` keyword in your `#[cxx::bridge]` [as described here][0]. + - You may also need to + `#include "third_party/rust/cxx/v1/crate/include/cxx.h"` +- Pass a C++ string from C++ into Rust. +- Pass a reference to a C++ object into Rust. +- Intentionally get the Rust function signatures mismatched from the + `#[cxx::bridge]`, and get used to the errors you see. +- Intentionally get the C++ function signatures mismatched from the + `#[cxx::bridge]`, and get used to the errors you see. +- Pass a `std::unique_ptr` of some type from C++ into Rust, so that Rust can own + some C++ object. +- Create a Rust object and pass it into C++, so that C++ owns it. (Hint: you + need a `Box`). +- Declare some methods on a C++ type. Call them from Rust. +- Declare some methods on a Rust type. Call them from C++. ## Part three -Now you understand the strengths and limitations of CXX interop, think of -a couple of use-cases for Rust in Chromium where the interface would be +Now you understand the strengths and limitations of CXX interop, think of a +couple of use-cases for Rust in Chromium where the interface would be sufficiently simple. Sketch how you might define that interface. ## Where to find help -* The [`cxx` binding reference][1] -* The [`rust_static_library` gn template][2] +- The [`cxx` binding reference][1] +- The [`rust_static_library` gn template][2]
As students explore Part Two, they're bound to have lots of questions about how to achieve these things, and also how CXX works behind the scenes. Some of the questions you may encounter: -* I'm seeing a problem initializing a variable of type X with type Y, where - X and Y are both function types. - This is because your C++ function doesn't quite match the declaration in your - `cxx::bridge`. -* I seem to be able to freely convert C++ references into Rust references. - Doesn't that risk UB? - For CXX's _opaque_ types, no, because they are zero-sized. For CXX trivial types - yes, it's _possible_ to cause UB, although CXX's design makes it quite - difficult to craft such an example. -
+- I'm seeing a problem initializing a variable of type X with type Y, where X + and Y are both function types. This is because your C++ function doesn't quite + match the declaration in your `cxx::bridge`. +- I seem to be able to freely convert C++ references into Rust references. + Doesn't that risk UB? For CXX's _opaque_ types, no, because they are + zero-sized. For CXX trivial types yes, it's _possible_ to cause UB, although + CXX's design makes it quite difficult to craft such an example. + +
[0]: https://cxx.rs/extern-c++.html#functions-and-member-functions [1]: https://cxx.rs/bindings.html -[2]: https://source.chromium.org/chromium/chromium/src/+/main:build/rust/rust_static_library.gni;l=16 \ No newline at end of file +[2]: https://source.chromium.org/chromium/chromium/src/+/main:build/rust/rust_static_library.gni;l=16 diff --git a/src/exercises/chromium/solutions.md b/src/exercises/chromium/solutions.md index 1fee997..982f42d 100644 --- a/src/exercises/chromium/solutions.md +++ b/src/exercises/chromium/solutions.md @@ -1,6 +1,5 @@ # Exercise Solutions -Solutions to the Chromium exercises can be found in -[this series of CLs][0]. +Solutions to the Chromium exercises can be found in [this series of CLs][0]. -[0]: https://chromium-review.googlesource.com/c/chromium/src/+/5096560 \ No newline at end of file +[0]: https://chromium-review.googlesource.com/c/chromium/src/+/5096560 diff --git a/src/exercises/chromium/testing.md b/src/exercises/chromium/testing.md index e513f10..0711f10 100644 --- a/src/exercises/chromium/testing.md +++ b/src/exercises/chromium/testing.md @@ -4,11 +4,9 @@ Time for another exercise! In your Chromium build: -* Add a testable function next to `hello_from_rust`. - Some suggestions: - adding two integers received as arguments, - computing the nth Fibonacci number, +- Add a testable function next to `hello_from_rust`. Some suggestions: adding + two integers received as arguments, computing the nth Fibonacci number, summing integers in a slice, etc. -* Add a separate `..._unittest.rs` file with a test for the new function. -* Add the new tests to `BUILD.gn`. -* Build the tests, run them, and verify that the new test works. +- Add a separate `..._unittest.rs` file with a test for the new function. +- Add the new tests to `BUILD.gn`. +- Build the tests, run them, and verify that the new test works. diff --git a/src/exercises/chromium/third-party.md b/src/exercises/chromium/third-party.md index 704544c..70596c8 100644 --- a/src/exercises/chromium/third-party.md +++ b/src/exercises/chromium/third-party.md @@ -1,11 +1,11 @@ # Exercise Add [uwuify][0] to Chromium, turning off the crate's [default features][1]. -Assume that the crate will be used in shipping Chromium, but won't be used -to handle untrustworthy input. +Assume that the crate will be used in shipping Chromium, but won't be used to +handle untrustworthy input. -(In the next exercise we'll use uwuify from Chromium, but feel free to -skip ahead and do that now if you like. Or, you could create a new +(In the next exercise we'll use uwuify from Chromium, but feel free to skip +ahead and do that now if you like. Or, you could create a new [`rust_executable` target][2] which uses `uwuify`).
@@ -23,15 +23,14 @@ The total crates needed are: - `smallvec`, and - `uwuify`. -If students are downloading even -more than that, they probably forgot to turn off the default features. +If students are downloading even more than that, they probably forgot to turn +off the default features. Thanks to [Daniel Liu][3] for this crate!
- [0]: https://crates.io/crates/uwuify [1]: https://doc.rust-lang.org/cargo/reference/features.html#the-default-feature [2]: https://source.chromium.org/chromium/chromium/src/+/main:build/rust/rust_executable.gni -[3]: https://github.com/Daniel-Liu-c0deb0t \ No newline at end of file +[3]: https://github.com/Daniel-Liu-c0deb0t diff --git a/src/exercises/concurrency/afternoon.md b/src/exercises/concurrency/afternoon.md index 281c61e..00a0fd1 100644 --- a/src/exercises/concurrency/afternoon.md +++ b/src/exercises/concurrency/afternoon.md @@ -2,10 +2,10 @@ To practice your Async Rust skills, we have again two exercises for you: -* Dining philosophers: we already saw this problem in the morning. This time - you are going to implement it with Async Rust. +- Dining philosophers: we already saw this problem in the morning. This time you + are going to implement it with Async Rust. -* A Broadcast Chat Application: this is a larger project that allows you +- A Broadcast Chat Application: this is a larger project that allows you experiment with more advanced Async Rust features.
diff --git a/src/exercises/concurrency/chat-app.md b/src/exercises/concurrency/chat-app.md index ef05408..95eee6e 100644 --- a/src/exercises/concurrency/chat-app.md +++ b/src/exercises/concurrency/chat-app.md @@ -1,14 +1,13 @@ # Broadcast Chat Application -In this exercise, we want to use our new knowledge to implement a broadcast -chat application. We have a chat server that the clients connect to and publish -their messages. The client reads user messages from the standard input, and -sends them to the server. The chat server broadcasts each message that it -receives to all the clients. +In this exercise, we want to use our new knowledge to implement a broadcast chat +application. We have a chat server that the clients connect to and publish their +messages. The client reads user messages from the standard input, and sends them +to the server. The chat server broadcasts each message that it receives to all +the clients. For this, we use [a broadcast channel][1] on the server, and -[`tokio_websockets`][2] for the communication between the client and the -server. +[`tokio_websockets`][2] for the communication between the client and the server. Create a new Cargo project and add the following dependencies: @@ -21,31 +20,31 @@ _Cargo.toml_: ``` ## The required APIs + You are going to need the following functions from `tokio` and [`tokio_websockets`][2]. Spend a few minutes to familiarize yourself with the -API. +API. - [StreamExt::next()][3] implemented by `WebSocketStream`: for asynchronously reading messages from a Websocket Stream. - [SinkExt::send()][4] implemented by `WebSocketStream`: for asynchronously sending messages on a Websocket Stream. -- [Lines::next_line()][5]: for asynchronously reading user messages - from the standard input. +- [Lines::next_line()][5]: for asynchronously reading user messages from the + standard input. - [Sender::subscribe()][6]: for subscribing to a broadcast channel. - ## Two binaries -Normally in a Cargo project, you can have only one binary, and one -`src/main.rs` file. In this project, we need two binaries. One for the client, -and one for the server. You could potentially make them two separate Cargo -projects, but we are going to put them in a single Cargo project with two -binaries. For this to work, the client and the server code should go under -`src/bin` (see the [documentation][7]). +Normally in a Cargo project, you can have only one binary, and one `src/main.rs` +file. In this project, we need two binaries. One for the client, and one for the +server. You could potentially make them two separate Cargo projects, but we are +going to put them in a single Cargo project with two binaries. For this to work, +the client and the server code should go under `src/bin` (see the +[documentation][7]). Copy the following server and client code into `src/bin/server.rs` and `src/bin/client.rs`, respectively. Your task is to complete these files as -described below. +described below. _src/bin/server.rs_: @@ -74,6 +73,7 @@ _src/bin/client.rs_: ``` ## Running the binaries + Run the server with: ```shell @@ -88,16 +88,16 @@ cargo run --bin client ## Tasks -* Implement the `handle_connection` function in `src/bin/server.rs`. - * Hint: Use `tokio::select!` for concurrently performing two tasks in a +- Implement the `handle_connection` function in `src/bin/server.rs`. + - Hint: Use `tokio::select!` for concurrently performing two tasks in a continuous loop. One task receives messages from the client and broadcasts them. The other sends messages received by the server to the client. -* Complete the main function in `src/bin/client.rs`. - * Hint: As before, use `tokio::select!` in a continuous loop for concurrently +- Complete the main function in `src/bin/client.rs`. + - Hint: As before, use `tokio::select!` in a continuous loop for concurrently performing two tasks: (1) reading user messages from standard input and sending them to the server, and (2) receiving messages from the server, and displaying them for the user. -* Optional: Once you are done, change the code to broadcast messages to all +- Optional: Once you are done, change the code to broadcast messages to all clients, but the sender of the message. [1]: https://docs.rs/tokio/latest/tokio/sync/broadcast/fn.channel.html diff --git a/src/exercises/concurrency/chat-async/src/bin/server.rs b/src/exercises/concurrency/chat-async/src/bin/server.rs index c3589ac..537e9bf 100644 --- a/src/exercises/concurrency/chat-async/src/bin/server.rs +++ b/src/exercises/concurrency/chat-async/src/bin/server.rs @@ -31,9 +31,7 @@ async fn handle_connection( ) -> Result<(), Box> { // ANCHOR_END: handle_connection - ws_stream - .send(Message::text("Welcome to chat! Type a message".into())) - .await?; + ws_stream.send(Message::text("Welcome to chat! Type a message".into())).await?; let mut bcast_rx = bcast_tx.subscribe(); // A continuous loop for concurrently performing two tasks: (1) receiving diff --git a/src/exercises/concurrency/dining-philosophers-async.md b/src/exercises/concurrency/dining-philosophers-async.md index 71450e7..fee6ef0 100644 --- a/src/exercises/concurrency/dining-philosophers-async.md +++ b/src/exercises/concurrency/dining-philosophers-async.md @@ -4,9 +4,9 @@ See [dining philosophers](dining-philosophers.md) for a description of the problem. As before, you will need a local -[Cargo installation](../../cargo/running-locally.md) for this exercise. Copy -the code below to a file called `src/main.rs`, fill out the blanks, and test -that `cargo run` does not deadlock: +[Cargo installation](../../cargo/running-locally.md) for this exercise. Copy the +code below to a file called `src/main.rs`, fill out the blanks, and test that +`cargo run` does not deadlock: @@ -32,8 +32,8 @@ that `cargo run` does not deadlock: } ``` -Since this time you are using Async Rust, you'll need a `tokio` dependency. -You can use the following `Cargo.toml`: +Since this time you are using Async Rust, you'll need a `tokio` dependency. You +can use the following `Cargo.toml`: @@ -44,14 +44,14 @@ version = "0.1.0" edition = "2021" [dependencies] -tokio = {version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"]} +tokio = { version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"] } ``` -Also note that this time you have to use the `Mutex` and the `mpsc` module -from the `tokio` crate. +Also note that this time you have to use the `Mutex` and the `mpsc` module from +the `tokio` crate.
-* Can you make your implementation single-threaded? +- Can you make your implementation single-threaded?
diff --git a/src/exercises/concurrency/dining-philosophers-async.rs b/src/exercises/concurrency/dining-philosophers-async.rs index 6f8c5bd..07785d3 100644 --- a/src/exercises/concurrency/dining-philosophers-async.rs +++ b/src/exercises/concurrency/dining-philosophers-async.rs @@ -15,9 +15,9 @@ // ANCHOR: solution // ANCHOR: Philosopher use std::sync::Arc; -use tokio::time; use tokio::sync::mpsc::{self, Sender}; use tokio::sync::Mutex; +use tokio::time; struct Fork; @@ -33,7 +33,8 @@ struct Philosopher { impl Philosopher { async fn think(&self) { self.thoughts - .send(format!("Eureka! {} has a new idea!", &self.name)).await + .send(format!("Eureka! {} has a new idea!", &self.name)) + .await .unwrap(); } // ANCHOR_END: Philosopher-think @@ -78,7 +79,7 @@ async fn main() { // To avoid a deadlock, we have to break the symmetry // somewhere. This will swap the forks without deinitializing // either of them. - if i == 0 { + if i == 0 { std::mem::swap(&mut left_fork, &mut right_fork); } philosophers.push(Philosopher { @@ -100,7 +101,6 @@ async fn main() { phil.eat().await; } }); - } // Output their thoughts diff --git a/src/exercises/concurrency/link-checker.md b/src/exercises/concurrency/link-checker.md index a5ba6ab..de7e953 100644 --- a/src/exercises/concurrency/link-checker.md +++ b/src/exercises/concurrency/link-checker.md @@ -78,9 +78,9 @@ cargo run ## Tasks -* Use threads to check the links in parallel: send the URLs to be checked to a +- Use threads to check the links in parallel: send the URLs to be checked to a channel and let a few threads check the URLs in parallel. -* Extend this to recursively extract links from all pages on the +- Extend this to recursively extract links from all pages on the `www.google.org` domain. Put an upper limit of 100 pages or so so that you don't end up being blocked by the site. diff --git a/src/exercises/concurrency/link-checker.rs b/src/exercises/concurrency/link-checker.rs index 0b88f85..442add2 100644 --- a/src/exercises/concurrency/link-checker.rs +++ b/src/exercises/concurrency/link-checker.rs @@ -13,10 +13,12 @@ // limitations under the License. // ANCHOR: solution -use std::{sync::mpsc, sync::Arc, sync::Mutex, thread}; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread; // ANCHOR: setup -use reqwest::{blocking::Client, Url}; +use reqwest::blocking::Client; +use reqwest::Url; use scraper::{Html, Selector}; use thiserror::Error; @@ -79,10 +81,7 @@ 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, - } + CrawlState { domain: start_url.domain().unwrap().to_string(), visited_pages } } /// Determine whether links within the given page should be extracted. @@ -138,10 +137,7 @@ fn control_crawl( result_receiver: mpsc::Receiver, ) -> Vec { let mut crawl_state = CrawlState::new(&start_url); - let start_command = CrawlCommand { - url: start_url, - extract_links: true, - }; + let start_command = CrawlCommand { url: start_url, extract_links: true }; command_sender.send(start_command).unwrap(); let mut pending_urls = 1; diff --git a/src/exercises/concurrency/morning.md b/src/exercises/concurrency/morning.md index 039f105..313c733 100644 --- a/src/exercises/concurrency/morning.md +++ b/src/exercises/concurrency/morning.md @@ -2,9 +2,9 @@ Let us practice our new concurrency skills with -* Dining philosophers: a classic problem in concurrency. +- Dining philosophers: a classic problem in concurrency. -* Multi-threaded link checker: a larger project where you'll use Cargo to +- Multi-threaded link checker: a larger project where you'll use Cargo to download dependencies and then check links in parallel.
diff --git a/src/exercises/concurrency/solutions-afternoon.md b/src/exercises/concurrency/solutions-afternoon.md index 959a68f..b9ff308 100644 --- a/src/exercises/concurrency/solutions-afternoon.md +++ b/src/exercises/concurrency/solutions-afternoon.md @@ -23,4 +23,3 @@ _src/bin/client.rs_: ```rust,compile_fail {{#include chat-async/src/bin/client.rs:solution}} ``` - diff --git a/src/generics/Cargo.toml b/src/generics/Cargo.toml index 13d31e6..65af53b 100644 --- a/src/generics/Cargo.toml +++ b/src/generics/Cargo.toml @@ -7,4 +7,3 @@ publish = false [[bin]] name = "generics" path = "exercise.rs" - diff --git a/src/generics/exercise.rs b/src/generics/exercise.rs index b6db17a..ae77872 100644 --- a/src/generics/exercise.rs +++ b/src/generics/exercise.rs @@ -48,18 +48,9 @@ fn min(l: T, r: T) -> T { // ANCHOR: main fn main() { - let cit1 = Citation { - author: "Shapiro", - year: 2011, - }; - let cit2 = Citation { - author: "Baumann", - year: 2010, - }; - let cit3 = Citation { - author: "Baumann", - year: 2019, - }; + let cit1 = Citation { author: "Shapiro", year: 2011 }; + let cit2 = Citation { author: "Baumann", year: 2010 }; + let cit3 = Citation { author: "Baumann", year: 2019 }; debug_assert_eq!(min(cit1, cit2), cit2); debug_assert_eq!(min(cit2, cit3), cit2); debug_assert_eq!(min(cit1, cit3), cit3); diff --git a/src/generics/generic-data.md b/src/generics/generic-data.md index 7ecb1e2..54bc15b 100644 --- a/src/generics/generic-data.md +++ b/src/generics/generic-data.md @@ -31,13 +31,17 @@ fn main() {
-* *Q:* Why `T` is specified twice in `impl Point {}`? Isn't that redundant? - * This is because it is a generic implementation section for generic type. They are independently generic. - * It means these methods are defined for any `T`. - * It is possible to write `impl Point { .. }`. - * `Point` is still generic and you can use `Point`, but methods in this block will only be available for `Point`. - -* Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`. - Update the code to allow points that have elements of different types, by using two type variables, e.g., `T` and `U`. +- _Q:_ Why `T` is specified twice in `impl Point {}`? Isn't that + redundant? + - This is because it is a generic implementation section for generic type. + They are independently generic. + - It means these methods are defined for any `T`. + - It is possible to write `impl Point { .. }`. + - `Point` is still generic and you can use `Point`, but methods in this + block will only be available for `Point`. + +- Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`. Update the + code to allow points that have elements of different types, by using two type + variables, e.g., `T` and `U`.
diff --git a/src/generics/generic-functions.md b/src/generics/generic-functions.md index 1979e76..4c2a319 100644 --- a/src/generics/generic-functions.md +++ b/src/generics/generic-functions.md @@ -5,8 +5,7 @@ minutes: 5 # Generic Functions Rust supports generics, which lets you abstract algorithms or data structures -(such as sorting or a binary tree) -over the types used or stored. +(such as sorting or a binary tree) over the types used or stored. ```rust,editable /// Pick `even` or `odd` depending on the value of `n`. @@ -26,16 +25,16 @@ fn main() {
-* Rust infers a type for T based on the types of the arguments and return value. +- Rust infers a type for T based on the types of the arguments and return value. -* This is similar to C++ templates, but Rust partially compiles the generic +- This is similar to C++ templates, but Rust partially compiles the generic function immediately, so that function must be valid for all types matching the constraints. For example, try modifying `pick` to return `even + odd` if `n == 0`. Even if only the `pick` instantiation with integers is used, Rust still considers it invalid. C++ would let you do this. -* Generic code is turned into non-generic code based on the call sites. - This is a zero-cost abstraction: you get exactly the same result as if you had +- Generic code is turned into non-generic code based on the call sites. This is + a zero-cost abstraction: you get exactly the same result as if you had hand-coded the data structures without the abstraction.
diff --git a/src/generics/impl-trait.md b/src/generics/impl-trait.md index b3d855d..8639f9e 100644 --- a/src/generics/impl-trait.md +++ b/src/generics/impl-trait.md @@ -30,20 +30,22 @@ fn main() {
-`impl Trait` allows you to work with types which you cannot name. -The meaning of `impl Trait` is a bit different in the different positions. +`impl Trait` allows you to work with types which you cannot name. The meaning of +`impl Trait` is a bit different in the different positions. -* For a parameter, `impl Trait` is like an anonymous generic parameter with a trait bound. +- For a parameter, `impl Trait` is like an anonymous generic parameter with a + trait bound. -* For a return type, it means that the return type is some concrete type that implements the trait, - without naming the type. This can be useful when you don't want to expose the concrete type in a - public API. +- For a return type, it means that the return type is some concrete type that + implements the trait, without naming the type. This can be useful when you + don't want to expose the concrete type in a public API. Inference is hard in return position. A function returning `impl Foo` picks the concrete type it returns, without writing it out in the source. A function returning a generic type like `collect() -> B` can return any type - satisfying `B`, and the caller may need to choose one, such as with `let x: - Vec<_> = foo.collect()` or with the turbofish, `foo.collect::>()`. + satisfying `B`, and the caller may need to choose one, such as with + `let x: Vec<_> = foo.collect()` or with the turbofish, + `foo.collect::>()`. What is the type of `debuggable`? Try `let debuggable: () = ..` to see what the error message shows. diff --git a/src/generics/trait-bounds.md b/src/generics/trait-bounds.md index 33fd835..2ebdcb6 100644 --- a/src/generics/trait-bounds.md +++ b/src/generics/trait-bounds.md @@ -25,11 +25,11 @@ fn main() {
-* Try making a `NonClonable` and passing it to `duplicate`. +- Try making a `NonClonable` and passing it to `duplicate`. -* When multiple traits are necessary, use `+` to join them. +- When multiple traits are necessary, use `+` to join them. -* Show a `where` clause, students will encounter it when reading code. +- Show a `where` clause, students will encounter it when reading code. ```rust,ignore fn duplicate(a: T) -> (T, T) @@ -38,13 +38,14 @@ fn main() { { (a.clone(), a.clone()) } - ``` + ``` - * It declutters the function signature if you have many parameters. - * It has additional features making it more powerful. - * If someone asks, the extra feature is that the type on the left of ":" can be arbitrary, like `Option`. + - It declutters the function signature if you have many parameters. + - It has additional features making it more powerful. + - If someone asks, the extra feature is that the type on the left of ":" can + be arbitrary, like `Option`. -* Note that Rust does not (yet) support specialization. For example, given the +- Note that Rust does not (yet) support specialization. For example, given the original `duplicate`, it is invalid to add a specialized `duplicate(a: u32)`.
diff --git a/src/glossary.md b/src/glossary.md index d706a98..6613463 100644 --- a/src/glossary.md +++ b/src/glossary.md @@ -43,7 +43,8 @@ Also, please keep the hard line breaks to ensure a nice formatting. - brace:\ `{` and `}`. Also called _curly brace_, they delimit _blocks_. - build:\ - The process of converting source code into executable code or a usable program. + The process of converting source code into executable code or a usable + program. - call:\ To invoke or execute a function or method. - channel:\ @@ -57,7 +58,8 @@ Also, please keep the hard line breaks to ensure a nice formatting. - constant:\ A value that does not change during the execution of a program. - control flow:\ - The order in which the individual statements or instructions are executed in a program. + The order in which the individual statements or instructions are executed in a + program. - crash:\ An unexpected and unhandled failure or termination of a program. - enumeration:\ @@ -65,64 +67,79 @@ Also, please keep the hard line breaks to ensure a nice formatting. - error:\ An unexpected condition or result that deviates from the expected behavior. - error handling:\ - The process of managing and responding to errors that occur during program execution. + The process of managing and responding to errors that occur during program + execution. - exercise:\ A task or problem designed to practice and test programming skills. - function:\ A reusable block of code that performs a specific task. - garbage collector:\ - A mechanism that automatically frees up memory occupied by objects that are no longer in use. + A mechanism that automatically frees up memory occupied by objects that are no + longer in use. - generics:\ - A feature that allows writing code with placeholders for types, enabling code reuse with different data types. + A feature that allows writing code with placeholders for types, enabling code + reuse with different data types. - immutable:\ Unable to be changed after creation. - integration test:\ - A type of test that verifies the interactions between different parts or components of a system. + A type of test that verifies the interactions between different parts or + components of a system. - keyword:\ - A reserved word in a programming language that has a specific meaning and cannot be used as an identifier. + A reserved word in a programming language that has a specific meaning and + cannot be used as an identifier. - library:\ A collection of precompiled routines or code that can be used by programs. - macro:\ - Rust macros can be recognized by a `!` in the name. Macros are used - when normal functions are not enough. A typical example is `format!`, - which takes a variable number of arguments, which isn't supported by - Rust functions. + Rust macros can be recognized by a `!` in the name. Macros are used when + normal functions are not enough. A typical example is `format!`, which takes a + variable number of arguments, which isn't supported by Rust functions. - `main` function:\ Rust programs start executing with the `main` function. - match:\ - A control flow construct in Rust that allows for pattern matching on the value of an expression. + A control flow construct in Rust that allows for pattern matching on the value + of an expression. - memory leak:\ - A situation where a program fails to release memory that is no longer needed, leading to a gradual increase in memory usage. + A situation where a program fails to release memory that is no longer needed, + leading to a gradual increase in memory usage. - method:\ A function associated with an object or a type in Rust. - module:\ - A namespace that contains definitions, such as functions, types, or traits, to organize code in Rust. + A namespace that contains definitions, such as functions, types, or traits, to + organize code in Rust. - move:\ The transfer of ownership of a value from one variable to another in Rust. - mutable:\ - A property in Rust that allows variables to be modified after they have been declared. + A property in Rust that allows variables to be modified after they have been + declared. - ownership:\ - The concept in Rust that defines which part of the code is responsible for managing the memory associated with a value. + The concept in Rust that defines which part of the code is responsible for + managing the memory associated with a value. - panic:\ - An unrecoverable error condition in Rust that results in the termination of the program. + An unrecoverable error condition in Rust that results in the termination of + the program. - parameter:\ A value that is passed into a function or method when it is called. - pattern:\ - A combination of values, literals, or structures that can be matched against an expression in Rust. + A combination of values, literals, or structures that can be matched against + an expression in Rust. - payload:\ The data or information carried by a message, event, or data structure. - program:\ - A set of instructions that a computer can execute to perform a specific task or solve a particular problem. + A set of instructions that a computer can execute to perform a specific task + or solve a particular problem. - programming language:\ A formal system used to communicate instructions to a computer, such as Rust. - receiver:\ - The first parameter in a Rust method that represents the instance on which the method is called. + The first parameter in a Rust method that represents the instance on which the + method is called. - reference counting:\ - A memory management technique in which the number of references to an object is tracked, and the object is deallocated when the count reaches zero. + A memory management technique in which the number of references to an object + is tracked, and the object is deallocated when the count reaches zero. - return:\ A keyword in Rust used to indicate the value to be returned from a function. - Rust:\ - A systems programming language that focuses on safety, performance, and concurrency. + A systems programming language that focuses on safety, performance, and + concurrency. - Rust Fundamentals:\ Days 1 to 3 of this course. - Rust in Android:\ @@ -130,39 +147,51 @@ Also, please keep the hard line breaks to ensure a nice formatting. - Rust in Chromium:\ See [Rust in Chromium](chromium.md). - safe:\ - Refers to code that adheres to Rust's ownership and borrowing rules, preventing memory-related errors. + Refers to code that adheres to Rust's ownership and borrowing rules, + preventing memory-related errors. - scope:\ The region of a program where a variable is valid and can be used. - standard library:\ A collection of modules providing essential functionality in Rust. - static:\ - A keyword in Rust used to define static variables or items with a `'static` lifetime. + A keyword in Rust used to define static variables or items with a `'static` + lifetime. - string:\ - A data type storing textual data. See [`String` vs `str`](basic-syntax/string-slices.html) for more. + A data type storing textual data. See + [`String` vs `str`](basic-syntax/string-slices.html) for more. - struct:\ - A composite data type in Rust that groups together variables of different types under a single name. + A composite data type in Rust that groups together variables of different + types under a single name. - test:\ - A Rust module containing functions that test the correctness of other functions. + A Rust module containing functions that test the correctness of other + functions. - thread:\ A separate sequence of execution in a program, allowing concurrent execution. - thread safety:\ - The property of a program that ensures correct behavior in a multithreaded environment. + The property of a program that ensures correct behavior in a multithreaded + environment. - trait:\ - A collection of methods defined for an unknown type, providing a way to achieve polymorphism in Rust. + A collection of methods defined for an unknown type, providing a way to + achieve polymorphism in Rust. - trait bound:\ - An abstraction where you can require types to implement some traits of your interest. + An abstraction where you can require types to implement some traits of your + interest. - type:\ - A classification that specifies which operations can be performed on values of a particular kind in Rust. + A classification that specifies which operations can be performed on values of + a particular kind in Rust. - type inference:\ - The ability of the Rust compiler to deduce the type of a variable or expression. + The ability of the Rust compiler to deduce the type of a variable or + expression. - undefined behavior:\ - Actions or conditions in Rust that have no specified result, often leading to unpredictable program behavior. + Actions or conditions in Rust that have no specified result, often leading to + unpredictable program behavior. - union:\ A data type that can hold values of different types but only one at a time. - unit test:\ Rust comes with built-in support for running small unit tests and larger integration tests. See [Unit Tests](testing/unit-tests.html). - unsafe:\ - The subset of Rust which allows you to trigger _undefined behavior_. See [Unsafe Rust](unsafe.html). + The subset of Rust which allows you to trigger _undefined behavior_. See + [Unsafe Rust](unsafe.html). - variable:\ - A memory location storing data. Variables are valid in a _scope_. + A memory location storing data. Variables are valid in a _scope_. diff --git a/src/hello-world/benefits.md b/src/hello-world/benefits.md index 8220d09..d135fbb 100644 --- a/src/hello-world/benefits.md +++ b/src/hello-world/benefits.md @@ -6,7 +6,8 @@ minutes: 3 Some unique selling points of Rust: -- _Compile time memory safety_ - whole classes of memory bugs are prevented at compile time +- _Compile time memory safety_ - whole classes of memory bugs are prevented at + compile time - No uninitialized variables. - No double-frees. - No use-after-free. @@ -39,14 +40,14 @@ later. Make sure to ask the class which languages they have experience with. Depending on the answer you can highlight different features of Rust: -* Experience with C or C++: Rust eliminates a whole class of _runtime errors_ +- Experience with C or C++: Rust eliminates a whole class of _runtime errors_ via the borrow checker. You get performance like in C and C++, but you don't have the memory unsafety issues. In addition, you get a modern language with constructs like pattern matching and built-in dependency management. -* Experience with Java, Go, Python, JavaScript...: You get the same memory safety - as in those languages, plus a similar high-level language feeling. In addition - you get fast and predictable performance like C and C++ (no garbage collector) - as well as access to low-level hardware (should you need it) +- Experience with Java, Go, Python, JavaScript...: You get the same memory + safety as in those languages, plus a similar high-level language feeling. In + addition you get fast and predictable performance like C and C++ (no garbage + collector) as well as access to low-level hardware (should you need it)
diff --git a/src/hello-world/hello-world.md b/src/hello-world/hello-world.md index e80ed85..afbde4f 100644 --- a/src/hello-world/hello-world.md +++ b/src/hello-world/hello-world.md @@ -15,11 +15,11 @@ fn main() { What you see: -* Functions are introduced with `fn`. -* Blocks are delimited by curly braces like in C and C++. -* The `main` function is the entry point of the program. -* Rust has hygienic macros, `println!` is an example of this. -* Rust strings are UTF-8 encoded and can contain any Unicode character. +- Functions are introduced with `fn`. +- Blocks are delimited by curly braces like in C and C++. +- The `main` function is the entry point of the program. +- Rust has hygienic macros, `println!` is an example of this. +- Rust strings are UTF-8 encoded and can contain any Unicode character.
@@ -28,20 +28,21 @@ a ton of it over the next four days so we start small with something familiar. Key points: -* Rust is very much like other languages in the C/C++/Java tradition. It is - imperative and it doesn't try to reinvent things unless - absolutely necessary. +- Rust is very much like other languages in the C/C++/Java tradition. It is + imperative and it doesn't try to reinvent things unless absolutely necessary. -* Rust is modern with full support for things like Unicode. +- Rust is modern with full support for things like Unicode. -* Rust uses macros for situations where you want to have a variable number of +- Rust uses macros for situations where you want to have a variable number of arguments (no function [overloading](basic-syntax/functions-interlude.md)). -* Macros being 'hygienic' means they don't accidentally capture identifiers from +- Macros being 'hygienic' means they don't accidentally capture identifiers from the scope they are used in. Rust macros are actually only [partially hygienic](https://veykril.github.io/tlborm/decl-macros/minutiae/hygiene.html). -* Rust is multi-paradigm. For example, it has powerful [object-oriented programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), - and, while it is not a functional language, it includes a range of [functional concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html). +- Rust is multi-paradigm. For example, it has powerful + [object-oriented programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), + and, while it is not a functional language, it includes a range of + [functional concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html).
diff --git a/src/hello-world/playground.md b/src/hello-world/playground.md index 82199b7..163c415 100644 --- a/src/hello-world/playground.md +++ b/src/hello-world/playground.md @@ -6,15 +6,15 @@ minutes: 2 The [Rust Playground](https://play.rust-lang.org/) provides an easy way to run short Rust programs, and is the basis for the examples and exercises in this -course. Try running the "hello-world" program it starts with. It comes with a +course. Try running the "hello-world" program it starts with. It comes with a few handy features: - Under "Tools", use the `rustfmt` option to format your code in the "standard" way. -- Rust has two main "profiles" for generating code: Debug (extra runtime - checks, less optimization) and Release (fewer runtime checks, lots of - optimization). These are accessible under "Debug" at the top. +- Rust has two main "profiles" for generating code: Debug (extra runtime checks, + less optimization) and Release (fewer runtime checks, lots of optimization). + These are accessible under "Debug" at the top. - If you're interested, use "ASM" under "..." to see the generated assembly code. diff --git a/src/hello-world/what-is-rust.md b/src/hello-world/what-is-rust.md index e6d3e45..52909f9 100644 --- a/src/hello-world/what-is-rust.md +++ b/src/hello-world/what-is-rust.md @@ -6,29 +6,28 @@ minutes: 10 Rust is a new programming language which had its [1.0 release in 2015][1]: -* Rust is a statically compiled language in a similar role as C++ - * `rustc` uses LLVM as its backend. -* Rust supports many [platforms and - architectures](https://doc.rust-lang.org/nightly/rustc/platform-support.html): - * x86, ARM, WebAssembly, ... - * Linux, Mac, Windows, ... -* Rust is used for a wide range of devices: - * firmware and boot loaders, - * smart displays, - * mobile phones, - * desktops, - * servers. - +- Rust is a statically compiled language in a similar role as C++ + - `rustc` uses LLVM as its backend. +- Rust supports many + [platforms and architectures](https://doc.rust-lang.org/nightly/rustc/platform-support.html): + - x86, ARM, WebAssembly, ... + - Linux, Mac, Windows, ... +- Rust is used for a wide range of devices: + - firmware and boot loaders, + - smart displays, + - mobile phones, + - desktops, + - servers.
Rust fits in the same area as C++: -* High flexibility. -* High level of control. -* Can be scaled down to very constrained devices such as microcontrollers. -* Has no runtime or garbage collection. -* Focuses on reliability and safety without sacrificing performance. +- High flexibility. +- High level of control. +- Can be scaled down to very constrained devices such as microcontrollers. +- Has no runtime or garbage collection. +- Focuses on reliability and safety without sacrificing performance.
diff --git a/src/index.md b/src/index.md index bcff48c..f4c2f38 100644 --- a/src/index.md +++ b/src/index.md @@ -4,53 +4,52 @@ [![GitHub contributors](https://img.shields.io/github/contributors/google/comprehensive-rust?style=flat-square)](https://github.com/google/comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields.io/github/stars/google/comprehensive-rust?style=flat-square)](https://github.com/google/comprehensive-rust/stargazers) -This is a free Rust course developed by the Android team at Google. The course covers -the full spectrum of Rust, from basic syntax to advanced topics like generics -and error handling. +This is a free Rust course developed by the Android team at Google. The course +covers the full spectrum of Rust, from basic syntax to advanced topics like +generics and error handling. > The latest version of the course can be found at -> . If you are reading -> somewhere else, please check there for updates. +> . If you are reading somewhere +> else, please check there for updates. The goal of the course is to teach you Rust. We assume you don't know anything about Rust and hope to: -* Give you a comprehensive understanding of the Rust syntax and language. -* Enable you to modify existing programs and write new programs in Rust. -* Show you common Rust idioms. +- Give you a comprehensive understanding of the Rust syntax and language. +- Enable you to modify existing programs and write new programs in Rust. +- Show you common Rust idioms. We call the first four course days Rust Fundamentals. Building on this, you're invited to dive into one or more specialized topics: -* [Android](android.md): a half-day course on using Rust for Android platform +- [Android](android.md): a half-day course on using Rust for Android platform development (AOSP). This includes interoperability with C, C++, and Java. -* [Chromium](chromium.md): a half-day course on using Rust within Chromium - based browsers. This includes interoperability with C++ and how to include +- [Chromium](chromium.md): a half-day course on using Rust within Chromium based + browsers. This includes interoperability with C++ and how to include third-party crates in Chromium. -* [Bare-metal](bare-metal.md): a whole-day class on using Rust for bare-metal +- [Bare-metal](bare-metal.md): a whole-day class on using Rust for bare-metal (embedded) development. Both microcontrollers and application processors are covered. -* [Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We +- [Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We cover both classical concurrency (preemptively scheduling using threads and - mutexes) and async/await concurrency (cooperative multitasking using - futures). - + mutexes) and async/await concurrency (cooperative multitasking using futures). ## Non-Goals Rust is a large language and we won't be able to cover all of it in a few days. Some non-goals of this course are: -* Learning how to develop macros: please see [Chapter 19.5 in the Rust - Book](https://doc.rust-lang.org/book/ch19-06-macros.html) and [Rust by - Example](https://doc.rust-lang.org/rust-by-example/macros.html) instead. +- Learning how to develop macros: please see + [Chapter 19.5 in the Rust Book](https://doc.rust-lang.org/book/ch19-06-macros.html) + and [Rust by Example](https://doc.rust-lang.org/rust-by-example/macros.html) + instead. ## Assumptions -The course assumes that you already know how to program. Rust is a statically-typed -language and we will sometimes make comparisons with C and C++ to better -explain or contrast the Rust approach. +The course assumes that you already know how to program. Rust is a +statically-typed language and we will sometimes make comparisons with C and C++ +to better explain or contrast the Rust approach. If you know how to program in a dynamically-typed language such as Python or JavaScript, then you will be able to follow along just fine too. diff --git a/src/iterators/exercise.md b/src/iterators/exercise.md index 4881c8a..55bb176 100644 --- a/src/iterators/exercise.md +++ b/src/iterators/exercise.md @@ -11,7 +11,6 @@ Copy the following code to and make the tests pass. Use an iterator expression and `collect` the result to construct the return value. - ```rust {{#include exercise.rs:offset_differences}} unimplemented!() @@ -19,4 +18,5 @@ return value. {{#include exercise.rs:unit-tests}} ``` + [1]: https://doc.rust-lang.org/std/iter/trait.Iterator.html diff --git a/src/iterators/exercise.rs b/src/iterators/exercise.rs index 66c19b6..c3b4a41 100644 --- a/src/iterators/exercise.rs +++ b/src/iterators/exercise.rs @@ -16,8 +16,8 @@ // 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. +/// 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) -> Vec diff --git a/src/iterators/fromiterator.md b/src/iterators/fromiterator.md index e50984e..f9419a5 100644 --- a/src/iterators/fromiterator.md +++ b/src/iterators/fromiterator.md @@ -9,10 +9,7 @@ minutes: 5 ```rust,editable fn main() { let primes = vec![2, 3, 5, 7]; - let prime_squares = primes - .into_iter() - .map(|prime| prime * prime) - .collect::>(); + let prime_squares = primes.into_iter().map(|p| p * p).collect::>(); println!("prime_squares: {prime_squares:?}"); } ``` @@ -30,11 +27,10 @@ where There are two ways to specify `B` for this method: - * With the "turbofish": `some_iterator.collect::()`, as - shown. The `_` shorthand used here lets Rust infer the type of the `Vec` - elements. - * With type inference: `let prime_squares: Vec<_> = - some_iterator.collect()`. Rewrite the example to use this form. +- With the "turbofish": `some_iterator.collect::()`, as shown. + The `_` shorthand used here lets Rust infer the type of the `Vec` elements. +- With type inference: `let prime_squares: Vec<_> = some_iterator.collect()`. + Rewrite the example to use this form. There are basic implementations of `FromIterator` for `Vec`, `HashMap`, etc. There are also more specialized implementations which let you do cool things diff --git a/src/iterators/intoiterator.md b/src/iterators/intoiterator.md index 35c5b19..aeb22c2 100644 --- a/src/iterators/intoiterator.md +++ b/src/iterators/intoiterator.md @@ -48,10 +48,7 @@ impl Iterator for GridIter { } fn main() { - let grid = Grid { - x_coords: vec![3, 5, 7, 9], - y_coords: vec![10, 20, 30, 40], - }; + let grid = Grid { x_coords: vec![3, 5, 7, 9], y_coords: vec![10, 20, 30, 40] }; for (x, y) in grid { println!("point = {x}, {y}"); } @@ -63,8 +60,8 @@ fn main() { Click through to the docs for `IntoIterator`. Every implementation of `IntoIterator` must declare two types: -* `Item`: the type to iterate over, such as `i8`, -* `IntoIter`: the `Iterator` type returned by the `into_iter` method. +- `Item`: the type to iterate over, such as `i8`, +- `IntoIter`: the `Iterator` type returned by the `into_iter` method. Note that `IntoIter` and `Item` are linked: the iterator must have the same `Item` type, which means that it returns `Option` diff --git a/src/iterators/iterator.md b/src/iterators/iterator.md index 6e20b89..826e1ac 100644 --- a/src/iterators/iterator.md +++ b/src/iterators/iterator.md @@ -5,11 +5,12 @@ minutes: 5 + # `Iterator` The [`Iterator`][1] trait supports iterating over values in a collection. It -requires a `next` method and provides lots of methods. Many standard library types -implement `Iterator`, and you can implement it yourself, too: +requires a `next` method and provides lots of methods. Many standard library +types implement `Iterator`, and you can implement it yourself, too: ```rust,editable struct Fibonacci { @@ -38,15 +39,15 @@ fn main() {
-* The `Iterator` trait implements many common functional programming operations over collections - (e.g. `map`, `filter`, `reduce`, etc). This is the trait where you can find all the documentation - about them. In Rust these functions should produce the code as efficient as equivalent imperative - implementations. +- The `Iterator` trait implements many common functional programming operations + over collections (e.g. `map`, `filter`, `reduce`, etc). This is the trait + where you can find all the documentation about them. In Rust these functions + should produce the code as efficient as equivalent imperative implementations. -* `IntoIterator` is the trait that makes for loops work. It is implemented by collection types such as - `Vec` and references to them such as `&Vec` and `&[T]`. Ranges also implement it. This is why - you can iterate over a vector with `for i in some_vec { .. }` but - `some_vec.next()` doesn't exist. +- `IntoIterator` is the trait that makes for loops work. It is implemented by + collection types such as `Vec` and references to them such as `&Vec` and + `&[T]`. Ranges also implement it. This is why you can iterate over a vector + with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist.
diff --git a/src/memory-management/approaches.md b/src/memory-management/approaches.md index c4cf06c..40d98c3 100644 --- a/src/memory-management/approaches.md +++ b/src/memory-management/approaches.md @@ -6,17 +6,19 @@ minutes: 10 Traditionally, languages have fallen into two broad categories: -* Full control via manual memory management: C, C++, Pascal, ... - * Programmer decides when to allocate or free heap memory. - * Programmer must determine whether a pointer still points to valid memory. - * Studies show, programmers make mistakes. -* Full safety via automatic memory management at runtime: Java, Python, Go, Haskell, ... - * A runtime system ensures that memory is not freed until it can no longer be referenced. - * Typically implemented with reference counting, garbage collection, or RAII. +- Full control via manual memory management: C, C++, Pascal, ... + - Programmer decides when to allocate or free heap memory. + - Programmer must determine whether a pointer still points to valid memory. + - Studies show, programmers make mistakes. +- Full safety via automatic memory management at runtime: Java, Python, Go, + Haskell, ... + - A runtime system ensures that memory is not freed until it can no longer be + referenced. + - Typically implemented with reference counting, garbage collection, or RAII. Rust offers a new mix: -> Full control *and* safety via compile time enforcement of correct memory +> Full control _and_ safety via compile time enforcement of correct memory > management. It does this with an explicit ownership concept. @@ -26,20 +28,19 @@ It does this with an explicit ownership concept. This slide is intended to help students coming from other languages to put Rust in context. -* C must manage heap manually with `malloc` and `free`. Common - errors include forgetting to call `free`, calling it multiple times for the - same pointer, or dereferencing a pointer after the memory it points to has - been freed. +- C must manage heap manually with `malloc` and `free`. Common errors include + forgetting to call `free`, calling it multiple times for the same pointer, or + dereferencing a pointer after the memory it points to has been freed. -* C++ has tools like smart pointers (`unique_ptr`, `shared_ptr`) - that take advantage of language guarantees about calling destructors to - ensure memory is freed when a function returns. It is still quite easy to - mis-use these tools and create similar bugs to C. +- C++ has tools like smart pointers (`unique_ptr`, `shared_ptr`) that take + advantage of language guarantees about calling destructors to ensure memory is + freed when a function returns. It is still quite easy to mis-use these tools + and create similar bugs to C. -* Java, Go, and Python rely on the garbage collector to identify memory that - is no longer reachable and discard it. This guarantees that any pointer can - be dereferenced, eliminating use-after-free and other classes of bugs. But, - GC has a runtime cost and is difficult to tune properly. +- Java, Go, and Python rely on the garbage collector to identify memory that is + no longer reachable and discard it. This guarantees that any pointer can be + dereferenced, eliminating use-after-free and other classes of bugs. But, GC + has a runtime cost and is difficult to tune properly. Rust's ownership and borrowing model can, in many cases, get the performance of C, with alloc and free operations precisely where they are required -- zero diff --git a/src/memory-management/clone.md b/src/memory-management/clone.md index f2fbb6a..a10da95 100644 --- a/src/memory-management/clone.md +++ b/src/memory-management/clone.md @@ -4,7 +4,8 @@ minutes: 2 # Clone -Sometimes you _want_ to make a copy of a value. The `Clone` trait accomplishes this. +Sometimes you _want_ to make a copy of a value. The `Clone` trait accomplishes +this. ```rust,editable #[derive(Default)] diff --git a/src/memory-management/copy-types.md b/src/memory-management/copy-types.md index ec119cf..835222b 100644 --- a/src/memory-management/copy-types.md +++ b/src/memory-management/copy-types.md @@ -5,11 +5,13 @@ minutes: 5 + # Copy Types While move semantics are the default, certain types are copied by default: + ```rust,editable fn main() { let x = 42; @@ -24,6 +26,7 @@ These types implement the `Copy` trait. You can opt-in your own types to use copy semantics: + ```rust,editable #[derive(Copy, Clone, Debug)] struct Point(i32, i32); @@ -36,22 +39,26 @@ fn main() { } ``` -* After the assignment, both `p1` and `p2` own their own data. -* We can also use `p1.clone()` to explicitly copy the data. +- After the assignment, both `p1` and `p2` own their own data. +- We can also use `p1.clone()` to explicitly copy the data.
Copying and cloning are not the same thing: -* Copying refers to bitwise copies of memory regions and does not work on arbitrary objects. -* Copying does not allow for custom logic (unlike copy constructors in C++). -* Cloning is a more general operation and also allows for custom behavior by implementing the `Clone` trait. -* Copying does not work on types that implement the `Drop` trait. +- Copying refers to bitwise copies of memory regions and does not work on + arbitrary objects. +- Copying does not allow for custom logic (unlike copy constructors in C++). +- Cloning is a more general operation and also allows for custom behavior by + implementing the `Clone` trait. +- Copying does not work on types that implement the `Drop` trait. In the above example, try the following: -* Add a `String` field to `struct Point`. It will not compile because `String` is not a `Copy` type. -* Remove `Copy` from the `derive` attribute. The compiler error is now in the `println!` for `p1`. -* Show that it works if you clone `p1` instead. +- Add a `String` field to `struct Point`. It will not compile because `String` + is not a `Copy` type. +- Remove `Copy` from the `derive` attribute. The compiler error is now in the + `println!` for `p1`. +- Show that it works if you clone `p1` instead.
diff --git a/src/memory-management/drop.md b/src/memory-management/drop.md index 986fddd..698a067 100644 --- a/src/memory-management/drop.md +++ b/src/memory-management/drop.md @@ -4,7 +4,8 @@ minutes: 10 # The `Drop` Trait -Values which implement [`Drop`][1] can specify code to run when they go out of scope: +Values which implement [`Drop`][1] can specify code to run when they go out of +scope: ```rust,editable struct Droppable { @@ -35,24 +36,24 @@ fn main() {
-* Note that `std::mem::drop` is not the same as `std::ops::Drop::drop`. -* Values are automatically dropped when they go out of scope. -* When a value is dropped, if it implements `std::ops::Drop` then its `Drop::drop` implementation - will be called. -* All its fields will then be dropped too, whether or not it implements `Drop`. -* `std::mem::drop` is just an empty function that takes any value. The significance is that it takes - ownership of the value, so at the end of its scope it gets dropped. This makes it a convenient way - to explicitly drop values earlier than they would otherwise go out of scope. - * This can be useful for objects that do some work on `drop`: releasing locks, closing files, - etc. +- Note that `std::mem::drop` is not the same as `std::ops::Drop::drop`. +- Values are automatically dropped when they go out of scope. +- When a value is dropped, if it implements `std::ops::Drop` then its + `Drop::drop` implementation will be called. +- All its fields will then be dropped too, whether or not it implements `Drop`. +- `std::mem::drop` is just an empty function that takes any value. The + significance is that it takes ownership of the value, so at the end of its + scope it gets dropped. This makes it a convenient way to explicitly drop + values earlier than they would otherwise go out of scope. + - This can be useful for objects that do some work on `drop`: releasing locks, + closing files, etc. Discussion points: -* Why doesn't `Drop::drop` take `self`? - * Short-answer: If it did, `std::mem::drop` would be called at the end of - the block, resulting in another call to `Drop::drop`, and a stack - overflow! -* Try replacing `drop(a)` with `a.drop()`. +- Why doesn't `Drop::drop` take `self`? + - Short-answer: If it did, `std::mem::drop` would be called at the end of the + block, resulting in another call to `Drop::drop`, and a stack overflow! +- Try replacing `drop(a)` with `a.drop()`.
diff --git a/src/memory-management/exercise.rs b/src/memory-management/exercise.rs index e5d536f..44251c5 100644 --- a/src/memory-management/exercise.rs +++ b/src/memory-management/exercise.rs @@ -114,10 +114,8 @@ impl PackageBuilder { fn main() { let base64 = PackageBuilder::new("base64").version("0.13").build(); println!("base64: {base64:?}"); - let log = PackageBuilder::new("log") - .version("0.4") - .language(Language::Rust) - .build(); + let log = + PackageBuilder::new("log").version("0.4").language(Language::Rust).build(); println!("log: {log:?}"); let serde = PackageBuilder::new("serde") .authors(vec!["djmitche".into()]) diff --git a/src/memory-management/move.md b/src/memory-management/move.md index b149985..aacfaa3 100644 --- a/src/memory-management/move.md +++ b/src/memory-management/move.md @@ -15,9 +15,9 @@ fn main() { } ``` -* The assignment of `s1` to `s2` transfers ownership. -* When `s1` goes out of scope, nothing happens: it does not own anything. -* When `s2` goes out of scope, the string data is freed. +- The assignment of `s1` to `s2` transfers ownership. +- When `s1` goes out of scope, nothing happens: it does not own anything. +- When `s2` goes out of scope, the string data is freed. Before move to `s2`: @@ -76,21 +76,29 @@ fn main() {
-* Mention that this is the opposite of the defaults in C++, which copies by value unless you use `std::move` (and the move constructor is defined!). +- Mention that this is the opposite of the defaults in C++, which copies by + value unless you use `std::move` (and the move constructor is defined!). -* It is only the ownership that moves. Whether any machine code is generated to manipulate the data itself is a matter of optimization, and such copies are aggressively optimized away. +- It is only the ownership that moves. Whether any machine code is generated to + manipulate the data itself is a matter of optimization, and such copies are + aggressively optimized away. -* Simple values (such as integers) can be marked `Copy` (see later slides). +- Simple values (such as integers) can be marked `Copy` (see later slides). -* In Rust, clones are explicit (by using `clone`). +- In Rust, clones are explicit (by using `clone`). In the `say_hello` example: -* With the first call to `say_hello`, `main` gives up ownership of `name`. Afterwards, `name` cannot be used anymore within `main`. -* The heap memory allocated for `name` will be freed at the end of the `say_hello` function. -* `main` can retain ownership if it passes `name` as a reference (`&name`) and if `say_hello` accepts a reference as a parameter. -* Alternatively, `main` can pass a clone of `name` in the first call (`name.clone()`). -* Rust makes it harder than C++ to inadvertently create copies by making move semantics the default, and by forcing programmers to make clones explicit. +- With the first call to `say_hello`, `main` gives up ownership of `name`. + Afterwards, `name` cannot be used anymore within `main`. +- The heap memory allocated for `name` will be freed at the end of the + `say_hello` function. +- `main` can retain ownership if it passes `name` as a reference (`&name`) and + if `say_hello` accepts a reference as a parameter. +- Alternatively, `main` can pass a clone of `name` in the first call + (`name.clone()`). +- Rust makes it harder than C++ to inadvertently create copies by making move + semantics the default, and by forcing programmers to make clones explicit. # More to Explore @@ -103,12 +111,11 @@ std::string s1 = "Cpp"; std::string s2 = s1; // Duplicate the data in s1. ``` -* The heap data from `s1` is duplicated and `s2` gets its own independent copy. -* When `s1` and `s2` go out of scope, they each free their own memory. +- The heap data from `s1` is duplicated and `s2` gets its own independent copy. +- When `s1` and `s2` go out of scope, they each free their own memory. Before copy-assignment: - ```bob Stack Heap .- - - - - - - - - - - - - -. .- - - - - - - - - - - -. @@ -146,7 +153,6 @@ After copy-assignment: `- - - - - - - - - - - - - -' ``` - Key points: - C++ has made a slightly different choice than Rust. Because `=` copies data, @@ -158,8 +164,8 @@ Key points: would take place. After the move, `s1` would be in a valid but unspecified state. Unlike Rust, the programmer is allowed to keep using `s1`. -- Unlike Rust, `=` in C++ can run arbitrary code as determined by the type - which is being copied or moved. +- Unlike Rust, `=` in C++ can run arbitrary code as determined by the type which + is being copied or moved. [`std::move`]: https://en.cppreference.com/w/cpp/utility/move diff --git a/src/memory-management/ownership.md b/src/memory-management/ownership.md index 1ee9105..c1214a6 100644 --- a/src/memory-management/ownership.md +++ b/src/memory-management/ownership.md @@ -8,6 +8,7 @@ All variable bindings have a _scope_ where they are valid and it is an error to use a variable outside its scope: + ```rust,editable,compile_fail struct Point(i32, i32); @@ -23,8 +24,8 @@ fn main() { We say that the variable _owns_ the value. Every Rust value has precisely one owner at all times. -At the end of the scope, the variable is _dropped_ and the data is freed. -A destructor can run here to free up resources. +At the end of the scope, the variable is _dropped_ and the data is freed. A +destructor can run here to free up resources.
diff --git a/src/memory-management/review.md b/src/memory-management/review.md index e6d588b..7a70d70 100644 --- a/src/memory-management/review.md +++ b/src/memory-management/review.md @@ -6,16 +6,16 @@ minutes: 5 Programs allocate memory in two ways: -* Stack: Continuous area of memory for local variables. - * Values have fixed sizes known at compile time. - * Extremely fast: just move a stack pointer. - * Easy to manage: follows function calls. - * Great memory locality. +- Stack: Continuous area of memory for local variables. + - Values have fixed sizes known at compile time. + - Extremely fast: just move a stack pointer. + - Easy to manage: follows function calls. + - Great memory locality. -* Heap: Storage of values outside of function calls. - * Values have dynamic sizes determined at runtime. - * Slightly slower than the stack: some book-keeping needed. - * No guarantee of memory locality. +- Heap: Storage of values outside of function calls. + - Values have dynamic sizes determined at runtime. + - Slightly slower than the stack: some book-keeping needed. + - No guarantee of memory locality. ## Example @@ -44,9 +44,12 @@ fn main() {
-* Mention that a `String` is backed by a `Vec`, so it has a capacity and length and can grow if mutable via reallocation on the heap. +- Mention that a `String` is backed by a `Vec`, so it has a capacity and length + and can grow if mutable via reallocation on the heap. -* If students ask about it, you can mention that the underlying memory is heap allocated using the [System Allocator] and custom allocators can be implemented using the [Allocator API] +- If students ask about it, you can mention that the underlying memory is heap + allocated using the [System Allocator] and custom allocators can be + implemented using the [Allocator API] ## More to Explore diff --git a/src/methods-and-traits/Cargo.toml b/src/methods-and-traits/Cargo.toml index b5347e6..b04dbde 100644 --- a/src/methods-and-traits/Cargo.toml +++ b/src/methods-and-traits/Cargo.toml @@ -7,4 +7,3 @@ publish = false [[bin]] name = "methods-and-traits" path = "exercise.rs" - diff --git a/src/methods-and-traits/deriving.md b/src/methods-and-traits/deriving.md index 16564b9..ac4efe9 100644 --- a/src/methods-and-traits/deriving.md +++ b/src/methods-and-traits/deriving.md @@ -17,7 +17,7 @@ struct Player { fn main() { let p1 = Player::default(); // Default trait adds `default` constructor. - let mut p2 = p1.clone(); // Clone trait adds `clone` method. + let mut p2 = p1.clone(); // Clone trait adds `clone` method. p2.name = String::from("EldurScrollz"); // Debug trait adds support for printing with `{:?}`. println!("{:?} vs. {:?}", p1, p2); diff --git a/src/methods-and-traits/exercise.md b/src/methods-and-traits/exercise.md index 2b2f40b..d20f189 100644 --- a/src/methods-and-traits/exercise.md +++ b/src/methods-and-traits/exercise.md @@ -9,11 +9,11 @@ trait objects. We'll only implement the drawing of it (as text) for simplicity. We will have a number of widgets in our library: -* `Window`: has a `title` and contains other widgets. -* `Button`: has a `label`. In reality, it would also take a callback - function to allow the program to do something when the button is clicked - but we won't include that since we're only drawing the GUI. -* `Label`: has a `label`. +- `Window`: has a `title` and contains other widgets. +- `Button`: has a `label`. In reality, it would also take a callback function to + allow the program to do something when the button is clicked but we won't + include that since we're only drawing the GUI. +- `Label`: has a `label`. The widgets will implement a `Widget` trait, see below. diff --git a/src/methods-and-traits/exercise.rs b/src/methods-and-traits/exercise.rs index 24bf690..78dbe27 100644 --- a/src/methods-and-traits/exercise.rs +++ b/src/methods-and-traits/exercise.rs @@ -35,9 +35,7 @@ pub struct Label { impl Label { fn new(label: &str) -> Label { - Label { - label: label.to_owned(), - } + Label { label: label.to_owned() } } } @@ -47,9 +45,7 @@ pub struct Button { impl Button { fn new(label: &str) -> Button { - Button { - label: Label::new(label), - } + Button { label: Label::new(label) } } } @@ -60,10 +56,7 @@ pub struct Window { impl Window { fn new(title: &str) -> Window { - Window { - title: title.to_owned(), - widgets: Vec::new(), - } + Window { title: title.to_owned(), widgets: Vec::new() } } fn add_widget(&mut self, widget: Box) { @@ -126,11 +119,7 @@ impl Widget for Button { impl Widget for Label { fn width(&self) -> usize { - self.label - .lines() - .map(|line| line.chars().count()) - .max() - .unwrap_or(0) + self.label.lines().map(|line| line.chars().count()).max().unwrap_or(0) } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { diff --git a/src/methods-and-traits/methods.md b/src/methods-and-traits/methods.md index 83691fe..0626972 100644 --- a/src/methods-and-traits/methods.md +++ b/src/methods-and-traits/methods.md @@ -15,22 +15,26 @@ struct Race { } impl Race { - fn new(name: &str) -> Self { // No receiver, a static method + // No receiver, a static method + fn new(name: &str) -> Self { Self { name: String::from(name), laps: Vec::new() } } - fn add_lap(&mut self, lap: i32) { // Exclusive borrowed read-write access to self + // Exclusive borrowed read-write access to self + fn add_lap(&mut self, lap: i32) { self.laps.push(lap); } - fn print_laps(&self) { // Shared and read-only borrowed access to self + // Shared and read-only borrowed access to self + fn print_laps(&self) { println!("Recorded {} laps for {}:", self.laps.len(), self.name); for (idx, lap) in self.laps.iter().enumerate() { println!("Lap {idx}: {lap} sec"); } } - fn finish(self) { // Exclusive ownership of self + // Exclusive ownership of self + fn finish(self) { let total: i32 = self.laps.iter().sum(); println!("Race {} is finished, total lap time: {}", self.name, total); } @@ -48,32 +52,42 @@ fn main() { } ``` -The `self` arguments specify the "receiver" - the object the method acts on. There -are several common receivers for a method: +The `self` arguments specify the "receiver" - the object the method acts on. +There are several common receivers for a method: -* `&self`: borrows the object from the caller using a shared and immutable +- `&self`: borrows the object from the caller using a shared and immutable reference. The object can be used again afterwards. -* `&mut self`: borrows the object from the caller using a unique and mutable +- `&mut self`: borrows the object from the caller using a unique and mutable reference. The object can be used again afterwards. -* `self`: takes ownership of the object and moves it away from the caller. The - method becomes the owner of the object. The object will be dropped (deallocated) - when the method returns, unless its ownership is explicitly +- `self`: takes ownership of the object and moves it away from the caller. The + method becomes the owner of the object. The object will be dropped + (deallocated) when the method returns, unless its ownership is explicitly transmitted. Complete ownership does not automatically mean mutability. -* `mut self`: same as above, but the method can mutate the object. -* No receiver: this becomes a static method on the struct. Typically used to +- `mut self`: same as above, but the method can mutate the object. +- No receiver: this becomes a static method on the struct. Typically used to create constructors which are called `new` by convention.
Key Points: -* It can be helpful to introduce methods by comparing them to functions. - * Methods are called on an instance of a type (such as a struct or enum), the first parameter represents the instance as `self`. - * Developers may choose to use methods to take advantage of method receiver syntax and to help keep them more organized. By using methods we can keep all the implementation code in one predictable place. -* Point out the use of the keyword `self`, a method receiver. - * Show that it is an abbreviated term for `self: Self` and perhaps show how the struct name could also be used. - * Explain that `Self` is a type alias for the type the `impl` block is in and can be used elsewhere in the block. - * Note how `self` is used like other structs and dot notation can be used to refer to individual fields. - * This might be a good time to demonstrate how the `&self` differs from `self` by trying to run `finish` twice. - * Beyond variants on `self`, there are also [special wrapper types](https://doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be receiver types, such as `Box`. + +- It can be helpful to introduce methods by comparing them to functions. + - Methods are called on an instance of a type (such as a struct or enum), the + first parameter represents the instance as `self`. + - Developers may choose to use methods to take advantage of method receiver + syntax and to help keep them more organized. By using methods we can keep + all the implementation code in one predictable place. +- Point out the use of the keyword `self`, a method receiver. + - Show that it is an abbreviated term for `self: Self` and perhaps show how + the struct name could also be used. + - Explain that `Self` is a type alias for the type the `impl` block is in and + can be used elsewhere in the block. + - Note how `self` is used like other structs and dot notation can be used to + refer to individual fields. + - This might be a good time to demonstrate how the `&self` differs from `self` + by trying to run `finish` twice. + - Beyond variants on `self`, there are also + [special wrapper types](https://doc.rust-lang.org/reference/special-types-and-traits.html) + allowed to be receiver types, such as `Box`.
diff --git a/src/methods-and-traits/trait-objects.md b/src/methods-and-traits/trait-objects.md index 65c678f..ba74ec9 100644 --- a/src/methods-and-traits/trait-objects.md +++ b/src/methods-and-traits/trait-objects.md @@ -7,19 +7,28 @@ minutes: 10 Trait objects allow for values of different types, for instance in a collection: ```rust,editable -struct Dog { name: String, age: i8 } -struct Cat { lives: i8 } // No name needed, cats won't respond anyway. +struct Dog { + name: String, + age: i8, +} +struct Cat { + lives: i8, +} trait Pet { fn talk(&self) -> String; } impl Pet for Dog { - fn talk(&self) -> String { format!("Woof, my name is {}!", self.name) } + fn talk(&self) -> String { + format!("Woof, my name is {}!", self.name) + } } impl Pet for Cat { - fn talk(&self) -> String { String::from("Miau!") } + fn talk(&self) -> String { + String::from("Miau!") + } } fn main() { @@ -74,19 +83,19 @@ Memory layout after allocating `pets`: - `dyn Pet` is a way to tell the compiler about a dynamically sized type that implements `Pet`. - In the example, `pets` is allocated on the stack and the vector data is on the - heap. The two vector elements are *fat pointers*: + heap. The two vector elements are _fat pointers_: - A fat pointer is a double-width pointer. It has two components: a pointer to - the actual object and a pointer to the [virtual method table] (vtable) for the - `Pet` implementation of that particular object. + the actual object and a pointer to the [virtual method table] (vtable) for + the `Pet` implementation of that particular object. - The data for the `Dog` named Fido is the `name` and `age` fields. The `Cat` has a `lives` field. - Compare these outputs in the above example: - ```rust,ignore - println!("{} {}", std::mem::size_of::(), std::mem::size_of::()); - println!("{} {}", std::mem::size_of::<&Dog>(), std::mem::size_of::<&Cat>()); - println!("{}", std::mem::size_of::<&dyn Pet>()); - println!("{}", std::mem::size_of::>()); - ``` + ```rust,ignore + println!("{} {}", std::mem::size_of::(), std::mem::size_of::()); + println!("{} {}", std::mem::size_of::<&Dog>(), std::mem::size_of::<&Cat>()); + println!("{}", std::mem::size_of::<&dyn Pet>()); + println!("{}", std::mem::size_of::>()); + ``` [virtual method table]: https://en.wikipedia.org/wiki/Virtual_method_table diff --git a/src/methods-and-traits/traits.md b/src/methods-and-traits/traits.md index ac59b1b..ce483b3 100644 --- a/src/methods-and-traits/traits.md +++ b/src/methods-and-traits/traits.md @@ -7,8 +7,13 @@ minutes: 10 Rust lets you abstract over types with traits. They're similar to interfaces: ```rust,editable -struct Dog { name: String, age: i8 } -struct Cat { lives: i8 } // No name needed, cats won't respond anyway. +struct Dog { + name: String, + age: i8, +} +struct Cat { + lives: i8, +} trait Pet { fn talk(&self) -> String; @@ -19,11 +24,15 @@ trait Pet { } impl Pet for Dog { - fn talk(&self) -> String { format!("Woof, my name is {}!", self.name) } + fn talk(&self) -> String { + format!("Woof, my name is {}!", self.name) + } } impl Pet for Cat { - fn talk(&self) -> String { String::from("Miau!") } + fn talk(&self) -> String { + String::from("Miau!") + } } fn main() { @@ -37,12 +46,12 @@ fn main() {
-* A trait defines a number of methods that types must have in order to implement +- A trait defines a number of methods that types must have in order to implement the trait. -* Traits are implemented in an `impl for { .. }` block. +- Traits are implemented in an `impl for { .. }` block. -* Traits may specify pre-implemented (provided) methods and methods that users +- Traits may specify pre-implemented (provided) methods and methods that users are required to implement themselves. Provided methods can rely on required methods. In this case, `greet` is provided, and relies on `talk`. diff --git a/src/modules/exercise.md b/src/modules/exercise.md index 4c2154f..82d0bc3 100644 --- a/src/modules/exercise.md +++ b/src/modules/exercise.md @@ -4,13 +4,13 @@ minutes: 20 # Exercise: Modules for the GUI Library -In this exercise, you will reorganize the GUI Library exercise from the -"Methods and Traits" segment of the course into a collection of modules. It is -typical to put each type or set of closely-related types into its own module, -so each widget type should get its own module. +In this exercise, you will reorganize the GUI Library exercise from the "Methods +and Traits" segment of the course into a collection of modules. It is typical to +put each type or set of closely-related types into its own module, so each +widget type should get its own module. -If you no longer have your version, that's fine - refer back to the [provided -solution](../methods-and-traits/solution.html). +If you no longer have your version, that's fine - refer back to the +[provided solution](../methods-and-traits/solution.html). ## Cargo Setup diff --git a/src/modules/filesystem.md b/src/modules/filesystem.md index 16a1636..6771cd2 100644 --- a/src/modules/filesystem.md +++ b/src/modules/filesystem.md @@ -11,12 +11,13 @@ mod garden; ``` This tells rust that the `garden` module content is found at `src/garden.rs`. -Similarly, a `garden::vegetables` module can be found at `src/garden/vegetables.rs`. +Similarly, a `garden::vegetables` module can be found at +`src/garden/vegetables.rs`. The `crate` root is in: -* `src/lib.rs` (for a library crate) -* `src/main.rs` (for a binary crate) +- `src/lib.rs` (for a library crate) +- `src/main.rs` (for a binary crate) Modules defined in files can be documented, too, using "inner doc comments". These document the item that contains them -- in this case, a module. @@ -26,24 +27,29 @@ These document the item that contains them -- in this case, a module. //! implementation. // Re-export types from this module. -pub use seeds::SeedPacket; pub use garden::Garden; +pub use seeds::SeedPacket; /// Sow the given seed packets. -pub fn sow(seeds: Vec) { todo!() } +pub fn sow(seeds: Vec) { + todo!() +} /// Harvest the produce in the garden that is ready. -pub fn harvest(garden: &mut Garden) { todo!() } +pub fn harvest(garden: &mut Garden) { + todo!() +} ```
-* Before Rust 2018, modules needed to be located at `module/mod.rs` instead of `module.rs`, and this is still a working alternative for editions after 2018. +- Before Rust 2018, modules needed to be located at `module/mod.rs` instead of + `module.rs`, and this is still a working alternative for editions after 2018. -* The main reason to introduce `filename.rs` as alternative to `filename/mod.rs` +- The main reason to introduce `filename.rs` as alternative to `filename/mod.rs` was because many files named `mod.rs` can be hard to distinguish in IDEs. -* Deeper nesting can use folders, even if the main module is a file: +- Deeper nesting can use folders, even if the main module is a file: ```ignore src/ @@ -53,14 +59,14 @@ pub fn harvest(garden: &mut Garden) { todo!() } └── sub_module.rs ``` -* The place rust will look for modules can be changed with a compiler directive: +- The place rust will look for modules can be changed with a compiler directive: ```rust,ignore #[path = "some/path.rs"] mod some_module; ``` - This is useful, for example, if you would like to place tests for a module in a file named - `some_module_test.rs`, similar to the convention in Go. + This is useful, for example, if you would like to place tests for a module in + a file named `some_module_test.rs`, similar to the convention in Go.
diff --git a/src/modules/modules.md b/src/modules/modules.md index 5a59767..d063088 100644 --- a/src/modules/modules.md +++ b/src/modules/modules.md @@ -29,8 +29,10 @@ fn main() {
-* Packages provide functionality and include a `Cargo.toml` file that describes how to build a bundle of 1+ crates. -* Crates are a tree of modules, where a binary crate creates an executable and a library crate compiles to a library. -* Modules define organization, scope, and are the focus of this section. +- Packages provide functionality and include a `Cargo.toml` file that describes + how to build a bundle of 1+ crates. +- Crates are a tree of modules, where a binary crate creates an executable and a + library crate compiles to a library. +- Modules define organization, scope, and are the focus of this section.
diff --git a/src/modules/paths.md b/src/modules/paths.md index 53bdba6..f8f570a 100644 --- a/src/modules/paths.md +++ b/src/modules/paths.md @@ -4,8 +4,8 @@ minutes: 10 # use, super, self -A module can bring symbols from another module into scope with `use`. -You will typically see something like this at the top of each module: +A module can bring symbols from another module into scope with `use`. You will +typically see something like this at the top of each module: ```rust,editable use std::collections::HashSet; @@ -17,16 +17,16 @@ use std::process::abort; Paths are resolved as follows: 1. As a relative path: - * `foo` or `self::foo` refers to `foo` in the current module, - * `super::foo` refers to `foo` in the parent module. + - `foo` or `self::foo` refers to `foo` in the current module, + - `super::foo` refers to `foo` in the parent module. 2. As an absolute path: - * `crate::foo` refers to `foo` in the root of the current crate, - * `bar::foo` refers to `foo` in the `bar` crate. + - `crate::foo` refers to `foo` in the root of the current crate, + - `bar::foo` refers to `foo` in the `bar` crate.
-* It is common to "re-export" symbols at a shorter path. For example, the +- It is common to "re-export" symbols at a shorter path. For example, the top-level `lib.rs` in a crate might have ```rust,ignore @@ -39,14 +39,14 @@ Paths are resolved as follows: making `DiskStorage` and `NetworkStorage` available to other crates with a convenient, short path. -* For the most part, only items that appear in a module need to be `use`'d. - However, a trait must be in scope to call any methods on that trait, even if - a type implementing that trait is already in scope. For example, to use the +- For the most part, only items that appear in a module need to be `use`'d. + However, a trait must be in scope to call any methods on that trait, even if a + type implementing that trait is already in scope. For example, to use the `read_to_string` method on a type implementing the `Read` trait, you need to `use std::io::Read`. -* The `use` statement can have a wildcard: `use std::io::*`. This is - discouraged because it is not clear which items are imported, and those might - change over time. +- The `use` statement can have a wildcard: `use std::io::*`. This is discouraged + because it is not clear which items are imported, and those might change over + time.
diff --git a/src/modules/solution.md b/src/modules/solution.md index 604f5b7..12ed1c6 100644 --- a/src/modules/solution.md +++ b/src/modules/solution.md @@ -62,20 +62,14 @@ pub struct Label { impl Label { pub fn new(label: &str) -> Label { - Label { - label: label.to_owned(), - } + Label { label: label.to_owned() } } } impl Widget for Label { fn width(&self) -> usize { // ANCHOR_END: Label-width - self.label - .lines() - .map(|line| line.chars().count()) - .max() - .unwrap_or(0) + self.label.lines().map(|line| line.chars().count()).max().unwrap_or(0) } // ANCHOR: Label-draw_into @@ -96,9 +90,7 @@ pub struct Button { impl Button { pub fn new(label: &str) -> Button { - Button { - label: Label::new(label), - } + Button { label: Label::new(label) } } } @@ -135,10 +127,7 @@ pub struct Window { impl Window { pub fn new(title: &str) -> Window { - Window { - title: title.to_owned(), - widgets: Vec::new(), - } + Window { title: title.to_owned(), widgets: Vec::new() } } pub fn add_widget(&mut self, widget: Box) { @@ -192,9 +181,8 @@ use widgets::Widget; fn main() { let mut window = widgets::Window::new("Rust GUI Demo 1.23"); - window.add_widget(Box::new(widgets::Label::new( - "This is a small text GUI demo.", - ))); + window + .add_widget(Box::new(widgets::Label::new("This is a small text GUI demo."))); window.add_widget(Box::new(widgets::Button::new("Click me!"))); window.draw(); } diff --git a/src/modules/visibility.md b/src/modules/visibility.md index 92914e7..3d9db79 100644 --- a/src/modules/visibility.md +++ b/src/modules/visibility.md @@ -6,9 +6,9 @@ minutes: 5 Modules are a privacy boundary: -* Module items are private by default (hides implementation details). -* Parent and sibling items are always visible. -* In other words, if an item is visible in module `foo`, it's visible in all the +- Module items are private by default (hides implementation details). +- Parent and sibling items are always visible. +- In other words, if an item is visible in module `foo`, it's visible in all the descendants of `foo`. ```rust,editable @@ -40,13 +40,16 @@ fn main() {
-* Use the `pub` keyword to make modules public. +- Use the `pub` keyword to make modules public. -Additionally, there are advanced `pub(...)` specifiers to restrict the scope of public visibility. +Additionally, there are advanced `pub(...)` specifiers to restrict the scope of +public visibility. -* See the [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself). -* Configuring `pub(crate)` visibility is a common pattern. -* Less commonly, you can give visibility to a specific path. -* In any case, visibility must be granted to an ancestor module (and all of its descendants). +- See the + [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself). +- Configuring `pub(crate)` visibility is a common pattern. +- Less commonly, you can give visibility to a specific path. +- In any case, visibility must be granted to an ancestor module (and all of its + descendants).
diff --git a/src/other-resources.md b/src/other-resources.md index 7376c28..5e858c4 100644 --- a/src/other-resources.md +++ b/src/other-resources.md @@ -7,55 +7,53 @@ online. The Rust project hosts many resources. These cover Rust in general: -* [The Rust Programming Language](https://doc.rust-lang.org/book/): the +- [The Rust Programming Language](https://doc.rust-lang.org/book/): the canonical free book about Rust. Covers the language in detail and includes a few projects for people to build. -* [Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the Rust +- [Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the Rust syntax via a series of examples which showcase different constructs. Sometimes includes small exercises where you are asked to expand on the code in the examples. -* [Rust Standard Library](https://doc.rust-lang.org/std/): full documentation of +- [Rust Standard Library](https://doc.rust-lang.org/std/): full documentation of the standard library for Rust. -* [The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete book +- [The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete book which describes the Rust grammar and memory model. More specialized guides hosted on the official Rust site: -* [The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, +- [The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, including working with raw pointers and interfacing with other languages (FFI). -* [Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): +- [Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): covers the new asynchronous programming model which was introduced after the Rust Book was written. -* [The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): an +- [The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): an introduction to using Rust on embedded devices without an operating system. ## Unofficial Learning Material A small selection of other guides and tutorial for Rust: -* [Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust +- [Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust from the perspective of low-level C programmers. -* [Rust for Embedded C - Programmers](https://docs.opentitan.org/doc/ug/rust_for_c/): covers Rust from - the perspective of developers who write firmware in C. -* [Rust for professionals](https://overexact.com/rust-for-professionals/): +- [Rust for Embedded C Programmers](https://docs.opentitan.org/doc/ug/rust_for_c/): + covers Rust from the perspective of developers who write firmware in C. +- [Rust for professionals](https://overexact.com/rust-for-professionals/): covers the syntax of Rust using side-by-side comparisons with other languages such as C, C++, Java, JavaScript, and Python. -* [Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help +- [Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help you learn Rust. -* [Ferrous Teaching - Material](https://ferrous-systems.github.io/teaching-material/index.html): a - series of small presentations covering both basic and advanced part of the +- [Ferrous Teaching Material](https://ferrous-systems.github.io/teaching-material/index.html): + a series of small presentations covering both basic and advanced part of the Rust language. Other topics such as WebAssembly, and async/await are also covered. -* [Beginner's Series to - Rust](https://docs.microsoft.com/en-us/shows/beginners-series-to-rust/) and - [Take your first steps with - Rust](https://docs.microsoft.com/en-us/learn/paths/rust-first-steps/): two - Rust guides aimed at new developers. The first is a set of 35 videos and the - second is a set of 11 modules which covers Rust syntax and basic constructs. -* [Learn Rust With Entirely Too Many Linked +- [Beginner's Series to Rust](https://docs.microsoft.com/en-us/shows/beginners-series-to-rust/) + and + [Take your first steps with Rust](https://docs.microsoft.com/en-us/learn/paths/rust-first-steps/): + two Rust guides aimed at new developers. The first is a set of 35 videos and + the second is a set of 11 modules which covers Rust syntax and basic + constructs. +- [Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial.github.io/too-many-lists/): in-depth exploration of Rust's memory management rules, through implementing a few different types of list structures. diff --git a/src/pattern-matching/destructuring.md b/src/pattern-matching/destructuring.md index c419e38..db84072 100644 --- a/src/pattern-matching/destructuring.md +++ b/src/pattern-matching/destructuring.md @@ -11,6 +11,7 @@ Like tuples, structs and enums can also be destructured by matching: ```rust,editable {{#include ../../third_party/rust-by-example/destructuring-structs.rs}} ``` + ## Enums Patterns can also be used to bind variables to parts of your values. This is how @@ -47,18 +48,25 @@ arm, `half` is bound to the value inside the `Ok` variant. In the second arm, # Structs -* Change the literal values in `foo` to match with the other patterns. -* Add a new field to `Foo` and make changes to the pattern as needed. -* The distinction between a capture and a constant expression can be hard to - spot. Try changing the `2` in the second arm to a variable, and see that it subtly - doesn't work. Change it to a `const` and see it working again. +- Change the literal values in `foo` to match with the other patterns. +- Add a new field to `Foo` and make changes to the pattern as needed. +- The distinction between a capture and a constant expression can be hard to + spot. Try changing the `2` in the second arm to a variable, and see that it + subtly doesn't work. Change it to a `const` and see it working again. # Enums Key points: -* The `if`/`else` expression is returning an enum that is later unpacked with a `match`. -* You can try adding a third variant to the enum definition and displaying the errors when running the code. Point out the places where your code is now inexhaustive and how the compiler tries to give you hints. -* The values in the enum variants can only be accessed after being pattern matched. The pattern binds references to the fields in the "match arm" after the `=>`. -* Demonstrate what happens when the search is inexhaustive. Note the advantage the Rust compiler provides by confirming when all cases are handled. + +- The `if`/`else` expression is returning an enum that is later unpacked with a + `match`. +- You can try adding a third variant to the enum definition and displaying the + errors when running the code. Point out the places where your code is now + inexhaustive and how the compiler tries to give you hints. +- The values in the enum variants can only be accessed after being pattern + matched. The pattern binds references to the fields in the "match arm" after + the `=>`. +- Demonstrate what happens when the search is inexhaustive. Note the advantage + the Rust compiler provides by confirming when all cases are handled.
diff --git a/src/pattern-matching/exercise.md b/src/pattern-matching/exercise.md index b485667..faab503 100644 --- a/src/pattern-matching/exercise.md +++ b/src/pattern-matching/exercise.md @@ -12,15 +12,13 @@ To evaluate a boxed expression, use the deref operator (`*`) to "unbox" it: `eval(*boxed_expr)`. Some expressions cannot be evaluated and will return an error. The standard -[`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) type is an -enum that represents either a successful value (`Ok(Value)`) or an error -(`Err(String)`). We will cover this type in detail later. - -Copy and paste the code into the Rust playground, and begin implementing -`eval`. The final product should pass the tests. It may be helpful to use -`todo!()` and get the tests to pass one-by-one. You can also skip a test -temporarily with +[`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) +type is an enum that represents either a successful value (`Ok(Value)`) or an +error (`Err(String)`). We will cover this type in detail later. + +Copy and paste the code into the Rust playground, and begin implementing `eval`. +The final product should pass the tests. It may be helpful to use `todo!()` and +get the tests to pass one-by-one. You can also skip a test temporarily with `#[ignore]`: ```none @@ -43,4 +41,3 @@ integer overflow. How could you handle this with `Result` instead of a panic? {{#include exercise.rs:tests}} ``` - diff --git a/src/pattern-matching/exercise.rs b/src/pattern-matching/exercise.rs index 9204f1b..84a5163 100644 --- a/src/pattern-matching/exercise.rs +++ b/src/pattern-matching/exercise.rs @@ -30,11 +30,7 @@ enum Operation { #[derive(Debug)] enum Expression { /// An operation on two subexpressions. - Op { - op: Operation, - left: Box, - right: Box, - }, + Op { op: Operation, left: Box, right: Box }, /// A literal value Value(i64), diff --git a/src/pattern-matching/let-control-flow.md b/src/pattern-matching/let-control-flow.md index 67407a2..98cac6d 100644 --- a/src/pattern-matching/let-control-flow.md +++ b/src/pattern-matching/let-control-flow.md @@ -10,10 +10,11 @@ are used for pattern matching: - `if let` expressions - `while let` expressions - `match` expressions + # `if let` expressions -The [`if let` -expression](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions) +The +[`if let` expression](https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions) lets you execute different code depending on whether a value matches a pattern: ```rust,editable @@ -33,12 +34,12 @@ fn main() { } ``` -# `let else` expressions +# `let else` expressions + For the common case of matching a pattern and returning from the function, use -[`let -else`](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html). -The "else" case must diverge (`return`, `break`, or panic - anything but -falling off the end of the block). +[`let else`](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html). +The "else" case must diverge (`return`, `break`, or panic - anything but falling +off the end of the block). ```rust,editable fn hex_or_die_trying(maybe_string: Option) -> Result { @@ -66,10 +67,12 @@ fn main() { } ``` -Like with `if let`, there is a [`while let`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops) +Like with `if let`, there is a +[`while let`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops) variant which repeatedly tests a value against a pattern: + ```rust,editable fn main() { let mut name = String::from("Comprehensive Rust 🦀"); @@ -89,16 +92,19 @@ The `while let` lets us keep iterating through all items. ## if-let -* Unlike `match`, `if let` does not have to cover all branches. This can make it more concise than `match`. -* A common usage is handling `Some` values when working with `Option`. -* Unlike `match`, `if let` does not support guard clauses for pattern matching. +- Unlike `match`, `if let` does not have to cover all branches. This can make it + more concise than `match`. +- A common usage is handling `Some` values when working with `Option`. +- Unlike `match`, `if let` does not support guard clauses for pattern matching. ## let-else -`if-let`s can pile up, as shown. The `let-else` construct supports flattening this nested code. -Rewrite the awkward version for students, so they can see the transformation. +`if-let`s can pile up, as shown. The `let-else` construct supports flattening +this nested code. Rewrite the awkward version for students, so they can see the +transformation. The rewritten version is: + ```rust fn hex_or_die_trying(maybe_string: Option) -> Result { let Some(s) = maybe_string else { @@ -119,7 +125,10 @@ fn hex_or_die_trying(maybe_string: Option) -> Result { # while-let -* Point out that the `while let` loop will keep going as long as the value matches the pattern. -* You could rewrite the `while let` loop as an infinite loop with an if statement that breaks when there is no value to unwrap for `name.pop()`. The `while let` provides syntactic sugar for the above scenario. +- Point out that the `while let` loop will keep going as long as the value + matches the pattern. +- You could rewrite the `while let` loop as an infinite loop with an if + statement that breaks when there is no value to unwrap for `name.pop()`. The + `while let` provides syntactic sugar for the above scenario.
diff --git a/src/references/exclusive.md b/src/references/exclusive.md index b8b7f5e..5f45982 100644 --- a/src/references/exclusive.md +++ b/src/references/exclusive.md @@ -8,6 +8,7 @@ Exclusive references, also known as mutable references, allow changing the value they refer to. They have type `&mut T`. + ```rust,editable fn main() { let mut point = (1, 2); @@ -21,14 +22,14 @@ fn main() { Key points: -* "Exclusive" means that only this reference can be used to access the value. - No other references (shared or exclusive) can exist at the same time, and the +- "Exclusive" means that only this reference can be used to access the value. No + other references (shared or exclusive) can exist at the same time, and the referenced value cannot be accessed while the exclusive reference exists. Try making an `&point.0` or changing `point.0` while `x_coord` is alive. -* Be sure to note the difference between `let mut x_coord: &i32` and `let - x_coord: &mut i32`. The first one represents a shared reference which can be - bound to different values, while the second represents an exclusive reference - to a mutable value. +- Be sure to note the difference between `let mut x_coord: &i32` and + `let x_coord: &mut i32`. The first one represents a shared reference which can + be bound to different values, while the second represents an exclusive + reference to a mutable value.
diff --git a/src/references/exercise.rs b/src/references/exercise.rs index d0203fd..edaddc5 100644 --- a/src/references/exercise.rs +++ b/src/references/exercise.rs @@ -32,10 +32,7 @@ fn normalize(vector: &mut [f64; 3]) { // ANCHOR: main fn main() { - println!( - "Magnitude of a unit vector: {}", - magnitude(&[0.0, 1.0, 0.0]) - ); + 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)); diff --git a/src/references/shared.md b/src/references/shared.md index 7e2ee00..b5c1980 100644 --- a/src/references/shared.md +++ b/src/references/shared.md @@ -9,6 +9,7 @@ for the value, and is also called "borrowing". Shared references are read-only, and the referenced data cannot change. + ```rust,editable fn main() { let a = 'A'; @@ -20,12 +21,14 @@ fn main() { } ``` -A shared reference to a type `T` has type `&T`. A reference value is made with the `&` -operator. The `*` operator "dereferences" a reference, yielding its value. +A shared reference to a type `T` has type `&T`. A reference value is made with +the `&` operator. The `*` operator "dereferences" a reference, yielding its +value. Rust will statically forbid dangling references: + ```rust,editable,compile_fail fn x_axis(x: i32) -> &(i32, i32) { let point = (x, 0); @@ -35,36 +38,34 @@ fn x_axis(x: i32) -> &(i32, i32) {
-* A reference is said to "borrow" the value it refers to, and this is a good +- A reference is said to "borrow" the value it refers to, and this is a good model for students not familiar with pointers: code can use the reference to access the value, but is still "owned" by the original variable. The course will get into more detail on ownership in day 3. -* References are implemented as pointers, and a key advantage is that they can +- References are implemented as pointers, and a key advantage is that they can be much smaller than the thing they point to. Students familiar with C or C++ will recognize references as pointers. Later parts of the course will cover how Rust prevents the memory-safety bugs that come from using raw pointers. -* Rust does not automatically create references for you - the `&` is always +- Rust does not automatically create references for you - the `&` is always required. -* Rust will auto-dereference in some cases, in particular when invoking - methods (try `r.count_ones()`). There is no need for an `->` operator - like in C++. +- Rust will auto-dereference in some cases, in particular when invoking methods + (try `r.count_ones()`). There is no need for an `->` operator like in C++. -* In this example, `r` is mutable so that it can be reassigned (`r = &b`). - Note that this re-binds `r`, so that it refers to something else. This is - different from C++, where assignment to a reference changes the referenced - value. +- In this example, `r` is mutable so that it can be reassigned (`r = &b`). Note + that this re-binds `r`, so that it refers to something else. This is different + from C++, where assignment to a reference changes the referenced value. -* A shared reference does not allow modifying the value it refers to, even if +- A shared reference does not allow modifying the value it refers to, even if that value was mutable. Try `*r = 'X'`. -* Rust is tracking the lifetimes of all references to ensure they live long - enough. Dangling references cannot occur in safe Rust. `x_axis` would return - a reference to `point`, but `point` will be deallocated when the function +- Rust is tracking the lifetimes of all references to ensure they live long + enough. Dangling references cannot occur in safe Rust. `x_axis` would return a + reference to `point`, but `point` will be deallocated when the function returns, so this will not compile. -* We will talk more about borrowing when we get to ownership. +- We will talk more about borrowing when we get to ownership.
diff --git a/src/running-the-course.md b/src/running-the-course.md index b0723d8..8b08bcb 100644 --- a/src/running-the-course.md +++ b/src/running-the-course.md @@ -19,31 +19,31 @@ Before you run the course, you will want to: you have a clean screen to present to the class. 1. Decide on the dates. Since the course takes four days, we recommend that you - schedule the days over two weeks. Course participants have said that - they find it helpful to have a gap in the course since it helps them process - all the information we give them. + schedule the days over two weeks. Course participants have said that they + find it helpful to have a gap in the course since it helps them process all + the information we give them. 1. Find a room large enough for your in-person participants. We recommend a class size of 15-25 people. That's small enough that people are comfortable asking questions --- it's also small enough that one instructor will have - time to answer the questions. Make sure the room has _desks_ for yourself and for the - students: you will all need to be able to sit and work with your laptops. - In particular, you will be doing a lot of live-coding as an instructor, so a lectern won't - be very helpful for you. + time to answer the questions. Make sure the room has _desks_ for yourself and + for the students: you will all need to be able to sit and work with your + laptops. In particular, you will be doing a lot of live-coding as an + instructor, so a lectern won't be very helpful for you. 1. On the day of your course, show up to the room a little early to set things up. We recommend presenting directly using `mdbook serve` running on your - laptop (see the [installation instructions][3]). This ensures optimal performance with no lag as you change pages. - Using your laptop will also allow you to fix typos as you or the course - participants spot them. - -1. Let people solve the exercises by themselves or in small groups. - We typically spend 30-45 minutes on exercises in the morning and in the afternoon (including time to review the solutions). - Make sure to - ask people if they're stuck or if there is anything you can help with. When - you see that several people have the same problem, call it out to the class - and offer a solution, e.g., by showing people where to find the relevant - information in the standard library. + laptop (see the [installation instructions][3]). This ensures optimal + performance with no lag as you change pages. Using your laptop will also + allow you to fix typos as you or the course participants spot them. + +1. Let people solve the exercises by themselves or in small groups. We typically + spend 30-45 minutes on exercises in the morning and in the afternoon + (including time to review the solutions). Make sure to ask people if they're + stuck or if there is anything you can help with. When you see that several + people have the same problem, call it out to the class and offer a solution, + e.g., by showing people where to find the relevant information in the + standard library. That is all, good luck running the course! We hope it will be as much fun for you as it has been for us! diff --git a/src/running-the-course/course-structure.md b/src/running-the-course/course-structure.md index b810081..6ca63d6 100644 --- a/src/running-the-course/course-structure.md +++ b/src/running-the-course/course-structure.md @@ -4,8 +4,8 @@ ## Rust Fundamentals -The first four days make up [Rust Fundamentals](../welcome-day-1.md). -The days are fast paced and we cover a lot of ground! +The first four days make up [Rust Fundamentals](../welcome-day-1.md). The days +are fast paced and we cover a lot of ground! {{%course outline Fundamentals}} @@ -16,14 +16,14 @@ specialized topics: ### Rust in Android -The [Rust in Android](../android.md) deep dive is a half-day course on using Rust for -Android platform development. This includes interoperability with C, C++, and -Java. +The [Rust in Android](../android.md) deep dive is a half-day course on using +Rust for Android platform development. This includes interoperability with C, +C++, and Java. -You will need an [AOSP checkout][1]. Make a checkout of the [course -repository][2] on the same machine and move the `src/android/` directory into -the root of your AOSP checkout. This will ensure that the Android build system -sees the `Android.bp` files in `src/android/`. +You will need an [AOSP checkout][1]. Make a checkout of the +[course repository][2] on the same machine and move the `src/android/` directory +into the root of your AOSP checkout. This will ensure that the Android build +system sees the `Android.bp` files in `src/android/`. Ensure that `adb sync` works with your emulator or real device and pre-build all Android examples using `src/android/build_all.sh`. Read the script to see the @@ -35,29 +35,29 @@ commands it runs and make sure they work when you run them by hand. ### Rust in Chromium The [Rust in Chromium](../chromium.md) deep dive is a half-day course on using -Rust as part of the Chromium browser. It includes using Rust in Chromium's -`gn` build system, bringing in third-party libraries ("crates") and C++ +Rust as part of the Chromium browser. It includes using Rust in Chromium's `gn` +build system, bringing in third-party libraries ("crates") and C++ interoperability. You will need to be able to build Chromium --- a debug, component build is -[recommended](../chromium/setup.md) for speed but any build will work. -Ensure that you can run the Chromium browser that you've built. +[recommended](../chromium/setup.md) for speed but any build will work. Ensure +that you can run the Chromium browser that you've built. ### Bare-Metal Rust -The [Bare-Metal Rust](../bare-metal.md) deep dive is a full day class on using Rust for -bare-metal (embedded) development. Both microcontrollers and application -processors are covered. +The [Bare-Metal Rust](../bare-metal.md) deep dive is a full day class on using +Rust for bare-metal (embedded) development. Both microcontrollers and +application processors are covered. -For the microcontroller part, you will need to buy the [BBC -micro:bit](https://microbit.org/) v2 development board ahead of time. Everybody -will need to install a number of packages as described on the [welcome -page](../bare-metal.md). +For the microcontroller part, you will need to buy the +[BBC micro:bit](https://microbit.org/) v2 development board ahead of time. +Everybody will need to install a number of packages as described on the +[welcome page](../bare-metal.md). ### Concurrency in Rust -The [Concurrency in Rust](../concurrency.md) deep dive is a full day class on classical -as well as `async`/`await` concurrency. +The [Concurrency in Rust](../concurrency.md) deep dive is a full day class on +classical as well as `async`/`await` concurrency. You will need a fresh crate set up and the dependencies downloaded and ready to go. You can then copy/paste the examples into `src/main.rs` to experiment with diff --git a/src/running-the-course/keyboard-shortcuts.md b/src/running-the-course/keyboard-shortcuts.md index 08a66ac..2e21320 100644 --- a/src/running-the-course/keyboard-shortcuts.md +++ b/src/running-the-course/keyboard-shortcuts.md @@ -2,7 +2,7 @@ There are several useful keyboard shortcuts in mdBook: -* Arrow-Left: Navigate to the previous page. -* Arrow-Right: Navigate to the next page. -* Ctrl + Enter: Execute the code sample that has focus. -* s: Activate the search bar. +- Arrow-Left: Navigate to the previous page. +- Arrow-Right: Navigate to the next page. +- Ctrl + Enter: Execute the code sample that has focus. +- s: Activate the search bar. diff --git a/src/running-the-course/translations.md b/src/running-the-course/translations.md index 6225b14..ac3eb31 100644 --- a/src/running-the-course/translations.md +++ b/src/running-the-course/translations.md @@ -3,11 +3,14 @@ The course has been translated into other languages by a set of wonderful volunteers: -* [Brazilian Portuguese][pt-BR] by [@rastringer], [@hugojacob], [@joaovicmendes], and [@henrif75]. -* [Chinese (Simplified)][zh-CN] by [@suetfei], [@wnghl], [@anlunx], [@kongy], [@noahdragon], [@superwhd], [@SketchK], and [@nodmp]. -* [Chinese (Traditional)][zh-TW] by [@hueich], [@victorhsieh], [@mingyc], [@kuanhungchen], and [@johnathan79717]. -* [Korean][ko] by [@keispace], [@jiyongp], and [@jooyunghan]. -* [Spanish][es] by [@deavid]. +- [Brazilian Portuguese][pt-BR] by [@rastringer], [@hugojacob], + [@joaovicmendes], and [@henrif75]. +- [Chinese (Simplified)][zh-CN] by [@suetfei], [@wnghl], [@anlunx], [@kongy], + [@noahdragon], [@superwhd], [@SketchK], and [@nodmp]. +- [Chinese (Traditional)][zh-TW] by [@hueich], [@victorhsieh], [@mingyc], + [@kuanhungchen], and [@johnathan79717]. +- [Korean][ko] by [@keispace], [@jiyongp], and [@jooyunghan]. +- [Spanish][es] by [@deavid]. Use the language picker in the top-right corner to switch between languages. @@ -16,10 +19,10 @@ Use the language picker in the top-right corner to switch between languages. There is a large number of in-progress translations. We link to the most recently updated translations: -* [Bengali][bn] by [@raselmandol]. -* [French][fr] by [@KookaS] and [@vcaen]. -* [German][de] by [@Throvn] and [@ronaldfw]. -* [Japanese][ja] by [@CoinEZ-JPN] and [@momotaro1105]. +- [Bengali][bn] by [@raselmandol]. +- [French][fr] by [@KookaS] and [@vcaen]. +- [German][de] by [@Throvn] and [@ronaldfw]. +- [Japanese][ja] by [@CoinEZ-JPN] and [@momotaro1105]. If you want to help with this effort, please see [our instructions] for how to get going. Translations are coordinated on the [issue tracker]. @@ -33,7 +36,6 @@ get going. Translations are coordinated on the [issue tracker]. [pt-BR]: https://google.github.io/comprehensive-rust/pt-BR/ [zh-CN]: https://google.github.io/comprehensive-rust/zh-CN/ [zh-TW]: https://google.github.io/comprehensive-rust/zh-TW/ - [@anlunx]: https://github.com/anlunx [@CoinEZ-JPN]: https://github.com/CoinEZ [@deavid]: https://github.com/deavid @@ -62,6 +64,5 @@ get going. Translations are coordinated on the [issue tracker]. [@vcaen]: https://github.com/vcaen [@victorhsieh]: https://github.com/victorhsieh [@wnghl]: https://github.com/wnghl - [our instructions]: https://github.com/google/comprehensive-rust/blob/main/TRANSLATIONS.md [issue tracker]: https://github.com/google/comprehensive-rust/issues/282 diff --git a/src/slices-and-lifetimes/exercise.md b/src/slices-and-lifetimes/exercise.md index 5786859..c742abf 100644 --- a/src/slices-and-lifetimes/exercise.md +++ b/src/slices-and-lifetimes/exercise.md @@ -4,10 +4,10 @@ minutes: 30 # Exercise: Protobuf Parsing -In this exercise, you will build a parser for the [protobuf binary -encoding](https://protobuf.dev/programming-guides/encoding/). Don't worry, it's -simpler than it seems! This illustrates a common parsing pattern, passing slices -of data. The underlying data itself is never copied. +In this exercise, you will build a parser for the +[protobuf binary encoding](https://protobuf.dev/programming-guides/encoding/). +Don't worry, it's simpler than it seems! This illustrates a common parsing +pattern, passing slices of data. The underlying data itself is never copied. Fully parsing a protobuf message requires knowing the types of the fields, indexed by their field numbers. That is typically provided in a `proto` file. In @@ -43,6 +43,7 @@ What remains for you is to implement the `parse_field` function and the `ProtoMessage` trait for `Person` and `PhoneNumber`. + ```rust,editable,compile_fail {{#include exercise.rs:preliminaries }} diff --git a/src/slices-and-lifetimes/exercise.rs b/src/slices-and-lifetimes/exercise.rs index 8629d65..ab73d9c 100644 --- a/src/slices-and-lifetimes/exercise.rs +++ b/src/slices-and-lifetimes/exercise.rs @@ -38,11 +38,11 @@ enum WireType { /// The Varint WireType indicates the value is a single VARINT. Varint, //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. + /// 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. + /// The I32 WireType indicates that the value is precisely 4 bytes in + /// little-endian order containing a 32-bit signed integer. I32, } @@ -162,13 +162,7 @@ fn parse_field(data: &[u8]) -> Result<(Field, &[u8]), Error> { (FieldValue::I32(value), remainder) } }; - Ok(( - Field { - field_num, - value: fieldvalue, - }, - remainder, - )) + Ok((Field { field_num, value: fieldvalue }, remainder)) } // ANCHOR: parse_message @@ -228,11 +222,12 @@ impl<'a> ProtoMessage<'a> for PhoneNumber<'a> { // ANCHOR: main fn main() { 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, + 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, ]) .unwrap(); println!("{:#?}", person); diff --git a/src/slices-and-lifetimes/lifetime-annotations.md b/src/slices-and-lifetimes/lifetime-annotations.md index ebee301..b90188d 100644 --- a/src/slices-and-lifetimes/lifetime-annotations.md +++ b/src/slices-and-lifetimes/lifetime-annotations.md @@ -7,10 +7,10 @@ minutes: 10 A reference has a _lifetime_, which must not "outlive" the value it refers to. This is verified by the borrow checker. -The lifetime can be implicit - this is what we have seen so far. Lifetimes can -also be explicit: `&'a Point`, `&'document str`. Lifetimes start with `'` and -`'a` is a typical default name. Read `&'a Point` as "a borrowed `Point` which -is valid for at least the lifetime `a`". +The lifetime can be implicit - this is what we have seen so far. Lifetimes can +also be explicit: `&'a Point`, `&'document str`. Lifetimes start with `'` and +`'a` is a typical default name. Read `&'a Point` as "a borrowed `Point` which is +valid for at least the lifetime `a`". Lifetimes are always inferred by the compiler: you cannot assign a lifetime yourself. Explicit lifetime annotations create constraints where there is @@ -19,27 +19,34 @@ ambiguity; the compiler verifies that there is a valid solution. Lifetimes become more complicated when considering passing values to and returning values from functions. + + ```rust,editable,compile_fail #[derive(Debug)] struct Point(i32, i32); fn left_most(p1: &Point, p2: &Point) -> &Point { - if p1.0 < p2.0 { p1 } else { p2 } + if p1.0 < p2.0 { + p1 + } else { + p2 + } } fn main() { - let p1: Point = Point(10, 10); - let p2: Point = Point(20, 20); - let p3 = left_most(&p1, &p2); // What is the lifetime of p3? - println!("p3: {p3:?}"); + let p1: Point = Point(10, 10); + let p2: Point = Point(20, 20); + let p3 = left_most(&p1, &p2); // What is the lifetime of p3? + println!("p3: {p3:?}"); } ```
-In this example, the the compiler does not know what lifetime to infer for -`p3`. Looking inside the function body shows that it can only safely assume -that `p3`'s lifetime is the shorter of `p1` and `p2`. But just like types, Rust +In this example, the the compiler does not know what lifetime to infer for `p3`. +Looking inside the function body shows that it can only safely assume that +`p3`'s lifetime is the shorter of `p1` and `p2`. But just like types, Rust requires explicit annotations of lifetimes on function arguments and return values. @@ -49,7 +56,8 @@ Add `'a` appropriately to `left_most`: fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point { ``` -This says, "given p1 and p2 which both outlive `'a`, the return value lives for at least `'a`. +This says, "given p1 and p2 which both outlive `'a`, the return value lives for +at least `'a`. In common cases, lifetimes can be elided, as described on the next slide. diff --git a/src/slices-and-lifetimes/lifetime-elision.md b/src/slices-and-lifetimes/lifetime-elision.md index 38b7c0f..1610185 100644 --- a/src/slices-and-lifetimes/lifetime-elision.md +++ b/src/slices-and-lifetimes/lifetime-elision.md @@ -5,15 +5,18 @@ minutes: 5 # Lifetimes in Function Calls Lifetimes for function arguments and return values must be fully specified, but -Rust allows lifetimes to be elided in most cases with [a few simple -rules](https://doc.rust-lang.org/nomicon/lifetime-elision.html). This is not -inference -- it is just a syntactic shorthand. +Rust allows lifetimes to be elided in most cases with +[a few simple rules](https://doc.rust-lang.org/nomicon/lifetime-elision.html). +This is not inference -- it is just a syntactic shorthand. -* Each argument which does not have a lifetime annotation is given one. -* If there is only one argument lifetime, it is given to all un-annotated return values. -* If there are multiple argument lifetimes, but the first one is for `self`, that lifetime is given to all un-annotated return values. +- Each argument which does not have a lifetime annotation is given one. +- If there is only one argument lifetime, it is given to all un-annotated return + values. +- If there are multiple argument lifetimes, but the first one is for `self`, + that lifetime is given to all un-annotated return values. + ```rust,editable #[derive(Debug)] struct Point(i32, i32); @@ -52,7 +55,8 @@ fn main() { In this example, `cab_distance` is trivially elided. -The `nearest` function provides another example of a function with multiple references in its arguments that requires explicit annotation. +The `nearest` function provides another example of a function with multiple +references in its arguments that requires explicit annotation. Try adjusting the signature to "lie" about the lifetimes returned: @@ -61,7 +65,7 @@ fn nearest<'a, 'q'>(points: &'a [Point], query: &'q Point) -> Option<&'q Point> ``` This won't compile, demonstrating that the annotations are checked for validity -by the compiler. Note that this is not the case for raw pointers (unsafe), and +by the compiler. Note that this is not the case for raw pointers (unsafe), and this is a common source of errors with unsafe Rust.
diff --git a/src/slices-and-lifetimes/slices.md b/src/slices-and-lifetimes/slices.md index d506a43..5f8855f 100644 --- a/src/slices-and-lifetimes/slices.md +++ b/src/slices-and-lifetimes/slices.md @@ -7,6 +7,7 @@ minutes: 10 A slice gives you a view into a larger collection: + ```rust,editable fn main() { let mut a: [i32; 6] = [10, 20, 30, 40, 50, 60]; @@ -18,25 +19,34 @@ fn main() { } ``` -* Slices borrow data from the sliced type. -* Question: What happens if you modify `a[3]` right before printing `s`? +- Slices borrow data from the sliced type. +- Question: What happens if you modify `a[3]` right before printing `s`?
-* We create a slice by borrowing `a` and specifying the starting and ending indexes in brackets. +- We create a slice by borrowing `a` and specifying the starting and ending + indexes in brackets. -* If the slice starts at index 0, Rust’s range syntax allows us to drop the starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are identical. +- If the slice starts at index 0, Rust’s range syntax allows us to drop the + starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are + identical. -* The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are identical. +- The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are + identical. -* To easily create a slice of the full array, we can therefore use `&a[..]`. +- To easily create a slice of the full array, we can therefore use `&a[..]`. -* `s` is a reference to a slice of `i32`s. Notice that the type of `s` (`&[i32]`) no longer mentions the array length. This allows us to perform computation on slices of different sizes. +- `s` is a reference to a slice of `i32`s. Notice that the type of `s` + (`&[i32]`) no longer mentions the array length. This allows us to perform + computation on slices of different sizes. -* Slices always borrow from another object. In this example, `a` has to remain 'alive' (in scope) for at least as long as our slice. +- Slices always borrow from another object. In this example, `a` has to remain + 'alive' (in scope) for at least as long as our slice. -* The question about modifying `a[3]` can spark an interesting discussion, but the answer is that for memory safety reasons - you cannot do it through `a` at this point in the execution, but you can read the data from both `a` and `s` safely. - It works before you created the slice, and again after the `println`, when the slice is no longer used. +- The question about modifying `a[3]` can spark an interesting discussion, but + the answer is that for memory safety reasons you cannot do it through `a` at + this point in the execution, but you can read the data from both `a` and `s` + safely. It works before you created the slice, and again after the `println`, + when the slice is no longer used.
diff --git a/src/slices-and-lifetimes/solution.md b/src/slices-and-lifetimes/solution.md index 81412e7..2dc2bc5 100644 --- a/src/slices-and-lifetimes/solution.md +++ b/src/slices-and-lifetimes/solution.md @@ -1,6 +1,7 @@ # Solution + ```rust,editable,compile_fail {{#include exercise.rs:solution}} ``` diff --git a/src/slices-and-lifetimes/str.md b/src/slices-and-lifetimes/str.md index 4d2f3e9..ba73194 100644 --- a/src/slices-and-lifetimes/str.md +++ b/src/slices-and-lifetimes/str.md @@ -5,6 +5,7 @@ minutes: 10 + # String References We can now understand the two string types in Rust: `&str` is almost like @@ -27,32 +28,36 @@ fn main() { Rust terminology: -* `&str` an immutable reference to a string slice. -* `String` a mutable string buffer. +- `&str` an immutable reference to a string slice. +- `String` a mutable string buffer.
-* `&str` introduces a string slice, which is an immutable reference to UTF-8 encoded string data - stored in a block of memory. String literals (`”Hello”`), are stored in the program’s binary. +- `&str` introduces a string slice, which is an immutable reference to UTF-8 + encoded string data stored in a block of memory. String literals (`”Hello”`), + are stored in the program’s binary. -* Rust’s `String` type is a wrapper around a vector of bytes. As with a `Vec`, it is owned. +- Rust’s `String` type is a wrapper around a vector of bytes. As with a + `Vec`, it is owned. -* As with many other types `String::from()` creates a string from a string literal; `String::new()` - creates a new empty string, to which string data can be added using the `push()` and `push_str()` methods. +- As with many other types `String::from()` creates a string from a string + literal; `String::new()` creates a new empty string, to which string data can + be added using the `push()` and `push_str()` methods. -* The `format!()` macro is a convenient way to generate an owned string from dynamic values. It - accepts the same format specification as `println!()`. +- The `format!()` macro is a convenient way to generate an owned string from + dynamic values. It accepts the same format specification as `println!()`. -* You can borrow `&str` slices from `String` via `&` and optionally range - selection. If you select a byte range that is not aligned to character - boundaries, the expression will panic. The `chars` iterator iterates over +- You can borrow `&str` slices from `String` via `&` and optionally range + selection. If you select a byte range that is not aligned to character + boundaries, the expression will panic. The `chars` iterator iterates over characters and is preferred over trying to get character boundaries right. -* For C++ programmers: think of `&str` as `std::string_view` from C++, but the one that always points - to a valid string in memory. Rust `String` is a rough equivalent of `std::string` from C++ - (main difference: it can only contain UTF-8 encoded bytes and will never use a small-string optimization). +- For C++ programmers: think of `&str` as `std::string_view` from C++, but the + one that always points to a valid string in memory. Rust `String` is a rough + equivalent of `std::string` from C++ (main difference: it can only contain + UTF-8 encoded bytes and will never use a small-string optimization). -* Byte strings literals allow you to create a `&[u8]` value directly: +- Byte strings literals allow you to create a `&[u8]` value directly: ```rust,editable diff --git a/src/slices-and-lifetimes/struct-lifetimes.md b/src/slices-and-lifetimes/struct-lifetimes.md index 09ad280..f201ba5 100644 --- a/src/slices-and-lifetimes/struct-lifetimes.md +++ b/src/slices-and-lifetimes/struct-lifetimes.md @@ -26,10 +26,18 @@ fn main() {
-* In the above example, the annotation on `Highlight` enforces that the data underlying the contained `&str` lives at least as long as any instance of `Highlight` that uses that data. -* If `text` is consumed before the end of the lifetime of `fox` (or `dog`), the borrow checker throws an error. -* Types with borrowed data force users to hold on to the original data. This can be useful for creating lightweight views, but it generally makes them somewhat harder to use. -* When possible, make data structures own their data directly. -* Some structs with multiple references inside can have more than one lifetime annotation. This can be necessary if there is a need to describe lifetime relationships between the references themselves, in addition to the lifetime of the struct itself. Those are very advanced use cases. +- In the above example, the annotation on `Highlight` enforces that the data + underlying the contained `&str` lives at least as long as any instance of + `Highlight` that uses that data. +- If `text` is consumed before the end of the lifetime of `fox` (or `dog`), the + borrow checker throws an error. +- Types with borrowed data force users to hold on to the original data. This can + be useful for creating lightweight views, but it generally makes them somewhat + harder to use. +- When possible, make data structures own their data directly. +- Some structs with multiple references inside can have more than one lifetime + annotation. This can be necessary if there is a need to describe lifetime + relationships between the references themselves, in addition to the lifetime + of the struct itself. Those are very advanced use cases.
diff --git a/src/smart-pointers/Cargo.toml b/src/smart-pointers/Cargo.toml index 1e2a539..f183a4c 100644 --- a/src/smart-pointers/Cargo.toml +++ b/src/smart-pointers/Cargo.toml @@ -7,4 +7,3 @@ publish = false [[bin]] name = "binary-tree" path = "exercise.rs" - diff --git a/src/smart-pointers/box.md b/src/smart-pointers/box.md index b63536e..a8e66c4 100644 --- a/src/smart-pointers/box.md +++ b/src/smart-pointers/box.md @@ -4,7 +4,8 @@ minutes: 10 # `Box` -[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned pointer to data on the heap: +[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned pointer +to data on the heap: ```rust,editable fn main() { @@ -13,7 +14,6 @@ fn main() { } ``` - ```bob Stack Heap .- - - - - - -. .- - - - - - -. @@ -27,7 +27,8 @@ fn main() { `- - - - - - -' `- - - - - - -' ``` -`Box` implements `Deref`, which means that you can [call methods +`Box` implements `Deref`, which means that you can +[call methods from `T` directly on a `Box`](https://doc.rust-lang.org/std/ops/trait.Deref.html#more-on-deref-coercion). Recursive data types or data types with dynamic sizes need to use a `Box`: @@ -35,14 +36,15 @@ Recursive data types or data types with dynamic sizes need to use a `Box`: ```rust,editable #[derive(Debug)] enum List { - /// A non-empty list, consisting of the first element and the rest of the list. + /// A non-empty list: first element and the rest of the list. Element(T, Box>), /// An empty list. Nil, } fn main() { - let list: List = List::Element(1, Box::new(List::Element(2, Box::new(List::Nil)))); + let list: List = + List::Element(1, Box::new(List::Element(2, Box::new(List::Nil)))); println!("{list:?}"); } ``` @@ -59,20 +61,28 @@ fn main() { : : : : '- - - - - - - - - - - - - - ' '- - - - - - - - - - - - - - - - - - - - - - - - -' ``` +
-* `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not null. -* A `Box` can be useful when you: - * have a type whose size that can't be known at compile time, but the Rust compiler wants to know an exact size. - * want to transfer ownership of a large amount of data. To avoid copying large amounts of data on the stack, instead store the data on the heap in a `Box` so only the pointer is moved. +- `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not + null. +- A `Box` can be useful when you: + - have a type whose size that can't be known at compile time, but the Rust + compiler wants to know an exact size. + - want to transfer ownership of a large amount of data. To avoid copying large + amounts of data on the stack, instead store the data on the heap in a `Box` + so only the pointer is moved. -* If `Box` was not used and we attempted to embed a `List` directly into the `List`, -the compiler would not compute a fixed size of the struct in memory (`List` would be of infinite size). +- If `Box` was not used and we attempted to embed a `List` directly into the + `List`, the compiler would not compute a fixed size of the struct in memory + (`List` would be of infinite size). -* `Box` solves this problem as it has the same size as a regular pointer and just points at the next -element of the `List` in the heap. +- `Box` solves this problem as it has the same size as a regular pointer and + just points at the next element of the `List` in the heap. -* Remove the `Box` in the List definition and show the compiler error. "Recursive with indirection" is a hint you might want to use a Box or reference of some kind, instead of storing a value directly. +- Remove the `Box` in the List definition and show the compiler error. + "Recursive with indirection" is a hint you might want to use a Box or + reference of some kind, instead of storing a value directly. # More to Explore @@ -86,7 +96,8 @@ enum List { } fn main() { - let list: List = List::Element(1, Box::new(List::Element(2, Box::new(List::Nil)))); + let list: List = + List::Element(1, Box::new(List::Element(2, Box::new(List::Nil)))); println!("{list:?}"); } ``` diff --git a/src/smart-pointers/exercise.rs b/src/smart-pointers/exercise.rs index 4cc7b78..9be7e3a 100644 --- a/src/smart-pointers/exercise.rs +++ b/src/smart-pointers/exercise.rs @@ -39,9 +39,7 @@ pub struct BinaryTree { impl BinaryTree { fn new() -> Self { - Self { - root: Subtree::new(), - } + Self { root: Subtree::new() } } fn insert(&mut self, value: T) { @@ -94,11 +92,7 @@ impl Subtree { impl Node { fn new(value: T) -> Self { - Self { - value, - left: Subtree::new(), - right: Subtree::new(), - } + Self { value, left: Subtree::new(), right: Subtree::new() } } } @@ -131,7 +125,8 @@ mod tests { fn has() { let mut tree = BinaryTree::new(); fn check_has(tree: &BinaryTree, exp: &[bool]) { - let got: Vec = (0..exp.len()).map(|i| tree.has(&(i as i32))).collect(); + let got: Vec = + (0..exp.len()).map(|i| tree.has(&(i as i32))).collect(); assert_eq!(&got, exp); } diff --git a/src/smart-pointers/rc.md b/src/smart-pointers/rc.md index 5bce0e7..6b55d5f 100644 --- a/src/smart-pointers/rc.md +++ b/src/smart-pointers/rc.md @@ -19,9 +19,9 @@ fn main() { } ``` -* See [`Arc`][2] and [`Mutex`][3] if you are in a multi-threaded context. -* You can *downgrade* a shared pointer into a [`Weak`][4] pointer to create cycles - that will get dropped. +- See [`Arc`][2] and [`Mutex`][3] if you are in a multi-threaded context. +- You can _downgrade_ a shared pointer into a [`Weak`][4] pointer to create + cycles that will get dropped. [1]: https://doc.rust-lang.org/std/rc/struct.Rc.html [2]: ../concurrency/shared_state/arc.md @@ -30,13 +30,16 @@ fn main() {
-* `Rc`'s count ensures that its contained value is valid for as long as there are references. -* `Rc` in Rust is like `std::shared_ptr` in C++. -* `Rc::clone` is cheap: it creates a pointer to the same allocation and increases the reference count. Does not make a deep clone and can generally be ignored when looking for performance issues in code. -* `make_mut` actually clones the inner value if necessary ("clone-on-write") and returns a mutable reference. -* Use `Rc::strong_count` to check the reference count. -* `Rc::downgrade` gives you a *weakly reference-counted* object to - create cycles that will be dropped properly (likely in combination with - `RefCell`). +- `Rc`'s count ensures that its contained value is valid for as long as there + are references. +- `Rc` in Rust is like `std::shared_ptr` in C++. +- `Rc::clone` is cheap: it creates a pointer to the same allocation and + increases the reference count. Does not make a deep clone and can generally be + ignored when looking for performance issues in code. +- `make_mut` actually clones the inner value if necessary ("clone-on-write") and + returns a mutable reference. +- Use `Rc::strong_count` to check the reference count. +- `Rc::downgrade` gives you a _weakly reference-counted_ object to create cycles + that will be dropped properly (likely in combination with `RefCell`).
diff --git a/src/std-traits/casting.md b/src/std-traits/casting.md index 896b071..4480a83 100644 --- a/src/std-traits/casting.md +++ b/src/std-traits/casting.md @@ -17,19 +17,25 @@ fn main() { ``` The results of `as` are _always_ defined in Rust and consistent across -platforms. This might not match your intuition for changing sign or casting to -a smaller type -- check the docs, and comment for clarity. +platforms. This might not match your intuition for changing sign or casting to a +smaller type -- check the docs, and comment for clarity. -Casting with `as` is a relatively sharp tool that is easy to use incorrectly, and can be a source of subtle bugs as future maintenance work changes the types that are used or the ranges of values in types. Casts are best used only when the intent is to indicate unconditional truncation (e.g. selecting the bottom 32 bits of a `u64` with `as u32`, regardless of what was in the high bits). +Casting with `as` is a relatively sharp tool that is easy to use incorrectly, +and can be a source of subtle bugs as future maintenance work changes the types +that are used or the ranges of values in types. Casts are best used only when +the intent is to indicate unconditional truncation (e.g. selecting the bottom 32 +bits of a `u64` with `as u32`, regardless of what was in the high bits). -For infallible casts (e.g. `u32` to `u64`), prefer using `From` or `Into` over `as` -to confirm that the cast is in fact infallible. For fallible casts, `TryFrom` and `TryInto` are available when you want to handle casts that fit differently from those that don't. +For infallible casts (e.g. `u32` to `u64`), prefer using `From` or `Into` over +`as` to confirm that the cast is in fact infallible. For fallible casts, +`TryFrom` and `TryInto` are available when you want to handle casts that fit +differently from those that don't.
Consider taking a break after this slide. -`as` is similar to a C++ static cast. Use of `as` in cases where data might be +`as` is similar to a C++ static cast. Use of `as` in cases where data might be lost is generally discouraged, or at least deserves an explanatory comment. This is common in casting integers to `usize` for use as an index. diff --git a/src/std-traits/closures.md b/src/std-traits/closures.md index c02da58..1012bf3 100644 --- a/src/std-traits/closures.md +++ b/src/std-traits/closures.md @@ -35,33 +35,35 @@ fn main() {
-An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or perhaps captures -nothing at all. It can be called multiple times concurrently. +An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or perhaps +captures nothing at all. It can be called multiple times concurrently. -An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it multiple times, -but not concurrently. +An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it +multiple times, but not concurrently. -If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It might consume -captured values. +If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It +might consume captured values. -`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. I.e. you can use an -`FnMut` wherever an `FnOnce` is called for, and you can use an `Fn` wherever an `FnMut` or `FnOnce` -is called for. +`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. +I.e. you can use an `FnMut` wherever an `FnOnce` is called for, and you can use +an `Fn` wherever an `FnMut` or `FnOnce` is called for. -When you define a function that takes a closure, you should take `FnOnce` if you can (i.e. you call it once), or `FnMut` -else, and last `Fn`. This allows the most flexibility for the caller. +When you define a function that takes a closure, you should take `FnOnce` if you +can (i.e. you call it once), or `FnMut` else, and last `Fn`. This allows the +most flexibility for the caller. -In contrast, when you have a closure, the most flexible you can have is `Fn` (it can be passed everywhere), then `FnMut`, -and lastly `FnOnce`. +In contrast, when you have a closure, the most flexible you can have is `Fn` (it +can be passed everywhere), then `FnMut`, and lastly `FnOnce`. -The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. `multiply_sum`), -depending on what the closure captures. +The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. +`multiply_sum`), depending on what the closure captures. + +By default, closures will capture by reference if they can. The `move` keyword +makes them capture by value. -By default, closures will capture by reference if they can. The `move` keyword makes them capture -by value. ```rust,editable fn make_greeter(prefix: String) -> impl Fn(&str) { - return move |name| println!("{} {}", prefix, name) + return move |name| println!("{} {}", prefix, name); } fn main() { diff --git a/src/std-traits/comparisons.md b/src/std-traits/comparisons.md index 3a55dc7..95359c5 100644 --- a/src/std-traits/comparisons.md +++ b/src/std-traits/comparisons.md @@ -13,7 +13,10 @@ types containing fields that implement these traits. provided method `ne`. The `==` and `!=` operators will call these methods. ```rust,editable -struct Key { id: u32, metadata: Option } +struct Key { + id: u32, + metadata: Option, +} impl PartialEq for Key { fn eq(&self, other: &Self) -> bool { self.id == other.id @@ -22,18 +25,21 @@ impl PartialEq for Key { ``` `Eq` is a full equivalence relation (reflexive, symmetric, and transitive) and -implies `PartialEq`. Functions that require full equivalence will use `Eq` as -a trait bound. +implies `PartialEq`. Functions that require full equivalence will use `Eq` as a +trait bound. ## `PartialOrd` and `Ord` -`PartialOrd` defines a partial ordering, with a `partial_cmp` method. It is -used to implement the `<`, `<=`, `>=`, and `>` operators. +`PartialOrd` defines a partial ordering, with a `partial_cmp` method. It is used +to implement the `<`, `<=`, `>=`, and `>` operators. ```rust,editable use std::cmp::Ordering; #[derive(Eq, PartialEq)] -struct Citation { author: String, year: u32 } +struct Citation { + author: String, + year: u32, +} impl PartialOrd for Citation { fn partial_cmp(&self, other: &Self) -> Option { match self.author.partial_cmp(&other.author) { @@ -48,10 +54,14 @@ impl PartialOrd for Citation {
-`PartialEq` can be implemented between different types, but `Eq` cannot, because it is reflexive: +`PartialEq` can be implemented between different types, but `Eq` cannot, because +it is reflexive: ```rust,editable -struct Key { id: u32, metadata: Option } +struct Key { + id: u32, + metadata: Option, +} impl PartialEq for Key { fn eq(&self, other: &u32) -> bool { self.id == *other diff --git a/src/std-traits/default.md b/src/std-traits/default.md index b4ff71f..333510a 100644 --- a/src/std-traits/default.md +++ b/src/std-traits/default.md @@ -27,27 +27,27 @@ fn main() { let default_struct = Derived::default(); println!("{default_struct:#?}"); - let almost_default_struct = Derived { - y: "Y is set!".into(), - ..Derived::default() - }; + let almost_default_struct = + Derived { y: "Y is set!".into(), ..Derived::default() }; println!("{almost_default_struct:#?}"); let nothing: Option = None; println!("{:#?}", nothing.unwrap_or_default()); } - ```
- * It can be implemented directly or it can be derived via `#[derive(Default)]`. - * A derived implementation will produce a value where all fields are set to their default values. - * This means all types in the struct must implement `Default` too. - * Standard Rust types often implement `Default` with reasonable values (e.g. `0`, `""`, etc). - * The partial struct initialization works nicely with default. - * The Rust standard library is aware that types can implement `Default` and provides convenience methods that use it. - * The `..` syntax is called [struct update syntax][2]. +- It can be implemented directly or it can be derived via `#[derive(Default)]`. +- A derived implementation will produce a value where all fields are set to + their default values. + - This means all types in the struct must implement `Default` too. +- Standard Rust types often implement `Default` with reasonable values (e.g. + `0`, `""`, etc). +- The partial struct initialization works nicely with default. +- The Rust standard library is aware that types can implement `Default` and + provides convenience methods that use it. +- The `..` syntax is called [struct update syntax][2].
diff --git a/src/std-traits/exercise.md b/src/std-traits/exercise.md index 8ac3171..400ad45 100644 --- a/src/std-traits/exercise.md +++ b/src/std-traits/exercise.md @@ -4,10 +4,10 @@ minutes: 30 # Exercise: ROT13 -In this example, you will implement the classic ["ROT13" -cipher](https://en.wikipedia.org/wiki/ROT13). Copy this code to the playground, -and implement the missing bits. Only rotate ASCII alphabetic characters, to -ensure the result is still valid UTF-8. +In this example, you will implement the classic +["ROT13" cipher](https://en.wikipedia.org/wiki/ROT13). Copy this code to the +playground, and implement the missing bits. Only rotate ASCII alphabetic +characters, to ensure the result is still valid UTF-8. ```rust,compile_fail {{#include exercise.rs:head }} diff --git a/src/std-traits/exercise.rs b/src/std-traits/exercise.rs index b141290..961b261 100644 --- a/src/std-traits/exercise.rs +++ b/src/std-traits/exercise.rs @@ -38,10 +38,8 @@ impl Read for RotDecoder { // ANCHOR: main fn main() { - let mut rot = RotDecoder { - input: "Gb trg gb gur bgure fvqr!".as_bytes(), - rot: 13, - }; + 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(); println!("{}", result); @@ -53,10 +51,8 @@ mod test { #[test] fn joke() { - let mut rot = RotDecoder { - input: "Gb trg gb gur bgure fvqr!".as_bytes(), - rot: 13, - }; + 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!"); @@ -65,10 +61,7 @@ mod test { #[test] fn binary() { let input: Vec = (0..=255u8).collect(); - let mut rot = RotDecoder::<&[u8]> { - input: input.as_ref(), - rot: 13, - }; + let mut rot = RotDecoder::<&[u8]> { input: input.as_ref(), rot: 13 }; let mut buf = [0u8; 256]; assert_eq!(rot.read(&mut buf).unwrap(), 256); for i in 0..=255 { diff --git a/src/std-traits/from-and-into.md b/src/std-traits/from-and-into.md index 57af224..f110ed0 100644 --- a/src/std-traits/from-and-into.md +++ b/src/std-traits/from-and-into.md @@ -30,9 +30,12 @@ fn main() {
-* That's why it is common to only implement `From`, as your type will get `Into` implementation too. -* When declaring a function argument input type like "anything that can be converted into a `String`", the rule is opposite, you should use `Into`. - Your function will accept types that implement `From` and those that _only_ implement `Into`. +- That's why it is common to only implement `From`, as your type will get `Into` + implementation too. +- When declaring a function argument input type like "anything that can be + converted into a `String`", the rule is opposite, you should use `Into`. Your + function will accept types that implement `From` and those that _only_ + implement `Into`.
diff --git a/src/std-traits/operators.md b/src/std-traits/operators.md index 250dc7b..16c8038 100644 --- a/src/std-traits/operators.md +++ b/src/std-traits/operators.md @@ -8,13 +8,16 @@ Operator overloading is implemented via traits in [`std::ops`][1]: ```rust,editable #[derive(Debug, Copy, Clone)] -struct Point { x: i32, y: i32 } +struct Point { + x: i32, + y: i32, +} impl std::ops::Add for Point { type Output = Self; fn add(self, other: Self) -> Self { - Self {x: self.x + other.x, y: self.y + other.y} + Self { x: self.x + other.x, y: self.y + other.y } } } @@ -29,16 +32,16 @@ fn main() { Discussion points: -* You could implement `Add` for `&Point`. In which situations is that useful? - * Answer: `Add:add` consumes `self`. If type `T` for which you are - overloading the operator is not `Copy`, you should consider overloading - the operator for `&T` as well. This avoids unnecessary cloning on the - call site. -* Why is `Output` an associated type? Could it be made a type parameter of the method? - * Short answer: Function type parameters are controlled by the caller, but - associated types (like `Output`) are controlled by the implementer of a - trait. -* You could implement `Add` for two different types, e.g. +- You could implement `Add` for `&Point`. In which situations is that useful? + - Answer: `Add:add` consumes `self`. If type `T` for which you are overloading + the operator is not `Copy`, you should consider overloading the operator for + `&T` as well. This avoids unnecessary cloning on the call site. +- Why is `Output` an associated type? Could it be made a type parameter of the + method? + - Short answer: Function type parameters are controlled by the caller, but + associated types (like `Output`) are controlled by the implementer of a + trait. +- You could implement `Add` for two different types, e.g. `impl Add<(i32, i32)> for Point` would add a tuple to a `Point`.
diff --git a/src/std-types/docs.md b/src/std-types/docs.md index 8723a02..19947ac 100644 --- a/src/std-types/docs.md +++ b/src/std-types/docs.md @@ -6,9 +6,13 @@ minutes: 5 Rust comes with extensive documentation. For example: - * All of the details about [loops](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html). - * Primitive types like [`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html). - * Standard library types like [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html) or [`BinaryHeap`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html). +- All of the details about + [loops](https://doc.rust-lang.org/stable/reference/expressions/loop-expr.html). +- Primitive types like + [`u8`](https://doc.rust-lang.org/stable/std/primitive.u8.html). +- Standard library types like + [`Option`](https://doc.rust-lang.org/stable/std/option/enum.Option.html) or + [`BinaryHeap`](https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html). In fact, you can document your own code: @@ -29,8 +33,8 @@ automatically documented at [`docs.rs`](https://docs.rs) using the [rustdoc](https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html) tool. It is idiomatic to document all public items in an API using this pattern. -To document an item from inside the item (such as inside a module), use `//!` -or `/*! .. */`, called "inner doc comments": +To document an item from inside the item (such as inside a module), use `//!` or +`/*! .. */`, called "inner doc comments": ```rust,editable //! This module contains functionality relating to divisibility of integers. @@ -38,7 +42,7 @@ or `/*! .. */`, called "inner doc comments":
-* Show students the generated docs for the `rand` crate at +- Show students the generated docs for the `rand` crate at .
diff --git a/src/std-types/exercise.rs b/src/std-types/exercise.rs index 75f15b5..3a09c34 100644 --- a/src/std-types/exercise.rs +++ b/src/std-types/exercise.rs @@ -25,9 +25,7 @@ struct Counter { impl Counter { /// Create a new Counter. fn new() -> Self { - Counter { - values: HashMap::new(), - } + Counter { values: HashMap::new() } } /// Count an occurrence of the given value. diff --git a/src/std-types/hashmap.md b/src/std-types/hashmap.md index 06072b4..f82406d 100644 --- a/src/std-types/hashmap.md +++ b/src/std-types/hashmap.md @@ -16,14 +16,16 @@ fn main() { page_counts.insert("Pride and Prejudice".to_string(), 303); if !page_counts.contains_key("Les Misérables") { - println!("We know about {} books, but not Les Misérables.", - page_counts.len()); + println!( + "We know about {} books, but not Les Misérables.", + page_counts.len() + ); } for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] { match page_counts.get(book) { Some(count) => println!("{book}: {count} pages"), - None => println!("{book} is unknown.") + None => println!("{book} is unknown."), } } @@ -39,33 +41,42 @@ fn main() {
-* `HashMap` is not defined in the prelude and needs to be brought into scope. -* Try the following lines of code. The first line will see if a book is in the hashmap and if not return an alternative value. The second line will insert the alternative value in the hashmap if the book is not found. - - ```rust,ignore - let pc1 = page_counts - .get("Harry Potter and the Sorcerer's Stone") - .unwrap_or(&336); - let pc2 = page_counts - .entry("The Hunger Games".to_string()) - .or_insert(374); - ``` -* Unlike `vec!`, there is unfortunately no standard `hashmap!` macro. - * Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`][1], which allows us to easily initialize a hash map from a literal array: - - ```rust,ignore - let page_counts = HashMap::from([ - ("Harry Potter and the Sorcerer's Stone".to_string(), 336), - ("The Hunger Games".to_string(), 374), - ]); - ``` - - * Alternatively HashMap can be built from any `Iterator` which yields key-value tuples. -* We are showing `HashMap`, and avoid using `&str` as key to make examples easier. Using references in collections can, of course, be done, - but it can lead into complications with the borrow checker. - * Try removing `to_string()` from the example above and see if it still compiles. Where do you think we might run into issues? - -* This type has several "method-specific" return types, such as `std::collections::hash_map::Keys`. These types often appear in searches of the Rust docs. Show students the docs for this type, and the helpful link back to the `keys` method. +- `HashMap` is not defined in the prelude and needs to be brought into scope. +- Try the following lines of code. The first line will see if a book is in the + hashmap and if not return an alternative value. The second line will insert + the alternative value in the hashmap if the book is not found. + + ```rust,ignore + let pc1 = page_counts + .get("Harry Potter and the Sorcerer's Stone") + .unwrap_or(&336); + let pc2 = page_counts + .entry("The Hunger Games".to_string()) + .or_insert(374); + ``` +- Unlike `vec!`, there is unfortunately no standard `hashmap!` macro. + - Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`][1], + which allows us to easily initialize a hash map from a literal array: + + ```rust,ignore + let page_counts = HashMap::from([ + ("Harry Potter and the Sorcerer's Stone".to_string(), 336), + ("The Hunger Games".to_string(), 374), + ]); + ``` + +- Alternatively HashMap can be built from any `Iterator` which yields key-value + tuples. +- We are showing `HashMap`, and avoid using `&str` as key to make + examples easier. Using references in collections can, of course, be done, but + it can lead into complications with the borrow checker. + - Try removing `to_string()` from the example above and see if it still + compiles. Where do you think we might run into issues? + +- This type has several "method-specific" return types, such as + `std::collections::hash_map::Keys`. These types often appear in searches of + the Rust docs. Show students the docs for this type, and the helpful link back + to the `keys` method. [1]: https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#impl-From%3C%5B(K,+V);+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E diff --git a/src/std-types/option.md b/src/std-types/option.md index e26c98a..a960dad 100644 --- a/src/std-types/option.md +++ b/src/std-types/option.md @@ -4,8 +4,8 @@ minutes: 10 # Option -We have already seen some use of `Option`. It stores either a -value of type `T` or nothing. For example, +We have already seen some use of `Option`. It stores either a value of type +`T` or nothing. For example, [`String::find`](https://doc.rust-lang.org/stable/std/string/struct.String.html#method.find) returns an `Option`. @@ -23,10 +23,14 @@ fn main() {
- * `Option` is widely used, not just in the standard library. - * `unwrap` will return the value in an `Option`, or panic. `expect` is similar but takes an error message. - * You can panic on None, but you can't "accidentally" forget to check for None. - * It's common to `unwrap`/`expect` all over the place when hacking something together, but production code typically handles `None` in a nicer fashion. - * The niche optimization means that `Option` often has the same size in memory as `T`. +- `Option` is widely used, not just in the standard library. +- `unwrap` will return the value in an `Option`, or panic. `expect` is similar + but takes an error message. + - You can panic on None, but you can't "accidentally" forget to check for + None. + - It's common to `unwrap`/`expect` all over the place when hacking something + together, but production code typically handles `None` in a nicer fashion. +- The niche optimization means that `Option` often has the same size in + memory as `T`.
diff --git a/src/std-types/result.md b/src/std-types/result.md index f6f19f8..6bef5b1 100644 --- a/src/std-types/result.md +++ b/src/std-types/result.md @@ -5,9 +5,9 @@ minutes: 10 # Result `Result` is similar to `Option`, but indicates the success or failure of an -operation, each with a different type. This is similar to the `Res` defined -in the expression exercise, but generic: `Result` where `T` is used in -the `Ok` variant and `E` appears in the `Err` variant. +operation, each with a different type. This is similar to the `Res` defined in +the expression exercise, but generic: `Result` where `T` is used in the +`Ok` variant and `E` appears in the `Err` variant. ```rust,editable use std::fs::File; @@ -23,7 +23,7 @@ fn main() { } else { println!("Could not read file content"); } - }, + } Err(err) => { println!("The diary could not be opened: {err}"); } @@ -33,11 +33,14 @@ fn main() {
- * As with `Option`, the successful value sits inside of `Result`, forcing the developer to - explicitly extract it. This encourages error checking. In the case where an error should never happen, - `unwrap()` or `expect()` can be called, and this is a signal of the developer intent too. - * `Result` documentation is a recommended read. Not during the course, but it is worth mentioning. - It contains a lot of convenience methods and functions that help functional-style programming. -* `Result` is the standard type to implement error handling as we will see on Day 3. +- As with `Option`, the successful value sits inside of `Result`, forcing the + developer to explicitly extract it. This encourages error checking. In the + case where an error should never happen, `unwrap()` or `expect()` can be + called, and this is a signal of the developer intent too. +- `Result` documentation is a recommended read. Not during the course, but it is + worth mentioning. It contains a lot of convenience methods and functions that + help functional-style programming. +- `Result` is the standard type to implement error handling as we will see on + Day 3.
diff --git a/src/std-types/std.md b/src/std-types/std.md index 872d652..e7b18f9 100644 --- a/src/std-types/std.md +++ b/src/std-types/std.md @@ -8,8 +8,11 @@ Rust comes with a standard library which helps establish a set of common types used by Rust libraries and programs. This way, two libraries can work together smoothly because they both use the same `String` type. -In fact, Rust contains several layers of the Standard Library: `core`, `alloc` and `std`. -* `core` includes the most basic types and functions that don't depend on `libc`, allocator or - even the presence of an operating system. -* `alloc` includes types which require a global heap allocator, such as `Vec`, `Box` and `Arc`. -* Embedded Rust applications often only use `core`, and sometimes `alloc`. +In fact, Rust contains several layers of the Standard Library: `core`, `alloc` +and `std`. + +- `core` includes the most basic types and functions that don't depend on + `libc`, allocator or even the presence of an operating system. +- `alloc` includes types which require a global heap allocator, such as `Vec`, + `Box` and `Arc`. +- Embedded Rust applications often only use `core`, and sometimes `alloc`. diff --git a/src/std-types/string.md b/src/std-types/string.md index ae06546..e2c119a 100644 --- a/src/std-types/string.md +++ b/src/std-types/string.md @@ -18,30 +18,41 @@ fn main() { println!("s2: len = {}, capacity = {}", s2.len(), s2.capacity()); let s3 = String::from("🇨🇭"); - println!("s3: len = {}, number of chars = {}", s3.len(), - s3.chars().count()); + println!("s3: len = {}, number of chars = {}", s3.len(), s3.chars().count()); } ``` -`String` implements [`Deref`][2], which means that you can call all -`str` methods on a `String`. +`String` implements [`Deref`][2], which means that you can call +all `str` methods on a `String`. [1]: https://doc.rust-lang.org/std/string/struct.String.html [2]: https://doc.rust-lang.org/std/string/struct.String.html#deref-methods-str
-* `String::new` returns a new empty string, use `String::with_capacity` when you know how much data you want to push to the string. -* `String::len` returns the size of the `String` in bytes (which can be different from its length in characters). -* `String::chars` returns an iterator over the actual characters. Note that a `char` can be different from what a human will consider a "character" due to [grapheme clusters](https://docs.rs/unicode-segmentation/latest/unicode_segmentation/struct.Graphemes.html). -* When people refer to strings they could either be talking about `&str` or `String`. -* When a type implements `Deref`, the compiler will let you transparently call methods from `T`. - * We haven't discussed the `Deref` trait yet, so at this point this mostly explains the structure of the sidebar in the documentation. - * `String` implements `Deref` which transparently gives it access to `str`'s methods. - * Write and compare `let s3 = s1.deref();` and `let s3 = &*s1;`. -* `String` is implemented as a wrapper around a vector of bytes, many of the operations you see supported on vectors are also supported on `String`, but with some extra guarantees. -* Compare the different ways to index a `String`: - * To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, out-of-bounds. - * To a substring by using `s3[0..4]`, where that slice is on character boundaries or not. +- `String::new` returns a new empty string, use `String::with_capacity` when you + know how much data you want to push to the string. +- `String::len` returns the size of the `String` in bytes (which can be + different from its length in characters). +- `String::chars` returns an iterator over the actual characters. Note that a + `char` can be different from what a human will consider a "character" due to + [grapheme clusters](https://docs.rs/unicode-segmentation/latest/unicode_segmentation/struct.Graphemes.html). +- When people refer to strings they could either be talking about `&str` or + `String`. +- When a type implements `Deref`, the compiler will let you + transparently call methods from `T`. + - We haven't discussed the `Deref` trait yet, so at this point this mostly + explains the structure of the sidebar in the documentation. + - `String` implements `Deref` which transparently gives it + access to `str`'s methods. + - Write and compare `let s3 = s1.deref();` and `let s3 = &*s1;`. +- `String` is implemented as a wrapper around a vector of bytes, many of the + operations you see supported on vectors are also supported on `String`, but + with some extra guarantees. +- Compare the different ways to index a `String`: + - To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, + out-of-bounds. + - To a substring by using `s3[0..4]`, where that slice is on character + boundaries or not.
diff --git a/src/std-types/vec.md b/src/std-types/vec.md index 0c8ea67..6684a66 100644 --- a/src/std-types/vec.md +++ b/src/std-types/vec.md @@ -38,16 +38,18 @@ methods on a `Vec`.
-* `Vec` is a type of collection, along with `String` and `HashMap`. The data it contains is stored - on the heap. This means the amount of data doesn't need to be known at compile time. It can grow - or shrink at runtime. -* Notice how `Vec` is a generic type too, but you don't have to specify `T` explicitly. As always - with Rust type inference, the `T` was established during the first `push` call. -* `vec![...]` is a canonical macro to use instead of `Vec::new()` and it supports adding initial - elements to the vector. -* To index the vector you use `[` `]`, but they will panic if out of bounds. Alternatively, using - `get` will return an `Option`. The `pop` function will remove the last element. -* Slices are covered on day 3. For now, students only need to know that a value +- `Vec` is a type of collection, along with `String` and `HashMap`. The data it + contains is stored on the heap. This means the amount of data doesn't need to + be known at compile time. It can grow or shrink at runtime. +- Notice how `Vec` is a generic type too, but you don't have to specify `T` + explicitly. As always with Rust type inference, the `T` was established during + the first `push` call. +- `vec![...]` is a canonical macro to use instead of `Vec::new()` and it + supports adding initial elements to the vector. +- To index the vector you use `[` `]`, but they will panic if out of bounds. + Alternatively, using `get` will return an `Option`. The `pop` function will + remove the last element. +- Slices are covered on day 3. For now, students only need to know that a value of type `Vec` gives access to all of the documented slice methods, too.
diff --git a/src/testing/exercise.md b/src/testing/exercise.md index ee843aa..b10d2b5 100644 --- a/src/testing/exercise.md +++ b/src/testing/exercise.md @@ -10,17 +10,17 @@ The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used to validate credit card numbers. The algorithm takes a string as input and does the following to validate the credit card number: -* Ignore all spaces. Reject number with less than two digits. +- Ignore all spaces. Reject number with less than two digits. -* Moving from **right to left**, double every second digit: for the number `1234`, - we double `3` and `1`. For the number `98765`, we double `6` and `8`. +- Moving from **right to left**, double every second digit: for the number + `1234`, we double `3` and `1`. For the number `98765`, we double `6` and `8`. -* After doubling a digit, sum the digits if the result is greater than 9. So doubling `7` becomes `14` which - becomes `1 + 4 = 5`. +- After doubling a digit, sum the digits if the result is greater than 9. So + doubling `7` becomes `14` which becomes `1 + 4 = 5`. -* Sum all the undoubled and doubled digits. +- Sum all the undoubled and doubled digits. -* The credit card number is valid if the sum ends with `0`. +- The credit card number is valid if the sum ends with `0`. The provided code provides a buggy implementation of the luhn algorithm, along with two basic unit tests that confirm that most the algorithm is implemented diff --git a/src/testing/exercise.rs b/src/testing/exercise.rs index 24d9250..385eb9b 100644 --- a/src/testing/exercise.rs +++ b/src/testing/exercise.rs @@ -24,11 +24,8 @@ pub fn luhn(cc_number: &str) -> bool { 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 - }; + sum += + if double_digit > 9 { double_digit - 9 } else { double_digit }; } else { sum += digit; } @@ -53,11 +50,8 @@ pub fn luhn(cc_number: &str) -> bool { digits += 1; if double { let double_digit = digit * 2; - sum += if double_digit > 9 { - double_digit - 9 - } else { - double_digit - }; + sum += + if double_digit > 9 { double_digit - 9 } else { double_digit }; } else { sum += digit; } diff --git a/src/testing/googletest.md b/src/testing/googletest.md index b22efc5..0634dcc 100644 --- a/src/testing/googletest.md +++ b/src/testing/googletest.md @@ -47,21 +47,22 @@ Error: See failure output above {{#include googletest.rs:test_multiline_string_diff}} ``` - shows a color-coded diff (colors not shown here): - - - ```text - Value of: haiku - Expected: is equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write." - Actual: "Memory safety found,\nRust's strong typing guides the way,\nSecure code you'll write.", - which isn't equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write." - Difference(-actual / +expected): - Memory safety found, - -Rust's strong typing guides the way, - +Rust's silly humor guides the way, - Secure code you'll write. - at src/testing/googletest.rs:17:5 - ``` +shows a color-coded diff (colors not shown here): + + + +```text + Value of: haiku +Expected: is equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write." +Actual: "Memory safety found,\nRust's strong typing guides the way,\nSecure code you'll write.", + which isn't equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write." +Difference(-actual / +expected): + Memory safety found, +-Rust's strong typing guides the way, ++Rust's silly humor guides the way, + Secure code you'll write. + at src/testing/googletest.rs:17:5 +``` - The crate is a Rust port of [GoogleTest for C++](https://google.github.io/googletest/). diff --git a/src/testing/lints.md b/src/testing/lints.md index f55af92..846ecf7 100644 --- a/src/testing/lints.md +++ b/src/testing/lints.md @@ -4,9 +4,9 @@ minutes: 5 # Compiler Lints and Clippy -The Rust compiler produces fantastic error messages, as well as helpful -built-in lints. [Clippy](https://doc.rust-lang.org/clippy/) provides even more -lints, organized into groups that can be enabled per-project. +The Rust compiler produces fantastic error messages, as well as helpful built-in +lints. [Clippy](https://doc.rust-lang.org/clippy/) provides even more lints, +organized into groups that can be enabled per-project. ```rust,editable,should_panic #[deny(clippy::cast_possible_truncation)] diff --git a/src/testing/mocking.md b/src/testing/mocking.md index c71e77e..1c62cde 100644 --- a/src/testing/mocking.md +++ b/src/testing/mocking.md @@ -4,8 +4,8 @@ minutes: 5 # Mocking -For mocking, [Mockall] is a widely used library. You need to refactor your -code to use traits, which you can then quickly mock: +For mocking, [Mockall] is a widely used library. You need to refactor your code +to use traits, which you can then quickly mock: ```rust,ignore {{#include mockall.rs:simple_example}} @@ -15,16 +15,17 @@ code to use traits, which you can then quickly mock:
-- The advice here is for Android (AOSP) where Mockall is the recommended mocking library. - There are other [mocking libraries available on crates.io](https://crates.io/keywords/mock), - in particular in the area of mocking HTTP services. The other mocking libraries work - in a similar fashion as Mockall, meaning that they make it easy to get a mock implementation - of a given trait. - -- Note that mocking is somewhat *controversial*: mocks allow you to completely isolate a - test from its dependencies. The immediate result is faster and more stable - test execution. On the other hand, the mocks can be configured wrongly and - return output different from what the real dependencies would do. +- The advice here is for Android (AOSP) where Mockall is the recommended mocking + library. There are other + [mocking libraries available on crates.io](https://crates.io/keywords/mock), + in particular in the area of mocking HTTP services. The other mocking + libraries work in a similar fashion as Mockall, meaning that they make it easy + to get a mock implementation of a given trait. + +- Note that mocking is somewhat _controversial_: mocks allow you to completely + isolate a test from its dependencies. The immediate result is faster and more + stable test execution. On the other hand, the mocks can be configured wrongly + and return output different from what the real dependencies would do. If at all possible, it is recommended that you use the real dependencies. As an example, many databases allow you to configure an in-memory backend. This diff --git a/src/testing/other.md b/src/testing/other.md index e62b24b..f1eea8e 100644 --- a/src/testing/other.md +++ b/src/testing/other.md @@ -26,7 +26,7 @@ These tests only have access to the public API of your crate. Rust has built-in support for documentation tests: -```rust +````rust /// Shortens a string to the given length. /// /// ``` @@ -37,9 +37,11 @@ Rust has built-in support for documentation tests: pub fn shorten_string(s: &str, length: usize) -> &str { &s[..std::cmp::min(length, s.len())] } -``` - -* Code blocks in `///` comments are automatically seen as Rust code. -* The code will be compiled and executed as part of `cargo test`. -* Adding `# ` in the code will hide it from the docs, but will still compile/run it. -* Test the above code on the [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0). +```` + +- Code blocks in `///` comments are automatically seen as Rust code. +- The code will be compiled and executed as part of `cargo test`. +- Adding `#` in the code will hide it from the docs, but will still compile/run + it. +- Test the above code on the + [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0). diff --git a/src/testing/unit-tests.md b/src/testing/unit-tests.md index 766491f..fc99bf6 100644 --- a/src/testing/unit-tests.md +++ b/src/testing/unit-tests.md @@ -6,11 +6,11 @@ minutes: 5 Rust and Cargo come with a simple unit test framework: -* Unit tests are supported throughout your code. +- Unit tests are supported throughout your code. -* Integration tests are supported via the `tests/` directory. +- Integration tests are supported via the `tests/` directory. -Tests are marked with `#[test]`. Unit tests are often put in a nested `tests` +Tests are marked with `#[test]`. Unit tests are often put in a nested `tests` module, using `#[cfg(test)]` to conditionally compile them only when building tests. @@ -43,8 +43,8 @@ mod test { } ``` -* This lets you unit test private helpers. -* The `#[cfg(test)]` attribute is only active when you run `cargo test`. +- This lets you unit test private helpers. +- The `#[cfg(test)]` attribute is only active when you run `cargo test`.
diff --git a/src/testing/useful-crates.md b/src/testing/useful-crates.md index 91a6847..2314a5b 100644 --- a/src/testing/useful-crates.md +++ b/src/testing/useful-crates.md @@ -8,6 +8,8 @@ Rust comes with only basic support for writing tests. Here are some additional crates which we recommend for writing tests: -* [googletest](https://docs.rs/googletest): Comprehensive test assertion library in the tradition of GoogleTest for C++. -* [proptest](https://docs.rs/proptest): Property-based testing for Rust. -* [rstest](https://docs.rs/rstest): Support for fixtures and parameterised tests. +- [googletest](https://docs.rs/googletest): Comprehensive test assertion library + in the tradition of GoogleTest for C++. +- [proptest](https://docs.rs/proptest): Property-based testing for Rust. +- [rstest](https://docs.rs/rstest): Support for fixtures and parameterised + tests. diff --git a/src/thanks.md b/src/thanks.md index 44e13f5..56f67c0 100644 --- a/src/thanks.md +++ b/src/thanks.md @@ -1,6 +1,7 @@ --- course: none --- + # Thanks! _Thank you for taking Comprehensive Rust 🦀!_ We hope you enjoyed it and that it @@ -8,6 +9,5 @@ was useful. We've had a lot of fun putting the course together. The course is not perfect, so if you spotted any mistakes or have ideas for improvements, please get in -[contact with us on -GitHub](https://github.com/google/comprehensive-rust/discussions). We would love -to hear from you. +[contact with us on GitHub](https://github.com/google/comprehensive-rust/discussions). +We would love to hear from you. diff --git a/src/tuples-and-arrays/Cargo.toml b/src/tuples-and-arrays/Cargo.toml index f61a7b1..1867373 100644 --- a/src/tuples-and-arrays/Cargo.toml +++ b/src/tuples-and-arrays/Cargo.toml @@ -7,4 +7,3 @@ publish = false [[bin]] name = "transpose" path = "exercise.rs" - diff --git a/src/tuples-and-arrays/destructuring.md b/src/tuples-and-arrays/destructuring.md index 7ba67f6..d959b82 100644 --- a/src/tuples-and-arrays/destructuring.md +++ b/src/tuples-and-arrays/destructuring.md @@ -36,9 +36,10 @@ fn describe_point(point: (i32, i32)) {
-* Create a new array pattern using `_` to represent an element. -* Add more values to the array. -* Point out that how `..` will expand to account for different number of elements. -* Show matching against the tail with patterns `[.., b]` and `[a@..,b]` +- Create a new array pattern using `_` to represent an element. +- Add more values to the array. +- Point out that how `..` will expand to account for different number of + elements. +- Show matching against the tail with patterns `[.., b]` and `[a@..,b]`
diff --git a/src/tuples-and-arrays/exercise.md b/src/tuples-and-arrays/exercise.md index 342ebbb..1be4092 100644 --- a/src/tuples-and-arrays/exercise.md +++ b/src/tuples-and-arrays/exercise.md @@ -16,6 +16,7 @@ Use an array such as the above to write a function `transpose` which will transpose a matrix (turn rows into columns): + ```bob ⎛⎡1 2 3⎤⎞ ⎡1 4 7⎤ "transpose"⎜⎢4 5 6⎥⎟ "=="⎢2 5 8⎥ diff --git a/src/tuples-and-arrays/iteration.md b/src/tuples-and-arrays/iteration.md index 2df452a..2eb8ffc 100644 --- a/src/tuples-and-arrays/iteration.md +++ b/src/tuples-and-arrays/iteration.md @@ -11,18 +11,19 @@ fn main() { let primes = [2, 3, 5, 7, 11, 13, 17, 19]; for prime in primes { for i in 2..prime { - assert_ne!(prime % i, 0); - } - } + assert_ne!(prime % i, 0); + } + } } ```
-This functionality uses the `IntoIterator` trait, but we haven't covered that yet. +This functionality uses the `IntoIterator` trait, but we haven't covered that +yet. The `assert_ne!` macro is new here. There are also `assert_eq!` and `assert!` -macros. These are always checked while, debug-only variants like -`debug_assert!` compile to nothing in release builds. +macros. These are always checked while, debug-only variants like `debug_assert!` +compile to nothing in release builds.
diff --git a/src/tuples-and-arrays/match.md b/src/tuples-and-arrays/match.md index 2abd352..808e2e7 100644 --- a/src/tuples-and-arrays/match.md +++ b/src/tuples-and-arrays/match.md @@ -10,6 +10,7 @@ comparisons are done from top to bottom and the first match wins. The patterns can be simple values, similarly to `switch` in C and C++: ```rust,editable +#[rustfmt::skip] fn main() { let input = 'x'; match input { @@ -23,28 +24,36 @@ fn main() { ``` The `_` pattern is a wildcard pattern which matches any value. The expressions -_must_ be irrefutable, meaning that it covers every possibility, so `_` is -often used as the final catch-all case. +_must_ be irrefutable, meaning that it covers every possibility, so `_` is often +used as the final catch-all case. -Match can be used as an expression. Just like `if`, each match arm must have the same type. The type is the last -expression of the block, if any. In the example above, the type is `()`. +Match can be used as an expression. Just like `if`, each match arm must have the +same type. The type is the last expression of the block, if any. In the example +above, the type is `()`. -A variable in the pattern (`key` in this example) will create a binding that -can be used within the match arm. +A variable in the pattern (`key` in this example) will create a binding that can +be used within the match arm. A match guard causes the arm to match only if the condition is true.
Key Points: -* You might point out how some specific characters are being used when in a pattern - * `|` as an `or` - * `..` can expand as much as it needs to be - * `1..=5` represents an inclusive range - * `_` is a wild card - -* Match guards as a separate syntax feature are important and necessary when we wish to concisely express more complex ideas than patterns alone would allow. -* They are not the same as separate `if` expression inside of the match arm. An `if` expression inside of the branch block (after `=>`) happens after the match arm is selected. Failing the `if` condition inside of that block won't result in other arms -of the original `match` expression being considered. -* The condition defined in the guard applies to every expression in a pattern with an `|`. + +- You might point out how some specific characters are being used when in a + pattern + - `|` as an `or` + - `..` can expand as much as it needs to be + - `1..=5` represents an inclusive range + - `_` is a wild card + +- Match guards as a separate syntax feature are important and necessary when we + wish to concisely express more complex ideas than patterns alone would allow. +- They are not the same as separate `if` expression inside of the match arm. An + `if` expression inside of the branch block (after `=>`) happens after the + match arm is selected. Failing the `if` condition inside of that block won't + result in other arms of the original `match` expression being considered. +- The condition defined in the guard applies to every expression in a pattern + with an `|`. +
diff --git a/src/tuples-and-arrays/tuples-and-arrays.md b/src/tuples-and-arrays/tuples-and-arrays.md index b047c42..e5c828d 100644 --- a/src/tuples-and-arrays/tuples-and-arrays.md +++ b/src/tuples-and-arrays/tuples-and-arrays.md @@ -5,17 +5,18 @@ minutes: 10 # Tuples and Arrays Tuples and arrays are the first "compound" types we have seen. All elements of -an array have the same type, while tuples can accommodate different types. -Both types have a size fixed at compile time. +an array have the same type, while tuples can accommodate different types. Both +types have a size fixed at compile time. | | Types | Literals | -|--------|-------------------------------|-----------------------------------| +| ------ | ----------------------------- | --------------------------------- | | Arrays | `[T; N]` | `[20, 30, 40]`, `[0; 3]` | | Tuples | `()`, `(T,)`, `(T1, T2)`, ... | `()`, `('x',)`, `('x', 1.2)`, ... | Array assignment and access: + ```rust,editable fn main() { let mut a: [i8; 10] = [42; 10]; @@ -27,6 +28,7 @@ fn main() { Tuple assignment and access: + ```rust,editable fn main() { let t: (i8, bool) = (7, true); @@ -41,37 +43,40 @@ Key points: Arrays: -* A value of the array type `[T; N]` holds `N` (a compile-time constant) elements of the same type `T`. - Note that the length of the array is *part of its type*, which means that `[u8; 3]` and - `[u8; 4]` are considered two different types. Slices, which have a size determined at runtime, - are covered later. +- A value of the array type `[T; N]` holds `N` (a compile-time constant) + elements of the same type `T`. Note that the length of the array is _part of + its type_, which means that `[u8; 3]` and `[u8; 4]` are considered two + different types. Slices, which have a size determined at runtime, are covered + later. -* Try accessing an out-of-bounds array element. Array accesses are checked at +- Try accessing an out-of-bounds array element. Array accesses are checked at runtime. Rust can usually optimize these checks away, and they can be avoided using unsafe Rust. -* We can use literals to assign values to arrays. +- We can use literals to assign values to arrays. -* The `println!` macro asks for the debug implementation with the `?` format - parameter: `{}` gives the default output, `{:?}` gives the debug output. Types such as - integers and strings implement the default output, but arrays only implement the debug output. - This means that we must use debug output here. +- The `println!` macro asks for the debug implementation with the `?` format + parameter: `{}` gives the default output, `{:?}` gives the debug output. Types + such as integers and strings implement the default output, but arrays only + implement the debug output. This means that we must use debug output here. -* Adding `#`, eg `{a:#?}`, invokes a "pretty printing" format, which can be easier to read. +- Adding `#`, eg `{a:#?}`, invokes a "pretty printing" format, which can be + easier to read. Tuples: -* Like arrays, tuples have a fixed length. +- Like arrays, tuples have a fixed length. -* Tuples group together values of different types into a compound type. +- Tuples group together values of different types into a compound type. -* Fields of a tuple can be accessed by the period and the index of the value, e.g. `t.0`, `t.1`. +- Fields of a tuple can be accessed by the period and the index of the value, + e.g. `t.0`, `t.1`. -* The empty tuple `()` is also known as the "unit type". It is both a type, and - the only valid value of that type --- that is to say both the type and its value - are expressed as `()`. It is used to indicate, for example, that a function or - expression has no return value, as we'll see in a future slide. - * You can think of it as `void` that can be familiar to you from other - programming languages. +- The empty tuple `()` is also known as the "unit type". It is both a type, and + the only valid value of that type --- that is to say both the type and its + value are expressed as `()`. It is used to indicate, for example, that a + function or expression has no return value, as we'll see in a future slide. + - You can think of it as `void` that can be familiar to you from other + programming languages.
diff --git a/src/types-and-values/arithmetic.md b/src/types-and-values/arithmetic.md index 294888b..30ebbc5 100644 --- a/src/types-and-values/arithmetic.md +++ b/src/types-and-values/arithmetic.md @@ -27,11 +27,11 @@ actually undefined, and might do different things on different platforms or compilers. In Rust, it's defined. Change the `i32`'s to `i16` to see an integer overflow, which panics (checked) -in a debug build and wraps in a release build. There are other options, such -as overflowing, saturating, and carrying. These are accessed with method -syntax, e.g., `(a * b).saturating_add(b * c).saturating_add(c * a)`. +in a debug build and wraps in a release build. There are other options, such as +overflowing, saturating, and carrying. These are accessed with method syntax, +e.g., `(a * b).saturating_add(b * c).saturating_add(c * a)`. -In fact, the compiler will detect overflow of constant expressions, which is -why the example requires a separate function. +In fact, the compiler will detect overflow of constant expressions, which is why +the example requires a separate function.
diff --git a/src/types-and-values/exercise.md b/src/types-and-values/exercise.md index fc5fd74..3b6529a 100644 --- a/src/types-and-values/exercise.md +++ b/src/types-and-values/exercise.md @@ -4,11 +4,11 @@ minutes: 30 # Exercise: Fibonacci -The first and second Fibonacci numbers are both `1`. For n>2, he n'th -Fibonacci number is calculated recursively as the sum of the n-1'th and n-2'th -Fibonacci numbers. +The first and second Fibonacci numbers are both `1`. For n>2, he n'th Fibonacci +number is calculated recursively as the sum of the n-1'th and n-2'th Fibonacci +numbers. -Write a function `fib(n)` that calculates the n'th Fibonacci number. When will +Write a function `fib(n)` that calculates the n'th Fibonacci number. When will this function panic? ```rust,editable,should_panic diff --git a/src/types-and-values/inference.md b/src/types-and-values/inference.md index 7e68843..8a82a48 100644 --- a/src/types-and-values/inference.md +++ b/src/types-and-values/inference.md @@ -7,6 +7,7 @@ minutes: 5 Rust will look at how the variable is _used_ to determine the type: + ```rust,editable fn takes_u32(x: u32) { println!("u32: {x}"); @@ -28,11 +29,13 @@ fn main() {
-This slide demonstrates how the Rust compiler infers types based on constraints given by variable declarations and usages. +This slide demonstrates how the Rust compiler infers types based on constraints +given by variable declarations and usages. -It is very important to emphasize that variables declared like this are not of some sort of dynamic "any type" that can -hold any data. The machine code generated by such declaration is identical to the explicit declaration of a type. -The compiler does the job for us and helps us write more concise code. +It is very important to emphasize that variables declared like this are not of +some sort of dynamic "any type" that can hold any data. The machine code +generated by such declaration is identical to the explicit declaration of a +type. The compiler does the job for us and helps us write more concise code. When nothing constrains the type of an integer literal, Rust defaults to `i32`. This sometimes appears as `{integer}` in error messages. Similarly, diff --git a/src/types-and-values/strings.md b/src/types-and-values/strings.md index b62998c..54ed4de 100644 --- a/src/types-and-values/strings.md +++ b/src/types-and-values/strings.md @@ -5,10 +5,10 @@ minutes: 10 # Strings Rust has two types to represent strings, both of which will be covered in more -depth later. Both _always_ store UTF-8 encoded strings. +depth later. Both _always_ store UTF-8 encoded strings. - * `String` - a modifiable, owned string. - * `&str` - a read-only string. String literals have this type. +- `String` - a modifiable, owned string. +- `&str` - a read-only string. String literals have this type. ```rust,editable fn main() { @@ -31,18 +31,19 @@ later, but this is enough for subsequent slides and exercises to use strings. - Invalid UTF-8 in a string is UB, and this not allowed in safe Rust. -- `String` is a user-defined type with a constructor (`::new()`) and methods like `s.push_str(..)`. +- `String` is a user-defined type with a constructor (`::new()`) and methods + like `s.push_str(..)`. -- The `&` in `&str` indicates that this is a reference. We will cover references later, so for now - just think of `&str` as a unit meaning "a read-only string". +- The `&` in `&str` indicates that this is a reference. We will cover references + later, so for now just think of `&str` as a unit meaning "a read-only string". - The commented-out line is indexing into the string by byte position. `12..13` does not end on a character boundary, so the program panics. Adjust it to a range that does, based on the error message. -- Raw strings allow you to create a `&str` value with escapes disabled: `r"\n" - == "\\\\n"`. You can embed double-quotes by using an equal amount of `#` on - either side of the quotes: +- Raw strings allow you to create a `&str` value with escapes disabled: + `r"\n" == "\\n"`. You can embed double-quotes by using an equal amount of `#` + on either side of the quotes: ```rust,editable diff --git a/src/types-and-values/values.md b/src/types-and-values/values.md index f1b9d2c..311a27e 100644 --- a/src/types-and-values/values.md +++ b/src/types-and-values/values.md @@ -4,10 +4,11 @@ minutes: 10 # Values -Here are some basic built-in types, and the syntax for literal values of each type. +Here are some basic built-in types, and the syntax for literal values of each +type. | | Types | Literals | -|------------------------|--------------------------------------------|--------------------------------| +| ---------------------- | ------------------------------------------ | ------------------------------ | | Signed integers | `i8`, `i16`, `i32`, `i64`, `i128`, `isize` | `-10`, `0`, `1_000`, `123_i64` | | Unsigned integers | `u8`, `u16`, `u32`, `u64`, `u128`, `usize` | `0`, `123`, `10_u16` | | Floating point numbers | `f32`, `f64` | `3.14`, `-10.0e20`, `2_f32` | @@ -16,16 +17,17 @@ Here are some basic built-in types, and the syntax for literal values of each ty The types have widths as follows: -* `iN`, `uN`, and `fN` are _N_ bits wide, -* `isize` and `usize` are the width of a pointer, -* `char` is 32 bits wide, -* `bool` is 8 bits wide. +- `iN`, `uN`, and `fN` are _N_ bits wide, +- `isize` and `usize` are the width of a pointer, +- `char` is 32 bits wide, +- `bool` is 8 bits wide.
There are a few syntaxes which are not shown above: -- All underscores in numbers can be left out, they are for legibility only. - So `1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written as `123i64`. +- All underscores in numbers can be left out, they are for legibility only. So + `1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written as + `123i64`.
diff --git a/src/types-and-values/variables.md b/src/types-and-values/variables.md index 1d1c0cc..3c822e3 100644 --- a/src/types-and-values/variables.md +++ b/src/types-and-values/variables.md @@ -18,10 +18,10 @@ fn main() {
-* Uncomment the `x = 20` to demonstrate that variables are immutable by default. +- Uncomment the `x = 20` to demonstrate that variables are immutable by default. Add the `mut` keyword to allow changes. -* The `i32` here is the type of the variable. This must be known at compile +- The `i32` here is the type of the variable. This must be known at compile time, but type inference (covered later) allows the programmer to omit it in many cases. diff --git a/src/unsafe-rust/dereferencing.md b/src/unsafe-rust/dereferencing.md index 77dcc29..953318e 100644 --- a/src/unsafe-rust/dereferencing.md +++ b/src/unsafe-rust/dereferencing.md @@ -35,19 +35,20 @@ fn main() {
-It is good practice (and required by the Android Rust style guide) to write a comment for each -`unsafe` block explaining how the code inside it satisfies the safety requirements of the unsafe -operations it is doing. +It is good practice (and required by the Android Rust style guide) to write a +comment for each `unsafe` block explaining how the code inside it satisfies the +safety requirements of the unsafe operations it is doing. In the case of pointer dereferences, this means that the pointers must be [_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety), i.e.: - * The pointer must be non-null. - * The pointer must be _dereferenceable_ (within the bounds of a single allocated object). - * The object must not have been deallocated. - * There must not be concurrent accesses to the same location. - * If the pointer was obtained by casting a reference, the underlying object must be live and no - reference may be used to access the memory. +- The pointer must be non-null. +- The pointer must be _dereferenceable_ (within the bounds of a single allocated + object). +- The object must not have been deallocated. +- There must not be concurrent accesses to the same location. +- If the pointer was obtained by casting a reference, the underlying object must + be live and no reference may be used to access the memory. In most cases the pointer must also be properly aligned. diff --git a/src/unsafe-rust/exercise.md b/src/unsafe-rust/exercise.md index 028f41c..13cf089 100644 --- a/src/unsafe-rust/exercise.md +++ b/src/unsafe-rust/exercise.md @@ -10,15 +10,15 @@ functions you would use from C to read the names of files in a directory. You will want to consult the manual pages: -* [`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html) -* [`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html) -* [`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html) +- [`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html) +- [`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html) +- [`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html) You will also want to browse the [`std::ffi`] module. There you find a number of string types which you need for the exercise: | Types | Encoding | Use | -|----------------------------|----------------|--------------------------------| +| -------------------------- | -------------- | ------------------------------ | | [`str`] and [`String`] | UTF-8 | Text processing in Rust | | [`CStr`] and [`CString`] | NUL-terminated | Communicating with C functions | | [`OsStr`] and [`OsString`] | OS-specific | Communicating with the OS | @@ -27,13 +27,15 @@ You will convert between all these types: - `&str` to `CString`: you need to allocate space for a trailing `\0` character, - `CString` to `*const i8`: you need a pointer to call C functions, -- `*const i8` to `&CStr`: you need something which can find the trailing `\0` character, -- `&CStr` to `&[u8]`: a slice of bytes is the universal interface for "some unknown data", +- `*const i8` to `&CStr`: you need something which can find the trailing `\0` + character, +- `&CStr` to `&[u8]`: a slice of bytes is the universal interface for "some + unknown data", - `&[u8]` to `&OsStr`: `&OsStr` is a step towards `OsString`, use - [`OsStrExt`](https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) - to create it, -- `&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to return it and call - `readdir` again. + [`OsStrExt`](https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) to + create it, +- `&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to + return it and call `readdir` again. The [Nomicon] also has a very useful chapter about FFI. diff --git a/src/unsafe-rust/exercise.rs b/src/unsafe-rust/exercise.rs index dce668c..0eb0cc6 100644 --- a/src/unsafe-rust/exercise.rs +++ b/src/unsafe-rust/exercise.rs @@ -86,7 +86,8 @@ impl DirectoryIterator { // 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}"))?; + 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() { diff --git a/src/unsafe-rust/mutable-static.md b/src/unsafe-rust/mutable-static.md index 3ca06ed..543f819 100644 --- a/src/unsafe-rust/mutable-static.md +++ b/src/unsafe-rust/mutable-static.md @@ -21,23 +21,29 @@ static variables: static mut COUNTER: u32 = 0; fn add_to_counter(inc: u32) { - unsafe { COUNTER += inc; } // Potential data race! + unsafe { + COUNTER += inc; + } } fn main() { add_to_counter(42); - unsafe { println!("COUNTER: {COUNTER}"); } // Potential data race! + unsafe { + println!("COUNTER: {COUNTER}"); + } } ```
-- The program here is safe because it is single-threaded. However, the Rust compiler is conservative - and will assume the worst. Try removing the `unsafe` and see how the compiler explains that it is - undefined behavior to mutate a static from multiple threads. +- The program here is safe because it is single-threaded. However, the Rust + compiler is conservative and will assume the worst. Try removing the `unsafe` + and see how the compiler explains that it is undefined behavior to mutate a + static from multiple threads. -- Using a mutable static is generally a bad idea, but there are some cases where it might make sense - in low-level `no_std` code, such as implementing a heap allocator or working with some C APIs. +- Using a mutable static is generally a bad idea, but there are some cases where + it might make sense in low-level `no_std` code, such as implementing a heap + allocator or working with some C APIs.
diff --git a/src/unsafe-rust/unions.md b/src/unsafe-rust/unions.md index d45a0d1..10d8ca9 100644 --- a/src/unsafe-rust/unions.md +++ b/src/unsafe-rust/unions.md @@ -16,17 +16,18 @@ union MyUnion { fn main() { let u = MyUnion { i: 42 }; println!("int: {}", unsafe { u.i }); - println!("bool: {}", unsafe { u.b }); // Undefined behavior! + println!("bool: {}", unsafe { u.b }); // Undefined behavior! } ```
-Unions are very rarely needed in Rust as you can usually use an enum. They are occasionally needed -for interacting with C library APIs. +Unions are very rarely needed in Rust as you can usually use an enum. They are +occasionally needed for interacting with C library APIs. If you just want to reinterpret bytes as a different type, you probably want -[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html) or a safe -wrapper such as the [`zerocopy`](https://crates.io/crates/zerocopy) crate. +[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn.transmute.html) +or a safe wrapper such as the [`zerocopy`](https://crates.io/crates/zerocopy) +crate.
diff --git a/src/unsafe-rust/unsafe-functions.md b/src/unsafe-rust/unsafe-functions.md index c5e7b14..efbb113 100644 --- a/src/unsafe-rust/unsafe-functions.md +++ b/src/unsafe-rust/unsafe-functions.md @@ -34,7 +34,8 @@ fn main() { // Not upholding the UTF-8 encoding requirement breaks memory safety! // println!("emoji: {}", unsafe { emojis.get_unchecked(0..3) }); - // println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..3) })); + // println!("char count: {}", count_chars(unsafe { + // emojis.get_unchecked(0..3) })); } fn count_chars(s: &str) -> usize { @@ -44,8 +45,8 @@ fn count_chars(s: &str) -> usize { ## Writing Unsafe Functions -You can mark your own functions as `unsafe` if they require particular conditions to avoid undefined -behaviour. +You can mark your own functions as `unsafe` if they require particular +conditions to avoid undefined behaviour. ```rust,editable /// Swaps the values pointed to by the given pointers. @@ -78,10 +79,10 @@ fn main() { `get_unchecked`, like most `_unchecked` functions, is unsafe, because it can create UB if the range is incorrect. `abs` is incorrect for a different reason: -it is an external function (FFI). Calling external functions is usually only a +it is an external function (FFI). Calling external functions is usually only a problem when those functions do things with pointers which might violate Rust's -memory model, but in general any C function might have undefined behaviour -under any arbitrary circumstances. +memory model, but in general any C function might have undefined behaviour under +any arbitrary circumstances. The `"C"` in this example is the ABI; [other ABIs are available too](https://doc.rust-lang.org/reference/items/external-blocks.html). diff --git a/src/unsafe-rust/unsafe-traits.md b/src/unsafe-rust/unsafe-traits.md index 57c71c5..4f524ee 100644 --- a/src/unsafe-rust/unsafe-traits.md +++ b/src/unsafe-rust/unsafe-traits.md @@ -4,8 +4,8 @@ minutes: 5 # Implementing Unsafe Traits -Like with functions, you can mark a trait as `unsafe` if the implementation must guarantee -particular conditions to avoid undefined behaviour. +Like with functions, you can mark a trait as `unsafe` if the implementation must +guarantee particular conditions to avoid undefined behaviour. For example, the `zerocopy` crate has an unsafe trait that looks [something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html): @@ -20,7 +20,10 @@ use std::slice; pub unsafe trait AsBytes { fn as_bytes(&self) -> &[u8] { unsafe { - slice::from_raw_parts(self as *const Self as *const u8, size_of_val(self)) + slice::from_raw_parts( + self as *const Self as *const u8, + size_of_val(self), + ) } } } @@ -31,8 +34,8 @@ unsafe impl AsBytes for u32 {}
-There should be a `# Safety` section on the Rustdoc for the trait explaining the requirements for -the trait to be safely implemented. +There should be a `# Safety` section on the Rustdoc for the trait explaining the +requirements for the trait to be safely implemented. The actual safety section for `AsBytes` is rather longer and more complicated. diff --git a/src/unsafe-rust/unsafe.md b/src/unsafe-rust/unsafe.md index 897e0c7..6faa145 100644 --- a/src/unsafe-rust/unsafe.md +++ b/src/unsafe-rust/unsafe.md @@ -6,22 +6,22 @@ minutes: 5 The Rust language has two parts: -* **Safe Rust:** memory safe, no undefined behavior possible. -* **Unsafe Rust:** can trigger undefined behavior if preconditions are violated. +- **Safe Rust:** memory safe, no undefined behavior possible. +- **Unsafe Rust:** can trigger undefined behavior if preconditions are violated. -We saw mostly safe Rust in this course, but it's important to know -what Unsafe Rust is. +We saw mostly safe Rust in this course, but it's important to know what Unsafe +Rust is. -Unsafe code is usually small and isolated, and its correctness should be carefully -documented. It is usually wrapped in a safe abstraction layer. +Unsafe code is usually small and isolated, and its correctness should be +carefully documented. It is usually wrapped in a safe abstraction layer. Unsafe Rust gives you access to five new capabilities: -* Dereference raw pointers. -* Access or modify mutable static variables. -* Access `union` fields. -* Call `unsafe` functions, including `extern` functions. -* Implement `unsafe` traits. +- Dereference raw pointers. +- Access or modify mutable static variables. +- Access `union` fields. +- Call `unsafe` functions, including `extern` functions. +- Implement `unsafe` traits. We will briefly cover unsafe capabilities next. For full details, please see [Chapter 19.1 in the Rust Book](https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html) diff --git a/src/user-defined-types/aliases.md b/src/user-defined-types/aliases.md index 2709136..4c998dd 100644 --- a/src/user-defined-types/aliases.md +++ b/src/user-defined-types/aliases.md @@ -4,7 +4,8 @@ minutes: 2 # Type Aliases -A type alias creates a name for another type. The two types can be used interchangeably. +A type alias creates a name for another type. The two types can be used +interchangeably. ```rust,editable enum CarryableConcreteItem { @@ -15,7 +16,8 @@ enum CarryableConcreteItem { type Item = CarryableConcreteItem; // Aliases are more useful with long, complex types: -use std::{sync::{Arc, RwLock}, cell::RefCell}; +use std::cell::RefCell; +use std::sync::{Arc, RwLock}; type PlayerInventory = RwLock>>>; ``` diff --git a/src/user-defined-types/enums.md b/src/user-defined-types/enums.md index 6563ca5..dc34b80 100644 --- a/src/user-defined-types/enums.md +++ b/src/user-defined-types/enums.md @@ -4,8 +4,8 @@ minutes: 5 # Enums -The `enum` keyword allows the creation of a type which has a few -different variants: +The `enum` keyword allows the creation of a type which has a few different +variants: ```rust,editable #[derive(Debug)] @@ -31,82 +31,89 @@ fn main() { Key Points: -* Enumerations allow you to collect a set of values under one type. -* `Direction` is a type with variants. There are two values of `Direction`: `Direction::Left` and `Direction::Right`. -* `PlayerMove` is a type with three variants. In addition to the payloads, Rust will store a discriminant so that it knows at runtime which variant is in a `PlayerMove` value. -* This might be a good time to compare structs and enums: - * In both, you can have a simple version without fields (unit struct) or one with different types of fields (variant payloads). - * You could even implement the different variants of an enum with separate structs but then they wouldn’t be the same type as they would if they were all defined in an enum. -* Rust uses minimal space to store the discriminant. - * If necessary, it stores an integer of the smallest required size - * If the allowed variant values do not cover all bit patterns, it will use +- Enumerations allow you to collect a set of values under one type. +- `Direction` is a type with variants. There are two values of `Direction`: + `Direction::Left` and `Direction::Right`. +- `PlayerMove` is a type with three variants. In addition to the payloads, Rust + will store a discriminant so that it knows at runtime which variant is in a + `PlayerMove` value. +- This might be a good time to compare structs and enums: + - In both, you can have a simple version without fields (unit struct) or one + with different types of fields (variant payloads). + - You could even implement the different variants of an enum with separate + structs but then they wouldn’t be the same type as they would if they were + all defined in an enum. +- Rust uses minimal space to store the discriminant. + - If necessary, it stores an integer of the smallest required size + - If the allowed variant values do not cover all bit patterns, it will use invalid bit patterns to encode the discriminant (the "niche optimization"). For example, `Option<&u8>` stores either a pointer to an integer or `NULL` for the `None` variant. - * You can control the discriminant if needed (e.g., for compatibility with C): - - - ```rust,editable - #[repr(u32)] - enum Bar { - A, // 0 - B = 10000, - C, // 10001 - } - - fn main() { - println!("A: {}", Bar::A as u32); - println!("B: {}", Bar::B as u32); - println!("C: {}", Bar::C as u32); - } - ``` - - Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 - bytes. + - You can control the discriminant if needed (e.g., for compatibility with C): + + + ```rust,editable + #[repr(u32)] + enum Bar { + A, // 0 + B = 10000, + C, // 10001 + } + + fn main() { + println!("A: {}", Bar::A as u32); + println!("B: {}", Bar::B as u32); + println!("C: {}", Bar::C as u32); + } + ``` + + Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 + bytes. ## More to Explore Rust has several optimizations it can employ to make enums take up less space. - * Null pointer optimization: For [some - types](https://doc.rust-lang.org/std/option/#representation), Rust guarantees - that `size_of::()` equals `size_of::>()`. - - Example code if you want to show how the bitwise representation *may* look like in practice. - It's important to note that the compiler provides no guarantees regarding this representation, therefore this is totally unsafe. - - - ```rust,editable - use std::mem::transmute; - - macro_rules! dbg_bits { - ($e:expr, $bit_type:ty) => { - println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); - }; - } - - fn main() { - unsafe { - println!("bool:"); - dbg_bits!(false, u8); - dbg_bits!(true, u8); - - println!("Option:"); - dbg_bits!(None::, u8); - dbg_bits!(Some(false), u8); - dbg_bits!(Some(true), u8); - - println!("Option>:"); - dbg_bits!(Some(Some(false)), u8); - dbg_bits!(Some(Some(true)), u8); - dbg_bits!(Some(None::), u8); - dbg_bits!(None::>, u8); - - println!("Option<&i32>:"); - dbg_bits!(None::<&i32>, usize); - dbg_bits!(Some(&0i32), usize); - } - } - ``` +- Null pointer optimization: For + [some types](https://doc.rust-lang.org/std/option/#representation), Rust + guarantees that `size_of::()` equals `size_of::>()`. + + Example code if you want to show how the bitwise representation _may_ look + like in practice. It's important to note that the compiler provides no + guarantees regarding this representation, therefore this is totally unsafe. + + + ```rust,editable + use std::mem::transmute; + + macro_rules! dbg_bits { + ($e:expr, $bit_type:ty) => { + println!("- {}: {:#x}", stringify!($e), transmute::<_, $bit_type>($e)); + }; + } + + fn main() { + unsafe { + println!("bool:"); + dbg_bits!(false, u8); + dbg_bits!(true, u8); + + println!("Option:"); + dbg_bits!(None::, u8); + dbg_bits!(Some(false), u8); + dbg_bits!(Some(true), u8); + + println!("Option>:"); + dbg_bits!(Some(Some(false)), u8); + dbg_bits!(Some(Some(true)), u8); + dbg_bits!(Some(None::), u8); + dbg_bits!(None::>, u8); + + println!("Option<&i32>:"); + dbg_bits!(None::<&i32>, usize); + dbg_bits!(Some(&0i32), usize); + } + } + ```
diff --git a/src/user-defined-types/exercise.rs b/src/user-defined-types/exercise.rs index 4009990..d804199 100644 --- a/src/user-defined-types/exercise.rs +++ b/src/user-defined-types/exercise.rs @@ -96,10 +96,7 @@ fn main() { "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 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: {:?}", diff --git a/src/user-defined-types/named-structs.md b/src/user-defined-types/named-structs.md index 4e9fe7f..34b56b5 100644 --- a/src/user-defined-types/named-structs.md +++ b/src/user-defined-types/named-structs.md @@ -17,10 +17,7 @@ fn describe(person: &Person) { } fn main() { - let mut peter = Person { - name: String::from("Peter"), - age: 27, - }; + let mut peter = Person { name: String::from("Peter"), age: 27 }; describe(&peter); peter.age = 28; @@ -31,10 +28,7 @@ fn main() { let avery = Person { name, age }; describe(&avery); - let jackie = Person { - name: String::from("Jackie"), - ..avery - }; + let jackie = Person { name: String::from("Jackie"), ..avery }; describe(&jackie); } ``` @@ -43,14 +37,20 @@ fn main() { Key Points: -* Structs work like in C or C++. - * Like in C++, and unlike in C, no typedef is needed to define a type. - * Unlike in C++, there is no inheritance between structs. -* This may be a good time to let people know there are different types of structs. - * Zero-sized structs (e.g. `struct Foo;`) might be used when implementing a trait on some type but don’t have any data that you want to store in the value itself. - * The next slide will introduce Tuple structs, used when the field names are not important. -* If you already have variables with the right names, then you can create the -struct using a shorthand. -* The syntax `..avery` allows us to copy the majority of the fields from the old struct without having to explicitly type it all out. It must always be the last element. +- Structs work like in C or C++. + - Like in C++, and unlike in C, no typedef is needed to define a type. + - Unlike in C++, there is no inheritance between structs. +- This may be a good time to let people know there are different types of + structs. + - Zero-sized structs (e.g. `struct Foo;`) might be used when implementing a + trait on some type but don’t have any data that you want to store in the + value itself. + - The next slide will introduce Tuple structs, used when the field names are + not important. +- If you already have variables with the right names, then you can create the + struct using a shorthand. +- The syntax `..avery` allows us to copy the majority of the fields from the old + struct without having to explicitly type it all out. It must always be the + last element.
diff --git a/src/user-defined-types/static-and-const.md b/src/user-defined-types/static-and-const.md index 904b611..6adb8da 100644 --- a/src/user-defined-types/static-and-const.md +++ b/src/user-defined-types/static-and-const.md @@ -4,8 +4,8 @@ minutes: 5 # Static and Const -Static and constant variables are two different ways to create globally-scoped values that -cannot be moved or reallocated during the execution of the program. +Static and constant variables are two different ways to create globally-scoped +values that cannot be moved or reallocated during the execution of the program. ## `const` @@ -13,6 +13,7 @@ Constant variables are evaluated at compile time and their values are inlined wherever they are used: + ```rust,editable const DIGEST_SIZE: usize = 3; const ZERO: Option = Some(42); @@ -33,11 +34,13 @@ fn main() { According to the [Rust RFC Book][1] these are inlined upon use. -Only functions marked `const` can be called at compile time to generate `const` values. `const` functions can however be called at runtime. +Only functions marked `const` can be called at compile time to generate `const` +values. `const` functions can however be called at runtime. ## `static` -Static variables will live during the whole execution of the program, and therefore will not move: +Static variables will live during the whole execution of the program, and +therefore will not move: ```rust,editable static BANNER: &str = "Welcome to RustOS 3.14"; @@ -47,31 +50,37 @@ fn main() { } ``` -As noted in the [Rust RFC Book][1], these are not inlined upon use and have an actual associated memory location. This is useful for unsafe and -embedded code, and the variable lives through the entirety of the program execution. -When a globally-scoped value does not have a reason to need object identity, `const` is generally preferred. +As noted in the [Rust RFC Book][1], these are not inlined upon use and have an +actual associated memory location. This is useful for unsafe and embedded code, +and the variable lives through the entirety of the program execution. When a +globally-scoped value does not have a reason to need object identity, `const` is +generally preferred.
-* Mention that `const` behaves semantically similar to C++'s `constexpr`. -* `static`, on the other hand, is much more similar to a `const` or mutable global variable in C++. -* `static` provides object identity: an address in memory and state as required by types with interior mutability such as `Mutex`. -* It isn't super common that one would need a runtime evaluated constant, but it is helpful and safer than using a static. +- Mention that `const` behaves semantically similar to C++'s `constexpr`. +- `static`, on the other hand, is much more similar to a `const` or mutable + global variable in C++. +- `static` provides object identity: an address in memory and state as required + by types with interior mutability such as `Mutex`. +- It isn't super common that one would need a runtime evaluated constant, but it + is helpful and safer than using a static. ### Properties table: -| Property | Static | Constant | -|---|---|---| -| Has an address in memory | Yes | No (inlined) | -| Lives for the entire duration of the program | Yes | No | -| Can be mutable | Yes (unsafe) | No | -| Evaluated at compile time | Yes (initialised at compile time) | Yes | -| Inlined wherever it is used | No | Yes | +| Property | Static | Constant | +| -------------------------------------------- | --------------------------------- | ------------ | +| Has an address in memory | Yes | No (inlined) | +| Lives for the entire duration of the program | Yes | No | +| Can be mutable | Yes (unsafe) | No | +| Evaluated at compile time | Yes (initialised at compile time) | Yes | +| Inlined wherever it is used | No | Yes | # More to Explore -Because `static` variables are accessible from any thread, they must be `Sync`. Interior mutability -is possible through a [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html), atomic or +Because `static` variables are accessible from any thread, they must be `Sync`. +Interior mutability is possible through a +[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html), atomic or similar. Thread-local data can be created with the macro `std::thread_local`. diff --git a/src/user-defined-types/tuple-structs.md b/src/user-defined-types/tuple-structs.md index 41865a8..653e874 100644 --- a/src/user-defined-types/tuple-structs.md +++ b/src/user-defined-types/tuple-structs.md @@ -5,6 +5,7 @@ minutes: 10 + # Tuple Structs If the field names are unimportant, you can use a tuple struct: @@ -36,17 +37,23 @@ fn main() { let force = compute_thruster_force(); set_thruster_force(force); } - ```
-* Newtypes are a great way to encode additional information about the value in a primitive type, for example: - * The number is measured in some units: `Newtons` in the example above. - * The value passed some validation when it was created, so you no longer have to validate it again at every use: `PhoneNumber(String)` or `OddNumber(u32)`. -* Demonstrate how to add a `f64` value to a `Newtons` type by accessing the single field in the newtype. - * Rust generally doesn’t like inexplicit things, like automatic unwrapping or for instance using booleans as integers. - * Operator overloading is discussed on Day 3 (generics). -* The example is a subtle reference to the [Mars Climate Orbiter](https://en.wikipedia.org/wiki/Mars_Climate_Orbiter) failure. +- Newtypes are a great way to encode additional information about the value in a + primitive type, for example: + - The number is measured in some units: `Newtons` in the example above. + - The value passed some validation when it was created, so you no longer have + to validate it again at every use: `PhoneNumber(String)` or + `OddNumber(u32)`. +- Demonstrate how to add a `f64` value to a `Newtons` type by accessing the + single field in the newtype. + - Rust generally doesn’t like inexplicit things, like automatic unwrapping or + for instance using booleans as integers. + - Operator overloading is discussed on Day 3 (generics). +- The example is a subtle reference to the + [Mars Climate Orbiter](https://en.wikipedia.org/wiki/Mars_Climate_Orbiter) + failure.
diff --git a/src/welcome-day-1.md b/src/welcome-day-1.md index feac267..2f268e6 100644 --- a/src/welcome-day-1.md +++ b/src/welcome-day-1.md @@ -6,15 +6,14 @@ session: Day 1 Morning # Welcome to Day 1 -This is the first day of Rust Fundamentals. We will cover a lot of ground -today: +This is the first day of Rust Fundamentals. We will cover a lot of ground today: -* Basic Rust syntax: variables, scalar and compound types, enums, structs, +- Basic Rust syntax: variables, scalar and compound types, enums, structs, references, functions, and methods. -* Types and type inference. -* Control flow constructs: loops, conditionals, and so on. -* User-defined types: structs and enums. -* Pattern matching: destructuring enums, structs, and arrays. +- Types and type inference. +- Control flow constructs: loops, conditionals, and so on. +- User-defined types: structs and enums. +- Pattern matching: destructuring enums, structs, and arrays. ## Schedule @@ -24,16 +23,16 @@ today: Please remind the students that: -* They should ask questions when they get them, don't save them to the end. -* The class is meant to be interactive and discussions are very much encouraged! - * As an instructor, you should try to keep the discussions relevant, i.e., +- They should ask questions when they get them, don't save them to the end. +- The class is meant to be interactive and discussions are very much encouraged! + - As an instructor, you should try to keep the discussions relevant, i.e., keep the discussions related to how Rust does things vs some other language. It can be hard to find the right balance, but err on the side of allowing discussions since they engage people much more than one-way communication. -* The questions will likely mean that we talk about things ahead of the slides. - * This is perfectly okay! Repetition is an important part of learning. Remember - that the slides are just a support and you are free to skip them as you - like. +- The questions will likely mean that we talk about things ahead of the slides. + - This is perfectly okay! Repetition is an important part of learning. + Remember that the slides are just a support and you are free to skip them as + you like. The idea for the first day is to show the "basic" things in Rust that should have immediate parallels in other languages. The more advanced parts of Rust @@ -42,7 +41,7 @@ come on the subsequent days. If you're teaching this in a classroom, this is a good place to go over the schedule. Note that there is an exercise at the end of each segment, followed by a break. Plan to cover the exercise solution after the break. The times listed -here are a suggestion in order to keep the course on schedule. Feel free to -be flexible and adjust as necessary! +here are a suggestion in order to keep the course on schedule. Feel free to be +flexible and adjust as necessary!
diff --git a/src/welcome-day-2.md b/src/welcome-day-2.md index 939823b..e10da17 100644 --- a/src/welcome-day-2.md +++ b/src/welcome-day-2.md @@ -9,11 +9,11 @@ session: Day 2 Morning Now that we have seen a fair amount of Rust, today will focus on Rust's type system: - * Pattern matching: extracting data from structures. - * Methods: associating functions with types. - * Traits: behaviors shared by multiple types. - * Generics: parameterizing types on other types. - * Standard library types and traits: a tour of Rust's rich standard library. +- Pattern matching: extracting data from structures. +- Methods: associating functions with types. +- Traits: behaviors shared by multiple types. +- Generics: parameterizing types on other types. +- Standard library types and traits: a tour of Rust's rich standard library. ## Schedule diff --git a/src/welcome-day-3.md b/src/welcome-day-3.md index f15bf89..6fe0816 100644 --- a/src/welcome-day-3.md +++ b/src/welcome-day-3.md @@ -8,8 +8,9 @@ session: Day 3 Morning Today, we will cover: -* Memory management, lifetimes, and the borrow checker: how Rust ensures memory safety. -* Smart pointers: standard library pointer types. +- Memory management, lifetimes, and the borrow checker: how Rust ensures memory + safety. +- Smart pointers: standard library pointer types. ## Schedule diff --git a/src/welcome-day-4.md b/src/welcome-day-4.md index 81acd1f..5a38b27 100644 --- a/src/welcome-day-4.md +++ b/src/welcome-day-4.md @@ -8,11 +8,11 @@ session: Day 4 Morning Today we will cover topics relating to building large-scale software in Rust: -* Iterators: a deep dive on the `Iterator` trait. -* Modules and visibility. -* Testing. -* Error handling: panics, `Result`, and the try operator `?`. -* Unsafe Rust: the escape hatch when you can't express yourself in safe Rust. +- Iterators: a deep dive on the `Iterator` trait. +- Modules and visibility. +- Testing. +- Error handling: panics, `Result`, and the try operator `?`. +- Unsafe Rust: the escape hatch when you can't express yourself in safe Rust. ## Schedule
- + `core`
-* Slices, `&str`, `CStr` -* `NonZeroU8`... -* `Option`, `Result` -* `Display`, `Debug`, `write!`... -* `Iterator` -* `panic!`, `assert_eq!`... -* `NonNull` and all the usual pointer-related functions -* `Future` and `async`/`await` -* `fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`... -* `Duration` +- Slices, `&str`, `CStr` +- `NonZeroU8`... +- `Option`, `Result` +- `Display`, `Debug`, `write!`... +- `Iterator` +- `panic!`, `assert_eq!`... +- `NonNull` and all the usual pointer-related functions +- `Future` and `async`/`await` +- `fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`... +- `Duration` -* `Box`, `Cow`, `Arc`, `Rc` -* `Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque` -* `String`, `CString`, `format!` +- `Box`, `Cow`, `Arc`, `Rc` +- `Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque` +- `String`, `CString`, `format!` -* `Error` -* `HashMap` -* `Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc` -* `File` and the rest of `fs` -* `println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io` -* `Path`, `OsString` -* `net` -* `Command`, `Child`, `ExitCode` -* `spawn`, `sleep` and the rest of `thread` -* `SystemTime`, `Instant` +- `Error` +- `HashMap` +- `Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc` +- `File` and the rest of `fs` +- `println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io` +- `Path`, `OsString` +- `net` +- `Command`, `Child`, `ExitCode` +- `spawn`, `sleep` and the rest of `thread` +- `SystemTime`, `Instant`