Module 0 - Installing the tools

In this file you'll find instructions on how to install the tools we'll use during the course.

All of these tools are available for Linux, macOS and Windows users. We'll need the tools to write and compile our Rust code, and allow for remote mentoring. Important: these instructions are to be followed at home, before the start of the first tutorial. If you have any problems with installation, contact the lecturers! We won't be addressing installation problems during the first tutorial.

Rust and Cargo

First we'll need rustc, the standard Rust compiler. rustc is generally not invoked directly, but through cargo, the Rust package manager. rustup takes care of installing rustc and cargo.

This part is easy: go to https://rustup.rs and follow the instructions. Please make sure you're installing the latest default toolchain. Once done, run

rustc -V && cargo -V

The output should be something like this:

rustc 1.67.1 (d5a82bbd2 2023-02-07)
cargo 1.67.1 (8ecd4f20a 2023-01-10)

Using Rustup, you can install Rust toolchains and components. More info:

Rustfmt and Clippy

To avoid discussions, Rust provides its own formatting tool, Rustfmt. We'll also be using Clippy, a collection of lints to analyze your code, that catches common mistakes for you. You'll notice that Rusts Clippy can be a very helpful companion. Both Rustfmt and Clippy are installed by Rustup by default.

To run Rustfmt on your project, execute:

cargo fmt

To run clippy:

cargo clippy

More info:

Visual Studio Code

During the course, we will use Visual Studio Code (vscode) to write code in. Of course, you're free to use your favorite editor, but if you encounter problems, you can't rely on support from us. Also, we'll use vscode to allow for remote collaboration and mentoring during tutorial sessions.

You can find the installation instructions here: https://code.visualstudio.com/.

We will install some plugins as well. The first one is Rust-Analyzer. Installation instructions can be found here https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer. Rust-Analyzer provides a lot of help during development and in indispensable when getting started with Rust.

Another plugin we'll install is Live Share. We will use the plugin to share screens and provide help during remote tutorial sessions. The extension pack also contains the Live Share Audio plugin, which allows for audio communication during share sessions. Installation instructions can be found here: https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare-pack

The last plugin we'll use is CodeLLDB. This plugin enables debugging Rust code from within vscode. You can find instructions here: https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb.

More info:

Git

We will use Git as version control tool. If you haven't installed Git already, you can find instructions here: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git. If you're new to Git, you'll also appreciate GitHubs intro to Git https://docs.github.com/en/get-started/using-git/about-git and the Git intro with vscode, which you can find here: https://www.youtube.com/watch?v=i_23KUAEtUM.

More info: https://www.youtube.com/playlist?list=PLg7s6cbtAD15G8lNyoaYDuKZSKyJrgwB-

Course code

Now that everything is installed, you can clone the source code repository. The repository can be found here: https://github.com/tweedegolf/101-rs.

To clone the repository, you'll need an account on GitHub. Make sure you have one, it will serve you well, even outside this workshop.

Instructions on cloning the repository can be found here: https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls

Trying it out

Now that you've got the code on your machine, navigate to it using your favorite terminal and run:

cd exercises/0-intro
cargo run

