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:
Ivan Tham 2020-06-01 08:26:32 +08:00 committed by GitHub
parent 7a06c79008
commit b61c8e588a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
145 changed files with 256 additions and 809 deletions

View file

@ -20,7 +20,7 @@ cd rust-cookbook
Cookbook is built with [mdBook], so install that first with Cargo: 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: To build and view the cookbook locally, run:

View file

@ -2,6 +2,7 @@
name = "rust-cookbook" name = "rust-cookbook"
version = "0.1.0" version = "0.1.0"
authors = ["Brian Anderson <banderson@mozilla.com>"] authors = ["Brian Anderson <banderson@mozilla.com>"]
edition = "2018"
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
publish = false publish = false
@ -9,6 +10,7 @@ build = "build.rs"
[dependencies] [dependencies]
ansi_term = "0.11.0" ansi_term = "0.11.0"
approx = "0.3"
base64 = "0.9" base64 = "0.9"
bitflags = "1.0" bitflags = "1.0"
byteorder = "1.0" byteorder = "1.0"
@ -58,7 +60,7 @@ url = "2.1"
walkdir = "2.0" walkdir = "2.0"
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
syslog = "4.0" syslog = "5.0"
[build-dependencies] [build-dependencies]
skeptic = "0.13" skeptic = "0.13"

View file

@ -19,7 +19,7 @@ If you'd like to read it locally:
```bash ```bash
$ git clone https://github.com/rust-lang-nursery/rust-cookbook $ git clone https://github.com/rust-lang-nursery/rust-cookbook
$ cd rust-cookbook $ cd rust-cookbook
$ cargo install mdbook --vers "0.1.8" $ cargo install mdbook --vers "0.3.5"
$ mdbook serve --open $ mdbook serve --open
``` ```

View file

@ -3,12 +3,14 @@
title = "Rust Cookbook" title = "Rust Cookbook"
description = "Collection of useful Rust code examples" description = "Collection of useful Rust code examples"
authors = ["Rust Language Community"] authors = ["Rust Language Community"]
edition = "2018"
multilingual = false multilingual = false
language = "en"
src = "src" src = "src"
[output.html] [output.html]
mathjax-support = false mathjax-support = false
theme = "theme" # theme = "theme"
additional-css = ["theme/custom.css"] additional-css = ["theme/custom.css"]
[output.html.playpen] [output.html.playpen]

View file

@ -18,7 +18,7 @@ if [[ "${CONTENT_TESTS:-}" == 1 ]]; then
pyenv local 3.6.0 pyenv local 3.6.0
pip3 install --user link-checker==0.1.0 pip3 install --user link-checker==0.1.0
fi fi
cargo install mdbook --vers '0.1.8' --debug cargo install mdbook --vers '0.3.5' --debug
fi fi
exit 0 exit 0

View file

