Skip to content

Commit

Permalink
update original
Browse files Browse the repository at this point in the history
  • Loading branch information
funkill committed Nov 28, 2024
1 parent 2ecc9f8 commit 275553c
Show file tree
Hide file tree
Showing 18 changed files with 95 additions and 97 deletions.
4 changes: 1 addition & 3 deletions rust-cookbook/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,7 @@ Mark examples that depend on external systems with `no_run` or remove them
if they are not required for the example. Avoid inline comments, preferring
explanation in the description.

> ```rust
> extern crate rand;
>
> ```rust,edition2018
> use rand::distributions::{Normal, Distribution};
>
> fn main() {
Expand Down
4 changes: 2 additions & 2 deletions rust-cookbook/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ bitflags = "1.0"
byteorder = "1.0"
cc = "1.0"
chrono = "0.4"
clap = "2.29"
clap = "4.5"
crossbeam = "0.5"
crossbeam-channel = "0.3.9"
csv = "1.0"
data-encoding = "2.1.0"
env_logger = "0.5"
env_logger = "0.11.3"
error-chain = "0.12"
flate2 = "1.0"
glob = "0.3"
Expand Down
2 changes: 1 addition & 1 deletion rust-cookbook/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ If you'd like to read it locally:
```bash
$ git clone https://github.com/rust-lang-nursery/rust-cookbook
$ cd rust-cookbook
$ cargo install mdbook --vers "0.4.5"
$ cargo install mdbook --vers "0.4.43"
$ mdbook serve --open
```

Expand Down
3 changes: 0 additions & 3 deletions rust-cookbook/build.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
extern crate skeptic;
extern crate walkdir;

use walkdir::WalkDir;

const REMOVED_TESTS: &[&str] = &[
Expand Down
2 changes: 1 addition & 1 deletion rust-cookbook/ci/install_deps.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ if [[ "${CONTENT_TESTS:-}" == 1 ]]; then
pyenv local 3.6.0
pip3 install --user link-checker==0.1.0
fi
cargo install mdbook --vers '0.4.5' --debug
cargo install mdbook --vers '0.4.43' --debug
fi

exit 0
66 changes: 37 additions & 29 deletions rust-cookbook/src/cli/arguments/clap-basic.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,52 @@ This application describes the structure of its command-line interface using
`clap`'s builder style. The [documentation] gives two other possible ways to
instantiate an application.

In the builder style, `with_name` is the unique identifier that `value_of` will
use to retrieve the value passed. The `short` and `long` options control the
In the builder style, each possible argument is described by an `Arg`
struct. The string given to `Arg::new()` is the internal
name of the argument. The `short` and `long` options control the
flag the user will be expected to type; short flags look like `-f` and long
flags look like `--file`.

The `get_one()` method is used to get an argument's value.
It returns `Some(&`value`)` if the argument was supplied by
the user, else `None`.

The use of `PathBuf` is to allow file paths which are legal
in Linux and MacOS, but not in Rust UTF-8 strings. This is
best practice: one encounters such paths quite rarely in
practice, but when it happens it is really frustrating
without this.

```rust,edition2018
use clap::{Arg, App};
use std::path::PathBuf;
use clap::{Arg, Command, builder::PathBufValueParser};
fn main() {
let matches = App::new("My Test Program")
let matches = Command::new("My Test Program")
.version("0.1.0")
.author("Hackerman Jones <[email protected]>")
.about("Teaches argument parsing")
.arg(Arg::with_name("file")
.short("f")
.arg(Arg::new("file")
.short('f')
.long("file")
.takes_value(true)
.help("A cool file"))
.arg(Arg::with_name("num")
.short("n")
.help("A cool file")
.value_parser(PathBufValueParser::default()))
.arg(Arg::new("num")
.short('n')
.long("number")
.takes_value(true)
.help("Five less than your favorite number"))
.get_matches();
let myfile = matches.value_of("file").unwrap_or("input.txt");
println!("The file passed is: {}", myfile);
let default_file = PathBuf::from("input.txt");
let myfile: &PathBuf = matches.get_one("file").unwrap_or(&default_file);
println!("The file passed is: {}", myfile.display());
let num_str = matches.value_of("num");
let num_str: Option<&String> = matches.get_one("num");
match num_str {
None => println!("No idea what your favorite number is."),
Some(s) => {
match s.parse::<i32>() {
let parsed: Result<i32, _> = s.parse();
match parsed {
Ok(n) => println!("Your favorite number must be {}.", n + 5),
Err(_) => println!("That's not a number! {}", s),
}
Expand All @@ -47,24 +60,19 @@ fn main() {
}
```

Usage information is generated by `clap`. The usage for the example application
looks like this.
Usage information is generated by `clap -h`. The usage for
the example application looks like this.

```
My Test Program 0.1.0
Hackerman Jones <[email protected]>
Teaches argument parsing
USAGE:
testing [OPTIONS]
FLAGS:
-h, --help Prints help information
-V, --version Prints version information
Usage: clap-cookbook [OPTIONS]
OPTIONS:
-f, --file <file> A cool file
-n, --number <num> Five less than your favorite number
Options:
-f, --file <file> A cool file
-n, --number <num> Five less than your favorite number
-h, --help Print help
-V, --version Print version
```

We can test the application by running a command like the following.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() {
let mut vec = vec![String::new(); 100_000];
vec.par_iter_mut().for_each(|p| {
let mut rng = thread_rng();
*p = (0..5).map(|_| rng.sample(&Alphanumeric)).collect()
*p = (0..5).map(|_| rng.sample(&Alphanumeric) as char).collect()
});
vec.par_sort_unstable();
}
Expand Down
5 changes: 1 addition & 4 deletions rust-cookbook/src/concurrency/thread/crossbeam-complex.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ to prevent the entire program from blocking on the worker for-loops. You can
think of the calls to `drop` as signaling that no more messages will be sent.


```rust
extern crate crossbeam;
extern crate crossbeam_channel;

```rust,edition2018
use std::thread;
use std::time::Duration;
use crossbeam_channel::bounded;
Expand Down
2 changes: 1 addition & 1 deletion rust-cookbook/src/concurrency/thread/crossbeam-spsc.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn main() {
```

[crossbeam-channel]: https://docs.rs/crate/crossbeam-channel/
[ex-crossbeam-spawn]: concurrency/threads.html#spawn-a-short-lived-thread
[ex-crossbeam-spawn]: #spawn-a-short-lived-thread
[`crossbeam::scope`]: https://docs.rs/crossbeam/*/crossbeam/fn.scope.html
[`Scope::spawn`]: https://docs.rs/crossbeam/*/crossbeam/thread/struct.Scope.html#method.spawn
[`crossbeam_channel::unbounded`]: https://docs.rs/crossbeam-channel/*/crossbeam_channel/fn.unbounded.html
1 change: 1 addition & 0 deletions rust-cookbook/src/concurrency/thread/threadpool-fractal.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use image::{ImageBuffer, Pixel, Rgb};
# foreign_links {
# MpscRecv(RecvError);
# Io(std::io::Error);
# Image(image::ImageError);
# }
# }
#
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,23 @@

[`Builder`] configures logging.

[`Builder::parse`] parses `MY_APP_LOG`
[`Builder::from_env`] parses `MY_APP_LOG`
environment variable contents in the form of [`RUST_LOG`] syntax.
Then, [`Builder::init`] initializes the logger.
All these steps are normally done internally by [`env_logger::init`].

```rust,edition2018
use std::env;
use env_logger::Builder;
fn main() {
Builder::new()
.parse(&env::var("MY_APP_LOG").unwrap_or_default())
.init();
Builder::from_env("MY_APP_LOG").init();
log::info!("informational message");
log::warn!("warning message");
log::error!("this is an error {}", "message");
}
```

[`env_logger::init`]: https://docs.rs/env_logger/*/env_logger/fn.init.html
[`Builder`]: https://docs.rs/env_logger/*/env_logger/struct.Builder.html
[`Builder::from_env`]: https://docs.rs/env_logger/*/env_logger/struct.Builder.html#method.from_env
[`Builder::init`]: https://docs.rs/env_logger/*/env_logger/struct.Builder.html#method.init
[`Builder::parse`]: https://docs.rs/env_logger/*/env_logger/struct.Builder.html#method.parse
[`RUST_LOG`]: https://docs.rs/env_logger/*/env_logger/#enabling-logging
2 changes: 1 addition & 1 deletion rust-cookbook/src/links.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Keep lines sorted.

<!-- Crates -->

[ansi_term-badge]: https://badge-cache.kominick.com/crates/v/base64.svg?label=ansi_term
[ansi_term-badge]: https://badge-cache.kominick.com/crates/v/ansi_term.svg?label=ansi_term
[ansi_term]: https://docs.rs/ansi_term/
[base64-badge]: https://badge-cache.kominick.com/crates/v/base64.svg?label=base64
[base64]: https://docs.rs/base64/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ by [`serde_json::to_string`] and [`serde_json::from_str`] performs deserializati

Note that serialization followed by deserialization gives back the original matrix.

```rust
extern crate nalgebra;
extern crate serde_json;

```rust,edition2018
use nalgebra::DMatrix;
fn main() -> Result<(), std::io::Error> {
Expand Down
2 changes: 2 additions & 0 deletions rust-cookbook/src/web.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
| Recipe | Crates | Categories |
|--------|--------|------------|
| [Make a HTTP GET request][ex-url-basic] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |
| [Set custom headers and URL parameters for a REST request][ex-url-header] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |
| [Query the GitHub API][ex-rest-get] | [![reqwest-badge]][reqwest] [![serde-badge]][serde] | [![cat-net-badge]][cat-net] [![cat-encoding-badge]][cat-encoding] |
| [Check if an API resource exists][ex-rest-head] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |
| [Create and delete Gist with GitHub API][ex-rest-post] | [![reqwest-badge]][reqwest] [![serde-badge]][serde] | [![cat-net-badge]][cat-net] [![cat-encoding-badge]][cat-encoding] |
Expand Down Expand Up @@ -60,6 +61,7 @@
[ex-http-response-mime-type]: web/mime.html#parse-the-mime-type-of-a-http-response

[ex-url-basic]: web/clients/requests.html#make-a-http-get-request
[ex-url-header]: web/clients/requests.html#set-custom-headers-and-url-parameters-for-a-rest-request
[ex-rest-custom-params]: web/clients/requests.html#set-custom-headers-and-url-parameters-for-a-rest-request
[ex-rest-get]: web/clients/apis.html#query-the-github-api
[ex-rest-head]: web/clients/apis.html#check-if-an-api-resource-exists
Expand Down
2 changes: 2 additions & 0 deletions rust-cookbook/src/web/clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
| Recipe | Crates | Categories |
|--------|--------|------------|
| [Make a HTTP GET request][ex-url-basic] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |
| [Set custom headers and URL parameters for a REST request][ex-url-header] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |
| [Query the GitHub API][ex-rest-get] | [![reqwest-badge]][reqwest] [![serde-badge]][serde] | [![cat-net-badge]][cat-net] [![cat-encoding-badge]][cat-encoding] |
| [Check if an API resource exists][ex-rest-head] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |
| [Create and delete Gist with GitHub API][ex-rest-post] | [![reqwest-badge]][reqwest] [![serde-badge]][serde] | [![cat-net-badge]][cat-net] [![cat-encoding-badge]][cat-encoding] |
Expand All @@ -12,6 +13,7 @@
| [POST a file to paste-rs][ex-file-post] | [![reqwest-badge]][reqwest] | [![cat-net-badge]][cat-net] |

[ex-url-basic]: clients/requests.html#make-a-http-get-request
[ex-url-header]: web/clients/requests.html#set-custom-headers-and-url-parameters-for-a-rest-request
[ex-rest-custom-params]: clients/requests.html#set-custom-headers-and-url-parameters-for-a-rest-request
[ex-rest-get]: clients/apis.html#query-the-github-api
[ex-rest-head]: clients/apis.html#check-if-an-api-resource-exists
Expand Down
9 changes: 8 additions & 1 deletion rust-cookbook/src/web/clients/api/rest-get.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ processing the response into User instances.
```rust,edition2018,no_run
use serde::Deserialize;
use reqwest::Error;
use reqwest::header::USER_AGENT;
#[derive(Deserialize, Debug)]
struct User {
Expand All @@ -25,7 +26,13 @@ async fn main() -> Result<(), Error> {
owner = "rust-lang-nursery",
repo = "rust-cookbook");
println!("{}", request_url);
let response = reqwest::get(&request_url).await?;
let client = reqwest::Client::new();
let response = client
.get(request_url)
.header(USER_AGENT, "rust-web-api-client") // gh api requires a user-agent header
.send()
.await?;
let users: Vec<User> = response.json().await?;
println!("{:?}", users);
Expand Down
2 changes: 2 additions & 0 deletions rust-cookbook/src/web/clients/requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

{{#include requests/get.md}}

{{#include requests/header.md}}

{{#include ../../links.md}}
Loading

0 comments on commit 275553c

Please sign in to comment.