Rust Programming Cookbook
eBook - ePub

Rust Programming Cookbook

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

Claus Matzinger

Compartir libro
  1. 444 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Rust Programming Cookbook

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

Claus Matzinger

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Rust Programming Cookbook un PDF/ePUB en línea?
Sí, puedes acceder a Rust Programming Cookbook de Claus Matzinger en formato PDF o ePUB, así como a otros libros populares de Computer Science y Systems Architecture. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2019
ISBN
9781789531749
Edición
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...

Índice