This command may take a while to run the first time, as Cargo will first fetch the crate index from the registry. It will compile and run the intro package, which you can find in exercises/0-intro. If everything goes well, you should see some output:

   Compiling intro v0.1.0 (/home/henkdieter/tg/edu/101-rs/exercises/0-intro)
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/intro`
πŸ¦€ Hello, world! πŸ¦€
You've successfully compiled and run your first Rust project!

If Rust-Analyzer is set up correctly, you can also click the '▢️ Run'-button that is shown in exercises/0-intro/src/main.rs. With CodeLLDB installed correctly, you can also start a debug session by clicking 'Debug', right next to the '▢️ Run'-button. Play a little with setting breakpoints by clicking on a line number, making a red circle appear and stepping over/into/out of functions using the controls. You can view variable values by hovering over them while execution is paused, or by expanding the 'Local' view under 'Variables' in the left panel during a debug session.

Module A1 - Language basics

Slides (or pdf)

A1.1 Basic syntax

Open exercises/A1/1-basic-syntax in your editor. This folder contains a number of exercises with which you can practise basic Rust syntax.

While inside the exercises/A1/1-basic-syntax folder, to get started, run:

cargo run --bin 01

This will try to compile exercise 1. Try and get the example to run, and continue on with the next exercise by replacing the number of the exercise in the cargo run command.

Some exercises contain unit tests. To run the test in src/bin/01.rs, run

cargo test --bin 01

Make sure all tests pass!

A1.2 Move semantics

This exercise is adapted from the move semantics exercise from Rustlings

This exercise enables you to practise with move semantics. It works similarly to exercise A1.1. To get started, exercises/A1/2-move-semantics in your editor and run

cargo run --bin 01

01.rs should compile as is, but you'll have to make sure the others compile as well. For some exercises, instructions are included as doc comments at the top of the file. Make sure to adhere to them.

Module A2 - Advanced Syntax, Ownership, references

Slides (or pdf)

A2.0 Borrowing

Fix the two examples in the exercises/A2/0-borrowing crate! Don't forget you can run individual binaries by using cargo run --bin 01 in that directory! Make sure to follow the instructions that are in the comments!

A2.1 Error Propagation

Follow the instructions in the comments of excercises/A2/1-error-propagating/src/main.rs!

A2.2 Slices

Follow the instructions in the comments of excercises/A2/2-slices/src/main.rs! Don't take too much time on the extra assignment, instead come back later once you've done the rest of the excercises.

A2.3 Error Handling

Follow the instructions in the comments of excercises/A2/3-error-handling/src/main.rs!

A2.4 Boxed Data

Follow the instructions in the comments of excercises/A2/4-boxed-data/src/main.rs!

A2.5 Bonus - Ring Buffer

This is a bonus exercise! Follow the instructions in the comments of excercises/A2/5-bonus-ring-buffer/src/main.rs!

Module A3 - Traits and generics

Slides (or pdf)

A3 Local Storage Vec

In this exercise, we'll create a type called LocalStorageVec, which is generic list of items that resides either on the stack or the heap, depending on its size. If its size is small enough for items to be put on the stack, the LocalStorageVec buffer is backed by an array. LocalStorageVec is not only generic over the type (T) of items in the list, but also by the size (N) of this stack-located array using a relatively new feature called 'const generics'. Once the LocalStorageVec contains more items than fit in the array, a heap based Vec is allocated as space for the items to reside in.

Within this exercise, the objectives are annotated with a number of stars (⭐), indicating the difficulty. You are likely not to be able to finish all exercises during the turorial session

Questions

  1. When is such a data structure more efficient than a standard Vec?
  2. What are the downsides, compared to just using a Vec?

Open the exercises/A3/2-local-storage-vec crate. It contains a src/lib.rs file, meaning this crate is a library. lib.rs contains a number of tests, which can be run by calling cargo test. Don't worry if they don't pass or even compile right now: it's your job to fix that in this exercise. Most of the tests are commented out right now, to enable a step-by-step approach. Before you begin, have a look at the code and the comments in there, they contain various helpful clues.

A3.A Defining the type ⭐

Currently, the LocalStorageVec enum is incomplete. Give it two variants: Stack and Heap. Stack contains two named fields, buf and len. buf will be the array with a capacity to hold N items of type T; len is a field of type usize that will denote the amount of items actually stored. The Heap variant has an unnamed field containing a Vec<T>. If you've defined the LocalStorageVec variants correctly, running cargo test should output something like

running 1 test
test test::it_compiles ... ignored, This test is just to validate the definition of `LocalStorageVec`. If it compiles, all is OK

test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s

This test does (and should) not run, but is just there for checking your variant definition.

Hint 1 You may be able to reverse-engineer the `LocalStorageVec` definition using the code of the `it_compiles` test case.

Hint 2 (If you got stuck, but try to resist me for a while)

Below definition works. Read the code comments and make sure you understand what's going on.

#![allow(unused)]
fn main() {
// Define an enum `LocalStorageVec` that is generic over
// type `T` and a constant `N` of type `usize`
pub enum LocalStorageVec<T, const N: usize> {
    // Define a struct-like variant called `Stack` containing two named fields:
    // - `buf` is an array with elements of `T` of size `N`
    // - `len` is a field of type `usize`
    Stack { buf: [T; N], len: usize },
    // Define a tuplle-like variant called `Heap`, containing a single field
    // of type `Vec<T>`, which is a heap-based growable, contiguous list of `T`
    Heap(Vec<T>),
}
}

A3.B impl-ing From<Vec<T> ⭐

Uncomment the test it_from_vecs, and add an implementation for From<Vec<T>> to LocalStorageVec<T>. To do so, copy the following code in your lib.rs file and replace the todo! macro invocation with your code that creates a heap-based LocalStorageVec containing the passed Vec<T>.

#![allow(unused)]
fn main() {
impl<T, const N: usize> From<Vec<T>> for LocalStorageVec<T, N> {
    fn from(v: Vec<T>) -> Self {
        todo!("Implement me");
    }
}
}

Question

  1. How would you pronounce the first line of the code you just copied in English?*

Run cargo test to validate your implementation.

A3.C impl LocalStorageVec ⭐⭐

To make the LocalStorageVec more useful, we'll add more methods to it. Create an impl-block for LocalStorageVec. Don't forget to declare and provide the generic paramereters. For now, to make implementations easier, we will add a bound T, requiring that it implements Copy and Default. First off, uncomment the test called it_constructs. Make it compile and pass by creating a associated function called new on LocalStorageVec that creates a new, empty LocalStorageVec instance without heap allocation.

The next methods we'll implement are len, push, pop, insert, remove and clear:

  • len returns the length of the LocalStorageVec
  • push appends an item to the end of the LocalStorageVec and increments its length. Possibly moves the contents to the heap if they no longer fit on the stack.
  • pop removes an item from the end of the LocalStorageVec, optionally returns it and decrements its length. If the length is 0, pop returns None
  • insert inserts an item at the given index and increments the length of the LocalStorageVec
  • remove removes an item at the given index and returns it.
  • clear resets the length of the LocalStorageVec to 0.

Uncomment the corresponding test cases and make them compile and pass. Be sure to have a look at the methods provided for slices [T] and Vec<T> Specifically, [T]::copy_within and Vec::extend_from_slice can be of use.

A3.D Iterator and IntoIterator ⭐⭐

Our LocalStorageVec can be used in the real world now, but we still shouldn't be satisfied. There are various traits in the standard library that we can implement for our LocalStorageVec that would make users of our crate happy.

First off, we will implement the IntoIterator and Iterator traits. Go ahead and uncomment the it_iters test case. Let's define a new type:

#![allow(unused)]
fn main() {
pub struct LocalStorageVecIter<T, const N: usize> {
    vec: LocalStorageVec<T, N>,
    counter: usize,
}
}

This is the type we'll implement the Iterator trait on. You'll need to specify the item this Iterator implementation yields, as well as an implementation for Iterator::next, which yields the next item. You'll be able to make this easier by bounding T to Default when implementing the Iterator trait, as then you can use the std::mem::take function to take an item from the LocalStorageVec and replace it with the default value for T.

Take a look at the list of methods under the 'provided methods' section. In there, lots of useful methods that come free with the implementation of the Iterator trait are defined, and implemented in terms of the next method. Knowing in the back of your head what methods there are, greatly helps in improving your efficiency in programming with Rust. Which of the provided methods can you override in order to make the implementation of LocalStorageVecIter more efficient, given that we can access the fields and methods of LocalStorageVec?

Now to instantiate a LocalStorageVecIter, implement the [IntoIter] trait for it, in such a way that calling into_iter yields a LocalStorageVecIter.

A3.E AsRef and AsMut ⭐⭐

AsRef and AsMut are used to implement cheap reference-to-reference coercion. For instance, our LocalStorageVec<T, N> is somewhat similar to a slice &[T], as both represent a contiguous series of T values. This is true whether the LocalStorageVec buffer resides on the stack or on the heap.

Uncomment the it_as_refs test case and implement AsRef<[T]> and AsMut<[T]>.

Hint Make sure to take into account the value of `len` for the `Stack` variant of `LocalStorageVec` when creating a slice.

A3.F Index ⭐⭐

To allow users of the LocalStorageVec to read items or slices from its buffer, we can implement the Index trait. This trait is generic over the type of the item used for indexing. In order to make our LocalStorageVec versatile, we should implement:

  • Index<usize>, allowing us to get a single item by calling vec[1];
  • Index<RangeTo<usize>>, allowing us to get the first n items (excluding item n) by calling vec[..n];
  • Index<RangeFrom<usize>>, allowing us to get the last n items by calling vec[n..];
  • Index<Range<usize>>, allowing us to get the items between n and m items (excluding item m) by calling vec[n..m];

Each of these implementations can be implemented in terms of the as_ref implementation, as slices [T] all support indexing by the previous types. That is, [T] also implements Index for those types. Uncomment the it_indexes test case and run cargo test in order to validate your implementation.

A3.G Removing bounds ⭐⭐

When we implemented the borrowing Iterator, we saw that it's possible to define methods in separate impl blocks with different type bounds. Some of the functionality you wrote used the assumption that T is both Copy and Default. However, this means that each of those methods are only defined for LocalStorageVecs containing items of type T that in fact do implement Copy and Default, which is not ideal. How many methods can you rewrite having one or both of these bounds removed?

A3.H Borrowing Iterator ⭐⭐⭐

We've already got an iterator for LocalStorageVec, though it has the limitation that in order to construct it, the LocalStorageVec needs to be consumed. What if we only want to iterate over the items, and not consume them? We will need another iterator type, one that contains an immutable reference to the LocalStorageVec and that will thus need a lifetime annotation. Add a method called iter to LocalStorageVec that takes a shared &self reference, and instantiates the borrowing iterator. Implement the Iterator trait with the appropriate Item reference type for your borrowing iterator. To validate your code, uncomment and run the it_borrowing_iters test case.

Note that this time, the test won't compile if you require the items of LocalStorageVec be Copy! That means you'll have to define LocalStorageVec::iter in a new impl block that does not put this bound on T:

#![allow(unused)]
fn main() {
impl<T: Default + Copy, const N: usize> LocalStorageVec<T, N> {
    // Methods you've implemented so far
}

impl<T: const N: usize> LocalStorageVec<T, N> {
    pub fn iter(&self) -> /* TODO */
}
}

Defining methods in separate impl blocks means some methods are not available for certain instances of the generic type. In our case, the new method is only available for LocalStorageVecs containing items of type T that implement both Copy and Default, but iter is available for all LocalStorageVecs.

A3.I Generic Index ⭐⭐⭐⭐

You've probably duplicated a lot of code in the last exercise. We can reduce the boilerplate by defining an empty trait:

#![allow(unused)]
fn main() {
trait LocalStorageVecIndex {}
}

First, implement this trait for usize, RangeTo<usize>, RangeFrom<usize>, and Range<usize>.

Next, replace the implementations from the previous exercise with a blanket implementation of Index. In English:

"For each type T, I and constant N of type usize, *implement Index<I> for LocalStorageVec<T, N>, where I implements LocalStorageVecIndex and [T] implements Index<I>"

If you've done this correctly, it_indexes should again compile and pass.

A3.J Deref and DerefMut ⭐⭐⭐⭐

The next trait that makes our LocalStorageVec more flexible in use are Deref and DerefMut that utilize the 'deref coercion' feature of Rust to allow types to be treated as if they were some type they look like. That would allow us to use any method that is defined on [T] by calling them on a LocalStorageVec. Before continueing, read the section 'Treating a Type Like a Reference by Implementing the Deref Trait' from The Rust Programming Language (TRPL). Don't confuse deref coercion with any kind of inheritance! Using Deref and DerefMut for inheritance is frowned upon in Rust.

Below, an implementation of Deref and DerefMut is provided in terms of the AsRef and AsMut implementations. Notice the specific way in which as_ref and as_mut are called.

#![allow(unused)]
fn main() {
impl<T, const N: usize> Deref for LocalStorageVec<T, N> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        <Self as AsRef<[T]>>::as_ref(self)
    }
}

impl<T, const N: usize> DerefMut for LocalStorageVec<T, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        <Self as AsMut<[T]>>::as_mut(self)
    }
}
}

Question

  • Replacing the implementation of deref with self.as_ref() results in a stack overflow when running an unoptimized version. Why? (Hint: deref coercion)

Module B - Application programming

Slides (or pdf)

Code written in this exercise has to adhere to the Rust API Guidelines. A checklist can be found here.

B.1 Serializing and deserializing of Strings with serde ⭐

This exercise is adapted from the serde_lifetimes exercise by Ferrous Systems

Open exercises/B/1-my-serde-app/src/main.rs. In there, you'll find some Rust code we will do this exercise with.

We used todo!() macros to mark places where you should put code to make the program run. Look at the serde_json api for help.

Hint Serde comes with two traits: `Serializable` and `Deserializable`. These traits can be `derive` d for your `struct` or `enum` types. Other `serde-*` crates use these traits to convert our data type from and to corresponding representation (`serde-json` to JSON, `serde-yaml` to YAML, etc.).

How come main returns an anyhow::Result<()>? By having main return a result, we can bubble errors up all the way to runtime. You can find more information about it in Rust By Example. The anyhow::Result is a more flexible type of Result, which allows for easy conversion of error types.

What is that r#"... thing?
r in front of a string literal means it's a "raw" string. Escape sequences (\n, \", etc.) don't work, and thus they are very convenient for things like regular expressions, JSON literals, etc.

Optionally r can be followed by one or more symbols (like # in our case), and then your string ends when there's a closing double quote followed by the same number of the same symbols. This is great for cases when you want to have double quotes inside your string literal. For our example r#" ... "# works great for JSON. In rare cases you'd want to put two or more pound signs. Like, when you store CSS color values in your JSON strings:

#![allow(unused)]
fn main() {
// here `"#` would not terminate the string
r##"
    {
        "color": "#ff00ff"
    }
