mirror of
https://github.com/rust-lang-nursery/rust-cookbook
synced 2024-11-21 11:03:09 +00:00
Update to edition 2018 (#565)
* Update to edition 2018 Update mdbook to 0.3.5 Command: sed -i '/extern crate/ {N;s/\n$//}' src/**.md; sed -i 's/extern crate error_chain;/use error_chain::error_chain;/; s/extern crate lazy_static;/use lazy_static::lazy_static;/; s/extern crate bitflags;/use bitflags::bitflags;/; s/extern crate serde_json;/ use serde_json::json;/; s/extern crate serde_derive;/use serde::{Serialize, Deserialize};/; /macro_use/d; /extern crate/ d; s/```rust/```rust,edition2018/; s/bail!/error_chain::&/; s/\(debug\|info\|warn\|error\)!/log::&/;' src/**.md Fix #530 * Update rand-dist.md * Fixes #569 * dump syslog version 4 depends on error-chain v 0.11 and version 5 depends on v 0.12 !!!! Co-authored-by: Andrew Gauger <andygauge@gmail.com>
This commit is contained in:
parent
7a06c79008
commit
b61c8e588a
145 changed files with 256 additions and 809 deletions
|
@ -20,7 +20,7 @@ cd rust-cookbook
|
|||
Cookbook is built with [mdBook], so install that first with Cargo:
|
||||
|
||||
```
|
||||
cargo install --version 0.1.8 mdbook
|
||||
cargo install --version 0.3.5 mdbook
|
||||
```
|
||||
|
||||
To build and view the cookbook locally, run:
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
name = "rust-cookbook"
|
||||
version = "0.1.0"
|
||||
authors = ["Brian Anderson <banderson@mozilla.com>"]
|
||||
edition = "2018"
|
||||
license = "MIT/Apache-2.0"
|
||||
publish = false
|
||||
|
||||
|
@ -9,6 +10,7 @@ build = "build.rs"
|
|||
|
||||
[dependencies]
|
||||
ansi_term = "0.11.0"
|
||||
approx = "0.3"
|
||||
base64 = "0.9"
|
||||
bitflags = "1.0"
|
||||
byteorder = "1.0"
|
||||
|
@ -58,7 +60,7 @@ url = "2.1"
|
|||
walkdir = "2.0"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
syslog = "4.0"
|
||||
syslog = "5.0"
|
||||
|
||||
[build-dependencies]
|
||||
skeptic = "0.13"
|
||||
|
|
|
@ -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.1.8"
|
||||
$ cargo install mdbook --vers "0.3.5"
|
||||
$ mdbook serve --open
|
||||
```
|
||||
|
||||
|
|
|
@ -3,12 +3,14 @@
|
|||
title = "Rust Cookbook"
|
||||
description = "Collection of useful Rust code examples"
|
||||
authors = ["Rust Language Community"]
|
||||
edition = "2018"
|
||||
multilingual = false
|
||||
language = "en"
|
||||
src = "src"
|
||||
|
||||
[output.html]
|
||||
mathjax-support = false
|
||||
theme = "theme"
|
||||
# theme = "theme"
|
||||
additional-css = ["theme/custom.css"]
|
||||
|
||||
[output.html.playpen]
|
||||
|
|
|
@ -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.1.8' --debug
|
||||
cargo install mdbook --vers '0.3.5' --debug
|
||||
fi
|
||||
|
||||
exit 0
|
||||
|
|
15
src/about.md
15
src/about.md
|
@ -56,8 +56,7 @@ Consider this example for "generate random numbers within a range":
|
|||
|
||||
[![rand-badge]][rand] [![cat-science-badge]][cat-science]
|
||||
|
||||
```rust
|
||||
extern crate rand;
|
||||
```rust,edition2018
|
||||
use rand::Rng;
|
||||
|
||||
fn main() {
|
||||
|
@ -111,10 +110,8 @@ The basic pattern we use is to have a `fn main() -> Result`.
|
|||
|
||||
The structure generally looks like:
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate error_chain;
|
||||
|
||||
```rust,edition2018
|
||||
use error_chain::error_chain;
|
||||
use std::net::IpAddr;
|
||||
use std::str;
|
||||
|
||||
|
@ -150,10 +147,8 @@ default like below. In order to read full contents click on the
|
|||
"expand" (<i class="fa fa-expand"></i>) button located in the top
|
||||
right corner of the snippet.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate url;
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use url::{Url, Position};
|
||||
#
|
||||
|
|
|
@ -5,9 +5,7 @@
|
|||
Randomly generates a string of given length ASCII characters with custom
|
||||
user-defined bytestring, with [`gen_range`].
|
||||
|
||||
```rust
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018
|
||||
fn main() {
|
||||
use rand::Rng;
|
||||
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
|
||||
|
|
|
@ -5,9 +5,7 @@
|
|||
Randomly generates a tuple `(i32, bool, f64)` and variable of user defined type `Point`.
|
||||
Implements the [`Distribution`] trait on type Point for [`Standard`] in order to allow random generation.
|
||||
|
||||
```rust,ignore
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018,ignore
|
||||
use rand::Rng;
|
||||
use rand::distributions::{Distribution, Standard};
|
||||
|
||||
|
|
|
@ -12,10 +12,7 @@ generator [`rand::Rng`].
|
|||
The [distributions available are documented here][rand-distributions].
|
||||
An example using the [`Normal`] distribution is shown below.
|
||||
|
||||
```rust,ignore
|
||||
extern crate rand_distr;
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018,ignore
|
||||
use rand_distr::{Distribution, Normal, NormalError};
|
||||
|
||||
fn main() -> Result<(), NormalError> {
|
||||
|
|
|
@ -5,9 +5,7 @@
|
|||
Randomly generates a string of given length ASCII characters in the range `A-Z,
|
||||
a-z, 0-9`, with [`Alphanumeric`] sample.
|
||||
|
||||
```rust,ignore
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018,ignore
|
||||
use rand::{thread_rng, Rng};
|
||||
use rand::distributions::Alphanumeric;
|
||||
|
||||
|
|
|
@ -4,9 +4,7 @@
|
|||
|
||||
Generates a random value within half-open `[0, 10)` range (not including `10`) with [`Rng::gen_range`].
|
||||
|
||||
```rust,ignore
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018,ignore
|
||||
use rand::Rng;
|
||||
|
||||
fn main() {
|
||||
|
@ -20,9 +18,7 @@ fn main() {
|
|||
This has the same effect, but may be faster when repeatedly generating numbers
|
||||
in the same range.
|
||||
|
||||
```rust,ignore
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018,ignore
|
||||
|
||||
use rand::distributions::{Distribution, Uniform};
|
||||
|
||||
|
|
|
@ -8,9 +8,7 @@ initialized generator. Integers are uniformly distributed over the range of the
|
|||
type, and floating point numbers are uniformly distributed from 0 up to but not
|
||||
including 1.
|
||||
|
||||
```rust
|
||||
extern crate rand;
|
||||
|
||||
```rust,edition2018
|
||||
use rand::Rng;
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -6,7 +6,7 @@ This example sorts a Vector of integers via [`vec::sort`]. Alternative would
|
|||
be to use [`vec::sort_unstable`] which can be faster, but does not preserve
|
||||
the order of equal elements.
|
||||
|
||||
```rust
|
||||
```rust,edition2018
|
||||
fn main() {
|
||||
let mut vec = vec![1, 5, 10, 2, 15];
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
A Vector of f32 or f64 can be sorted with [`vec::sort_by`] and [`PartialOrd::partial_cmp`].
|
||||
|
||||
```rust
|
||||
```rust,edition2018
|
||||
fn main() {
|
||||
let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0];
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ order (By name and age). In order to make Person sortable you need four traits [
|
|||
[`PartialEq`], [`Ord`] and [`PartialOrd`]. These traits can be simply derived.
|
||||
You can also provide a custom comparator function using a [`vec:sort_by`] method and sort only by age.
|
||||
|
||||
```rust
|
||||
```rust,edition2018
|
||||
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
struct Person {
|
||||
name: String,
|
||||
|
|
|
@ -10,9 +10,7 @@ There are two main data structures in [`ansi_term`]: [`ANSIString`] and [`Style`
|
|||
|
||||
### Printing colored text to the Terminal
|
||||
|
||||
```rust
|
||||
extern crate ansi_term;
|
||||
|
||||
```rust,edition2018
|
||||
use ansi_term::Colour;
|
||||
|
||||
fn main() {
|
||||
|
@ -29,9 +27,7 @@ For anything more complex than plain foreground colour changes, the code
|
|||
needs to construct `Style` struct. [`Style::new()`] creates the struct,
|
||||
and properties chained.
|
||||
|
||||
```rust
|
||||
extern crate ansi_term;
|
||||
|
||||
```rust,edition2018
|
||||
use ansi_term::Style;
|
||||
|
||||
fn main() {
|
||||
|
@ -43,9 +39,7 @@ fn main() {
|
|||
|
||||
`Colour` implements many similar functions as `Style` and can chain methods.
|
||||
|
||||
```rust
|
||||
extern crate ansi_term;
|
||||
|
||||
```rust,edition2018
|
||||
use ansi_term::Colour;
|
||||
use ansi_term::Style;
|
||||
|
||||
|
|
|
@ -11,9 +11,7 @@ use to retrieve the value passed. 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`.
|
||||
|
||||
```rust
|
||||
extern crate clap;
|
||||
|
||||
```rust,edition2018
|
||||
use clap::{Arg, App};
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -10,9 +10,7 @@ under `backup/logs`path with [`Builder::append_dir_all`].
|
|||
[`GzEncoder`] is responsible for transparently compressing the
|
||||
data prior to writing it into `archive.tar.gz`.
|
||||
|
||||
```rust,no_run
|
||||
extern crate tar;
|
||||
extern crate flate2;
|
||||
```rust,edition2018,no_run
|
||||
|
||||
use std::fs::File;
|
||||
use flate2::Compression;
|
||||
|
|
|
@ -7,9 +7,7 @@ extract ([`Archive::unpack`]) all files from a compressed tarball
|
|||
named `archive.tar.gz` located in the current working directory
|
||||
to the same location.
|
||||
|
||||
```rust,no_run
|
||||
extern crate flate2;
|
||||
extern crate tar;
|
||||
```rust,edition2018,no_run
|
||||
|
||||
use std::fs::File;
|
||||
use flate2::read::GzDecoder;
|
||||
|
|
|
@ -6,12 +6,8 @@ Iterate over the [`Archive::entries`]. Use [`Path::strip_prefix`] to remove
|
|||
the specified path prefix (`bundle/logs`). Finally, extract the [`tar::Entry`]
|
||||
via [`Entry::unpack`].
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate flate2;
|
||||
extern crate tar;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
use flate2::read::GzDecoder;
|
||||
|
|
|
@ -4,9 +4,7 @@
|
|||
|
||||
This example demonstrates using the [`rayon::any`] and [`rayon::all`] methods, which are parallelized counterparts to [`std::any`] and [`std::all`]. [`rayon::any`] checks in parallel whether any element of the iterator matches the predicate, and returns as soon as one is found. [`rayon::all`] checks in parallel whether all elements of the iterator match the predicate, and returns as soon as a non-matching element is found.
|
||||
|
||||
```rust
|
||||
extern crate rayon;
|
||||
|
||||
```rust,edition2018
|
||||
use rayon::prelude::*;
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -6,9 +6,7 @@ The example uses the `rayon` crate, which is a data parallelism library for Rust
|
|||
`rayon` provides the [`par_iter_mut`] method for any parallel iterable data type.
|
||||
This is an iterator-like chain that potentially executes in parallel.
|
||||
|
||||
```rust
|
||||
extern crate rayon;
|
||||
|
||||
```rust,edition2018
|
||||
use rayon::prelude::*;
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -11,9 +11,7 @@ new iteration, and [`rayon::reduce`] performs an operation given the previous
|
|||
reduction and the current element. Also shows use of [`rayon::sum`],
|
||||
which has the same result as the reduce operation in this example.
|
||||
|
||||
```rust
|
||||
extern crate rayon;
|
||||
|
||||
```rust,edition2018
|
||||
use rayon::prelude::*;
|
||||
|
||||
struct Person {
|
||||
|
|
|
@ -12,9 +12,7 @@ necessarily the first one.
|
|||
Also note that the argument to the closure is a reference to a reference
|
||||
(`&&x`). See the discussion on [`std::find`] for additional details.
|
||||
|
||||
```rust
|
||||
extern crate rayon;
|
||||
|
||||
```rust,edition2018
|
||||
use rayon::prelude::*;
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -9,9 +9,7 @@ values in parallel. Although [multiple options]
|
|||
exist to sort an enumerable data type, [`par_sort_unstable`]
|
||||
is usually faster than [stable sorting] algorithms.
|
||||
|
||||
```rust,ignore
|
||||
extern crate rand;
|
||||
extern crate rayon;
|
||||
```rust,edition2018,ignore
|
||||
|
||||
use rand::{Rng, thread_rng};
|
||||
use rand::distributions::Alphanumeric;
|
||||
|
|
|
@ -8,12 +8,8 @@ then saves them in a new folder called `thumbnails`.
|
|||
[`glob::glob_with`] finds jpeg files in current directory. `rayon` resizes
|
||||
images in parallel using [`par_iter`] calling [`DynamicImage::resize`].
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate glob;
|
||||
extern crate image;
|
||||
extern crate rayon;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use std::path::Path;
|
||||
use std::fs::create_dir_all;
|
||||
|
@ -38,7 +34,7 @@ fn main() -> Result<()> {
|
|||
.collect();
|
||||
|
||||
if files.len() == 0 {
|
||||
bail!("No .jpg files found in current directory");
|
||||
error_chain::bail!("No .jpg files found in current directory");
|
||||
}
|
||||
|
||||
let thumb_dir = "thumbnails";
|
||||
|
|
|
@ -9,9 +9,7 @@ you can reference data from the calling function.
|
|||
|
||||
This example splits the array in half and performs the work in separate threads.
|
||||
|
||||
```rust
|
||||
extern crate crossbeam;
|
||||
|
||||
```rust,edition2018
|
||||
fn main() {
|
||||
let arr = &[1, 25, -4, 10];
|
||||
let max = find_max(arr);
|
||||
|
|
|
@ -9,9 +9,7 @@ exchanged between the two threads using a [`crossbeam_channel::unbounded`]
|
|||
channel, meaning there is no limit to the number of storeable messages. The
|
||||
producer thread sleeps for half a second in between messages.
|
||||
|
||||
```rust
|
||||
extern crate crossbeam;
|
||||
extern crate crossbeam_channel;
|
||||
```rust,edition2018
|
||||
|
||||
use std::{thread, time};
|
||||
use crossbeam_channel::unbounded;
|
||||
|
|
|
@ -9,12 +9,9 @@ the state cannot be simultaneously accessed by multiple threads, preventing
|
|||
race conditions. A [`MutexGuard`] must be acquired to read or mutate the
|
||||
value stored in a [`Mutex`].
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
use lazy_static::lazy_static;
|
||||
use std::sync::Mutex;
|
||||
#
|
||||
# error_chain!{ }
|
||||
|
|
|
@ -16,14 +16,8 @@ Create [`ThreadPool`] with thread count equal to number of cores with [`num_cpus
|
|||
[`ImageBuffer::put_pixel`] uses the data to set the pixel color.
|
||||
[`ImageBuffer::save`] writes the image to `output.png`.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate threadpool;
|
||||
extern crate num;
|
||||
extern crate num_cpus;
|
||||
extern crate image;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
use std::sync::mpsc::{channel, RecvError};
|
||||
use threadpool::ThreadPool;
|
||||
use num::complex::Complex;
|
||||
|
|
|
@ -8,11 +8,7 @@ present in the system found with [`num_cpus::get`]. [`Walkdir::new`] iterates
|
|||
the current directory and calls [`execute`] to perform the operations of reading
|
||||
and computing SHA256 hash.
|
||||
|
||||
```rust,no_run
|
||||
extern crate walkdir;
|
||||
extern crate ring;
|
||||
extern crate num_cpus;
|
||||
extern crate threadpool;
|
||||
```rust,edition2018,no_run
|
||||
|
||||
use walkdir::WalkDir;
|
||||
use std::fs::File;
|
||||
|
|
|
@ -9,9 +9,7 @@ function [`pbkdf2::derive`]. Verifies the hash is correct with
|
|||
[`SecureRandom::fill`], which fills the salt byte array with
|
||||
securely generated random numbers.
|
||||
|
||||
```rust,ignore
|
||||
extern crate ring;
|
||||
extern crate data_encoding;
|
||||
```rust,edition2018,ignore
|
||||
|
||||
use data_encoding::HEXUPPER;
|
||||
use ring::error::Unspecified;
|
||||
|
|
|
@ -4,9 +4,8 @@
|
|||
|
||||
Uses [`ring::hmac`] to creates a [`hmac::Signature`] of a string then verifies the signature is correct.
|
||||
|
||||
```rust
|
||||
extern crate ring;
|
||||
|
||||
```rust,edition2018
|
||||
use ring::{hmac, rand};
|
||||
use ring::rand::SecureRandom;
|
||||
use ring::error::Unspecified;
|
||||
|
|
|
@ -5,12 +5,8 @@
|
|||
Writes some data to a file, then calculates the SHA-256 [`digest::Digest`] of
|
||||
the file's contents using [`digest::Context`].
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate data_encoding;
|
||||
extern crate ring;
|
||||
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
use data_encoding::HEXUPPER;
|
||||
use ring::digest::{Context, Digest, SHA256};
|
||||
use std::fs::File;
|
||||
|
|
|
@ -6,10 +6,8 @@ Creates type safe bitfield type `MyFlags` with help of [`bitflags!`] macro
|
|||
and implements elementary `clear` operation as well as [`Display`] trait for it.
|
||||
Subsequently, shows basic bitwise operations and formatting.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate bitflags;
|
||||
|
||||
```rust,edition2018
|
||||
use bitflags::bitflags;
|
||||
use std::fmt;
|
||||
|
||||
bitflags! {
|
||||
|
|
|
@ -4,8 +4,7 @@
|
|||
|
||||
This recipe lists the nationalities of the first 7999 artists in the database of the [`Museum of Modern Art`] in descending order.
|
||||
|
||||
```rust,no_run
|
||||
extern crate postgres;
|
||||
```rust,edition2018,no_run
|
||||
use postgres::{Client, Error, NoTls};
|
||||
|
||||
struct Nation {
|
||||
|
|
|
@ -6,9 +6,7 @@ Use the [`postgres`] crate to create tables in a Postgres database.
|
|||
|
||||
[`Client::connect`] helps in connecting to an existing database. The recipe uses a URL string format with `Client::connect`. It assumes an existing database named `library`, the username is `postgres` and the password is `postgres`.
|
||||
|
||||
```rust,no_run
|
||||
extern crate postgres;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use postgres::{Client, NoTls, Error};
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
|
|
|
@ -4,9 +4,8 @@
|
|||
|
||||
The recipe inserts data into the `author` table using [`execute`] method of `Client`. Then, displays the data from the `author` table using [`query`] method of `Client`.
|
||||
|
||||
```rust,no_run
|
||||
extern crate postgres;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use postgres::{Client, NoTls, Error};
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
|
|
@ -7,9 +7,7 @@ Use the `rusqlite` crate to open SQLite databases. See
|
|||
|
||||
[`Connection::open`] will create the database if it doesn't already exist.
|
||||
|
||||
```rust,no_run
|
||||
extern crate rusqlite;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use rusqlite::{Connection, Result};
|
||||
use rusqlite::NO_PARAMS;
|
||||
|
||||
|
|
|
@ -6,7 +6,6 @@
|
|||
This recipe inserts data into `cat_colors` and `cats` tables using the [`execute`] method of `Connection`. First, the data is inserted into the `cat_colors` table. After a record for a color is inserted, [`last_insert_rowid`] method of `Connection` is used to get `id` of the last color inserted. This `id` is used while inserting data into the `cats` table. Then, the select query is prepared using the [`prepare`] method which gives a [`statement`] struct. Then, query is executed using [`query_map`] method of [`statement`].
|
||||
|
||||
```rust,no_run
|
||||
extern crate rusqlite;
|
||||
|
||||
use rusqlite::NO_PARAMS;
|
||||
use rusqlite::{Connection, Result};
|
||||
|
|
|
@ -12,9 +12,7 @@ a unique constraint on the color name. When an attempt to insert
|
|||
a duplicate color is made, the transaction rolls back.
|
||||
|
||||
|
||||
```rust,no_run
|
||||
extern crate rusqlite;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use rusqlite::{Connection, Result, NO_PARAMS};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
|
|
|
@ -10,8 +10,7 @@ cannot be calculated.
|
|||
Escape sequences that are available for the
|
||||
[`DateTime::format`] can be found at [`chrono::format::strftime`].
|
||||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
```rust,edition2018
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
|
||||
fn day_earlier(date_time: DateTime<Utc>) -> Option<DateTime<Utc>> {
|
||||
|
|
|
@ -7,7 +7,7 @@ Measures [`time::Instant::elapsed`] since [`time::Instant::now`].
|
|||
Calling [`time::Instant::elapsed`] returns a [`time::Duration`] that we print at the end of the example.
|
||||
This method will not mutate or reset the [`time::Instant`] object.
|
||||
|
||||
```rust
|
||||
```rust,edition2018
|
||||
use std::time::{Duration, Instant};
|
||||
# use std::thread;
|
||||
#
|
||||
|
|
|
@ -4,8 +4,7 @@
|
|||
|
||||
Gets the local time and displays it using [`offset::Local::now`] and then converts it to the UTC standard using the [`DateTime::from_utc`] struct method. A time is then converted using the [`offset::FixedOffset`] struct and the UTC time is then converted to UTC+8 and UTC-2.
|
||||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
```rust,edition2018
|
||||
|
||||
use chrono::{DateTime, FixedOffset, Local, Utc};
|
||||
|
||||
|
|
|
@ -5,8 +5,7 @@
|
|||
Gets the current UTC [`DateTime`] and its hour/minute/second via [`Timelike`]
|
||||
and its year/month/day/weekday via [`Datelike`].
|
||||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
```rust,edition2018
|
||||
use chrono::{Datelike, Timelike, Utc};
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -7,8 +7,7 @@ current time in the well-known formats [RFC 2822] using [`DateTime::to_rfc2822`]
|
|||
and [RFC 3339] using [`DateTime::to_rfc3339`], and in a custom format using
|
||||
[`DateTime::format`].
|
||||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
```rust,edition2018
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -13,8 +13,7 @@ requires that such a DateTime struct must be creatable that it uniquely
|
|||
identifies a date and a time. For parsing dates and times without timezones use
|
||||
[`NaiveDate`], [`NaiveTime`], and [`NaiveDateTime`].
|
||||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
```rust,edition2018
|
||||
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
|
||||
use chrono::format::ParseError;
|
||||
|
||||
|
|
|
@ -6,8 +6,7 @@ to [UNIX timestamp] using [`NaiveDateTime::timestamp`].
|
|||
Then it calculates what was the date after one billion seconds
|
||||
since January 1, 1970 0:00:00 UTC, using [`NaiveDateTime::from_timestamp`].
|
||||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
```rust,edition2018
|
||||
|
||||
use chrono::{NaiveDate, NaiveDateTime};
|
||||
|
||||
|
|
|
@ -18,9 +18,7 @@ cc = "1"
|
|||
|
||||
### `build.rs`
|
||||
|
||||
```rust,no_run
|
||||
extern crate cc;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
fn main() {
|
||||
cc::Build::new()
|
||||
.cpp(true)
|
||||
|
@ -43,7 +41,7 @@ int multiply(int x, int y) {
|
|||
|
||||
### `src/main.rs`
|
||||
|
||||
```rust,ignore
|
||||
```rust,edition2018,ignore
|
||||
extern {
|
||||
fn multiply(x : i32, y : i32) -> i32;
|
||||
}
|
||||
|
|
|
@ -30,9 +30,7 @@ error-chain = "0.11"
|
|||
|
||||
### `build.rs`
|
||||
|
||||
```rust,no_run
|
||||
extern crate cc;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
fn main() {
|
||||
cc::Build::new()
|
||||
.file("src/hello.c")
|
||||
|
@ -57,8 +55,7 @@ void greet(const char* name) {
|
|||
|
||||
### `src/main.rs`
|
||||
|
||||
```rust,ignore
|
||||
# #[macro_use] extern crate error_chain;
|
||||
```rust,edition2018,ignore
|
||||
use std::ffi::CString;
|
||||
use std::os::raw::c_char;
|
||||
#
|
||||
|
|
|
@ -23,9 +23,7 @@ cc = "1"
|
|||
|
||||
### `build.rs`
|
||||
|
||||
```rust,no_run
|
||||
extern crate cc;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
fn main() {
|
||||
cc::Build::new()
|
||||
.define("APP_NAME", "\"foo\"")
|
||||
|
@ -51,7 +49,7 @@ void print_app_info() {
|
|||
|
||||
### `src/main.rs`
|
||||
|
||||
```rust,ignore
|
||||
```rust,edition2018,ignore
|
||||
extern {
|
||||
fn print_app_info();
|
||||
}
|
||||
|
|
|
@ -11,12 +11,8 @@ encoding using a custom pattern from [`log4rs::encode::pattern`].
|
|||
Assigns the configuration to [`log4rs::config::Config`] and sets the default
|
||||
[`log::LevelFilter`].
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate log4rs;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use log::LevelFilter;
|
||||
use log4rs::append::file::FileAppender;
|
||||
|
@ -44,7 +40,7 @@ fn main() -> Result<()> {
|
|||
|
||||
log4rs::init_config(config)?;
|
||||
|
||||
info!("Hello, world!");
|
||||
log::info!("Hello, world!");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -9,10 +9,7 @@ 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
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate env_logger;
|
||||
```rust,edition2018
|
||||
|
||||
use std::env;
|
||||
use env_logger::Builder;
|
||||
|
@ -22,9 +19,9 @@ fn main() {
|
|||
.parse(&env::var("MY_APP_LOG").unwrap_or_default())
|
||||
.init();
|
||||
|
||||
info!("informational message");
|
||||
warn!("warning message");
|
||||
error!("this is an error {}", "message");
|
||||
log::info!("informational message");
|
||||
log::warn!("warning message");
|
||||
log::error!("this is an error {}", "message");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -5,33 +5,30 @@
|
|||
Creates two modules `foo` and nested `foo::bar` with logging directives
|
||||
controlled separately with [`RUST_LOG`] environmental variable.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate env_logger;
|
||||
```rust,edition2018
|
||||
|
||||
mod foo {
|
||||
mod bar {
|
||||
pub fn run() {
|
||||
warn!("[bar] warn");
|
||||
info!("[bar] info");
|
||||
debug!("[bar] debug");
|
||||
log::warn!("[bar] warn");
|
||||
log::info!("[bar] info");
|
||||
log::debug!("[bar] debug");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() {
|
||||
warn!("[foo] warn");
|
||||
info!("[foo] info");
|
||||
debug!("[foo] debug");
|
||||
log::warn!("[foo] warn");
|
||||
log::info!("[foo] info");
|
||||
log::debug!("[foo] debug");
|
||||
bar::run();
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
warn!("[root] warn");
|
||||
info!("[root] info");
|
||||
debug!("[root] debug");
|
||||
log::warn!("[root] warn");
|
||||
log::info!("[root] info");
|
||||
log::debug!("[root] debug");
|
||||
foo::run();
|
||||
}
|
||||
```
|
||||
|
|
|
@ -10,12 +10,7 @@ a timestamp used in the final log.
|
|||
The example calls [`Builder::format`] to set a closure which formats each
|
||||
message text with timestamp, [`Record::level`] and body ([`Record::args`]).
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate chrono;
|
||||
extern crate env_logger;
|
||||
|
||||
```rust,edition2018
|
||||
use std::io::Write;
|
||||
use chrono::Local;
|
||||
use env_logger::Builder;
|
||||
|
@ -34,9 +29,9 @@ fn main() {
|
|||
.filter(None, LevelFilter::Info)
|
||||
.init();
|
||||
|
||||
warn!("warn");
|
||||
info!("info");
|
||||
debug!("debug");
|
||||
log::warn!("warn");
|
||||
log::info!("info");
|
||||
log::debug!("debug");
|
||||
}
|
||||
```
|
||||
stderr output will contain
|
||||
|
|
|
@ -6,10 +6,7 @@ Implements a custom logger `ConsoleLogger` which prints to stdout.
|
|||
In order to use the logging macros, `ConsoleLogger` implements
|
||||
the [`log::Log`] trait and [`log::set_logger`] installs it.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
```rust,edition2018
|
||||
use log::{Record, Level, Metadata, LevelFilter, SetLoggerError};
|
||||
|
||||
static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger;
|
||||
|
@ -34,9 +31,9 @@ fn main() -> Result<(), SetLoggerError> {
|
|||
log::set_logger(&CONSOLE_LOGGER)?;
|
||||
log::set_max_level(LevelFilter::Info);
|
||||
|
||||
info!("hello log");
|
||||
warn!("warning");
|
||||
error!("oops");
|
||||
log::info!("hello log");
|
||||
log::warn!("warning");
|
||||
log::error!("oops");
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
|
|
@ -3,16 +3,13 @@
|
|||
[![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging]
|
||||
|
||||
The `log` crate provides logging utilities. The `env_logger` crate configures
|
||||
logging via an environment variable. The [`debug!`] macro works like other
|
||||
logging via an environment variable. The [`log::debug!`] macro works like other
|
||||
[`std::fmt`] formatted strings.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate env_logger;
|
||||
```rust,edition2018
|
||||
|
||||
fn execute_query(query: &str) {
|
||||
debug!("Executing query: {}", query);
|
||||
log::debug!("Executing query: {}", query);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
@ -38,5 +35,5 @@ following line at the very end of the output:
|
|||
DEBUG:main: Executing query: DROP TABLE students
|
||||
```
|
||||
|
||||
[`debug!`]: https://docs.rs/log/*/log/macro.debug.html
|
||||
[`log::debug!`]: https://docs.rs/log/*/log/macro.debug.html
|
||||
[`std::fmt`]: https://doc.rust-lang.org/std/fmt/
|
||||
|
|
|
@ -3,12 +3,9 @@
|
|||
[![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging]
|
||||
|
||||
Proper error handling considers exceptions exceptional. Here, an error logs
|
||||
to stderr with `log`'s convenience macro [`error!`].
|
||||
to stderr with `log`'s convenience macro [`log::error!`].
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate env_logger;
|
||||
```rust,edition2018
|
||||
|
||||
fn execute_query(_query: &str) -> Result<(), &'static str> {
|
||||
Err("I'm afraid I can't do that")
|
||||
|
@ -19,9 +16,9 @@ fn main() {
|
|||
|
||||
let response = execute_query("DROP TABLE students");
|
||||
if let Err(err) = response {
|
||||
error!("Failed to execute query: {}", err);
|
||||
log::error!("Failed to execute query: {}", err);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[`error!`]: https://docs.rs/log/*/log/macro.error.html
|
||||
[`log::error!`]: https://docs.rs/log/*/log/macro.error.html
|
||||
|
|
|
@ -4,10 +4,7 @@
|
|||
|
||||
Creates a custom logger configuration using the [`Builder::target`] to set the target of the log output to [`Target::Stdout`].
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate env_logger;
|
||||
```rust,edition2018
|
||||
|
||||
use env_logger::{Builder, Target};
|
||||
|
||||
|
@ -16,7 +13,7 @@ fn main() {
|
|||
.target(Target::Stdout)
|
||||
.init();
|
||||
|
||||
error!("This error has been printed to Stdout");
|
||||
log::error!("This error has been printed to Stdout");
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -7,12 +7,8 @@ with [`syslog::init`]. [`syslog::Facility`] records the program submitting
|
|||
the log entry's classification, [`log::LevelFilter`] denotes allowed log verbosity
|
||||
and `Option<&str>` holds optional application name.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
```rust,edition2018
|
||||
# #[cfg(target_os = "linux")]
|
||||
extern crate syslog;
|
||||
|
||||
# #[cfg(target_os = "linux")]
|
||||
use syslog::{Facility, Error};
|
||||
|
||||
|
@ -21,8 +17,8 @@ fn main() -> Result<(), Error> {
|
|||
syslog::init(Facility::LOG_USER,
|
||||
log::LevelFilter::Debug,
|
||||
Some("My app name"))?;
|
||||
debug!("this is a debug {}", "message");
|
||||
error!("this is an error!");
|
||||
log::debug!("this is a debug {}", "message");
|
||||
log::error!("this is an error!");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
@ -7,10 +7,8 @@ Runs `git --version` using [`Command`], then parses the version number into a
|
|||
[`semver::VersionReq`] to the parsed version. The command output resembles
|
||||
"git version x.y.z".
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate semver;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use std::process::Command;
|
||||
use semver::{Version, VersionReq};
|
||||
|
@ -30,7 +28,7 @@ fn main() -> Result<()> {
|
|||
let output = Command::new("git").arg("--version").output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
bail!("Command executed with failing error code");
|
||||
error_chain::bail!("Command executed with failing error code");
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8(output.stdout)?;
|
||||
|
@ -40,7 +38,7 @@ fn main() -> Result<()> {
|
|||
let parsed_version = Version::parse(version)?;
|
||||
|
||||
if !version_test.matches(&parsed_version) {
|
||||
bail!("Command version lower than minimum supported version (found {}, need {})",
|
||||
error_chain::bail!("Command version lower than minimum supported version (found {}, need {})",
|
||||
parsed_version, version_constraint);
|
||||
}
|
||||
|
||||
|
|
|
@ -8,9 +8,7 @@ contains pre-release and build metadata as defined in the [Semantic Versioning S
|
|||
Note that, in accordance with the Specification, build metadata is parsed but not considered when
|
||||
comparing versions. In other words, two versions may be equal even if their build strings differ.
|
||||
|
||||
```rust
|
||||
extern crate semver;
|
||||
|
||||
```rust,edition2018
|
||||
use semver::{Identifier, Version, SemVerError};
|
||||
|
||||
fn main() -> Result<(), SemVerError> {
|
||||
|
|
|
@ -10,9 +10,7 @@ incrementing the minor version number resets the patch version number to 0 and
|
|||
incrementing the major version number resets both the minor and patch version
|
||||
numbers to 0.
|
||||
|
||||
```rust
|
||||
extern crate semver;
|
||||
|
||||
```rust,edition2018
|
||||
use semver::{Version, SemVerError};
|
||||
|
||||
fn main() -> Result<(), SemVerError> {
|
||||
|
|
|
@ -6,10 +6,8 @@ Given a list of version &strs, finds the latest [`semver::Version`].
|
|||
[`semver::VersionReq`] filters the list with [`VersionReq::matches`].
|
||||
Also demonstrates `semver` pre-release preferences.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate semver;
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use semver::{Version, VersionReq};
|
||||
#
|
||||
|
|
|
@ -4,9 +4,7 @@
|
|||
|
||||
Given two versions, [`is_prerelease`] asserts that one is pre-release and the other is not.
|
||||
|
||||
```rust
|
||||
extern crate semver;
|
||||
|
||||
```rust,edition2018
|
||||
use semver::{Version, SemVerError};
|
||||
|
||||
fn main() -> Result<(), SemVerError> {
|
||||
|
|
|
@ -6,8 +6,7 @@
|
|||
be necessary when receiving information over the network, such that bytes
|
||||
received are from another system.
|
||||
|
||||
```rust
|
||||
extern crate byteorder;
|
||||
```rust,edition2018
|
||||
|
||||
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
|
||||
use std::io::Error;
|
||||
|
|
|
@ -10,10 +10,8 @@ is able to represent any valid JSON data.
|
|||
|
||||
The example below shows a `&str` of JSON being parsed. The expected value is declared using the [`json!`] macro.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
|
||||
```rust,edition2018
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, Error};
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
|
|
|
@ -5,9 +5,7 @@
|
|||
Parse some TOML into a universal `toml::Value` that is able to represent any
|
||||
valid TOML data.
|
||||
|
||||
```rust
|
||||
extern crate toml;
|
||||
|
||||
```rust,edition2018
|
||||
use toml::{Value, de::Error};
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
|
@ -33,10 +31,8 @@ fn main() -> Result<(), Error> {
|
|||
|
||||
Parse TOML into your own structs using [Serde].
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate toml;
|
||||
```rust,edition2018
|
||||
use serde::Deserialize;
|
||||
|
||||
use toml::de::Error;
|
||||
use std::collections::HashMap;
|
||||
|
|
|
@ -4,12 +4,9 @@
|
|||
|
||||
Reads CSV records with a tab [`delimiter`].
|
||||
|
||||
```rust
|
||||
extern crate csv;
|
||||
```rust,edition2018
|
||||
use csv::Error;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
use serde::Deserialize;
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Record {
|
||||
name: String,
|
||||
|
|
|
@ -4,10 +4,8 @@
|
|||
|
||||
Returns _only_ the rows from `data` with a field that matches `query`.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate csv;
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use std::io;
|
||||
#
|
||||
|
|
|
@ -6,11 +6,9 @@ CSV files often contain invalid data. For these cases, the `csv` crate
|
|||
provides a custom deserializer, [`csv::invalid_option`], which automatically
|
||||
converts invalid data to None values.
|
||||
|
||||
```rust
|
||||
extern crate csv;
|
||||
```rust,edition2018
|
||||
use csv::Error;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Record {
|
||||
|
|
|
@ -6,8 +6,7 @@ Reads standard CSV records into [`csv::StringRecord`] — a weakly typed
|
|||
data representation which expects valid UTF-8 rows. Alternatively,
|
||||
[`csv::ByteRecord`] makes no assumptions about UTF-8.
|
||||
|
||||
```rust
|
||||
extern crate csv;
|
||||
```rust,edition2018
|
||||
use csv::Error;
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
|
@ -34,11 +33,8 @@ fn main() -> Result<(), Error> {
|
|||
Serde deserializes data into strongly type structures. See the
|
||||
[`csv::Reader::deserialize`] method.
|
||||
|
||||
```rust
|
||||
extern crate csv;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
```rust,edition2018
|
||||
use serde::Deserialize;
|
||||
#[derive(Deserialize)]
|
||||
struct Record {
|
||||
year: u16,
|
||||
|
|
|
@ -5,13 +5,9 @@
|
|||
The following example shows how to serialize custom structs as CSV records using
|
||||
the [serde] crate.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate csv;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
use serde::Serialize;
|
||||
use std::io;
|
||||
#
|
||||
# error_chain! {
|
||||
|
|
|
@ -8,10 +8,8 @@ a simple record containing string data only. Data with more complex values
|
|||
such as numbers, floats, and options use [`serialize`]. Since CSV
|
||||
writer uses internal buffer, always explicitly [`flush`] when done.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate csv;
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use std::io;
|
||||
#
|
||||
|
|
|
@ -8,14 +8,8 @@ csv file, and [serde] to deserialize and serialize the rows to and from bytes.
|
|||
|
||||
See [`csv::Reader::deserialize`], [`serde::Deserialize`], and [`std::str::FromStr`]
|
||||
|
||||
```rust
|
||||
extern crate csv;
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate serde;
|
||||
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
use csv::{Reader, Writer};
|
||||
use serde::{de, Deserialize, Deserializer};
|
||||
use std::str::FromStr;
|
||||
|
|
|
@ -5,10 +5,8 @@
|
|||
Encodes byte slice into `base64` String using [`encode`]
|
||||
and decodes it with [`decode`].
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate base64;
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use std::str;
|
||||
use base64::{encode, decode};
|
||||
|
|
|
@ -12,9 +12,7 @@ returns a `Vec<u8>` if the input data is successfully decoded.
|
|||
The example below coverts `&[u8]` data to hexadecimal equivalent. Compares this
|
||||
value to the expected value.
|
||||
|
||||
```rust
|
||||
extern crate data_encoding;
|
||||
|
||||
```rust,edition2018
|
||||
use data_encoding::{HEXUPPER, DecodeError};
|
||||
|
||||
fn main() -> Result<(), DecodeError> {
|
||||
|
|
|
@ -6,9 +6,7 @@ Encode an input string with [percent-encoding] using the [`utf8_percent_encode`]
|
|||
function from the `percent-encoding` crate. Then decode using the [`percent_decode`]
|
||||
function.
|
||||
|
||||
```rust,ignore
|
||||
extern crate percent_encoding;
|
||||
|
||||
```rust,edition2018,ignore
|
||||
use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS};
|
||||
use std::str::Utf8Error;
|
||||
|
||||
|
|
|
@ -7,8 +7,7 @@ using the [`form_urlencoded::byte_serialize`] and subsequently
|
|||
decodes it with [`form_urlencoded::parse`]. Both functions return iterators
|
||||
that collect into a `String`.
|
||||
|
||||
```rust
|
||||
extern crate url;
|
||||
```rust,edition2018
|
||||
use url::form_urlencoded::{byte_serialize, parse};
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -11,12 +11,9 @@ The below recipes attempts to deserialize the value `256` into a
|
|||
`u8`. An error will bubble up from Serde then csv and finally up to the
|
||||
user code.
|
||||
|
||||
```rust
|
||||
# extern crate csv;
|
||||
#[macro_use]
|
||||
extern crate error_chain;
|
||||
# #[macro_use]
|
||||
# extern crate serde_derive;
|
||||
```rust,edition2018
|
||||
use error_chain::error_chain;
|
||||
# use serde::Deserialize;
|
||||
#
|
||||
# use std::fmt;
|
||||
#
|
||||
|
|
|
@ -17,9 +17,8 @@ first number. Returns uptime unless there is an error.
|
|||
Other recipes in this book will hide the [error-chain] boilerplate, and can be
|
||||
seen by expanding the code with the ⤢ button.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate error_chain;
|
||||
```rust,edition2018
|
||||
use error_chain::error_chain;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
|
|
|
@ -12,10 +12,8 @@ the string response into an integer. The Rust standard library,
|
|||
use [`foreign_links`]. An additional [`ErrorKind`] variant for the web service
|
||||
error uses `errors` block of the `error_chain!` macro.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate error_chain;
|
||||
extern crate reqwest;
|
||||
```rust,edition2018
|
||||
use error_chain::error_chain;
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
|
|
|
@ -5,9 +5,7 @@
|
|||
Find recursively in the current directory duplicate filenames,
|
||||
printing them only once.
|
||||
|
||||
```rust,no_run
|
||||
extern crate walkdir;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use std::collections::HashMap;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
|
|
|
@ -6,10 +6,8 @@ Find JSON files modified within the last day in the current directory.
|
|||
Using [`follow_links`] ensures symbolic links are followed like they were
|
||||
normal directories and files.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate walkdir;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use walkdir::WalkDir;
|
||||
#
|
||||
|
|
|
@ -6,10 +6,8 @@ Find all image files in the `/media/` directory matching the `img_[0-9]*.png` pa
|
|||
|
||||
A custom [`MatchOptions`] struct is passed to the [`glob_with`] function making the glob pattern case insensitive while keeping the other options [`Default`].
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate glob;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use glob::{glob_with, MatchOptions};
|
||||
#
|
||||
|
|
|
@ -10,9 +10,7 @@ ln -s /tmp/foo/ /tmp/foo/bar/baz/qux
|
|||
```
|
||||
The following would assert that a loop exists.
|
||||
|
||||
```rust,no_run
|
||||
extern crate same_file;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use same_file::is_same_file;
|
||||
|
|
|
@ -10,9 +10,8 @@ last modification. [`Duration::as_secs`] converts the time to seconds and
|
|||
compared with 24 hours (24 * 60 * 60 seconds). [`Metadata::is_file`] filters
|
||||
out directories.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
```rust,edition2018
|
||||
# use error_chain::error_chain;
|
||||
#
|
||||
use std::{env, fs};
|
||||
|
||||
|
|
|
@ -8,10 +8,8 @@ In this case, the `**` pattern matches the current directory and all subdirector
|
|||
Use the `**` pattern in any path portion. For example, `/media/**/*.png`
|
||||
matches all PNGs in `media` and it's subdirectories.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate glob;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use glob::glob;
|
||||
#
|
||||
|
|
|
@ -5,9 +5,7 @@
|
|||
Recursion depth can be flexibly set by [`WalkDir::min_depth`] & [`WalkDir::max_depth`] methods.
|
||||
Calculates sum of all file sizes to 3 subfolders depth, ignoring files in the root folder.
|
||||
|
||||
```rust
|
||||
extern crate walkdir;
|
||||
|
||||
```rust,edition2018
|
||||
use walkdir::WalkDir;
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -10,9 +10,7 @@ Uses [`filter_entry`] to descend recursively into entries passing the
|
|||
Root dir `"."` yields through [`WalkDir::depth`] usage in `is_not_hidden`
|
||||
predicate.
|
||||
|
||||
```rust,no_run
|
||||
extern crate walkdir;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use walkdir::{DirEntry, WalkDir};
|
||||
|
||||
fn is_not_hidden(entry: &DirEntry) -> bool {
|
||||
|
|
|
@ -10,9 +10,7 @@ The [`Mmap::map`] function assumes the file
|
|||
behind the memory map is not being modified at the same time by another process
|
||||
or else a [race condition] occurs.
|
||||
|
||||
```rust
|
||||
extern crate memmap;
|
||||
|
||||
```rust,edition2018
|
||||
use memmap::Mmap;
|
||||
use std::fs::File;
|
||||
use std::io::{Write, Error};
|
||||
|
|
|
@ -8,7 +8,7 @@ time with the [`Lines`] iterator created by
|
|||
trait. [`File::create`] opens a [`File`] for writing, [`File::open`] for
|
||||
reading.
|
||||
|
||||
```rust
|
||||
```rust,edition2018
|
||||
use std::fs::File;
|
||||
use std::io::{Write, BufReader, BufRead, Error};
|
||||
|
||||
|
|
|
@ -6,9 +6,7 @@ Use [`same_file::Handle`] to a file that can be tested for equality with
|
|||
other handles. In this example, the handles of file to be read from and
|
||||
to be written to are tested for equality.
|
||||
|
||||
```rust,no_run
|
||||
extern crate same_file;
|
||||
|
||||
```rust,edition2018,no_run
|
||||
use same_file::Handle;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader, Error, ErrorKind};
|
||||
|
|
|
@ -4,9 +4,7 @@
|
|||
|
||||
Shows the number of logical CPU cores in current machine using [`num_cpus::get`].
|
||||
|
||||
```rust
|
||||
extern crate num_cpus;
|
||||
|
||||
```rust,edition2018
|
||||
fn main() {
|
||||
println!("Number of logical cores is {}", num_cpus::get());
|
||||
}
|
||||
|
|
|
@ -5,10 +5,8 @@
|
|||
Declares a lazily evaluated constant [`HashMap`]. The [`HashMap`] will
|
||||
be evaluated once and stored behind a global static reference.
|
||||
|
||||
```rust
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
```rust,edition2018
|
||||
use lazy_static::lazy_static;
|
||||
use std::collections::HashMap;
|
||||
|
||||
lazy_static! {
|
||||
|
|
|
@ -6,7 +6,7 @@ In this example, the port is displayed on the console, and the program will
|
|||
listen until a request is made. `SocketAddrV4` assigns a random port when
|
||||
setting port to 0.
|
||||
|
||||
```rust,no_run
|
||||
```rust,edition2018,no_run
|
||||
use std::net::{SocketAddrV4, Ipv4Addr, TcpListener};
|
||||
use std::io::{Read, Error};
|
||||
|
||||
|
|
2
src/os/external/continuous.md
vendored
2
src/os/external/continuous.md
vendored
|
@ -10,7 +10,7 @@ The recipe below calls [`Stdio::piped`] to create a pipe, and reads
|
|||
The below recipe is equivalent to the Unix shell command
|
||||
`journalctl | grep usb`.
|
||||
|
||||
```rust,no_run
|
||||
```rust,edition2018,no_run
|
||||
use std::process::{Command, Stdio};
|
||||
use std::io::{BufRead, BufReader, Error, ErrorKind};
|
||||
|
||||
|
|
2
src/os/external/error-file.md
vendored
2
src/os/external/error-file.md
vendored
|
@ -12,7 +12,7 @@ cursor position.
|
|||
The below recipe is equivalent to run the Unix shell command `ls
|
||||
. oops >out.txt 2>&1`.
|
||||
|
||||
```rust,no_run
|
||||
```rust,edition2018,no_run
|
||||
use std::fs::File;
|
||||
use std::io::Error;
|
||||
use std::process::{Command, Stdio};
|
||||
|
|
5
src/os/external/piped.md
vendored
5
src/os/external/piped.md
vendored
|
@ -9,9 +9,8 @@ sort -hr | head -n 10`.
|
|||
[`Command`]s represent a process. Output of a child process is captured with a
|
||||
[`Stdio::piped`] between parent and child.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
#
|
||||
use std::process::{Command, Stdio};
|
||||
#
|
||||
|
|
8
src/os/external/process-output.md
vendored
8
src/os/external/process-output.md
vendored
|
@ -5,10 +5,8 @@
|
|||
Runs `git log --oneline` as an external [`Command`] and inspects its [`Output`]
|
||||
using [`Regex`] to get the hash and message of the last 5 commits.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate regex;
|
||||
```rust,edition2018,no_run
|
||||
# use error_chain::error_chain;
|
||||
|
||||
use std::process::Command;
|
||||
use regex::Regex;
|
||||
|
@ -31,7 +29,7 @@ fn main() -> Result<()> {
|
|||
let output = Command::new("git").arg("log").arg("--oneline").output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
bail!("Command executed with failing error code");
|
||||
error_chain::bail!("Command executed with failing error code");
|
||||
}
|
||||
|
||||
let pattern = Regex::new(r"(?x)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue