Rust Programming Cookbook
eBook - ePub

Rust Programming Cookbook

Explore the latest features of Rust 2018 for building fast and secure apps

  1. 444 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Rust Programming Cookbook

Explore the latest features of Rust 2018 for building fast and secure apps

About this book

Practical solutions to overcome challenges in creating console and web applications and working with systems-level and embedded code, network programming, deep neural networks, and much more.

Key Features

  • Work through recipes featuring advanced concepts such as concurrency, unsafe code, and macros to migrate your codebase to the Rust programming language
  • Learn how to run machine learning models with Rust
  • Explore error handling, macros, and modularization to write maintainable code

Book Description

Rust 2018, Rust's first major milestone since version 1.0, brings more advancement in the Rust language. The Rust Programming Cookbook is a practical guide to help you overcome challenges when writing Rust code.

This Rust book covers recipes for configuring Rust for different environments and architectural designs, and provides solutions to practical problems. It will also take you through Rust's core concepts, enabling you to create efficient, high-performance applications that use features such as zero-cost abstractions and improved memory management. As you progress, you'll delve into more advanced topics, including channels and actors, for building scalable, production-grade applications, and even get to grips with error handling, macros, and modularization to write maintainable code. You will then learn how to overcome common roadblocks when using Rust for systems programming, IoT, web development, and network programming. Finally, you'll discover what Rust 2018 has to offer for embedded programmers.

By the end of the book, you'll have learned how to build fast and safe applications and services using Rust.

What you will learn

  • Understand how Rust provides unique solutions to solve system programming language problems
  • Grasp the core concepts of Rust to develop fast and safe applications
  • Explore the possibility of integrating Rust units into existing applications for improved efficiency
  • Discover how to achieve better parallelism and security with Rust
  • Write Python extensions in Rust
  • Compile external assembly files and use the Foreign Function Interface (FFI)
  • Build web applications and services using Rust for high performance

Who this book is for

The Rust cookbook is for software developers looking to enhance their knowledge of Rust and leverage its features using modern programming practices. Familiarity with Rust language is expected to get the most out of this book.

Trusted by 375,005 students

Access to over 1.5 million titles for a fair monthly price.

Study more efficiently using our study tools.

Information

Year
2019
Print ISBN
9781789530667
eBook ISBN
9781789531749

Getting Practical with Rust

Even after nine chapters of Rust, we are still missing the parts that make applications pleasant to use. Many crates within Rust's ecosystem provide important functions across different domains and, depending on the application type, you might need several additional crates. In this chapter, we will look at various parts within Rust's standard library and public crate repository to make our application development faster, easier, and—in general—more productive. Although this chapter has a strong focus on command-line applications, we think that many of the recipes are just as applicable for other types, such as web servers or shared utility libraries. You can look forward to learning how to create usable Rust programs that integrate well with the OS and behave in ways that users know and expect. On top of that, we added a recipe for machine learning enthusiasts who are looking to use Rust for their work.
Here is the full list of what we will cover:
  • Random number generation
  • File I/O
  • Dynamic JSON
  • Regular expressions
  • Filesystem access
  • Command-line arguments
  • Piping input and output
  • Web requests
  • Using state-of-the-art machine learning libraries
  • Logging
  • Starting subprocesses

Generating random numbers

