Skip to content

Commit 7c537ee

Browse files
committed
deploy: c9b89df
1 parent e792cf1 commit 7c537ee

36 files changed

+2284
-1902
lines changed

about.html

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,9 @@ <h2 id="how-to-use-the-recipes"><a class="header" href="#how-to-use-the-recipes"
207207
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
208208

209209
fn main() {
210-
let mut rng = rand::thread_rng();
211-
println!("Random f64: {}", rng.gen::&lt;f64&gt;());
210+
let mut rng = rand::rng();
211+
let random_number: u32 = rng.random();
212+
println!("Random number: {}", random_number);
212213
}</code></pre></pre>
213214
<p>To work with it locally we can run the following commands to create
214215
a new cargo project, and change to that directory:</p>
@@ -231,13 +232,14 @@ <h2 id="how-to-use-the-recipes"><a class="header" href="#how-to-use-the-recipes"
231232
should read after deciding which crate suites your purpose.</p>
232233
<h2 id="a-note-about-error-handling"><a class="header" href="#a-note-about-error-handling">A note about error handling</a></h2>
233234
<p>Rust has <a href="https://doc.rust-lang.org/std/error/trait.Error.html"><code>std::error::Trait</code></a> which is implemented to handle exceptions.
234-
Handling multiple types of these traits can be simplified using <a href="https://docs.rs/anyhow/latest/anyhow/"><code>anyhow</code></a>
235-
or specified with an <code>enum</code> which macros exist to make this easier within
236-
<a href="https://docs.rs/thiserror/latest/thiserror/"><code>thiserror</code></a> for library authors.</p>
237-
<p>Error chain has been shown in this book for historical reasons before Rust
238-
<code>std</code> and crates represented macro use as a preference. For more background
239-
on error handling in Rust, read <a href="https://doc.rust-lang.org/book/ch09-00-error-handling.html">this page of the Rust book</a>
240-
and <a href="https://brson.github.io/2016/11/30/starting-with-error-chain">this blog post</a>.</p>
235+
This cookbook uses <a href="https://docs.rs/anyhow/latest/anyhow/"><code>anyhow</code></a> for simplified error handling in examples,
236+
which provides easy error propagation and context. For library authors,
237+
<a href="https://docs.rs/thiserror/latest/thiserror/"><code>thiserror</code></a> provides a more structured approach using derive macros
238+
to create custom error types.</p>
239+
<p>This cookbook previously used the <code>error-chain</code> crate, but has been updated
240+
to use <code>anyhow</code> as it's now the preferred approach for application-level
241+
error handling. For more background on error handling in Rust, read
242+
<a href="https://doc.rust-lang.org/book/ch09-00-error-handling.html">this page of the Rust book</a> and <a href="https://brson.github.io/2016/11/30/starting-with-error-chain">this blog post</a>.</p>
241243
<h2 id="a-note-about-crate-representation"><a class="header" href="#a-note-about-crate-representation">A note about crate representation</a></h2>
242244
<p>This cookbook is intended eventually to provide expansive coverage of
243245
the Rust crate ecosystem, but today is limited in scope while we get

algorithms/randomness.html

Lines changed: 57 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -163,42 +163,37 @@ <h1 id="generate-random-values"><a class="header" href="#generate-random-values"
163163
<h2 id="generate-random-numbers"><a class="header" href="#generate-random-numbers">Generate random numbers</a></h2>
164164
<p><a href="https://docs.rs/rand/"><img src="https://badge-cache.kominick.com/crates/v/rand.svg?label=rand" alt="rand-badge" /></a> <a href="https://crates.io/categories/science"><img src="https://badge-cache.kominick.com/badge/science--x.svg?style=social" alt="cat-science-badge" /></a></p>
165165
<p>Generates random numbers with help of random-number
166-
generator <a href="https://docs.rs/rand/*/rand/trait.Rng.html"><code>rand::Rng</code></a> obtained via <a href="https://docs.rs/rand/*/rand/trait.Rng.html"><code>rand::rng</code></a>. Each thread has an
166+
generator <a href="https://docs.rs/rand/0.9/rand/trait.Rng.html"><code>rand::Rng</code></a> obtained via <a href="https://docs.rs/rand/0.9/rand/trait.Rng.html"><code>rand::rng</code></a>. Each thread has an
167167
initialized generator. Integers are uniformly distributed over the range of the
168168
type, and floating point numbers are uniformly distributed from 0 up to but not
169169
including 1.</p>
170170
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
171171

