Source code for the book Rust in Action

Overview

Welcome to Rust in Action source code

This source code repository is a companion to the Rust in Action book available from Manning Publications.

Supporting the book

Most book sales are generated on the basis of trusted referrals and recommendations. Please add your rating or review on Goodreads, Amazon or perhaps even your own blog.

If you haven't got it yet, here are some links so that you can buy Rust in Action for yourself:

Providing feedback

The issue tracker is open, and is useful for minor bug reports.

Please use https://livebook.manning.com/books/rust-in-action to submit issues for anything larger, especially if you want to discuss the book's text rather than a specific line of code. That way you can communicate with a community of thousands of other readers.

Contact the author

You are very welcome to contact me at any stage! The best channel is Twitter and my email address is available on my website. I'm also active on Reddit, LinkedIn and the Rust user forum and the discord servers for Rust.

Comments
  • Cannot run ch1-time-api

    Cannot run ch1-time-api

    error: failed to select a version for the requirement `ring = "^0.11.0"`
      candidate versions found which didn't match: 0.16.11, 0.16.10, 0.16.9, ...
      location searched: crates.io index
    required by package `cookie v0.9.1`
        ... which is depended on by `rocket v0.3.0`
        ... which is depended on by `ch1-time-api v0.1.0
    
    opened by akolybelnikov 9
  • ch 1 - penguins - unknown character escape

    ch 1 - penguins - unknown character escape

    I'm not really sure how to fix it, but it won't compile. Listing 1.2 on page 9.

    I tried updating rust, etc but nothing changed

    Screen Shot 2021-07-31 at 11 01 16 PM

    Screen Shot 2021-07-31 at 10 58 48 PM

    Obviously I'm at the start of the book so can't offer much help, but if I figure out the solution I'll leave a reply here.

    opened by KevinBatdorf 4
  • ch2-mandelbrot doesn't compile

    ch2-mandelbrot doesn't compile

    all_rows doesn't exist in this scope: https://github.com/rust-in-action/code/blob/7d7955e9605ca156f6eb7cb5bc9f124c97927d25/ch2/ch2-mandelbrot/src/main.rs#L28

    opened by ropewalker 4
  • WIP - ActionKV Index Maintenance - maybe bug

    WIP - ActionKV Index Maintenance - maybe bug

    Hey - want to start out by saying thank again for the great book!

    The insert_but_ignore_index code appears incorrect to me. If the underlying file is pointing at position in_the_middle when insert is called, the KV will be correctly appended at the end of the file, but the index will say the KV is at position in_the_middle

    https://github.com/rust-in-action/code/blob/e23c70ec1cb9e9b9037f364b8edfa6ee882e8f77/ch7/ch7-actionkv2/src/lib.rs#L174-L182

    I wrote test_index_maintenance to confirm my suspicion, expecting it to fail. But the test passes!

    To understand what was happening, I altered get_at to print out the file' position after performing the read - and then the test fails!

        pub fn get_at(&mut self, position: u64) -> io::Result<KeyValuePair> {
            let mut f = BufReader::new(&mut self.f);
            f.seek(SeekFrom::Start(position))?;
            let kv = ActionKV::process_record(&mut f)?;
    
            // Even though `f.seek` does take `&mut self`, my understanding is calling it
            // with `SeekFrom::Current(0)` simply says "where am I at in the stream" without
            // altering anything. In fact there's even a convenience function that claims
            // exactly this: https://doc.rust-lang.org/std/io/trait.Seek.html#method.stream_position
            //
            // However, commenting these two lines makes `test_index_maintenance` pass
            let final_pos = f.seek(SeekFrom::Current(0))?;
            println!("after reading at {}, final_pos is {}", position, final_pos);
            Ok(kv)
        }
    

    So now there's at least these few options on what's going on.

    1. .seek(SeekFrom::Current(0)) is not actually a functional no-op, and calling it breaks the system in some expected way. i.e. what I thought looked like a bug in .insert isn't a bug.
    2. There is a bug in .insert and for some magic the .seek(SeekFrom::Current(0)) sheds light on it. (Maybe something due to the extra buffer flush?
    3. .seek(SeekFrom::Current(0)) is intended to be a no-op, but there is a bug in it that this case triggered.

    I'd assume 1 is by far the most likely, followed by 2 and then 3 a long way off.

    Either way hope this helps and interested to hear what the answer is!

    (Related: #4 since it also mentions the in memory index)

    opened by Michael-J-Ward 4
  • Your definition of NTP offset is wrong

    Your definition of NTP offset is wrong

    Hi, thanks for the book and the much helping source code. I think I found a problem here: https://github.com/rust-in-action/code/blob/cff02d525ac50a1aa16dafba9780da66fc6d6661/ch9/ch9-clock3/src/main.rs#L41-L44 Per the definition in https://en.wikipedia.org/wiki/Network_Time_Protocol your code should be let offset = (self.t2 - self.t1) + (self.t3 - self.t4);

    Both this code and the book wording threw me off balance enough to check the wikipedia article, as your code doesn't have any difference between delta and theta, except for the 2 factor. their fixed definitions makes much more sense.

    opened by 8thMage 3
  • ch2-mandelbrot renders whitespaces

    ch2-mandelbrot renders whitespaces

    https://github.com/rust-in-action/code/blob/7d7955e9605ca156f6eb7cb5bc9f124c97927d25/ch2/ch2-mandelbrot/src/main.rs#L73-L74

    This should be calculate_mandelbrot(1000, -2.0, 1.0, -1.0, 1.0, 80, 24) as mentioned in https://www.reddit.com/r/rust/comments/o980ip/rust_in_action_is_released/h3aktuf

    opened by ropewalker 3
  • Ch11 build code is incomplete and not updated

    Ch11 build code is incomplete and not updated

    I wasn't able to run the basic starting example. The shown configuration and tools are both incomplete and not updated. When trying to build using bootimage, the command is now different (cargo bootimage) and in particular there was an error about not being able to find the crate core.

    It's thus incomplete because cargo-xbuild is installed but not actually used. Fortunately, I knew there was another tutorial on writing a kernel with Rust where I found the updated information: https://os.phil-opp.com/minimal-rust-kernel/

    Basically, with Rust nightly 2020–07–15, we can now just simply write this in .cargo/config.toml:

    [unstable]
    build-std = ["core", "compiler_builtins", "alloc"]
    

    Also this is much better because I was also able, with the latest version which fixed a bug with the nightly toolchain, to continue using rust-analyzer in vscode. OTOH, you are left with no intellisense with cargo-xbuild.

    I hope this info will be helpful for someone, you can see the source code of the chapter with updated configuration at https://github.com/jiayihu/lab/tree/master/rust/fledge-os

    opened by jiayihu 3
  • Code uses pre rust-2018 conventions

    Code uses pre rust-2018 conventions

    The code seems to use pre rust-2018 conventions. For example in the first chapter the code:

    extern crate serde_derive;   // <3>
    ...
    #[derive(Serialize)] // <6> Automatically generate a string representation of this struct (which will be used as JSON)
    struct Timestamp { // <7> Syntax to create a custom type 
    

    Can be re-written as

    use serde::Serialize;
    ...
    #[derive(Serialize)] // <6> Automatically generate a string representation of this struct (which will be used as JSON)
    struct Timestamp { // <7> Syntax to create a custom type 
    
    opened by SillyMoo 3
  • ch2-complex - use of unstable library feature 'dec2flt': internal routines only exposed for testing

    ch2-complex - use of unstable library feature 'dec2flt': internal routines only exposed for testing

    I am new to Rust but when I run the chapter 2-complex example codes, then there is an error like below.

    error[E0658]: use of unstable library feature 'dec2flt': internal routines only exposed for testing
     --> src/main.rs:1:5
      |
    1 | use core::num::dec2flt::number;
      |     ^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    Rust & Cargo version

    • 1.62.0
    opened by ryukato 2
  • build(deps): bump smallvec from 0.6.9 to 0.6.14 in /ch8/ch8-simple

    build(deps): bump smallvec from 0.6.9 to 0.6.14 in /ch8/ch8-simple

    Bumps smallvec from 0.6.9 to 0.6.14.

    Release notes

    Sourced from smallvec's releases.

    v0.6.14

    • Fix a possible buffer overflow in insert_many (#252, #254).

    v0.6.13

    • Use the maybe-unit crate in place of soon-to-be-deprecated std::mem::uninitialized (#180). When built with Rust 1.36 or later, this fixes a source of undefined behavior. It also fixes deprecation warnings in Rust 1.39 and later, and test failures when run in MIRI. In Rust 1.35 and earlier it provides some safety improvements but does not completely eliminate undefined behavior. (However, we are not aware of any cases where the undefined behavior causes bugs in practice in those toolchains.)

    v0.6.12

    • Move code using default fn into its own module (#161).

    v0.6.11

    • The unstable alloc feature is no longer needed. This crate can now build with the std feature disabled on stable Rust 1.36 or later (#159).

    v0.6.10

    • Fix a bug in extend with certain iterators (#150).
    • Fix soundness bugs in the grow method (#151, #152).
    • Fix typo in docs (#144).
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 2
  • Ch8: Mget unresolved import

    Ch8: Mget unresolved import

    I try to build mget on rust v1.60 on mac and the build fails because of:

    ➜  ch8-mget git:(1st-edition) ✗ cargo build
       Compiling mget v0.1.0 (/Users/adria/Programming/rust-in-action/ch8/ch8-mget)
    error[E0432]: unresolved import `smoltcp::phy::TapInterface`
     --> src/main.rs:2:5
      |
    2 | use smoltcp::phy::TapInterface;
      |     ^^^^^^^^^^^^^^^^^^^^^^^^^^ no `TapInterface` in `phy`
    
    error[E0432]: unresolved import `smoltcp::phy::TapInterface`
     --> src/http.rs:7:38
      |
    7 | use smoltcp::phy::{wait as phy_wait, TapInterface};
      |                                      ^^^^^^^^^^^^ no `TapInterface` in `phy` 
    

    I also had to modify Cargo.toml because curly bracket content cannot be separated over several lines.

    In my IDE, I can however see that TapInterface exists. Any idea?

    opened by elchead 2
  • ch6/ch6-particles does not compile on MacOS with `zsh: illegal hardware instruction  cargo run`

    ch6/ch6-particles does not compile on MacOS with `zsh: illegal hardware instruction cargo run`

    OS: MacOS

    When in the root ch6-particles crate created with cargo, the following error is generated:

    zsh: illegal hardware instruction  cargo run
    

    Oddly, the programs behaves as expected (well, without the standard output) when commenting out the eprintln! line.

    From my findings so far this appears to an OS specific issue and any suggestions would be much appreciated!

    opened by Nsandomeno 2
  • Chapter 10, 10.18, ch10-render-hex, Mac OS X

    Chapter 10, 10.18, ch10-render-hex, Mac OS X

    The book has the following input for the ch10-render-hex project

    $ cargo run -- $(
    >   echo 'Rust in Action' |
    >   sha1sum |
    >   cut -f1 -d' '
    > )
    

    However on Mac OS X, the tool is shasum and not sha1sum, and works great with the following input

    $ cargo run -- $(
    >   echo 'Rust in Action' |
    >   shasum |
    >   cut -f1 -d' '
    > )
    

    Just thought I should share for the author or anyone else searching for why they're getting "Opps, all Noops!" in their cereal box.

    Very cool project, and great book. Thanks!

    opened by zanayr 0
  • ch11-fledgeos-0 not building. Fix provided. Error: feature(const_fn) has been removed

    ch11-fledgeos-0 not building. Fix provided. Error: feature(const_fn) has been removed

    image

    Errors:

    1. feature = "const_fn", feature(const_fn) has been removed
    2. cannot find macro asm in this scope

    Steps to fix:

    1. Clear the cargo cache so that the old dependencies are not picked up (can use this cargo-cache crate, or google this up).
    2. Update the following packages to the new versions as specified below.
    [dependencies]
    bootloader = "0.9.22"
    x86_64 = "0.14.10"
    
    1. Code should build and run as expected.
    opened by AtulJatia 0
  • NTP offset definition in book and source code is incorrect

    NTP offset definition in book and source code is incorrect

    In https://github.com/rust-in-action/code/blob/1st-edition/ch9/ch9-clock3/src/main.rs#L40-L50:

    impl NTPResult {
      fn offset(&self) -> i64 {
        let delta = self.delay();
        delta.abs() / 2
      }
    
      fn delay(&self) -> i64 {
        let duration = (self.t4 - self.t1) - (self.t3 - self.t2);
        duration.num_milliseconds()
      }
    }
    

    The definition of offset is incorrect (source on Wikipedia). Offset can be positive or negative, whereas delay is always positive. You can see that the equations above always return positive values.

    Offset should let delta = (self.t2 - self.t1) - (self.t3 - self.t4);. Currently, it rearranges to let delta = (self.t2 - self.t1) - (self.t4 - self.t3);, i.e. the last two terms are swapped.

    (I see there was an attempt to correct in #51, but as the OP later noted, the PR did not fix the issue.)

    opened by GabrielBianconi 0
Code to follow along the "Zero To Production" book on API development in Rust.

Zero To Production / Code (Chapter 10 - Part 1) Zero To Production In Rust is an opinionated introduction to backend development using Rust. This repo

Luca Palmieri 2.8k Dec 31, 2022
Rust crate to implement a counterpart to the PBRT book's (3rd edition) C++ code.

Rust crate to implement a counterpart to the PBRT book's (3rd edition) C++ code.

Jan Walter 763 Dec 27, 2022
Complete code for the larger example programs from the book.

Code Examples for Programming Rust This repository contains complete code for the larger example programs from the book “Programming Rust”, by Jim Bla

Programming Rust 670 Jan 1, 2023
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
clone of grep cli written in Rust. From Chapter 12 of the Rust Programming Language book

minigrep is a clone of the grep cli in rust Minigrep will find a query string in a file. To test it out, clone the project and run cargo run body poem

Raunak Singh 1 Dec 14, 2021
The ray tracer challenge in rust - Repository to follow my development of "The Raytracer Challenge" book by Jamis Buck in the language Rust

The Ray Tracer Challenge This repository contains all the code written, while step by implementing Ray Tracer, based on the book "The Ray Tracer Chall

Jakob Westhoff 54 Dec 25, 2022
A minimal version of 'grep' implemented in Rust. Exercise in the "The Rust Programming Language" book.

Minigrep - A simple grep-like tool implemented in Rust This simple CLI tool searches for a given pattern in a specified file and as a result, it print

Filip Szutkowski 3 Mar 15, 2024
High Assurance Rust - A free book about developing secure and robust systems software.

High Assurance Rust - A free book about developing secure and robust systems software.

Tiemoko Ballo 1.1k Jan 9, 2023
Learn programming with Rust as a first language (book)

Learn programming with Rust as first language This is a book to learn programming from scratch. Read the book here: https://deavid.github.io/lprfl/ LI

David Martínez Martí 2 May 21, 2022
Search and read 'The Rust Book' from the terminal

TheBook TheBook is a command line utility that allows you to SEARCH and READ The Rust Programming Language (popularly known as 'The Book' ) from the t

0xHiro 技術者 239 Jan 4, 2023
Elemental System Designs is an open source project to document system architecture design of popular apps and open source projects that we want to study

Elemental System Designs is an open source project to document system architecture design of popular apps and open source projects that we want to study

Jason Shin 9 Apr 10, 2022
Book - Actix user guides

User guides Actix User Guide Actix API Documentation (Development) Actix API Documentation (Releases) Actix Web User Guide Actix Web API Documentation

Actix 185 Dec 25, 2022
Majestic Lisp book and implementation, in Brazillian Portuguese.

Majestic Lisp Criado e desenvolvido por Lucas S. Vieira <lucasvieira at protonmail dot com>. Seja bem-vindo(a) a Majestic Lisp, um dialeto de Lisp cuj

Lucas Vieira 3 Oct 26, 2022
Generate SUMMARY.md files based on your book's file structure

mdbook-autosummary Generate a SUMMARY.md for your mdBook based on your folder structure! Warning The implementation is hacky and has several limitatio

Hyper 3 Sep 30, 2023
The source code that accompanies Hands-on Rust: Effective Learning through 2D Game Development and Play by Herbert Wolverson

Hands-on Rust Source Code This repository contains the source code for the examples found in Hands-on Rust. These are also available from my publisher

Herbert 261 Dec 14, 2022
This repository contains the Rust source code for the algorithms in the textbook Algorithms, 4th Edition

Overview This repository contains the Rust source code for the algorithms in the textbook Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.

chuan 549 Dec 26, 2022
Source code of Ferrocene, safety-critical Rust toolchain

Ferrocene is a toolchain to enable the use of the Rust programming language in safety-critical environments. It is a proper downstream of the main Rus

Ferrocene 530 Oct 7, 2023
Source code from Atlas, our 64k demo presented at Revision 2019 with Macau Exports

Atlas source code dump This is a dump of the source code for the engine, graphics tool and player for Atlas, our 64k demo released with Macau Exports

Monad 65 Jan 2, 2023
Tool to convert variable and function names in C/C++ source code to snake_case

FixNameCase Tool to convert variable and function names in C/C++ source code to snake_case. Hidden files and files listed in .gitignore are untouched.

AgriConnect 4 May 25, 2023