Random number generation is a fundamental technology that we use daily—encryption, simulation, approximation, testing, data selection, and more. Each of these applications has its own requirements for the random number generator (https://xkcd.com/221/). While encryption needs a generator that is as close to true randomness (https://www.random.org/) as possible, simulation, testing, and data selection may need to have reproducible samples drawn from a certain distribution.
Due to printing constraints we had to replace the original emoji with characters and numbers. Check out the GitHub repository for this book for the full version.
Since there is no random generator in Rust's standard library, the rand crate is the way to go for many projects. Let's see how we can use it.

How to do it...

We can obtain randomness in just a few steps:
  1. Open a Terminal to create a new project using cargo new random-numbers --lib. Use VS Code to open the project directory.
  2. First, we need to add the rand crate as a dependency in Cargo.toml. Open it to add the following:
[dependencies]
rand = {version = "0.7", features = ["small_rng"]}
rand_distr = "0.2"
rand_pcg = "0.2"
  1. Since we are exploring how to use the rand library, we are going to add to the test module and implement three tests. Let's start by replacing the default content in src/lib.rs with some required imports:
#[cfg(test)]
mod tests {
use rand::prelude::*;
use rand::SeedableRng;
use rand_distr::{Bernoulli, Distribution, Normal, Uniform};
}
  1. Right underneath the imports (inside the mod tests scope), we are going to add the first test to check how Random Number Generators (RNGs) and Pseudo-Random Number Generators (PRNGs) work. To have predictable random numbers, we make every generator based on the first, which uses an array literal for initialization:
 #[test]
fn test_rngs() {
let mut rng: StdRng = SeedableRng::from_seed([42;32]);
assert_eq!(rng.gen::<u8>(), 152);

let mut small_rng = SmallRng::from_rng(&mut rng).unwrap();
assert_eq!(small_rng.gen::<u8>(), 174);

let mut pcg = rand_pcg::Pcg32::from_rng(&mut rng).unwrap();
assert_eq!(pcg.gen::<u8>(), 135);
}
  1. Having seen regular (P)RNGs, we can move on to something more sophisticated. How about using these RNGs to operate on sequences? Let's add this test that uses PRNGs to do a shuffle and pick results:
 #[test]
fn test_sequences() {
let mut rng: StdRng = SeedableRng::from_seed([42;32]);

let emoji = "ABCDEF".chars();
let chosen_one = emoji.clone().choose(&mut rng).unwrap();
assert_eq!(chosen_one, 'B');

let chosen = emoji.choose_multiple(&mut rng, 3);
assert_eq!(chosen, ['F', 'B', 'E']);

let mut three_wise_monkeys = vec!['1', '2', '3'];
three_wise_monkeys.shuffle(&mut rng);
three_wise_monkeys.shuffle(&mut rng);
assert_eq!(three_wise_monkeys, ['1', '3', '2']);

let mut three_wise_monkeys = vec!['1', '2', '3'];
let partial = three_wise_monkeys.partial_shuffle(&mut rng, 2);
assert_eq!(partial.0, ['3', '2']);
}
  1. As we stated in this recipe's introduction, RNGs can follow a distribution. Now, let's add another test to the tests module to draw random numbers that follow a distribution using the rand crate:
 const SAMPLES: usize = 10_000;

#[test]
fn test_distributions() {
let mut rng: StdRng = SeedableRng::from_seed([42;32]);

let uniform = Uniform::new_inclusive(1, 100);
let total_uniform: u32 = uniform.sample_iter(&mut rng)
.take(SAMPLES).sum();
assert!((50.0 - (total_uniform as f32 / (
SAMPLES as f32)).round()).abs() <= 2.0);

let bernoulli = Bernoulli::new(0.8).unwrap();
let total_bernoulli: usize = bernoulli
.sample_iter(&mut rng)
.take(SAMPLES)
.filter(|s| *s)
.count();

assert_eq!(
((total_bernoulli as f32 / SAMPLES as f32) * 10.0)
.round()
.trunc(),
8.0
);

let normal = Normal::new(2.0, 0.5).unwrap();
let total_normal: f32 = normal.sample_iter(&mut rng)
.take(SAMPLES).sum();
assert_eq!((total_normal / (SAMPLES as f32)).round(), 2.0);
}
  1. Lastly, we can run the tests to see whether the test outputs positive results:
$ cargo test
Compiling random-numbers v0.1.0 (Rust-Cookbook/Chapter10/random-numbers)
Finished dev [unoptimized + debuginfo] target(s) in 0.56s
Running target/debug/deps/random_numbers-df3e1bbb371b7353

running 3 tests
test tests::test_sequences ... ok
test tests::test_rngs ... ok
test tests::test_distributions ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Doc-tests random-numbers

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Let's see how it's done behind the scenes.

How it works...

The rand crate has lived through several major version revisions since 2018 and several things have changed. In particular, the crate is now organized differently (https://rust-random.github.io/book/guide-gen.html), with several companion crates that contain implementations for lesser-used parts.
This is why, in step 2, we don't only import a single crate, even though they all share a single GitHub repository (https://github.com/rust-random/rand). The reason for this split was presumably to be compatible with the different requirements across the field.
RNGs represent—in short—a numeric sequence that is determined on the fly based on its predecessor. What is the first number though? It's called the seed and can be some literal (for reproducibility in tests) or as close to true randomness as possible (when not testing).

Popular seeds include seconds since 1 Jan 1970, entropy by the OS, user input, and more. The less predictable it is, the better.
In step 3, we set up the remaining code with some imports that we are using right away in step 4. There, we get into using different types of RNGs (https://rust-random.github.io/book/guide-rngs.html). The first is rand crate's StdRng, which is an abstraction over (as of this writing) the ChaCha PRNG (https://docs.rs/rand/0.7.0/rand/rngs/struct.StdRng.html), chosen for efficiency and cryptographic security. The second algorithm is SmallRng (https://docs.rs/rand/0.7.0/rand/rngs/struct.SmallRng.html), a PRNG chosen by the rand team that has great throughput and resource efficiency. However, since it is fairly easy to predict, the use cases have to be chosen carefully. The last algorithm (Pcg32) is a pick from the list of available PRNGs (https://rust-random.github.io/book/guide-rngs.html), which comes as part of a different crate.
In step 5, we work with sequences and choose from or shuffle through them. Functions include partial shuffling (that is, picking a random subset) and full, in-place shuffles, as wel...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. About Packt
  5. Foreword
  6. Contributors
  7. Preface
  8. Starting Off with Rust
  9. Going Further with Advanced Rust
  10. Managing Projects with Cargo
  11. Fearless Concurrency
  12. Handling Errors and Other Results
  13. Expressing Yourself with Macros
  14. Integrating Rust with Other Languages
  15. Safe Programming for the Web
  16. Systems Programming Made Easy
  17. Getting Practical with Rust
  18. Other Books You May Enjoy

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.5M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1.5 million books across 990+ topics, we’ve got you covered! Learn about our mission
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access Rust Programming Cookbook by Claus Matzinger in PDF and/or ePUB format, as well as other popular books in Informatica & Programmazione in C++. We have over 1.5 million books available in our catalogue for you to explore.