172172
fn main() {
173-
let mut rng = rand::rng();
174-
175-
let n1: u8 = rng.random();
176-
let n2: u16 = rng.random();
177-
println!("Random u8: {}", n1);
178-
println!("Random u16: {}", n2);
179-
println!("Random u32: {}", rng.random::&lt;u32&gt;());
180-
println!("Random i32: {}", rng.random::&lt;i32&gt;());
181-
println!("Random float: {}", rng.random::&lt;f64&gt;());
173+
let mut rng = rand::thread_rng();
174+
let random_number: u32 = rng.gen();
175+
println!("Random number: {}", random_number);
182176
}</code></pre></pre>
183177
<h2 id="generate-random-numbers-within-a-range"><a class="header" href="#generate-random-numbers-within-a-range">Generate random numbers within a range</a></h2>
184178
<p><a href="https://docs.rs/rand/"><img src="https://badge-cache.kominick.com/crates/v/rand.svg?label=rand" alt="rand-badge" /></a> <a href="https://crates.io/categories/science"><img src="https://badge-cache.kominick.com/badge/science--x.svg?style=social" alt="cat-science-badge" /></a></p>
185-
<p>Generates a random value within half-open <code>[0, 10)</code> range (not including <code>10</code>) with <a href="https://doc.rust-lang.org/rand/*/rand/trait.Rng.html#method.random_range"><code>Rng::random_range</code></a>.</p>
179+
<p>Generates a random value within half-open <code>[0, 10)</code> range (not including <code>10</code>) with [<code>Rng::gen_range</code>].</p>
186180
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
187181

188182
fn main() {
189183
let mut rng = rand::rng();
190-
println!("Integer: {}", rng.random_range(0..10));
191-
println!("Float: {}", rng.random_range(0.0..10.0));
184+
println!("Integer: {}", rng.gen_range(0..10));
185+
println!("Float: {}", rng.gen_range(0.0..10.0));
192186
}</code></pre></pre>
193-
<p><a href="https://docs.rs/rand/*/rand/distributions/uniform/struct.Uniform.html"><code>Uniform</code></a> can obtain values with <a href="https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)">uniform distribution</a>.
187+
<p>[<code>Uniform</code>] can obtain values with <a href="https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)">uniform distribution</a>.
194188
This has the same effect, but may be faster when repeatedly generating numbers
195189
in the same range.</p>
196-
<pre><pre class="playground"><code class="language-rust edition2018">
197-
use rand::distributions::{Distribution, Uniform};
190+
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
191+
use rand_distr::{Distribution, Uniform};
198192