@ -56,8 +56,7 @@ Consider this example for "generate random numbers within a range":
[![rand-badge]][rand] [![cat-science-badge]][cat-science] [![rand-badge]][rand] [![cat-science-badge]][cat-science]
```rust ```rust,edition2018
extern crate rand;
use rand::Rng; use rand::Rng;
fn main() { fn main() {
@ -111,10 +110,8 @@ The basic pattern we use is to have a `fn main() -> Result`.
The structure generally looks like: The structure generally looks like:
```rust ```rust,edition2018
#[macro_use] use error_chain::error_chain;
extern crate error_chain;
use std::net::IpAddr; use std::net::IpAddr;
use std::str; 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 "expand" (<i class="fa fa-expand"></i>) button located in the top
right corner of the snippet. right corner of the snippet.
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate url;
use url::{Url, Position}; use url::{Url, Position};
# #

View file

@ -5,9 +5,7 @@
Randomly generates a string of given length ASCII characters with custom Randomly generates a string of given length ASCII characters with custom
user-defined bytestring, with [`gen_range`]. user-defined bytestring, with [`gen_range`].
```rust ```rust,edition2018
extern crate rand;
fn main() { fn main() {
use rand::Rng; use rand::Rng;
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\

View file

@ -5,9 +5,7 @@
Randomly generates a tuple `(i32, bool, f64)` and variable of user defined type `Point`. 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. Implements the [`Distribution`] trait on type Point for [`Standard`] in order to allow random generation.
```rust,ignore ```rust,edition2018,ignore
extern crate rand;
use rand::Rng; use rand::Rng;
use rand::distributions::{Distribution, Standard}; use rand::distributions::{Distribution, Standard};

View file

@ -12,10 +12,7 @@ generator [`rand::Rng`].
The [distributions available are documented here][rand-distributions]. The [distributions available are documented here][rand-distributions].
An example using the [`Normal`] distribution is shown below. An example using the [`Normal`] distribution is shown below.
```rust,ignore ```rust,edition2018,ignore
extern crate rand_distr;
extern crate rand;
use rand_distr::{Distribution, Normal, NormalError}; use rand_distr::{Distribution, Normal, NormalError};
fn main() -> Result<(), NormalError> { fn main() -> Result<(), NormalError> {

View file

@ -5,9 +5,7 @@
Randomly generates a string of given length ASCII characters in the range `A-Z, Randomly generates a string of given length ASCII characters in the range `A-Z,
a-z, 0-9`, with [`Alphanumeric`] sample. a-z, 0-9`, with [`Alphanumeric`] sample.
```rust,ignore ```rust,edition2018,ignore
extern crate rand;
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric; use rand::distributions::Alphanumeric;

View file

@ -4,9 +4,7 @@
Generates a random value within half-open `[0, 10)` range (not including `10`) with [`Rng::gen_range`]. Generates a random value within half-open `[0, 10)` range (not including `10`) with [`Rng::gen_range`].
```rust,ignore ```rust,edition2018,ignore
extern crate rand;
use rand::Rng; use rand::Rng;
fn main() { fn main() {
@ -20,9 +18,7 @@ fn main() {
This has the same effect, but may be faster when repeatedly generating numbers This has the same effect, but may be faster when repeatedly generating numbers
in the same range. in the same range.
```rust,ignore ```rust,edition2018,ignore
extern crate rand;
use rand::distributions::{Distribution, Uniform}; use rand::distributions::{Distribution, Uniform};

View file

@ -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 type, and floating point numbers are uniformly distributed from 0 up to but not
including 1. including 1.
```rust ```rust,edition2018
extern crate rand;
use rand::Rng; use rand::Rng;
fn main() { fn main() {

View file

@ -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 be to use [`vec::sort_unstable`] which can be faster, but does not preserve
the order of equal elements. the order of equal elements.
```rust ```rust,edition2018
fn main() { fn main() {
let mut vec = vec![1, 5, 10, 2, 15]; let mut vec = vec![1, 5, 10, 2, 15];

View file

@ -4,7 +4,7 @@
A Vector of f32 or f64 can be sorted with [`vec::sort_by`] and [`PartialOrd::partial_cmp`]. A Vector of f32 or f64 can be sorted with [`vec::sort_by`] and [`PartialOrd::partial_cmp`].
```rust ```rust,edition2018
fn main() { fn main() {
let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0]; let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0];

View file

@ -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. [`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. 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)] #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Person { struct Person {
name: String, name: String,

View file

@ -10,9 +10,7 @@ There are two main data structures in [`ansi_term`]: [`ANSIString`] and [`Style`
### Printing colored text to the Terminal ### Printing colored text to the Terminal
```rust ```rust,edition2018
extern crate ansi_term;
use ansi_term::Colour; use ansi_term::Colour;
fn main() { 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, needs to construct `Style` struct. [`Style::new()`] creates the struct,
and properties chained. and properties chained.
```rust ```rust,edition2018
extern crate ansi_term;
use ansi_term::Style; use ansi_term::Style;
fn main() { fn main() {
@ -43,9 +39,7 @@ fn main() {
`Colour` implements many similar functions as `Style` and can chain methods. `Colour` implements many similar functions as `Style` and can chain methods.
```rust ```rust,edition2018
extern crate ansi_term;
use ansi_term::Colour; use ansi_term::Colour;
use ansi_term::Style; use ansi_term::Style;

View file

@ -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 flag the user will be expected to type; short flags look like `-f` and long
flags look like `--file`. flags look like `--file`.
```rust ```rust,edition2018
extern crate clap;
use clap::{Arg, App}; use clap::{Arg, App};
fn main() { fn main() {

View file

@ -10,9 +10,7 @@ under `backup/logs`path with [`Builder::append_dir_all`].
[`GzEncoder`] is responsible for transparently compressing the [`GzEncoder`] is responsible for transparently compressing the
data prior to writing it into `archive.tar.gz`. data prior to writing it into `archive.tar.gz`.
```rust,no_run ```rust,edition2018,no_run
extern crate tar;
extern crate flate2;
use std::fs::File; use std::fs::File;
use flate2::Compression; use flate2::Compression;

View file

@ -7,9 +7,7 @@ extract ([`Archive::unpack`]) all files from a compressed tarball
named `archive.tar.gz` located in the current working directory named `archive.tar.gz` located in the current working directory
to the same location. to the same location.
```rust,no_run ```rust,edition2018,no_run
extern crate flate2;
extern crate tar;
use std::fs::File; use std::fs::File;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;

View file

@ -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`] the specified path prefix (`bundle/logs`). Finally, extract the [`tar::Entry`]
via [`Entry::unpack`]. via [`Entry::unpack`].
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate flate2;
extern crate tar;
use std::fs::File; use std::fs::File;
use std::path::PathBuf; use std::path::PathBuf;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;

View file

@ -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. 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 ```rust,edition2018
extern crate rayon;
use rayon::prelude::*; use rayon::prelude::*;
fn main() { fn main() {

View file

@ -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. `rayon` provides the [`par_iter_mut`] method for any parallel iterable data type.
This is an iterator-like chain that potentially executes in parallel. This is an iterator-like chain that potentially executes in parallel.
```rust ```rust,edition2018
extern crate rayon;
use rayon::prelude::*; use rayon::prelude::*;
fn main() { fn main() {

View file

@ -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`], reduction and the current element. Also shows use of [`rayon::sum`],
which has the same result as the reduce operation in this example. which has the same result as the reduce operation in this example.
```rust ```rust,edition2018
extern crate rayon;
use rayon::prelude::*; use rayon::prelude::*;
struct Person { struct Person {

View file

@ -12,9 +12,7 @@ necessarily the first one.
Also note that the argument to the closure is a reference to a reference Also note that the argument to the closure is a reference to a reference
(`&&x`). See the discussion on [`std::find`] for additional details. (`&&x`). See the discussion on [`std::find`] for additional details.
```rust ```rust,edition2018
extern crate rayon;
use rayon::prelude::*; use rayon::prelude::*;
fn main() { fn main() {

View file

@ -9,9 +9,7 @@ values in parallel. Although [multiple options]
exist to sort an enumerable data type, [`par_sort_unstable`] exist to sort an enumerable data type, [`par_sort_unstable`]
is usually faster than [stable sorting] algorithms. is usually faster than [stable sorting] algorithms.
```rust,ignore ```rust,edition2018,ignore
extern crate rand;
extern crate rayon;
use rand::{Rng, thread_rng}; use rand::{Rng, thread_rng};
use rand::distributions::Alphanumeric; use rand::distributions::Alphanumeric;

View file

@ -8,12 +8,8 @@ then saves them in a new folder called `thumbnails`.
[`glob::glob_with`] finds jpeg files in current directory. `rayon` resizes [`glob::glob_with`] finds jpeg files in current directory. `rayon` resizes
images in parallel using [`par_iter`] calling [`DynamicImage::resize`]. images in parallel using [`par_iter`] calling [`DynamicImage::resize`].
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate glob;
extern crate image;
extern crate rayon;
use std::path::Path; use std::path::Path;
use std::fs::create_dir_all; use std::fs::create_dir_all;
@ -38,7 +34,7 @@ fn main() -> Result<()> {
.collect(); .collect();
if files.len() == 0 { 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"; let thumb_dir = "thumbnails";

View file

@ -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. This example splits the array in half and performs the work in separate threads.
```rust ```rust,edition2018
extern crate crossbeam;
fn main() { fn main() {
let arr = &[1, 25, -4, 10]; let arr = &[1, 25, -4, 10];
let max = find_max(arr); let max = find_max(arr);

View file

@ -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 channel, meaning there is no limit to the number of storeable messages. The
producer thread sleeps for half a second in between messages. producer thread sleeps for half a second in between messages.
```rust ```rust,edition2018
extern crate crossbeam;
extern crate crossbeam_channel;
use std::{thread, time}; use std::{thread, time};
use crossbeam_channel::unbounded; use crossbeam_channel::unbounded;

View file

@ -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 race conditions. A [`MutexGuard`] must be acquired to read or mutate the
value stored in a [`Mutex`]. value stored in a [`Mutex`].
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain; use lazy_static::lazy_static;
#[macro_use]
extern crate lazy_static;
use std::sync::Mutex; use std::sync::Mutex;
# #
# error_chain!{ } # error_chain!{ }

View file

@ -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::put_pixel`] uses the data to set the pixel color.
[`ImageBuffer::save`] writes the image to `output.png`. [`ImageBuffer::save`] writes the image to `output.png`.
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate threadpool;
extern crate num;
extern crate num_cpus;
extern crate image;
use std::sync::mpsc::{channel, RecvError}; use std::sync::mpsc::{channel, RecvError};
use threadpool::ThreadPool; use threadpool::ThreadPool;
use num::complex::Complex; use num::complex::Complex;

View file

@ -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 the current directory and calls [`execute`] to perform the operations of reading
and computing SHA256 hash. and computing SHA256 hash.
```rust,no_run ```rust,edition2018,no_run
extern crate walkdir;
extern crate ring;
extern crate num_cpus;
extern crate threadpool;
use walkdir::WalkDir; use walkdir::WalkDir;
use std::fs::File; use std::fs::File;

View file

@ -9,9 +9,7 @@ function [`pbkdf2::derive`]. Verifies the hash is correct with
[`SecureRandom::fill`], which fills the salt byte array with [`SecureRandom::fill`], which fills the salt byte array with
securely generated random numbers. securely generated random numbers.
```rust,ignore ```rust,edition2018,ignore
extern crate ring;
extern crate data_encoding;
use data_encoding::HEXUPPER; use data_encoding::HEXUPPER;
use ring::error::Unspecified; use ring::error::Unspecified;

View file

@ -4,9 +4,8 @@
Uses [`ring::hmac`] to creates a [`hmac::Signature`] of a string then verifies the signature is correct. 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::{hmac, rand};
use ring::rand::SecureRandom; use ring::rand::SecureRandom;
use ring::error::Unspecified; use ring::error::Unspecified;

View file

@ -5,12 +5,8 @@
Writes some data to a file, then calculates the SHA-256 [`digest::Digest`] of Writes some data to a file, then calculates the SHA-256 [`digest::Digest`] of
the file's contents using [`digest::Context`]. the file's contents using [`digest::Context`].
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate data_encoding;
extern crate ring;
use data_encoding::HEXUPPER; use data_encoding::HEXUPPER;
use ring::digest::{Context, Digest, SHA256}; use ring::digest::{Context, Digest, SHA256};
use std::fs::File; use std::fs::File;

View 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. and implements elementary `clear` operation as well as [`Display`] trait for it.
Subsequently, shows basic bitwise operations and formatting. Subsequently, shows basic bitwise operations and formatting.
```rust ```rust,edition2018
#[macro_use] use bitflags::bitflags;
extern crate bitflags;
use std::fmt; use std::fmt;
bitflags! { bitflags! {

View file

@ -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. 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 ```rust,edition2018,no_run
extern crate postgres;
use postgres::{Client, Error, NoTls}; use postgres::{Client, Error, NoTls};
struct Nation { struct Nation {

View file

@ -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`. [`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 ```rust,edition2018,no_run
extern crate postgres;
use postgres::{Client, NoTls, Error}; use postgres::{Client, NoTls, Error};
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {

View file

@ -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`. 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 postgres::{Client, NoTls, Error};
use std::collections::HashMap; use std::collections::HashMap;

View file

@ -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. [`Connection::open`] will create the database if it doesn't already exist.
```rust,no_run ```rust,edition2018,no_run
extern crate rusqlite;
use rusqlite::{Connection, Result}; use rusqlite::{Connection, Result};
use rusqlite::NO_PARAMS; use rusqlite::NO_PARAMS;

View file

@ -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`]. 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 ```rust,no_run
extern crate rusqlite;
use rusqlite::NO_PARAMS; use rusqlite::NO_PARAMS;
use rusqlite::{Connection, Result}; use rusqlite::{Connection, Result};

View file

@ -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. a duplicate color is made, the transaction rolls back.
```rust,no_run ```rust,edition2018,no_run
extern crate rusqlite;
use rusqlite::{Connection, Result, NO_PARAMS}; use rusqlite::{Connection, Result, NO_PARAMS};
fn main() -> Result<()> { fn main() -> Result<()> {

View file

@ -10,8 +10,7 @@ cannot be calculated.
Escape sequences that are available for the Escape sequences that are available for the
[`DateTime::format`] can be found at [`chrono::format::strftime`]. [`DateTime::format`] can be found at [`chrono::format::strftime`].
```rust ```rust,edition2018
extern crate chrono;
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
fn day_earlier(date_time: DateTime<Utc>) -> Option<DateTime<Utc>> { fn day_earlier(date_time: DateTime<Utc>) -> Option<DateTime<Utc>> {

View file

@ -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. 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. This method will not mutate or reset the [`time::Instant`] object.
```rust ```rust,edition2018
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
# use std::thread; # use std::thread;
# #

View file

@ -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. 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 ```rust,edition2018
extern crate chrono;
use chrono::{DateTime, FixedOffset, Local, Utc}; use chrono::{DateTime, FixedOffset, Local, Utc};

View file

@ -5,8 +5,7 @@
Gets the current UTC [`DateTime`] and its hour/minute/second via [`Timelike`] Gets the current UTC [`DateTime`] and its hour/minute/second via [`Timelike`]
and its year/month/day/weekday via [`Datelike`]. and its year/month/day/weekday via [`Datelike`].
```rust ```rust,edition2018
extern crate chrono;
use chrono::{Datelike, Timelike, Utc}; use chrono::{Datelike, Timelike, Utc};
fn main() { fn main() {

View file

@ -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 and [RFC 3339] using [`DateTime::to_rfc3339`], and in a custom format using
[`DateTime::format`]. [`DateTime::format`].
```rust ```rust,edition2018
extern crate chrono;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
fn main() { fn main() {

View file

@ -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 identifies a date and a time. For parsing dates and times without timezones use
[`NaiveDate`], [`NaiveTime`], and [`NaiveDateTime`]. [`NaiveDate`], [`NaiveTime`], and [`NaiveDateTime`].
```rust ```rust,edition2018
extern crate chrono;
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime}; use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
use chrono::format::ParseError; use chrono::format::ParseError;

View file

@ -6,8 +6,7 @@ to [UNIX timestamp] using [`NaiveDateTime::timestamp`].
Then it calculates what was the date after one billion seconds Then it calculates what was the date after one billion seconds
since January 1, 1970 0:00:00 UTC, using [`NaiveDateTime::from_timestamp`]. since January 1, 1970 0:00:00 UTC, using [`NaiveDateTime::from_timestamp`].
```rust ```rust,edition2018
extern crate chrono;
use chrono::{NaiveDate, NaiveDateTime}; use chrono::{NaiveDate, NaiveDateTime};

View file

@ -18,9 +18,7 @@ cc = "1"
### `build.rs` ### `build.rs`
```rust,no_run ```rust,edition2018,no_run
extern crate cc;
fn main() { fn main() {
cc::Build::new() cc::Build::new()
.cpp(true) .cpp(true)
@ -43,7 +41,7 @@ int multiply(int x, int y) {
### `src/main.rs` ### `src/main.rs`
```rust,ignore ```rust,edition2018,ignore
extern { extern {
fn multiply(x : i32, y : i32) -> i32; fn multiply(x : i32, y : i32) -> i32;
} }

View file

@ -30,9 +30,7 @@ error-chain = "0.11"
### `build.rs` ### `build.rs`
```rust,no_run ```rust,edition2018,no_run
extern crate cc;
fn main() { fn main() {
cc::Build::new() cc::Build::new()
.file("src/hello.c") .file("src/hello.c")
@ -57,8 +55,7 @@ void greet(const char* name) {
### `src/main.rs` ### `src/main.rs`
```rust,ignore ```rust,edition2018,ignore
# #[macro_use] extern crate error_chain;
use std::ffi::CString; use std::ffi::CString;
use std::os::raw::c_char; use std::os::raw::c_char;
# #

View file

@ -23,9 +23,7 @@ cc = "1"
### `build.rs` ### `build.rs`
```rust,no_run ```rust,edition2018,no_run
extern crate cc;
fn main() { fn main() {
cc::Build::new() cc::Build::new()
.define("APP_NAME", "\"foo\"") .define("APP_NAME", "\"foo\"")
@ -51,7 +49,7 @@ void print_app_info() {
### `src/main.rs` ### `src/main.rs`
```rust,ignore ```rust,edition2018,ignore
extern { extern {
fn print_app_info(); fn print_app_info();
} }

View file

@ -11,12 +11,8 @@ encoding using a custom pattern from [`log4rs::encode::pattern`].
Assigns the configuration to [`log4rs::config::Config`] and sets the default Assigns the configuration to [`log4rs::config::Config`] and sets the default
[`log::LevelFilter`]. [`log::LevelFilter`].
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
#[macro_use]
extern crate log;
extern crate log4rs;
use log::LevelFilter; use log::LevelFilter;
use log4rs::append::file::FileAppender; use log4rs::append::file::FileAppender;
@ -44,7 +40,7 @@ fn main() -> Result<()> {
log4rs::init_config(config)?; log4rs::init_config(config)?;
info!("Hello, world!"); log::info!("Hello, world!");
Ok(()) Ok(())
} }

View file

@ -9,10 +9,7 @@ environment variable contents in the form of [`RUST_LOG`] syntax.
Then, [`Builder::init`] initializes the logger. Then, [`Builder::init`] initializes the logger.
All these steps are normally done internally by [`env_logger::init`]. All these steps are normally done internally by [`env_logger::init`].
```rust ```rust,edition2018
#[macro_use]
extern crate log;
extern crate env_logger;
use std::env; use std::env;
use env_logger::Builder; use env_logger::Builder;
@ -22,9 +19,9 @@ fn main() {
.parse(&env::var("MY_APP_LOG").unwrap_or_default()) .parse(&env::var("MY_APP_LOG").unwrap_or_default())
.init(); .init();
info!("informational message"); log::info!("informational message");
warn!("warning message"); log::warn!("warning message");
error!("this is an error {}", "message"); log::error!("this is an error {}", "message");
} }
``` ```

View file

@ -5,33 +5,30 @@
Creates two modules `foo` and nested `foo::bar` with logging directives Creates two modules `foo` and nested `foo::bar` with logging directives
controlled separately with [`RUST_LOG`] environmental variable. controlled separately with [`RUST_LOG`] environmental variable.
```rust ```rust,edition2018
#[macro_use]
extern crate log;
extern crate env_logger;
mod foo { mod foo {
mod bar { mod bar {
pub fn run() { pub fn run() {
warn!("[bar] warn"); log::warn!("[bar] warn");
info!("[bar] info"); log::info!("[bar] info");
debug!("[bar] debug"); log::debug!("[bar] debug");
} }
} }
pub fn run() { pub fn run() {
warn!("[foo] warn"); log::warn!("[foo] warn");
info!("[foo] info"); log::info!("[foo] info");
debug!("[foo] debug"); log::debug!("[foo] debug");
bar::run(); bar::run();
} }
} }
fn main() { fn main() {
env_logger::init(); env_logger::init();
warn!("[root] warn"); log::warn!("[root] warn");
info!("[root] info"); log::info!("[root] info");
debug!("[root] debug"); log::debug!("[root] debug");
foo::run(); foo::run();
} }
``` ```

View file

@ -10,12 +10,7 @@ a timestamp used in the final log.
The example calls [`Builder::format`] to set a closure which formats each The example calls [`Builder::format`] to set a closure which formats each
message text with timestamp, [`Record::level`] and body ([`Record::args`]). message text with timestamp, [`Record::level`] and body ([`Record::args`]).
```rust ```rust,edition2018
#[macro_use]
extern crate log;
extern crate chrono;
extern crate env_logger;
use std::io::Write; use std::io::Write;
use chrono::Local; use chrono::Local;
use env_logger::Builder; use env_logger::Builder;
@ -34,9 +29,9 @@ fn main() {
.filter(None, LevelFilter::Info) .filter(None, LevelFilter::Info)
.init(); .init();
warn!("warn"); log::warn!("warn");
info!("info"); log::info!("info");
debug!("debug"); log::debug!("debug");
} }
``` ```
stderr output will contain stderr output will contain

View file

@ -6,10 +6,7 @@ Implements a custom logger `ConsoleLogger` which prints to stdout.
In order to use the logging macros, `ConsoleLogger` implements In order to use the logging macros, `ConsoleLogger` implements
the [`log::Log`] trait and [`log::set_logger`] installs it. the [`log::Log`] trait and [`log::set_logger`] installs it.
```rust ```rust,edition2018
#[macro_use]
extern crate log;
use log::{Record, Level, Metadata, LevelFilter, SetLoggerError}; use log::{Record, Level, Metadata, LevelFilter, SetLoggerError};
static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger; static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger;
@ -34,9 +31,9 @@ fn main() -> Result<(), SetLoggerError> {
log::set_logger(&CONSOLE_LOGGER)?; log::set_logger(&CONSOLE_LOGGER)?;
log::set_max_level(LevelFilter::Info); log::set_max_level(LevelFilter::Info);
info!("hello log"); log::info!("hello log");
warn!("warning"); log::warn!("warning");
error!("oops"); log::error!("oops");
Ok(()) Ok(())
} }
``` ```

View file

@ -3,16 +3,13 @@
[![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging] [![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging]
The `log` crate provides logging utilities. The `env_logger` crate configures 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. [`std::fmt`] formatted strings.
```rust ```rust,edition2018
#[macro_use]
extern crate log;
extern crate env_logger;
fn execute_query(query: &str) { fn execute_query(query: &str) {
debug!("Executing query: {}", query); log::debug!("Executing query: {}", query);
} }
fn main() { fn main() {
@ -38,5 +35,5 @@ following line at the very end of the output:
DEBUG:main: Executing query: DROP TABLE students 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/ [`std::fmt`]: https://doc.rust-lang.org/std/fmt/

View file

@ -3,12 +3,9 @@
[![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging] [![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging]
Proper error handling considers exceptions exceptional. Here, an error logs 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 ```rust,edition2018
#[macro_use]
extern crate log;
extern crate env_logger;
fn execute_query(_query: &str) -> Result<(), &'static str> { fn execute_query(_query: &str) -> Result<(), &'static str> {
Err("I'm afraid I can't do that") Err("I'm afraid I can't do that")
@ -19,9 +16,9 @@ fn main() {
let response = execute_query("DROP TABLE students"); let response = execute_query("DROP TABLE students");
if let Err(err) = response { 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

View file

@ -4,10 +4,7 @@
Creates a custom logger configuration using the [`Builder::target`] to set the target of the log output to [`Target::Stdout`]. Creates a custom logger configuration using the [`Builder::target`] to set the target of the log output to [`Target::Stdout`].
```rust ```rust,edition2018
#[macro_use]
extern crate log;
extern crate env_logger;
use env_logger::{Builder, Target}; use env_logger::{Builder, Target};
@ -16,7 +13,7 @@ fn main() {
.target(Target::Stdout) .target(Target::Stdout)
.init(); .init();
error!("This error has been printed to Stdout"); log::error!("This error has been printed to Stdout");
} }
``` ```

View file

@ -7,12 +7,8 @@ with [`syslog::init`]. [`syslog::Facility`] records the program submitting
the log entry's classification, [`log::LevelFilter`] denotes allowed log verbosity the log entry's classification, [`log::LevelFilter`] denotes allowed log verbosity
and `Option<&str>` holds optional application name. and `Option<&str>` holds optional application name.
```rust ```rust,edition2018
#[macro_use]
extern crate log;
# #[cfg(target_os = "linux")] # #[cfg(target_os = "linux")]
extern crate syslog;
# #[cfg(target_os = "linux")] # #[cfg(target_os = "linux")]
use syslog::{Facility, Error}; use syslog::{Facility, Error};
@ -21,8 +17,8 @@ fn main() -> Result<(), Error> {
syslog::init(Facility::LOG_USER, syslog::init(Facility::LOG_USER,
log::LevelFilter::Debug, log::LevelFilter::Debug,
Some("My app name"))?; Some("My app name"))?;
debug!("this is a debug {}", "message"); log::debug!("this is a debug {}", "message");
error!("this is an error!"); log::error!("this is an error!");
Ok(()) Ok(())
} }

View file

@ -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 [`semver::VersionReq`] to the parsed version. The command output resembles
"git version x.y.z". "git version x.y.z".
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate semver;
use std::process::Command; use std::process::Command;
use semver::{Version, VersionReq}; use semver::{Version, VersionReq};
@ -30,7 +28,7 @@ fn main() -> Result<()> {
let output = Command::new("git").arg("--version").output()?; let output = Command::new("git").arg("--version").output()?;
if !output.status.success() { 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)?; let stdout = String::from_utf8(output.stdout)?;
@ -40,7 +38,7 @@ fn main() -> Result<()> {
let parsed_version = Version::parse(version)?; let parsed_version = Version::parse(version)?;
if !version_test.matches(&parsed_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); parsed_version, version_constraint);
} }

View file

@ -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 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. comparing versions. In other words, two versions may be equal even if their build strings differ.
```rust ```rust,edition2018
extern crate semver;
use semver::{Identifier, Version, SemVerError}; use semver::{Identifier, Version, SemVerError};
fn main() -> Result<(), SemVerError> { fn main() -> Result<(), SemVerError> {

View file

@ -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 incrementing the major version number resets both the minor and patch version
numbers to 0. numbers to 0.
```rust ```rust,edition2018
extern crate semver;
use semver::{Version, SemVerError}; use semver::{Version, SemVerError};
fn main() -> Result<(), SemVerError> { fn main() -> Result<(), SemVerError> {

View file

@ -6,10 +6,8 @@ Given a list of version &strs, finds the latest [`semver::Version`].
[`semver::VersionReq`] filters the list with [`VersionReq::matches`]. [`semver::VersionReq`] filters the list with [`VersionReq::matches`].
Also demonstrates `semver` pre-release preferences. Also demonstrates `semver` pre-release preferences.
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate semver;
use semver::{Version, VersionReq}; use semver::{Version, VersionReq};
# #

View file

@ -4,9 +4,7 @@
Given two versions, [`is_prerelease`] asserts that one is pre-release and the other is not. Given two versions, [`is_prerelease`] asserts that one is pre-release and the other is not.
```rust ```rust,edition2018
extern crate semver;
use semver::{Version, SemVerError}; use semver::{Version, SemVerError};
fn main() -> Result<(), SemVerError> { fn main() -> Result<(), SemVerError> {

View file

@ -6,8 +6,7 @@
be necessary when receiving information over the network, such that bytes be necessary when receiving information over the network, such that bytes
received are from another system. received are from another system.
```rust ```rust,edition2018
extern crate byteorder;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::io::Error; use std::io::Error;

View file

@ -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. The example below shows a `&str` of JSON being parsed. The expected value is declared using the [`json!`] macro.
```rust ```rust,edition2018
#[macro_use] use serde_json::json;
extern crate serde_json;
use serde_json::{Value, Error}; use serde_json::{Value, Error};
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {

View file

@ -5,9 +5,7 @@
Parse some TOML into a universal `toml::Value` that is able to represent any Parse some TOML into a universal `toml::Value` that is able to represent any
valid TOML data. valid TOML data.
```rust ```rust,edition2018
extern crate toml;
use toml::{Value, de::Error}; use toml::{Value, de::Error};
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
@ -33,10 +31,8 @@ fn main() -> Result<(), Error> {
Parse TOML into your own structs using [Serde]. Parse TOML into your own structs using [Serde].
```rust ```rust,edition2018
#[macro_use] use serde::Deserialize;
extern crate serde_derive;
extern crate toml;
use toml::de::Error; use toml::de::Error;
use std::collections::HashMap; use std::collections::HashMap;

View file

@ -4,12 +4,9 @@
Reads CSV records with a tab [`delimiter`]. Reads CSV records with a tab [`delimiter`].
```rust ```rust,edition2018
extern crate csv;
use csv::Error; use csv::Error;
#[macro_use] use serde::Deserialize;
extern crate serde_derive;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Record { struct Record {
name: String, name: String,

View file

@ -4,10 +4,8 @@
Returns _only_ the rows from `data` with a field that matches `query`. Returns _only_ the rows from `data` with a field that matches `query`.
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate csv;
use std::io; use std::io;
# #

View file

@ -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 provides a custom deserializer, [`csv::invalid_option`], which automatically
converts invalid data to None values. converts invalid data to None values.
```rust ```rust,edition2018
extern crate csv;
use csv::Error; use csv::Error;
#[macro_use] use serde::Deserialize;
extern crate serde_derive;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Record { struct Record {

View file

@ -6,8 +6,7 @@ Reads standard CSV records into [`csv::StringRecord`] — a weakly typed
data representation which expects valid UTF-8 rows. Alternatively, data representation which expects valid UTF-8 rows. Alternatively,
[`csv::ByteRecord`] makes no assumptions about UTF-8. [`csv::ByteRecord`] makes no assumptions about UTF-8.
```rust ```rust,edition2018
extern crate csv;
use csv::Error; use csv::Error;
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
@ -34,11 +33,8 @@ fn main() -> Result<(), Error> {
Serde deserializes data into strongly type structures. See the Serde deserializes data into strongly type structures. See the
[`csv::Reader::deserialize`] method. [`csv::Reader::deserialize`] method.
```rust ```rust,edition2018
extern crate csv; use serde::Deserialize;
#[macro_use]
extern crate serde_derive;
#[derive(Deserialize)] #[derive(Deserialize)]
struct Record { struct Record {
year: u16, year: u16,

View file

@ -5,13 +5,9 @@
The following example shows how to serialize custom structs as CSV records using The following example shows how to serialize custom structs as CSV records using
the [serde] crate. the [serde] crate.
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain; use serde::Serialize;
extern crate csv;
#[macro_use]
extern crate serde_derive;
use std::io; use std::io;
# #
# error_chain! { # error_chain! {

View file

@ -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 such as numbers, floats, and options use [`serialize`]. Since CSV
writer uses internal buffer, always explicitly [`flush`] when done. writer uses internal buffer, always explicitly [`flush`] when done.
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate csv;
use std::io; use std::io;
# #

View file

@ -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`] See [`csv::Reader::deserialize`], [`serde::Deserialize`], and [`std::str::FromStr`]
```rust ```rust,edition2018
extern crate csv; # use error_chain::error_chain;
# #[macro_use]
# extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use csv::{Reader, Writer}; use csv::{Reader, Writer};
use serde::{de, Deserialize, Deserializer}; use serde::{de, Deserialize, Deserializer};
use std::str::FromStr; use std::str::FromStr;

View file

@ -5,10 +5,8 @@
Encodes byte slice into `base64` String using [`encode`] Encodes byte slice into `base64` String using [`encode`]
and decodes it with [`decode`]. and decodes it with [`decode`].
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate base64;
use std::str; use std::str;
use base64::{encode, decode}; use base64::{encode, decode};

View file

@ -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 The example below coverts `&[u8]` data to hexadecimal equivalent. Compares this
value to the expected value. value to the expected value.
```rust ```rust,edition2018
extern crate data_encoding;
use data_encoding::{HEXUPPER, DecodeError}; use data_encoding::{HEXUPPER, DecodeError};
fn main() -> Result<(), DecodeError> { fn main() -> Result<(), DecodeError> {

View file

@ -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 from the `percent-encoding` crate. Then decode using the [`percent_decode`]
function. function.
```rust,ignore ```rust,edition2018,ignore
extern crate percent_encoding;
use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS}; use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS};
use std::str::Utf8Error; use std::str::Utf8Error;

View file

@ -7,8 +7,7 @@ using the [`form_urlencoded::byte_serialize`] and subsequently
decodes it with [`form_urlencoded::parse`]. Both functions return iterators decodes it with [`form_urlencoded::parse`]. Both functions return iterators
that collect into a `String`. that collect into a `String`.
```rust ```rust,edition2018
extern crate url;
use url::form_urlencoded::{byte_serialize, parse}; use url::form_urlencoded::{byte_serialize, parse};
fn main() { fn main() {

View file

@ -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 `u8`. An error will bubble up from Serde then csv and finally up to the
user code. user code.
```rust ```rust,edition2018
# extern crate csv; use error_chain::error_chain;
#[macro_use] # use serde::Deserialize;
extern crate error_chain;
# #[macro_use]
# extern crate serde_derive;
# #
# use std::fmt; # use std::fmt;
# #

View file

@ -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 Other recipes in this book will hide the [error-chain] boilerplate, and can be
seen by expanding the code with the ⤢ button. seen by expanding the code with the ⤢ button.
```rust ```rust,edition2018
#[macro_use] use error_chain::error_chain;
extern crate error_chain;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;

View file

@ -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 use [`foreign_links`]. An additional [`ErrorKind`] variant for the web service
error uses `errors` block of the `error_chain!` macro. error uses `errors` block of the `error_chain!` macro.
```rust ```rust,edition2018
#[macro_use] use error_chain::error_chain;
extern crate error_chain;
extern crate reqwest;
use std::io::Read; use std::io::Read;

View file

@ -5,9 +5,7 @@
Find recursively in the current directory duplicate filenames, Find recursively in the current directory duplicate filenames,
printing them only once. printing them only once.
```rust,no_run ```rust,edition2018,no_run
extern crate walkdir;
use std::collections::HashMap; use std::collections::HashMap;
use walkdir::WalkDir; use walkdir::WalkDir;

View file

@ -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 Using [`follow_links`] ensures symbolic links are followed like they were
normal directories and files. normal directories and files.
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate walkdir;
use walkdir::WalkDir; use walkdir::WalkDir;
# #

View file

@ -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`]. 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 ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate glob;
use glob::{glob_with, MatchOptions}; use glob::{glob_with, MatchOptions};
# #

View file

@ -10,9 +10,7 @@ ln -s /tmp/foo/ /tmp/foo/bar/baz/qux
``` ```
The following would assert that a loop exists. The following would assert that a loop exists.
```rust,no_run ```rust,edition2018,no_run
extern crate same_file;
use std::io; use std::io;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use same_file::is_same_file; use same_file::is_same_file;

View 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 compared with 24 hours (24 * 60 * 60 seconds). [`Metadata::is_file`] filters
out directories. out directories.
```rust ```rust,edition2018
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
# #
use std::{env, fs}; use std::{env, fs};

View file

@ -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` Use the `**` pattern in any path portion. For example, `/media/**/*.png`
matches all PNGs in `media` and it's subdirectories. matches all PNGs in `media` and it's subdirectories.
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate glob;
use glob::glob; use glob::glob;
# #

View file

@ -5,9 +5,7 @@
Recursion depth can be flexibly set by [`WalkDir::min_depth`] & [`WalkDir::max_depth`] methods. 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. Calculates sum of all file sizes to 3 subfolders depth, ignoring files in the root folder.
```rust ```rust,edition2018
extern crate walkdir;
use walkdir::WalkDir; use walkdir::WalkDir;
fn main() { fn main() {

View file

@ -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` Root dir `"."` yields through [`WalkDir::depth`] usage in `is_not_hidden`
predicate. predicate.
```rust,no_run ```rust,edition2018,no_run
extern crate walkdir;
use walkdir::{DirEntry, WalkDir}; use walkdir::{DirEntry, WalkDir};
fn is_not_hidden(entry: &DirEntry) -> bool { fn is_not_hidden(entry: &DirEntry) -> bool {

View file

@ -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 behind the memory map is not being modified at the same time by another process
or else a [race condition] occurs. or else a [race condition] occurs.
```rust ```rust,edition2018
extern crate memmap;
use memmap::Mmap; use memmap::Mmap;
use std::fs::File; use std::fs::File;
use std::io::{Write, Error}; use std::io::{Write, Error};

View file

@ -8,7 +8,7 @@ time with the [`Lines`] iterator created by
trait. [`File::create`] opens a [`File`] for writing, [`File::open`] for trait. [`File::create`] opens a [`File`] for writing, [`File::open`] for
reading. reading.
```rust ```rust,edition2018
use std::fs::File; use std::fs::File;
use std::io::{Write, BufReader, BufRead, Error}; use std::io::{Write, BufReader, BufRead, Error};

View file

@ -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 other handles. In this example, the handles of file to be read from and
to be written to are tested for equality. to be written to are tested for equality.
```rust,no_run ```rust,edition2018,no_run
extern crate same_file;
use same_file::Handle; use same_file::Handle;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::io::{BufRead, BufReader, Error, ErrorKind};

View file

@ -4,9 +4,7 @@
Shows the number of logical CPU cores in current machine using [`num_cpus::get`]. Shows the number of logical CPU cores in current machine using [`num_cpus::get`].
```rust ```rust,edition2018
extern crate num_cpus;
fn main() { fn main() {
println!("Number of logical cores is {}", num_cpus::get()); println!("Number of logical cores is {}", num_cpus::get());
} }

View file

@ -5,10 +5,8 @@
Declares a lazily evaluated constant [`HashMap`]. The [`HashMap`] will Declares a lazily evaluated constant [`HashMap`]. The [`HashMap`] will
be evaluated once and stored behind a global static reference. be evaluated once and stored behind a global static reference.
```rust ```rust,edition2018
#[macro_use] use lazy_static::lazy_static;
extern crate lazy_static;
use std::collections::HashMap; use std::collections::HashMap;
lazy_static! { lazy_static! {

View file

@ -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 listen until a request is made. `SocketAddrV4` assigns a random port when
setting port to 0. setting port to 0.
```rust,no_run ```rust,edition2018,no_run
use std::net::{SocketAddrV4, Ipv4Addr, TcpListener}; use std::net::{SocketAddrV4, Ipv4Addr, TcpListener};
use std::io::{Read, Error}; use std::io::{Read, Error};

View file

@ -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 The below recipe is equivalent to the Unix shell command
`journalctl | grep usb`. `journalctl | grep usb`.
```rust,no_run ```rust,edition2018,no_run
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::io::{BufRead, BufReader, Error, ErrorKind}; use std::io::{BufRead, BufReader, Error, ErrorKind};

View file

@ -12,7 +12,7 @@ cursor position.
The below recipe is equivalent to run the Unix shell command `ls The below recipe is equivalent to run the Unix shell command `ls
. oops >out.txt 2>&1`. . oops >out.txt 2>&1`.
```rust,no_run ```rust,edition2018,no_run
use std::fs::File; use std::fs::File;
use std::io::Error; use std::io::Error;
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};

View file

@ -9,9 +9,8 @@ sort -hr | head -n 10`.
[`Command`]s represent a process. Output of a child process is captured with a [`Command`]s represent a process. Output of a child process is captured with a
[`Stdio::piped`] between parent and child. [`Stdio::piped`] between parent and child.
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
# #
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
# #

View file

@ -5,10 +5,8 @@
Runs `git log --oneline` as an external [`Command`] and inspects its [`Output`] 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. using [`Regex`] to get the hash and message of the last 5 commits.
```rust,no_run ```rust,edition2018,no_run
# #[macro_use] # use error_chain::error_chain;
# extern crate error_chain;
extern crate regex;
use std::process::Command; use std::process::Command;
use regex::Regex; use regex::Regex;
@ -31,7 +29,7 @@ fn main() -> Result<()> {
let output = Command::new("git").arg("log").arg("--oneline").output()?; let output = Command::new("git").arg("log").arg("--oneline").output()?;
if !output.status.success() { 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) let pattern = Regex::new(r"(?x)

Some files were not shown because too many files have changed in this diff Show more