"##
}

B.2 Your first Rust project

In this exercise, you will create a Rust crate that adheres to the guidelines that were pointed out during the lecture. Additionally, you will add and use dependencies, create unit tests, and create some documentation. You can view this exercise as a stepping stone to the final project.

This exercise should be done in groups of 2 people

B.2.A Setting up ⭐

Create a new project using cargo new --name quizzer. Make sure it acts as both a binary and a library. That means there will be both a src/lib.rs and a src/bin/quizzer/main.rs file in your crate, where quizzer is the name of the binary:

$ tree
.
β”œβ”€β”€ Cargo.toml
β”œβ”€β”€ quiz.json
└── src
    β”œβ”€β”€ bin
    β”‚Β Β  └── quizzer
    β”‚Β Β      └── main.rs
    └── lib.rs

Add the following dependencies to your Cargo.toml file. Below items contain links to their page on lib.rs. Make sure you get a general idea of what these crates are for and how they can be used. Don't dive too deep just yet.

Your Cargo.toml should look like this:

[package]
name = "quizzer"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.66"
clap = { version = "4.0.18", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.87"

For clap and serde, the non-standard derive feature of each these crates is enabled. For clap, it allows us to derive the Parser trait, which greatly simplifies creating a CLI. The derive feaure from serde allows us to derive the Serialize and Deserialize traits on any struct we wish to serialize or deserialize using serde and its backends, in our case serde_json.

B.2.B Quizzer ⭐⭐⭐

This exercise is about both design and finding information. You'll have to figure out a model to represent your quiz questions, as well as a means to store them into a JSON file, and load them yourself. Also, you will have to find out how to parse the program arguments.

We will use the project we just set up to write a quiz game creator and player. You may add other dependencies as needed. It has the following functional requirements:

  • It runs as a command-line tool in your terminal.
  • It has two modes: question-entering mode and quiz mode. The mode is selected with a subcommand, passed as the first argument to the program.
    • Question-entering mode: Allows for entering multiple-choice quiz questions, with 4 possible answers each, exactly 1 of them being correct. The questions are stored on disk as a JSON file.
    • Quiz mode: Loads stored questions from the JSON file, presents the questions one-by-one to the player, reads and verifies the player input, and presents the score at the end of the game.
  • Errors are correctly handled, i.e. your application does not panic if it encounters any unexpected situation. Use anywhow and the question-mark (?) operator to make error-bubbling concise. You can read about the ?-operator here: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
  • Logic concerning creating, storing, and loading quiz questions is defined in the library part of your crate.
  • Functionality regarding user input (arg parsing, reading from stdin) is defined in the application code, not in your library.
  • Logical units of your crate are divided up into modules.

Before you start coding, make sure you've listed all open questions and found answers to them. You're also encouraged to draw a simple diagram of the module structure of your application, annotating each module with its responsibilities.

B.3 FizzBuzz

In this exercise, you will practise writing a unit test, and use Rusts benchmarking functionality to help you optimize a FizzBuzz app. You will need cargo-criterion, a tool that runs benchmarks and creates nice reports. You can install it by running

cargo install cargo-criterion --version=1.1.0

B.3.A Testing Fizz Buzz ⭐

Open exercises/B3-fizzbuzz/src/lib.rs. Create a unit test that verifies the correctness of the fizz_buzz function. You can use the include_str macro to include exercises/B/3-fizzbuzz/fizzbuzz.out as a &str into your binary. Each line of fizzbuzz.out contains the expected output of the fizz_buzz function given the line number as input. You can run the test with

cargo test

By default, Rusts test harness captures all output and discards it, If you like to debug your test code using print statements, you can run

cargo test -- --nocapture

to prevent the harness from capturing output.

B.3.B Benchmarking Fizz Buzz ⭐⭐

You'll probably have noticed the fizz_buzz implementation is not very optimized. We will use criterion to help us benchmark fizz_buzz. To run a benchmark, run the following command when in the exercises/B/3-fizzbuzz/ directory:

cargo criterion

This command will run the benchmarks, and report some statistics to your terminal. It also generates HTML reports including graphs that you can find under target/criterion/reports. For instance, target/criterion/reports/index.html is a summary of all benchmark. Open it with your browser and have a look.

Your job is to do some optimization of the fizz_buzz function, and use cargo-criterion to measure the impact of your changes. Don't be afraid to change the signature of fizz_buzz, if, for instance, you want to minimize the number of allocations done by this function. However, make sure that the function is able to correctly produce the output. How fast can you FizzBuzz?

Module C - Concurrency & Parallelism

Slides (or pdf)

C.1 TF-IDF β˜…β˜…

Follow the instructions in the comments of excercises/C/1-tf-ifd/src/main.rs!

C.2 Basic Mutex β˜…β˜…β˜…

Follow the instructions in the comments of excercises/C/2-mutex/src/main.rs!

C.3 Advanced Mutex (bonus) β˜…β˜…β˜…β˜…

The basic mutex performs a spin-loop while waiting to take the lock. That is terribly inefficient. Luckily, your operating system is able to wait until the lock becomes available, and will just put the thread to sleep in the meantime.

This functionality is exposed in the atomic_wait crate. The section on implementing a mutex from "Rust Atomics and Locks" explains how to use it.

  • change the AtomicBool for a AtomicU32
  • implement lock. Be careful about spurious wakes: after wait returns, you must stil check the condition
  • implement unlocking (Drop for MutexGuard<T> using wake_one.

The linked chapter goes on to further optimize the mutex. This really is no longer part of a 101 course, but we won't stop you if you try (and will still try to help if you get stuck)!

Module D - Trait objects and Rust patterns

Slides (or pdf)

D.1 BSN

The BSN (Burgerservicennummer) is a Dutch personal identification number that somewhat resembles the US Social Security Number in its use. The BSN is a number that adheres to some rules. In this exercise, we will create a Rust type that guarantees that it represents a valid BSN.

D.1.A Newtype ⭐⭐

In this part we will implement the BSN number validation, as well as a fallible constructor.

A BSN is valid if and only if it matches the following criteria:

  • It consists of 8 or 9 digits
  • It passes a variant of the 11 check (elfproef (Dutch)):

For 8-digit BSNs, we concatenate a 0 to the end. The digits of the number are labeled as ABCDEFGHI. For example: for BSN 123456789, A = 1, B = 2, C = 3, and so forth until I.

Then, (9 Γ— A) + (8 Γ— B) + (7 Γ— C) + (6 Γ— D) + (5 Γ— E) + (4 Γ— F) + (3 Γ— G) + (2 Γ— H) + (-1 Γ— I) must be a multiple of 11

Open exercises/D/1-bsn in your editor. You'll find the scaffolding code there, along with two files:

  • valid_bsns.in containing a list of valid BSNs
  • invalid_bsns.in containing a list of invalid BSNs.

In src/lib.rs, implement Bsn::validate to make the test_validation test case pass. Implement Bsn::try_from_string as well. To try just the test_validation test case, run:

cargo test -- test_validation

D.1.A Visitor with Serde ⭐⭐⭐

Next up is implementing the serde::Serialize and serde::Deserialize traits, to support serialization and deserialization of Bsns. In this case, simply deriving those traits won't suffice, as we want to represent the BSN as a string after serialization. We also want to deserialize strings directly into Bsns, while still upholding the guarantee that an instantiated Bsn represents a valid BSN. Therefore, you have to incorporate Bsn::validate into the implementation of the deserialization visitor.

More information on implementing the traits:

  • serde::Serialize: https://serde.rs/impl-serialize.html
  • serde::Deserialize: https://serde.rs/impl-deserialize.html

If everything works out, all tests should pass.

D.2 Typestate 3D Printer ⭐⭐

An imaginary 3D printer uses filament to create all kinds of things. Its states can be represented with the following state diagram:

                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                   β”‚                 β”‚
                   β”‚                 β”‚   Reset
                   β”‚      Idle       │◄────────────────────────────┐
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Ίβ”‚                 β”‚                             β”‚
         β”‚         β”‚                 β”‚                             β”‚
         β”‚         β”‚                 β”‚                             β”‚
         β”‚         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜                             β”‚
         β”‚                  β”‚                                      β”‚
         β”‚                  β”‚                                      β”‚
         β”‚                  β”‚ Start                                β”‚
         β”‚                  β”‚                                      β”‚
         β”‚                  β–Ό                                      β”‚
         β”‚         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚         β”‚                 β”‚                    β”‚                 β”‚
         β”‚         β”‚                 β”‚   Out of filament  β”‚                 β”‚
Product  β”‚         β”‚    Printing     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ί β”‚      Error      β”‚
retrievedβ”‚         β”‚                 β”‚                    β”‚                 β”‚
         β”‚         β”‚                 β”‚                    β”‚                 β”‚
         β”‚         β”‚                 β”‚                    β”‚                 β”‚
         β”‚         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                  β”‚
         β”‚                  β”‚ Product ready
         β”‚                  β”‚
         β”‚                  β–Ό
         β”‚         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚         β”‚                 β”‚
         β”‚         β”‚                 β”‚
         β”‚         β”‚  Product Ready  β”‚
         └──────────                 β”‚
                   β”‚                 β”‚
                   β”‚                 β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The printer boots in Idle state. Once a job is started, the printer enters the Printing state. In printing state, it keeps on printing the product until either it is ready or the printer is out of filament. If the printer is out of filament, the printer goes into Error state, which it can only come out of upon device reset. If the product is ready, the printer goes to Product Ready state, and once the user retrieves the product, the printer goes back to Idle.

The printer can be represented in Rust using the typestate pattern as described during the lecture. This allows you to write a simple 3D printer driver. In exercises/D/2-3d-printer, a Printer3D struct is instantiated. Add methods corresponding to each of the traits, that simulate the state transitions by printing the state. A method simulating checking if the printer is out of filament is provided.

Of course, to make the printer more realistic, you can add more states and transitions.

D.3 Dynamic deserialization ⭐⭐

In this exercise, you'll work with dynamic dispatch to deserialize with serde_json or serde_yaml, depending on the file extension. The starter code is in exercises/D/3-config-reader. Fix the todo's in there.

To run the program, you'll need to pass the file to deserialize to the binary, not to Cargo. To do this, run

cargo run -- <FILE_PATH>

Deserializing both config.json and config.yml should result in the Config being printed correctly.

Module E - Async and Rust for Web

Slides (or pdf)

E.1 Channels

Channels are a very useful way to communicate between threads and async tasks. They allow for decoupling your application into many tasks. You'll see how that can come in nicely in exercise E.2. In this exercise, you'll implement two variants: a oneshot channel and a multi-producer-single-consumer (MPSC) channel. If you're up for a challenge, you can write a broadcast channel as well.

E.1.A MPSC channel ⭐⭐

A multi-producer-single-consumer (MPSC) channel is a channel that allows for multiple Senders to send many messages to a single Receiver.

Open exercises/E/1-channels in your editor. You'll find the scaffolding code there. For part A, you'll work in src/mpsc.rs. Fix the todo!s in that file in order to make the test pass. To test, run:

cargo test -- mpsc

If your tests are stuck, probably either your implementation does not use the Waker correctly, or it returns Poll::Pending where it shouldn't.

E.1.B Oneshot channel ⭐⭐⭐

A oneshot is a channel that allows for one Sender to send exactly one message to a single Receiver.

For part B, you'll work in src/broadcast.rs. This time, you'll have to do more yourself. Intended behavior:

  • Receiver implements Future. It returns Poll::Ready(Ok(T)) if inner.data is Some(T), Poll::Pending if inner.data is None, and Poll::Ready(Err(Error::SenderDropped)) if the Sender was dropped.
  • Receiver::poll replaces inner.waker with the one from the Context.
  • Sender consumes self on send, allowing the it to be used no more than once. Sending sets inner.data to Some(T). It returns Err(Error::ReceiverDropped(T)) if the Receiver was dropped before sending.
  • Sender::send wakes inner.waker after putting the data in inner.data
  • Once the Sender is dropped, it marks itself dropped with inner
  • Once the Receiver is dropped, it marks itself dropped with inner
  • Upon succesfully sending the message, the consumed Sender is not marked as dropped. Instead std::mem::forget is used to avoid running the destructor.

To test, run:

cargo test -- broadcast

E.1.B Broadcast channel (bonus) ⭐⭐⭐⭐

A Broadcast channel is a channel that supports multiple senders and receivers. Each message that is sent by any of the senders, is received by every receiver. Therefore, the implemenentation has to hold on to messages until they have been sent to every receiver that has not yet been dropped. This furthermore implies that the message shoud be cloned upon broadcasting.

For this bonus exercise, we provide no scaffolding. Take your inspiration from the mpsc and oneshot modules, and implement a broadcast module yourself.

E.2 Chat app

In this exercise, you'll write a simple chat server and client based on Tokio. Open exercises/E/2-chat in your editor. The project contains a lib.rs file, in which a type Message resides. This Message defines the data the chat server and clients use to communicate.

E.2.A Server ⭐⭐⭐

The chat server, which resides in src/bin/server.rs listens for incoming TCP connections on port 8000, and spawns two tasks (futures):

  • handle_incoming: reads lines coming in from the TCP connection. It reads the username the client provides, and broadcasts incoming Messages, possibly after some modification.
  • handle_outgoing: sends messages that were broadcasted by the handle_incoming tasks to the client over TCP.

Both handle_incoming and handle_outgoing contain a number to todos. Fix them.

To start the server, run

cargo run --bin server

E.2.B Client ⭐⭐

The chat client, residing in src/bin/client.rs contains some todo's as well. Fix them to allow for registration and sending Messages to the server.

To start the client, run

cargo run --bin client

If everything works well, you should be able to run multiple clients and see messages sent from each client in every other.

E.3 Pastebin ⭐⭐⭐

This exercise is about writing a simple pastebin web server. Like the quizzer app, you will need to set up the project yourself. This webserver will be powered by axum.

  • Data is kept in memory. Bonus if you use a database or sqlite, but first make the app function properly without.
  • Expose a route to which a POST request can be sent, that accepts some plain text, and stores it along with a freshly generated UUID. The UUID is sent in the response. You can use the uuid crate to generate UUIDs.
  • Expose a route to which a GET request can be sent, that accepts a UUID and returns the plain text corresponding to the UUID, or a 404 error if it doesn't exist.
  • Expose a route to which a DELETE request can be sent, that accepts a UUID and deletes the plain text corresonding to that UUID.

Module F - Safe and Unsafe rust

Slides (or pdf)

C.1 Linked List β˜…β˜…β˜…

Follow the instructions in the comments of exercises/F/1-linked-list/src/bin/unsafe.rs!

C.2 Execve β˜…β˜…β˜…

Follow the instructions in exercises/F/2-execve/README.md and implement in exercises/F/2-execve/src/main.rs!

C.3 Tagged union β˜…β˜…β˜…

Follow the instructions in the comments of exercises/F/3-tagged-union/src/main.rs!

Module G - Foreign Function Interface

Slides (or pdf)

G.1 CRC in C β˜…β˜…β˜…

Use a CRC checksum function written in C in a Rust program

Follow the instructions exercises/G/1-crc-in-c/README.md!

G.2 CRC in Rust β˜…β˜…β˜…

Use a CRC checksum function written in Rust in a C program

Follow the instructions exercises/G/2-crc-in-rust/README.md!

G.3 Bindgen β˜…β˜…β˜…

Use cargo bindgen to generate the FFI bindings. Bindgen will look at a C header file, and generate rust functions, types and constants based on the C definitions.

But the generated code is ugly and non-idiomatic. To wrap a C library properly, good API design and documentation is needed.

Follow the instructions exercises/G/3-tweetnacl-bindgen/README.md!

G.4 PyO3 β˜…β˜…β˜…

Write a custom python extension using PyO3.

Python is a convenient and popular language, but it is not fast. By writing complex logic in faster languages, you can get the best of both worlds. PyO3 makes it extremely easy to write and distribute python extensions written in Rust.

Follow the instructions exercises/G/4-pyo3/README.md!

Module P - Final project

It is time to submit a proposal for the final project.

  • Form groups of 2 or 3 people. Working solo is not permitted.
  • Build a small Rust project yourselves
  • Up to 2 groups can work on the same topic

Proposal

The proposal needs to be submitted by 30th of March, 2023 by opening a Github repo, placing your proposal there, and either making it public or granting access to @hdoordt. Then, please send Henk a link to the repository via Discord so we know where to find it.

The proposal must contain the following sections:

  • Your names and Discord handles used in the Rust 101 Discord server
  • Introduction to your idea. What general problem does it solve? What do you hope to learn?
  • Requirements in brief. Just some bullet points on what your application or library should be able to do in order for the project to be deemed successful. Half a page maximum.
  • The dependencies you want to use (use https://lib.rs to discover crates)
  • Optional: A rudimentary diagram of the architecture

Of course, if you want to discuss your idea before handing in your proposal, or if you have any other questions, please reach out via Discord.

Any reparations to the proposals must be handed in on the 6th of April 2023

Final product

At the end of the project following will be required (deadline is the 4th of May, 2023)

  • The source of your project (GitHub)
  • A live 10 minute presentation, including a short demonstration (and an additional 2 minutes for questions) during the final lecture
  • A small report on what you did (3 pages max). It contains the following sections:
    • Introduction to your idea
    • Requirements in more detail (not too detailed, though)
    • Design diagram. Keep it high-level
    • Design choices. What choices did you make, what were alternatives, and why did you choose the way you did?
    • Dependencies and what they're used for
    • Evaluation. What went well? What went not so well? How does implmementing a bigger project in Rust feel compared to other languages?

Project suggestions

You are encouraged to suggest your own project, here are some suggestions. We will add more ideas as they come up.