Rust Programming Cookbook
eBook - ePub

Rust Programming Cookbook

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

Claus Matzinger

Partager le livre
  1. 444 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Rust Programming Cookbook

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

Claus Matzinger

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Rust Programming Cookbook est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Rust Programming Cookbook par Claus Matzinger en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Systems Architecture. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2019
ISBN
9781789531749
Édition
1

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 des matiĂšres