199193
fn main() {
200194
let mut rng = rand::rng();
201-
let die = Uniform::from(1..7);
195+
let die = Uniform::new_inclusive(1, 6)
196+
.expect("Failed to create uniform distribution: invalid range");
202197

203198
loop {
204199
let throw = die.sample(&amp;mut rng);
@@ -214,81 +209,92 @@ <h2 id="generate-random-numbers-with-given-distribution"><a class="header" href=
214209
<a href="https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)">uniform distribution</a>. The <a href="https://docs.rs/rand_distr/*/rand_distr/index.html"><code>rand_distr</code></a> crate provides
215210
other kinds of distributions. To use them, you instantiate
216211
a distribution, then sample from that distribution using
217-
<a href="https://docs.rs/rand/*/rand/distributions/trait.Distribution.html#tymethod.sample"><code>Distribution::sample</code></a> with help of a random-number
218-
generator <a href="https://docs.rs/rand/*/rand/trait.Rng.html"><code>rand::Rng</code></a>.</p>
212+
<a href="https://docs.rs/rand/0.9/rand/distr/trait.Distribution.html#tymethod.sample"><code>Distribution::sample</code></a> with help of a random-number
213+
generator <a href="https://docs.rs/rand/0.9/rand/trait.Rng.html"><code>rand::Rng</code></a>.</p>
219214
<p>The <a href="https://docs.rs/rand_distr/*/rand_distr/index.html">distributions available are documented here</a>.
220215
An example using the <a href="https://docs.rs/rand_distr/*/rand_distr/struct.Normal.html"><code>Normal</code></a> distribution is shown below.</p>
221-
<pre><code class="language-rust edition2018 ignore">use rand_distr::{Distribution, Normal, NormalError};
222-
use rand::rng;
216+
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
217+
use rand_distr::{Distribution, LogNormal, Normal};
218+
219+
fn main() {
220+
let mut rng = rand::rng();
221+
let normal = Normal::new(2.0, 3.0)
222+
.expect("Failed to create normal distribution");
223+
let log_normal = LogNormal::new(1.0, 0.5)
224+
.expect("Failed to create log-normal distribution");
223225

224-
fn main() -&gt; Result&lt;(), NormalError&gt; {
225-
let mut rng = rng();
226-
let normal = Normal::new(2.0, 3.0)?;
227226
let v = normal.sample(&amp;mut rng);
228227
println!("{} is from a N(2, 9) distribution", v);
229-
Ok(())
230-
}</code></pre>
228+
let v = log_normal.sample(&amp;mut rng);
229+
println!("{} is from an ln N(1, 0.25) distribution", v);
230+
}</code></pre></pre>
231231
<h2 id="generate-random-values-of-a-custom-type"><a class="header" href="#generate-random-values-of-a-custom-type">Generate random values of a custom type</a></h2>
232232
<p><a href="https://docs.rs/rand/"><img src="https://badge-cache.kominick.com/crates/v/rand.svg?label=rand" alt="rand-badge" /></a> <a href="https://crates.io/categories/science"><img src="https://badge-cache.kominick.com/badge/science--x.svg?style=social" alt="cat-science-badge" /></a></p>
233233
<p>Randomly generates a tuple <code>(i32, bool, f64)</code> and variable of user defined type <code>Point</code>.
234-
Implements the <a href="https://docs.rs/rand/*/rand/distributions/trait.Distribution.html"><code>Distribution</code></a> trait on type Point for <a href="https://docs.rs/rand/*/rand/distributions/struct.Standard.html"><code>Standard</code></a> in order to allow random generation.</p>
234+
Implements the [<code>Distribution</code>] trait on type Point for [<code>Standard</code>] in order to allow random generation.</p>
235235
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
236-
use rand::distributions::{Distribution, Standard};
237236

238237
#[derive(Debug)]
239238
struct Point {
240239
x: i32,
241240
y: i32,
242241
}
243242

244-
impl Distribution&lt;Point&gt; for Standard {
245-
fn sample&lt;R: Rng + ?Sized&gt;(&amp;self, rng: &amp;mut R) -&gt; Point {
246-
let (rand_x, rand_y) = rng.random();
243+
impl Point {
244+
fn random&lt;R: Rng&gt;(rng: &amp;mut R) -&gt; Self {
247245
Point {
248-
x: rand_x,
249-
y: rand_y,
246+
x: rng.random(),
247+
y: rng.random(),
250248
}
251249
}
252250
}
253251

254252
fn main() {
255253
let mut rng = rand::rng();
256254
let rand_tuple = rng.random::&lt;(i32, bool, f64)&gt;();
257-
let rand_point: Point = rng.random();
255+
let rand_point = Point::random(&amp;mut rng);
258256
println!("Random tuple: {:?}", rand_tuple);
259257
println!("Random Point: {:?}", rand_point);
260258
}</code></pre></pre>
261259
<h2 id="create-random-passwords-from-a-set-of-alphanumeric-characters"><a class="header" href="#create-random-passwords-from-a-set-of-alphanumeric-characters">Create random passwords from a set of alphanumeric characters</a></h2>
262260
<p><a href="https://docs.rs/rand/"><img src="https://badge-cache.kominick.com/crates/v/rand.svg?label=rand" alt="rand-badge" /></a> <a href="https://crates.io/categories/os"><img src="https://badge-cache.kominick.com/badge/OS--x.svg?style=social" alt="cat-os-badge" /></a></p>
263-
<p>Randomly generates a string of given length ASCII characters in the range <code>A-Z, a-z, 0-9</code>, with <a href="https://docs.rs/rand/*/rand/distributions/struct.Alphanumeric.html"><code>Alphanumeric</code></a> sample.</p>
264-
<pre><pre class="playground"><code class="language-rust edition2018">use rand::{rng, Rng};
265-
use rand::distributions::Alphanumeric;
261+
<p>Randomly generates a string of given length ASCII characters in the range <code>A-Z, a-z, 0-9</code>, with <a href="https://docs.rs/rand/0.9/rand/distr/struct.Alphanumeric.html"><code>Alphanumeric</code></a> sample.</p>
262+
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
266263

267264
fn main() {
268-
let rand_string: String = rng()
269-
.sample_iter(&amp;Alphanumeric)
270-
.take(30)
271-
.map(char::from)
265+
const CHARSET: &amp;[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
266+
abcdefghijklmnopqrstuvwxyz\
267+
0123456789";
268+
const PASSWORD_LEN: usize = 30;
269+
let mut rng = rand::rng();
270+
271+
let password: String = (0..PASSWORD_LEN)
272+
.map(|_| {
273+
let idx = rng.random_range(0..CHARSET.len());
274+
CHARSET[idx] as char
275+
})
272276
.collect();
273277

274-
println!("{}", rand_string);
278+
println!("{}", password);
275279
}</code></pre></pre>
276280
<h2 id="create-random-passwords-from-a-set-of-user-defined-characters"><a class="header" href="#create-random-passwords-from-a-set-of-user-defined-characters">Create random passwords from a set of user-defined characters</a></h2>
277281
<p><a href="https://docs.rs/rand/"><img src="https://badge-cache.kominick.com/crates/v/rand.svg?label=rand" alt="rand-badge" /></a> <a href="https://crates.io/categories/os"><img src="https://badge-cache.kominick.com/badge/OS--x.svg?style=social" alt="cat-os-badge" /></a></p>
278282
<p>Randomly generates a string of given length ASCII characters with custom
279-
user-defined bytestring, with <a href="https://docs.rs/rand/*/rand/trait.Rng.html#method.random_range"><code>random_range</code></a>.</p>
280-
<pre><pre class="playground"><code class="language-rust edition2018">fn main() {
281-
use rand::Rng;
282-
const CHARSET: &amp;[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
283-
abcdefghijklmnopqrstuvwxyz\
284-
0123456789)(*&amp;^%$#@!~";
285-
const PASSWORD_LEN: usize = 30;
283+
user-defined bytestring, with <a href="https://docs.rs/rand/0.9/rand/trait.Rng.html#method.gen_range"><code>gen_range</code></a>.</p>
284+
<pre><pre class="playground"><code class="language-rust edition2018">use rand::Rng;
285+
286+
const CHARSET: &amp;[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
287+
abcdefghijklmnopqrstuvwxyz\
288+
0123456789)(*&amp;^%$#@!~";
289+
const PASSWORD_LEN: usize = 30;
290+
291+
fn main() {
286292
let mut rng = rand::rng();
287293

288294
let password: String = (0..PASSWORD_LEN)
289295
.map(|_| {
290-
let idx = rng.random_range(0..CHARSET.len());
291-
CHARSET[idx] as char
296+
let idx = rng.gen_range(0..CHARSET.len());
297+
char::from(CHARSET[idx])
292298
})
293299
.collect();
294300

compression/tar.html

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,7 @@ <h2 id="decompress-a-tarball"><a class="header" href="#decompress-a-tarball">Dec
166166
extract (<a href="https://docs.rs/tar/*/tar/struct.Archive.html#method.unpack"><code>Archive::unpack</code></a>) all files from a compressed tarball
167167
named <code>archive.tar.gz</code> located in the current working directory
168168
to the same location.</p>
169-
<pre><pre class="playground"><code class="language-rust edition2018 no_run">
170-
use std::fs::File;
169+
<pre><pre class="playground"><code class="language-rust edition2018 no_run">use std::fs::File;
171170
use flate2::read::GzDecoder;
172171
use tar::Archive;
173172

@@ -189,8 +188,7 @@ <h2 id="compress-a-directory-into-tarball"><a class="header" href="#compress-a-d
189188
under <code>backup/logs</code> path with <a href="https://docs.rs/tar/*/tar/struct.Builder.html#method.append_dir_all"><code>Builder::append_dir_all</code></a>.
190189
<a href="https://docs.rs/flate2/*/flate2/write/struct.GzEncoder.html"><code>GzEncoder</code></a> is responsible for transparently compressing the
191190
data prior to writing it into <code>archive.tar.gz</code>.</p>
192-
<pre><pre class="playground"><code class="language-rust edition2018 no_run">
193-
use std::fs::File;
191+
<pre><pre class="playground"><code class="language-rust edition2018 no_run">use std::fs::File;
194192
use flate2::Compression;
195193
use flate2::write::GzEncoder;
196194

@@ -203,8 +201,7 @@ <h2 id="compress-a-directory-into-tarball"><a class="header" href="#compress-a-d
203201
Ok(())
204202
}</code></pre></pre>
205203
<p>To add the contents without renaming them, an empty string can be used as the first argument of <a href="https://docs.rs/tar/*/tar/struct.Builder.html#method.append_dir_all"><code>Builder::append_dir_all</code></a>:</p>
206-
<pre><pre class="playground"><code class="language-rust edition2018 no_run">
207-
use std::fs::File;
204+
<pre><pre class="playground"><code class="language-rust edition2018 no_run">use std::fs::File;
208205
use flate2::Compression;
209206
use flate2::write::GzEncoder;
210207

@@ -223,20 +220,13 @@ <h2 id="decompress-a-tarball-while-removing-a-prefix-from-the-paths"><a class="h
223220
<p>Iterate over the <a href="https://docs.rs/tar/*/tar/struct.Archive.html#method.entries"><code>Archive::entries</code></a>. Use <a href="https://doc.rust-lang.org/std/path/struct.Path.html#method.strip_prefix"><code>Path::strip_prefix</code></a> to remove
224221
the specified path prefix (<code>bundle/logs</code>). Finally, extract the <a href="https://docs.rs/tar/*/tar/struct.Entry.html"><code>tar::Entry</code></a>
225222
via <a href="https://docs.rs/tar/*/tar/struct.Entry.html#method.unpack"><code>Entry::unpack</code></a>.</p>
226-
<pre><pre class="playground"><code class="language-rust edition2018 no_run"><span class="boring">use error_chain::error_chain;
227-
</span>use std::fs::File;
223+
<pre><pre class="playground"><code class="language-rust edition2018 no_run">use anyhow::Result;
224+
use std::fs::File;
228225
use std::path::PathBuf;
229226
use flate2::read::GzDecoder;
230227
use tar::Archive;
231-
<span class="boring">
232-
</span><span class="boring">error_chain! {
233-
</span><span class="boring"> foreign_links {
234-
</span><span class="boring"> Io(std::io::Error);
235-
</span><span class="boring"> StripPrefixError(::std::path::StripPrefixError);
236-
</span><span class="boring"> }
237-
</span><span class="boring">}
238-
</span>
239-
fn main() -&gt; Result&lt;(), std::io::Error&gt; {
228+
229+
fn main() -&gt; Result&lt;()&gt; {
240230
let file = File::open("archive.tar.gz")?;
241231
let mut archive = Archive::new(GzDecoder::new(file));
242232
let prefix = "bundle/logs";

0 commit comments

Comments
 (0)