Automatically add exercise links to sections. (#52)

We use an mdbook preprocessor to automatically generate links to the relevant exercise for each section.
We remove all existing manual links and refactor the deploy process to push the rendered book to a branch.
This commit is contained in:
Luca Palmieri 2024-05-24 18:15:38 +02:00 committed by GitHub
parent 99591a715e
commit 1aae615bb4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
65 changed files with 1855 additions and 212 deletions

View file

@ -9,22 +9,20 @@ on:
- main - main
jobs: jobs:
formatter: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- uses: dprint/check@v2.2 - uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Install plugin
check-links: run: cargo install --path helpers/mdbook-exercise-linker
runs-on: ubuntu-latest - uses: taiki-e/install-action@v2
steps: with:
- name: Checkout repository tool: mdbook
uses: actions/checkout@v4
- name: Build book - name: Build book
run: | run: |
cd book cd book
curl -sSL https://github.com/rust-lang/mdBook/releases/download/v0.4.40/mdbook-v0.4.40-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=. mdbook build
./mdbook build
- name: Link Checker - name: Link Checker
uses: lycheeverse/lychee-action@v1 uses: lycheeverse/lychee-action@v1
with: with:
@ -34,3 +32,25 @@ jobs:
--require-https --require-https
--no-progress --no-progress
book/book book/book
# Upload the book as an artifact
- uses: actions/upload-artifact@v4
with:
name: book
path: book/book
# Commit and push all changed files.
# Must only affect files that are listed in "paths-ignore".
- name: Git commit build artifacts
# Only run on main branch push (e.g. pull request merge).
if: github.event_name == 'push'
run: |
git config --global user.name "${{ env.CI_COMMIT_AUTHOR }}"
git config --global user.email "username@users.noreply.github.com"
git add --force book/book
git commit -m "${{ env.CI_COMMIT_MESSAGE }}"
git push --set-upstream --force-with-lease origin deploy
formatter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dprint/check@v2.2

1675
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,3 @@
[workspace] [workspace]
members = ["exercises/*/*", "helpers/common", "helpers/ticket_fields"] members = ["exercises/*/*", "helpers/common", "helpers/mdbook-exercise-linker", "helpers/ticket_fields"]
resolver = "2" resolver = "2"

View file

@ -7,3 +7,6 @@ title = "100 Exercises To Learn Rust"
[output.html] [output.html]
git-repository-url = "https://github.com/mainmatter/100-exercises-to-learn-rust" git-repository-url = "https://github.com/mainmatter/100-exercises-to-learn-rust"
[preprocessor.exercise-linker]
exercise_root_url = "https://github.com/mainmatter/100-exercises-to-learn-rust/tree/main/exercises"

View file

@ -88,10 +88,6 @@ Don't move on to the next section until you've solved the exercise for the curre
Enjoy the course! Enjoy the course!
## References
- The exercise for this section is located in `exercises/01_intro/00_welcome`
## Author ## Author
This course was written by [Luca Palmieri](https://www.lpalmieri.com/), Principal Engineering This course was written by [Luca Palmieri](https://www.lpalmieri.com/), Principal Engineering

View file

@ -114,6 +114,3 @@ tag, the compiler can enforce different rules—e.g. you can't add a string to a
together. together.
If leveraged correctly, types can prevent whole classes of runtime bugs. If leveraged correctly, types can prevent whole classes of runtime bugs.
## References
- The exercise for this section is located in `exercises/01_intro/01_syntax`

View file

@ -15,6 +15,3 @@ Nailing the basics with a few exercises will get the language flowing under your
When we move on to more complex topics, such as traits and ownership, you'll be able to focus on the new concepts When we move on to more complex topics, such as traits and ownership, you'll be able to focus on the new concepts
without getting bogged down by the syntax or other trivial details. without getting bogged down by the syntax or other trivial details.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/00_intro`

View file

@ -119,10 +119,6 @@ error[E0308]: mismatched types
We'll see how to convert between types [later in this course](../04_traits/09_from.md). We'll see how to convert between types [later in this course](../04_traits/09_from.md).
## References
- The exercise for this section is located in `exercises/02_basic_calculator/01_integers`
## Further reading ## Further reading
- [The integer types section](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types) in the official Rust book - [The integer types section](https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types) in the official Rust book

View file

@ -97,8 +97,4 @@ help: consider assigning a value
| +++ | +++
``` ```
## References
- The exercise for this section is located in `exercises/02_basic_calculator/02_variables`
[^speed]: The Rust compiler needs all the help it can get when it comes to compilation speed. [^speed]: The Rust compiler needs all the help it can get when it comes to compilation speed.

View file

@ -100,6 +100,3 @@ In the example above, each branch of the `if` evaluates to a string literal,
which is then assigned to the `message` variable.\ which is then assigned to the `message` variable.\
The only requirement is that both `if` branches return the same type. The only requirement is that both `if` branches return the same type.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/03_if_else`

View file

@ -41,10 +41,6 @@ fn main() {
There are other mechanisms to work with recoverable errors in Rust, which [we'll cover later](../05_ticket_v2/06_fallibility.md). There are other mechanisms to work with recoverable errors in Rust, which [we'll cover later](../05_ticket_v2/06_fallibility.md).
For the time being we'll stick with panics as a brutal but simple stopgap solution. For the time being we'll stick with panics as a brutal but simple stopgap solution.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/04_panics`
## Further reading ## Further reading
- [The panic! macro documentation](https://doc.rust-lang.org/std/macro.panic.html) - [The panic! macro documentation](https://doc.rust-lang.org/std/macro.panic.html)

View file

@ -10,6 +10,3 @@ So far you've learned:
It looks like you're ready to tackle factorials! It looks like you're ready to tackle factorials!
## References
- The exercise for this section is located in `exercises/02_basic_calculator/05_factorial`

View file

@ -80,10 +80,6 @@ while i <= 5 {
This will compile and run without errors. This will compile and run without errors.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/06_while`
## Further reading ## Further reading
- [`while` loop documentation](https://doc.rust-lang.org/std/keyword.while.html) - [`while` loop documentation](https://doc.rust-lang.org/std/keyword.while.html)

View file

@ -54,10 +54,6 @@ for i in 1..(end + 1) {
} }
``` ```
## References
- The exercise for this section is located in `exercises/02_basic_calculator/07_for`
## Further reading ## Further reading
- [`for` loop documentation](https://doc.rust-lang.org/std/keyword.for.html) - [`for` loop documentation](https://doc.rust-lang.org/std/keyword.for.html)

View file

@ -100,10 +100,6 @@ Our recommendation is to enable `overflow-checks` for both profiles: it's better
incorrect results. The runtime performance hit is negligible in most cases; if you're working on a performance-critical incorrect results. The runtime performance hit is negligible in most cases; if you're working on a performance-critical
application, you can run benchmarks to decide if it's something you can afford. application, you can run benchmarks to decide if it's something you can afford.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/08_overflow`
## Further reading ## Further reading
- Check out ["Myths and legends about integer overflow in Rust"](https://huonw.github.io/blog/2016/04/myths-and-legends-about-integer-overflow-in-rust/) - Check out ["Myths and legends about integer overflow in Rust"](https://huonw.github.io/blog/2016/04/myths-and-legends-about-integer-overflow-in-rust/)

View file

@ -35,9 +35,5 @@ The opposite happens for underflows: `0 - 1` is `-1`, which is smaller than `u8:
You can't get saturating arithmetic via the `overflow-checks` profile setting—you have to explicitly opt into it You can't get saturating arithmetic via the `overflow-checks` profile setting—you have to explicitly opt into it
when performing the arithmetic operation. when performing the arithmetic operation.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/09_saturating`
[^method]: You can think of methods as functions that are "attached" to a specific type. [^method]: You can think of methods as functions that are "attached" to a specific type.
We'll cover methods (and how to define them) in the next chapter. We'll cover methods (and how to define them) in the next chapter.

View file

@ -94,10 +94,6 @@ When working with composite types, you'll have to rely on
different conversion mechanisms ([fallible](../05_ticket_v2/13_try_from.md) different conversion mechanisms ([fallible](../05_ticket_v2/13_try_from.md)
and [infallible](../04_traits/09_from.md)), which we'll explore later on. and [infallible](../04_traits/09_from.md)), which we'll explore later on.
## References
- The exercise for this section is located in `exercises/02_basic_calculator/10_as_casting`
## Further reading ## Further reading
- Check out [Rust's official reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast) - Check out [Rust's official reference](https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast)

View file

@ -17,6 +17,3 @@ To move forward you'll have to pick up several new Rust concepts, such as:
- Modules and visibility - Modules and visibility
- Strings - Strings
## References
- The exercise for this section is located in `exercises/03_ticket_v1/00_intro`

View file

@ -137,6 +137,3 @@ let is_open = Ticket::is_open(ticket);
The function call syntax makes it quite clear that `ticket` is being used as `self`, the first parameter of the method, The function call syntax makes it quite clear that `ticket` is being used as `self`, the first parameter of the method,
but it's definitely more verbose. Prefer the method call syntax when possible. but it's definitely more verbose. Prefer the method call syntax when possible.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/01_struct`

View file

@ -15,10 +15,6 @@ This means that users can create a ticket with an empty title, a suuuuuuuper lon
a nonsensical status (e.g. "Funny").\ a nonsensical status (e.g. "Funny").\
We can do better than that! We can do better than that!
## References
- The exercise for this section is located in `exercises/03_ticket_v1/02_validation`
## Further reading ## Further reading
- Check out [`String`'s documentation](https://doc.rust-lang.org/std/string/struct.String.html) - Check out [`String`'s documentation](https://doc.rust-lang.org/std/string/struct.String.html)

View file

@ -113,6 +113,3 @@ Nonetheless, it can be useful in some cases, like when writing unit tests. You m
that most of our test modules start with a `use super::*;` statement to bring all the items from the parent module that most of our test modules start with a `use super::*;` statement to bring all the items from the parent module
(the one being tested) into scope. (the one being tested) into scope.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/03_modules`

View file

@ -44,6 +44,3 @@ pub struct Configuration {
`Configuration` is public, but you can only access the `version` field from within the same crate. `Configuration` is public, but you can only access the `version` field from within the same crate.
The `active` field, instead, is private and can only be accessed from within the same module or one of its submodules. The `active` field, instead, is private and can only be accessed from within the same module or one of its submodules.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/04_visibility`

View file

@ -56,8 +56,4 @@ Accessor methods are public methods that allow you to read the value of a privat
Rust doesn't have a built-in way to generate accessor methods for you, like some other languages do. Rust doesn't have a built-in way to generate accessor methods for you, like some other languages do.
You have to write them yourself—they're just regular methods. You have to write them yourself—they're just regular methods.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/05_encapsulation`
[^newtype]: Or refine their type, a technique we'll explore [later on](../05_ticket_v2/15_outro.md). [^newtype]: Or refine their type, a technique we'll explore [later on](../05_ticket_v2/15_outro.md).

View file

@ -229,9 +229,5 @@ and truly understand how they work.
Towards the end of this chapter we'll explain _why_ Rust's ownership system is designed the way it is. Towards the end of this chapter we'll explain _why_ Rust's ownership system is designed the way it is.
For the time being, focus on understanding the _how_. Take each compiler error as a learning opportunity! For the time being, focus on understanding the _how_. Take each compiler error as a learning opportunity!
## References
- The exercise for this section is located in `exercises/03_ticket_v1/06_ownership`
[^refine]: This is a great mental model to start out, but it doesn't capture the _full_ picture. [^refine]: This is a great mental model to start out, but it doesn't capture the _full_ picture.
We'll refine our understanding of references [later in the course](../07_threads/06_interior_mutability.md). We'll refine our understanding of references [later in the course](../07_threads/06_interior_mutability.md).

View file

@ -107,6 +107,3 @@ ticket.set_description("New description".into());
ticket.set_status("In Progress".into()); ticket.set_status("In Progress".into());
``` ```
## References
- The exercise for this section is located in `exercises/03_ticket_v1/07_setters`

View file

@ -52,10 +52,6 @@ assert_eq!(std::mem::size_of::<u8>(), 1);
1 makes sense, because a `u8` is 8 bits long, or 1 byte. 1 makes sense, because a `u8` is 8 bits long, or 1 byte.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/08_stack`
[^stack-overflow]: If you have nested function calls, each function pushes its data onto the stack when it's called but [^stack-overflow]: If you have nested function calls, each function pushes its data onto the stack when it's called but
it doesn't pop it off until the innermost function returns. it doesn't pop it off until the innermost function returns.
If you have too many nested function calls, you can run out of stack space—the stack is not infinite! If you have too many nested function calls, you can run out of stack space—the stack is not infinite!

View file

@ -133,10 +133,6 @@ but there is no general-purpose "API" to retrieve runtime heap usage in Rust.\
You can, however, use a memory profiler tool (e.g. [DHAT](https://valgrind.org/docs/manual/dh-manual.html) You can, however, use a memory profiler tool (e.g. [DHAT](https://valgrind.org/docs/manual/dh-manual.html)
or [a custom allocator](https://docs.rs/dhat/latest/dhat/)) to inspect the heap usage of your program. or [a custom allocator](https://docs.rs/dhat/latest/dhat/)) to inspect the heap usage of your program.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/09_heap`
[^empty]: `std` doesn't allocate if you create an **empty** `String` (i.e. `String::new()`). [^empty]: `std` doesn't allocate if you create an **empty** `String` (i.e. `String::new()`).
Heap memory will be reserved when you push data into it for the first time. Heap memory will be reserved when you push data into it for the first time.

View file

@ -45,10 +45,6 @@ The same goes for `&mut String`.
The example above should clarify one thing: not all pointers point to the heap.\ The example above should clarify one thing: not all pointers point to the heap.\
They just point to a memory location, which _may_ be on the heap, but doesn't have to be. They just point to a memory location, which _may_ be on the heap, but doesn't have to be.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/10_references_in_memory`
[^fat]: [Later in the course](../04_traits/06_str_slice.md) we'll talk about **fat pointers**, [^fat]: [Later in the course](../04_traits/06_str_slice.md) we'll talk about **fat pointers**,
i.e. pointers with additional metadata. As the name implies, they are larger than i.e. pointers with additional metadata. As the name implies, they are larger than
the pointers we discussed in this chapter, also known as **thin pointers**. the pointers we discussed in this chapter, also known as **thin pointers**.

View file

@ -165,9 +165,5 @@ They would refer to a memory location that's no longer valid: a so-called [**dan
a close relative of [**use-after-free bugs**](https://owasp.org/www-community/vulnerabilities/Using_freed_memory). a close relative of [**use-after-free bugs**](https://owasp.org/www-community/vulnerabilities/Using_freed_memory).
Rust's ownership system rules out these kinds of bugs by design. Rust's ownership system rules out these kinds of bugs by design.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/11_destructor`
[^leak]: Rust doesn't guarantee that destructors will run. They won't, for example, if [^leak]: Rust doesn't guarantee that destructors will run. They won't, for example, if
you explicitly choose to [leak memory](../07_threads/03_leak.md). you explicitly choose to [leak memory](../07_threads/03_leak.md).

View file

@ -4,6 +4,3 @@ We've covered a lot of foundational Rust concepts in this chapter.\
Before moving on, let's go through one last exercise to consolidate what we've learned. Before moving on, let's go through one last exercise to consolidate what we've learned.
You'll have minimal guidance this time—just the exercise description and the tests to guide you. You'll have minimal guidance this time—just the exercise description and the tests to guide you.
## References
- The exercise for this section is located in `exercises/03_ticket_v1/12_outro`

View file

@ -19,6 +19,3 @@ On top of traits as a concept, we'll also cover some of the key traits that are
Since we'll be talking about conversions, we'll seize the opportunity to plug some of the "knowledge gaps" Since we'll be talking about conversions, we'll seize the opportunity to plug some of the "knowledge gaps"
from the previous chapter—e.g. what is `"A title"`, exactly? Time to learn more about slices too! from the previous chapter—e.g. what is `"A title"`, exactly? Time to learn more about slices too!
## References
- The exercise for this section is located in `exercises/04_traits/00_intro`

View file

@ -124,8 +124,4 @@ This is not necessary if:
You can find the list of traits and types in the prelude in the You can find the list of traits and types in the prelude in the
[Rust documentation](https://doc.rust-lang.org/std/prelude/index.html). [Rust documentation](https://doc.rust-lang.org/std/prelude/index.html).
## References
- The exercise for this section is located in `exercises/04_traits/01_trait`
[^inherent]: A method defined directly on a type, without using a trait, is also known as an **inherent method**. [^inherent]: A method defined directly on a type, without using a trait, is also known as an **inherent method**.

View file

@ -105,10 +105,6 @@ Which implementation should be used? The one defined in `B`? Or the one defined
There's no good answer, therefore the orphan rule was defined to prevent this scenario. There's no good answer, therefore the orphan rule was defined to prevent this scenario.
Thanks to the orphan rule, neither crate `B` nor crate `C` would compile. Thanks to the orphan rule, neither crate `B` nor crate `C` would compile.
## References
- The exercise for this section is located in `exercises/04_traits/02_orphan_rule`
## Further reading ## Further reading
- There are some caveats and exceptions to the orphan rule as stated above. - There are some caveats and exceptions to the orphan rule as stated above.

View file

@ -97,6 +97,3 @@ impl PartialEq for MyType {
} }
``` ```
## References
- The exercise for this section is located in `exercises/04_traits/03_operator_overloading`

View file

@ -97,10 +97,6 @@ impl ::core::cmp::PartialEq for Ticket {
The compiler will nudge you to derive traits when possible. The compiler will nudge you to derive traits when possible.
## References
- The exercise for this section is located in `exercises/04_traits/04_derive`
## Further reading ## Further reading
- [The little book of Rust macros](https://veykril.github.io/tlborm/) - [The little book of Rust macros](https://veykril.github.io/tlborm/)

View file

@ -171,6 +171,3 @@ each function signature is a contract between the caller and the callee, and the
This allows for better error messages, better documentation, less unintentional breakages across versions, This allows for better error messages, better documentation, less unintentional breakages across versions,
and faster compilation times. and faster compilation times.
## References
- The exercise for this section is located in `exercises/04_traits/05_trait_bounds`

View file

@ -115,6 +115,3 @@ If a method returns a `&String`, you're promising that there is heap-allocated U
If a method returns a `&str`, instead, you have a lot more freedom: you're just saying that _somewhere_ there's a If a method returns a `&str`, instead, you have a lot more freedom: you're just saying that _somewhere_ there's a
bunch of text data and that a subset of it matches what you need, therefore you're returning a reference to it. bunch of text data and that a subset of it matches what you need, therefore you're returning a reference to it.
## References
- The exercise for this section is located in `exercises/04_traits/06_str_slice`

View file

@ -90,6 +90,3 @@ is defined on both `T` and `U`, which one will be called?
We'll examine later in the course the "safest" use cases for deref coercion: smart pointers. We'll examine later in the course the "safest" use cases for deref coercion: smart pointers.
## References
- The exercise for this section is located in `exercises/04_traits/07_deref`

View file

@ -78,6 +78,3 @@ All the types we've seen so far are `Sized`: `u32`, `String`, `bool`, etc.
`&str` is `Sized` though! We know its size at compile time: two `usize`s, one for the pointer `&str` is `Sized` though! We know its size at compile time: two `usize`s, one for the pointer
and one for the length. and one for the length.
## References
- The exercise for this section is located in `exercises/04_traits/08_sized`

View file

@ -139,6 +139,3 @@ In most cases, the target type is either:
`.into()` will work out of the box as long as the compiler can infer the target type from the context without ambiguity. `.into()` will work out of the box as long as the compiler can infer the target type from the context without ambiguity.
## References
- The exercise for this section is located in `exercises/04_traits/09_from`

View file

@ -141,10 +141,6 @@ To recap:
- Use a **generic parameter** when you want to allow multiple implementations of the trait for the same type, - Use a **generic parameter** when you want to allow multiple implementations of the trait for the same type,
with different input types. with different input types.
## References
- The exercise for this section is located in `exercises/04_traits/10_assoc_vs_generic`
[^flexible]: Flexibility is rarely free: the trait definition is more complex due to `Output`, and implementors have to reason about [^flexible]: Flexibility is rarely free: the trait definition is more complex due to `Output`, and implementors have to reason about
what they want to return. The trade-off is only justified if that flexibility is actually needed. Keep that in mind what they want to return. The trade-off is only justified if that flexibility is actually needed. Keep that in mind
when designing your own traits. when designing your own traits.

View file

@ -106,6 +106,3 @@ The compiler implements `Clone` for `MyType` as you would expect: it clones each
then constructs a new `MyType` instance using the cloned fields.\ then constructs a new `MyType` instance using the cloned fields.\
Remember that you can use `cargo expand` (or your IDE) to explore the code generated by `derive` macros. Remember that you can use `cargo expand` (or your IDE) to explore the code generated by `derive` macros.
## References
- The exercise for this section is located in `exercises/04_traits/11_clone`

View file

@ -112,6 +112,3 @@ struct MyStruct {
} }
``` ```
## References
- The exercise for this section is located in `exercises/04_traits/12_copy`

View file

@ -51,6 +51,3 @@ error[E0184]: the trait `Copy` cannot be implemented for this type; the type has
| ^^^^ `Copy` not allowed on types with destructors | ^^^^ `Copy` not allowed on types with destructors
``` ```
## References
- The exercise for this section is located in `exercises/04_traits/13_drop`

View file

@ -26,6 +26,3 @@ A few guidelines to keep in mind:
Before moving on, let's go through one last exercise to consolidate what we've learned. Before moving on, let's go through one last exercise to consolidate what we've learned.
You'll have minimal guidance this time—just the exercise description and the tests to guide you. You'll have minimal guidance this time—just the exercise description and the tests to guide you.
## References
- The exercise for this section is located in `exercises/04_traits/14_outro`

View file

@ -14,6 +14,3 @@ We'll need to introduce a few more concepts along the way:
- The `TryFrom` and `TryInto` traits, for fallible conversions - The `TryFrom` and `TryInto` traits, for fallible conversions
- Rust's package system, explaining what's a library, what's a binary, how to use third-party crates - Rust's package system, explaining what's a library, what's a binary, how to use third-party crates
## References
- The exercise for this section is located in `exercises/05_ticket_v2/00_intro`

View file

@ -42,6 +42,3 @@ enum Status {
`enum`, just like `struct`, defines **a new Rust type**. `enum`, just like `struct`, defines **a new Rust type**.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/01_enum`

View file

@ -69,6 +69,3 @@ match status {
The `_` pattern matches anything that wasn't matched by the previous patterns. The `_` pattern matches anything that wasn't matched by the previous patterns.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/02_match`

View file

@ -87,6 +87,3 @@ match status {
} }
``` ```
## References
- The exercise for this section is located in `exercises/05_ticket_v2/03_variants_with_data`

View file

@ -65,6 +65,3 @@ Both `if let` and `let/else` are idiomatic Rust constructs.\
Use them as you see fit to improve the readability of your code, Use them as you see fit to improve the readability of your code,
but don't overdo it: `match` is always there when you need it. but don't overdo it: `match` is always there when you need it.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/04_if_let`

View file

@ -73,6 +73,3 @@ assert_eq!(second.2, 8);
Tuples are a convenient way of grouping values together when you can't be bothered to define a dedicated struct type. Tuples are a convenient way of grouping values together when you can't be bothered to define a dedicated struct type.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/05_nullability`

View file

@ -82,6 +82,3 @@ That's the big advantage of `Result`: it makes fallibility explicit.
Keep in mind, though, that panics exist. They aren't tracked by the type system, just like exceptions in other languages. Keep in mind, though, that panics exist. They aren't tracked by the type system, just like exceptions in other languages.
But they're meant for **unrecoverable errors** and should be used sparingly. But they're meant for **unrecoverable errors** and should be used sparingly.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/06_fallibility`

View file

@ -39,6 +39,3 @@ When you call a function that returns a `Result`, you have two key options:
} }
``` ```
## References
- The exercise for this section is located in `exercises/05_ticket_v2/07_unwrap`

View file

@ -37,6 +37,3 @@ match s.parse_u32() {
} }
``` ```
## References
- The exercise for this section is located in `exercises/05_ticket_v2/08_error_enums`

View file

@ -51,6 +51,3 @@ while `Debug` provides a low-level representation that's more suitable to develo
That's why `Debug` can be automatically implemented using the `#[derive(Debug)]` attribute, while `Display` That's why `Debug` can be automatically implemented using the `#[derive(Debug)]` attribute, while `Display`
**requires** a manual implementation. **requires** a manual implementation.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/09_error_trait`

View file

@ -62,6 +62,3 @@ binary crate inside. If you want to create a library crate instead, you can use
cargo new my-library --lib cargo new my-library --lib
``` ```
## References
- The exercise for this section is located in `exercises/05_ticket_v2/10_packages`

View file

@ -53,6 +53,3 @@ static_assertions = "1.1.0"
We've been using a few of these throughout the book to shorten our tests. We've been using a few of these throughout the book to shorten our tests.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/11_dependencies`

View file

@ -40,6 +40,3 @@ In the case of `thiserror`, we have:
- `#[error("{0}")]`: this is the syntax to define a `Display` implementation for each variant of the custom error type. - `#[error("{0}")]`: this is the syntax to define a `Display` implementation for each variant of the custom error type.
`{0}` is replaced by the zero-th field of the variant (`String`, in this case) when the error is displayed. `{0}` is replaced by the zero-th field of the variant (`String`, in this case) when the error is displayed.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/12_thiserror`

View file

@ -39,6 +39,3 @@ being attempted.
Just like `From` and `Into`, `TryFrom` and `TryInto` are dual traits.\ Just like `From` and `Into`, `TryFrom` and `TryInto` are dual traits.\
If you implement `TryFrom` for a type, you get `TryInto` for free. If you implement `TryFrom` for a type, you get `TryInto` for free.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/13_try_from`

View file

@ -149,6 +149,3 @@ You can use the `?` operator to shorten your error handling code significantly.\
In particular, the `?` operator will automatically convert the error type of the fallible operation into the error type In particular, the `?` operator will automatically convert the error type of the fallible operation into the error type
of the function, if a conversion is possible (i.e. if there is a suitable `From` implementation) of the function, if a conversion is possible (i.e. if there is a suitable `From` implementation)
## References
- The exercise for this section is located in `exercises/05_ticket_v2/14_source`

View file

@ -12,10 +12,6 @@ as long as they have a `TicketTitle`, they know it's valid **by construction**.
This is just an example of how you can use Rust's type system to make your code safer and more expressive. This is just an example of how you can use Rust's type system to make your code safer and more expressive.
## References
- The exercise for this section is located in `exercises/05_ticket_v2/15_outro`
## Further reading ## Further reading
- [Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) - [Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)

View file

@ -77,8 +77,5 @@ You can think of `'_` as a **placeholder** for the lifetime of the `&self` refer
See the [References](#references) section for a link to the official documentation on lifetime elision.\ See the [References](#references) section for a link to the official documentation on lifetime elision.\
In most cases, you can rely on the compiler telling you when you need to add explicit lifetime annotations. In most cases, you can rely on the compiler telling you when you need to add explicit lifetime annotations.
## References
- [std::vec::Vec::iter](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter)
- [std::slice::Iter](https://doc.rust-lang.org/std/slice/struct.Iter.html) - [std::slice::Iter](https://doc.rust-lang.org/std/slice/struct.Iter.html)
- [Lifetime elision rules](https://doc.rust-lang.org/reference/lifetime-elision.html) - [Lifetime elision rules](https://doc.rust-lang.org/reference/lifetime-elision.html)

View file

@ -0,0 +1,11 @@
[package]
name = "mdbook-exercise-linker"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.86"
clap = "4.5.4"
mdbook = "0.4.40"
semver = "1.0.23"
serde_json = "1.0.117"

View file

@ -0,0 +1,72 @@
use anyhow::{Context, Error};
use mdbook::book::Book;
use mdbook::preprocess::{Preprocessor, PreprocessorContext};
use mdbook::BookItem;
/// A no-op preprocessor.
pub struct ExerciseLinker;
impl ExerciseLinker {
pub fn new() -> ExerciseLinker {
ExerciseLinker
}
}
impl Preprocessor for ExerciseLinker {
fn name(&self) -> &str {
"exercise-linker"
}
fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book, Error> {
let config = ctx
.config
.get_preprocessor(self.name())
.context("Failed to get preprocessor configuration")?;
let key = String::from("exercise_root_url");
let root_url = config
.get(&key)
.context("Failed to get `exercise_root_url`")?;
let root_url = root_url
.as_str()
.context("`exercise_root_url` is not a string")?
.to_owned();
book.sections
.iter_mut()
.for_each(|i| process_book_item(i, &root_url));
Ok(book)
}
fn supports_renderer(&self, _renderer: &str) -> bool {
true
}
}
fn process_book_item(item: &mut BookItem, root_url: &str) {
match item {
BookItem::Chapter(chapter) => {
chapter.sub_items.iter_mut().for_each(|item| {
process_book_item(item, root_url);
});
let Some(source_path) = &chapter.source_path else {
return;
};
let source_path = source_path.display().to_string();
// Ignore non-exercise chapters
if !source_path.chars().take(2).all(|c| c.is_digit(10)) {
return;
}
let exercise_path = source_path.strip_suffix(".md").unwrap();
let link_section = format!(
"\n## Exercise\n\nThe exercise for this section is located in [`{exercise_path}`]({})",
format!("{}/{}", root_url, exercise_path)
);
chapter.content.push_str(&link_section);
}
BookItem::Separator => {}
BookItem::PartTitle(_) => {}
}
}

View file

@ -0,0 +1,67 @@
use std::io;
use std::process;
use clap::{Arg, ArgMatches, Command};
use mdbook::errors::Error;
use mdbook::preprocess::{CmdPreprocessor, Preprocessor};
use semver::{Version, VersionReq};
use mdbook_exercise_linker::ExerciseLinker;
pub fn make_app() -> Command {
Command::new("exercise-linker").subcommand(
Command::new("supports")
.arg(Arg::new("renderer").required(true))
.about("Check whether a renderer is supported by this preprocessor"),
)
}
fn main() {
let matches = make_app().get_matches();
// Users will want to construct their own preprocessor here
let preprocessor = ExerciseLinker::new();
if let Some(sub_args) = matches.subcommand_matches("supports") {
handle_supports(&preprocessor, sub_args);
} else if let Err(e) = handle_preprocessing(&preprocessor) {
eprintln!("{}", e);
process::exit(1);
}
}
fn handle_preprocessing(pre: &dyn Preprocessor) -> Result<(), Error> {
let (ctx, book) = CmdPreprocessor::parse_input(io::stdin())?;
let book_version = Version::parse(&ctx.mdbook_version)?;
let version_req = VersionReq::parse(mdbook::MDBOOK_VERSION)?;
if !version_req.matches(&book_version) {
eprintln!(
"Warning: The {} plugin was built against version {} of mdbook, \
but we're being called from version {}",
pre.name(),
mdbook::MDBOOK_VERSION,
ctx.mdbook_version
);
}
let processed_book = pre.run(&ctx, book)?;
serde_json::to_writer(io::stdout(), &processed_book)?;
Ok(())
}
fn handle_supports(pre: &dyn Preprocessor, sub_args: &ArgMatches) -> ! {
let renderer = sub_args
.get_one::<String>("renderer")
.expect("Required argument");
let supported = pre.supports_renderer(renderer);
// Signal whether the renderer is supported by exiting with 1 or 0.
if supported {
process::exit(0);
} else {
process::exit(1);
}
}