You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-17 06:37:34 +02:00
Format all Markdown files with dprint
(#1157)
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 😄 - `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.
This commit is contained in:
@ -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.
|
||||
|
||||
<details>
|
||||
|
||||
|
@ -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):
|
||||
|
||||
<!-- File Cargo.toml -->
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```toml
|
||||
{{#include compass/Cargo.toml}}
|
||||
```
|
||||
@ -52,6 +56,7 @@ _Embed.toml_ (you shouldn't need to change this):
|
||||
|
||||
<!-- File Embed.toml -->
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```toml
|
||||
{{#include compass/Embed.toml}}
|
||||
```
|
||||
@ -60,18 +65,23 @@ _.cargo/config.toml_ (you shouldn't need to change this):
|
||||
|
||||
<!-- File .cargo/config.toml -->
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```toml
|
||||
{{#include compass/.cargo/config.toml}}
|
||||
```
|
||||
|
||||
See the serial output on Linux with:
|
||||
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```sh
|
||||
picocom --baud 115200 --imap lfcrlf /dev/ttyACM0
|
||||
```
|
||||
|
||||
Or on Mac OS something like (the device name may be slightly different):
|
||||
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```sh
|
||||
picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502
|
||||
```
|
||||
|
@ -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 {
|
||||
|
@ -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.
|
||||
|
||||
<details>
|
||||
|
||||
|
@ -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.
|
||||
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.
|
||||
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):
|
||||
|
||||
<!-- File src/exceptions.rs -->
|
||||
|
||||
@ -62,6 +66,7 @@ _Cargo.toml_ (you shouldn't need to change this):
|
||||
|
||||
<!-- File Cargo.toml -->
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```toml
|
||||
{{#include rtc/Cargo.toml}}
|
||||
```
|
||||
@ -118,6 +123,7 @@ _.cargo/config.toml_ (you shouldn't need to change this):
|
||||
|
||||
<!-- File .cargo/config.toml -->
|
||||
<!-- mdbook-xgettext: skip -->
|
||||
|
||||
```toml
|
||||
{{#include rtc/.cargo/config.toml}}
|
||||
```
|
||||
|
@ -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:?}");
|
||||
}
|
||||
|
||||
|
@ -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<Option<Uart>>,
|
||||
|
@ -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);
|
||||
|
@ -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<u8> {
|
||||
if self.read_flag_register().contains(Flags::RXFE) {
|
||||
None
|
||||
|
@ -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.
|
||||
|
@ -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!
|
||||
|
||||
<img src="chwomium.png" alt="Chromium UI screenshot with uwu language">
|
||||
|
||||
<details>
|
||||
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`.
|
||||
|
||||
</details>
|
||||
|
@ -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]
|
||||
|
||||
<details>
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
[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
|
||||
[4]: https://code.visualstudio.com/docs/languages/rust
|
||||
|
@ -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]
|
||||
|
||||
<details>
|
||||
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.
|
||||
</details>
|
||||
|
||||
- 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.
|
||||
|
||||
</details>
|
||||
|
||||
[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
|
||||
[2]: https://source.chromium.org/chromium/chromium/src/+/main:build/rust/rust_static_library.gni;l=16
|
||||
|
@ -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
|
||||
[0]: https://chromium-review.googlesource.com/c/chromium/src/+/5096560
|
||||
|
@ -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.
|
||||
|
@ -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`).
|
||||
|
||||
<details>
|
||||
@ -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!
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
[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
|
||||
[3]: https://github.com/Daniel-Liu-c0deb0t
|
||||
|
@ -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.
|
||||
|
||||
<details>
|
||||
|
@ -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
|
||||
|
@ -31,9 +31,7 @@ async fn handle_connection(
|
||||
) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// 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
|
||||
|
@ -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:
|
||||
|
||||
<!-- File src/main.rs -->
|
||||
|
||||
@ -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`:
|
||||
|
||||
<!-- File 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.
|
||||
|
||||
<details>
|
||||
|
||||
* Can you make your implementation single-threaded?
|
||||
- Can you make your implementation single-threaded?
|
||||
|
||||
</details>
|
||||
|
@ -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
|
||||
|
@ -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.
|
||||
|
||||
|
@ -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<CrawlResult>,
|
||||
) -> Vec<Url> {
|
||||
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;
|
||||
|
||||
|
@ -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.
|
||||
|
||||
<details>
|
||||
|
@ -23,4 +23,3 @@ _src/bin/client.rs_:
|
||||
```rust,compile_fail
|
||||
{{#include chat-async/src/bin/client.rs:solution}}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user