mirror of
https://github.com/rust-lang-nursery/rust-cookbook
synced 2024-11-22 03:23:05 +00:00
removed error-chain from examples having only one error variant (#525)
* removed error-chain from 'Calculate SHA1 sum of iso files concurrently' * removed error chain from 'Salt and hash a password with PBKDF2' * removed error-chain from 'Parse string into DateTime struct' * removed error-chain from 'Log messages with a custom logger' * fixed compiler errors * removed unnecessary feature flag * removed error-chain from 'Log to the Unix syslog' * removed error-chain from 'Parse and increment a version string.' * removed error-chain from 'Parse a complex version string.' * removed error-chain from 'Check if given version is pre-release.' * removed error-chain from 'Percent-encode a string' * removed error-chain from 'Encode and decode hex' * removed error-chain from 'Read CSV records' * removed error-chain from 'Read CSV records with different delimiter' * removed error-chain from 'Handle invalid CSV data with Serde' * removed error-chain from 'Serialize and deserialize unstructured JSON' * removed error-chain from 'Deserialize a TOML configuration file' * removed error-chain from 'Read and write integers in little-endian byte order' * removed error-chain from 'Read lines of strings from a file' * removed error-chain from 'Avoid writing and reading from a same file' * removed error-chain from 'Access a file randomly using a memory map' * removed error-chain from 'Listen on unused port TCP/IP' * removed error-chain from 'Redirect both stdout and stderr of child process to the same file' * removed error-chain from 'Continuously process child process' outputs' * removed error-chain from 'Parse a URL from a string to a `Url` type' * removed error-chain from 'Create new URLs from a base URL' * removed error-chain from 'Extract the URL origin (scheme / host / port)' * removed error-chain from 'Remove fragment identifiers and query pairs from a URL' * removed error-chain from 'Query the GitHub API' * removed error-chain from 'Check if an API resource exists' * removed error-chain from 'Consume a paginated RESTful API' * addressed Travis CI failure * addressed Travis CI failure * addressed Travis CI issue
This commit is contained in:
parent
99e3d6b333
commit
cb949b04c0
30 changed files with 120 additions and 411 deletions
|
@ -9,22 +9,14 @@ the current directory and calls [`execute`] to perform the operations of reading
|
|||
and computing SHA1 hash.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate walkdir;
|
||||
extern crate ring;
|
||||
extern crate num_cpus;
|
||||
extern crate threadpool;
|
||||
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(std::io::Error);
|
||||
# }
|
||||
# }
|
||||
#
|
||||
use walkdir::WalkDir;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read};
|
||||
use std::io::{BufReader, Read, Error};
|
||||
use std::path::Path;
|
||||
use threadpool::ThreadPool;
|
||||
use std::sync::mpsc::channel;
|
||||
|
@ -37,8 +29,8 @@ use ring::digest::{Context, Digest, SHA1};
|
|||
# _ => false,
|
||||
# }
|
||||
# }
|
||||
#
|
||||
fn compute_digest<P: AsRef<Path>>(filepath: P) -> Result<(Digest, P)> {
|
||||
|
||||
fn compute_digest<P: AsRef<Path>>(filepath: P) -> Result<(Digest, P), Error> {
|
||||
let mut buf_reader = BufReader::new(File::open(&filepath)?);
|
||||
let mut context = Context::new(&SHA1);
|
||||
let mut buffer = [0; 1024];
|
||||
|
@ -54,7 +46,7 @@ fn compute_digest<P: AsRef<Path>>(filepath: P) -> Result<(Digest, P)> {
|
|||
Ok((context.finish(), filepath))
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let pool = ThreadPool::new(num_cpus::get());
|
||||
|
||||
let (tx, rx) = channel();
|
||||
|
@ -79,8 +71,6 @@ fn run() -> Result<()> {
|
|||
}
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`execute`]: https://docs.rs/threadpool/*/threadpool/struct.ThreadPool.html#method.execute
|
||||
|
|
|
@ -10,64 +10,55 @@ function [`pbkdf2::derive`]. Verifies the hash is correct with
|
|||
securely generated random numbers.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate data_encoding;
|
||||
extern crate ring;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Ring(ring::error::Unspecified);
|
||||
# }
|
||||
# }
|
||||
extern crate data_encoding;
|
||||
|
||||
use data_encoding::HEXUPPER;
|
||||
use ring::{digest, pbkdf2, rand};
|
||||
use ring::error::Unspecified;
|
||||
use ring::rand::SecureRandom;
|
||||
use ring::{digest, pbkdf2, rand};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
const CREDENTIAL_LEN: usize = digest::SHA512_OUTPUT_LEN;
|
||||
const N_ITER: u32 = 100_000;
|
||||
let rng = rand::SystemRandom::new();
|
||||
fn main() -> Result<(), Unspecified> {
|
||||
const CREDENTIAL_LEN: usize = digest::SHA512_OUTPUT_LEN;
|
||||
const N_ITER: u32 = 100_000;
|
||||
let rng = rand::SystemRandom::new();
|
||||
|
||||
let mut salt = [0u8; CREDENTIAL_LEN];
|
||||
rng.fill(&mut salt)?;
|
||||
let mut salt = [0u8; CREDENTIAL_LEN];
|
||||
rng.fill(&mut salt)?;
|
||||
|
||||
let password = "Guess Me If You Can!";
|
||||
let mut pbkdf2_hash = [0u8; CREDENTIAL_LEN];
|
||||
pbkdf2::derive(
|
||||
&digest::SHA512,
|
||||
N_ITER,
|
||||
&salt,
|
||||
password.as_bytes(),
|
||||
&mut pbkdf2_hash,
|
||||
);
|
||||
println!("Salt: {}", HEXUPPER.encode(&salt));
|
||||
println!("PBKDF2 hash: {}", HEXUPPER.encode(&pbkdf2_hash));
|
||||
let password = "Guess Me If You Can!";
|
||||
let mut pbkdf2_hash = [0u8; CREDENTIAL_LEN];
|
||||
pbkdf2::derive(
|
||||
&digest::SHA512,
|
||||
N_ITER,
|
||||
&salt,
|
||||
password.as_bytes(),
|
||||
&mut pbkdf2_hash,
|
||||
);
|
||||
println!("Salt: {}", HEXUPPER.encode(&salt));
|
||||
println!("PBKDF2 hash: {}", HEXUPPER.encode(&pbkdf2_hash));
|
||||
|
||||
let should_succeed = pbkdf2::verify(
|
||||
&digest::SHA512,
|
||||
N_ITER,
|
||||
&salt,
|
||||
password.as_bytes(),
|
||||
&pbkdf2_hash,
|
||||
);
|
||||
let wrong_password = "Definitely not the correct password";
|
||||
let should_fail = pbkdf2::verify(
|
||||
&digest::SHA512,
|
||||
N_ITER,
|
||||
&salt,
|
||||
wrong_password.as_bytes(),
|
||||
&pbkdf2_hash,
|
||||
);
|
||||
let should_succeed = pbkdf2::verify(
|
||||
&digest::SHA512,
|
||||
N_ITER,
|
||||
&salt,
|
||||
password.as_bytes(),
|
||||
&pbkdf2_hash,
|
||||
);
|
||||
let wrong_password = "Definitely not the correct password";
|
||||
let should_fail = pbkdf2::verify(
|
||||
&digest::SHA512,
|
||||
N_ITER,
|
||||
&salt,
|
||||
wrong_password.as_bytes(),
|
||||
&pbkdf2_hash,
|
||||
);
|
||||
|
||||
assert!(should_succeed.is_ok());
|
||||
assert!(!should_fail.is_ok());
|
||||
assert!(should_succeed.is_ok());
|
||||
assert!(!should_fail.is_ok());
|
||||
|
||||
Ok(())
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`pbkdf2::derive`]: https://briansmith.org/rustdoc/ring/pbkdf2/fn.derive.html
|
||||
|
|
|
@ -5,20 +5,13 @@
|
|||
Uses [`ring::hmac`] to creates a [`hmac::Signature`] of a string then verifies the signature is correct.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate ring;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Ring(ring::error::Unspecified);
|
||||
# }
|
||||
# }
|
||||
|
||||
use ring::{digest, hmac, rand};
|
||||
use ring::rand::SecureRandom;
|
||||
use ring::error::Unspecified;
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Unspecified> {
|
||||
let mut key_value = [0u8; 48];
|
||||
let rng = rand::SystemRandom::new();
|
||||
rng.fill(&mut key_value)?;
|
||||
|
@ -30,8 +23,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`hmac::Signature`]: https://briansmith.org/rustdoc/ring/hmac/struct.Signature.html
|
||||
|
|
|
@ -15,18 +15,11 @@ identifies a date and a time. For parsing dates and times without timezones use
|
|||
|
||||
```rust
|
||||
extern crate chrono;
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#
|
||||
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# DateParse(chrono::format::ParseError);
|
||||
# }
|
||||
# }
|
||||
use chrono::format::ParseError;
|
||||
|
||||
fn run() -> Result<()> {
|
||||
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let rfc2822 = DateTime::parse_from_rfc2822("Tue, 1 Jul 2003 10:52:37 +0200")?;
|
||||
println!("{}", rfc2822);
|
||||
|
||||
|
@ -47,8 +40,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`chrono::format::strftime`]: https://docs.rs/chrono/*/chrono/format/strftime/index.html
|
||||
|
|
|
@ -7,12 +7,10 @@ In order to use the logging macros, `ConsoleLogger` implements
|
|||
the [`log::Log`] trait and [`log::set_logger`] installs it.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
use log::{Record, Level, Metadata, LevelFilter};
|
||||
use log::{Record, Level, Metadata, LevelFilter, SetLoggerError};
|
||||
|
||||
static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger;
|
||||
|
||||
|
@ -31,14 +29,8 @@ impl log::Log for ConsoleLogger {
|
|||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# SetLogger(log::SetLoggerError);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), SetLoggerError> {
|
||||
log::set_logger(&CONSOLE_LOGGER)?;
|
||||
log::set_max_level(LevelFilter::Info);
|
||||
|
||||
|
@ -47,8 +39,6 @@ fn run() -> Result<()> {
|
|||
error!("oops");
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`log::Log`]: https://docs.rs/log/*/log/trait.Log.html
|
||||
|
|
|
@ -8,26 +8,16 @@ the log entry's classification, [`log::LevelFilter`] denotes allowed log verbosi
|
|||
and `Option<&str>` holds optional application name.
|
||||
|
||||
```rust
|
||||
# #![allow(unused_imports)]
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
# #[cfg(target_os = "linux")]
|
||||
extern crate syslog;
|
||||
|
||||
# #[cfg(target_os = "linux")]
|
||||
use syslog::Facility;
|
||||
#
|
||||
# #[cfg(target_os = "linux")]
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# SetLogger(syslog::Error);
|
||||
# }
|
||||
# }
|
||||
use syslog::{Facility, Error};
|
||||
|
||||
# #[cfg(target_os = "linux")]
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
syslog::init(Facility::LOG_USER,
|
||||
log::LevelFilter::Debug,
|
||||
Some("My app name"))?;
|
||||
|
@ -35,15 +25,11 @@ fn run() -> Result<()> {
|
|||
error!("this is an error!");
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
|
||||
# #[cfg(not(target_os = "linux"))]
|
||||
# error_chain! {}
|
||||
# #[cfg(not(target_os = "linux"))]
|
||||
# fn run() -> Result<()> {
|
||||
# Ok(())
|
||||
# fn main() {
|
||||
# println!("So far, only Linux systems are supported.");
|
||||
# }
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`log::LevelFilter`]: https://docs.rs/log/*/log/enum.LevelFilter.html
|
||||
|
|
|
@ -9,19 +9,11 @@ Note that, in accordance with the Specification, build metadata is parsed but no
|
|||
comparing versions. In other words, two versions may be equal even if their build strings differ.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate semver;
|
||||
|
||||
use semver::{Identifier, Version};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# SemVer(semver::SemVerError);
|
||||
# }
|
||||
# }
|
||||
use semver::{Identifier, Version, SemVerError};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), SemVerError> {
|
||||
let version_str = "1.0.49-125+g72ee7853";
|
||||
let parsed_version = Version::parse(version_str)?;
|
||||
|
||||
|
@ -45,8 +37,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`semver::Version`]: https://docs.rs/semver/*/semver/struct.Version.html
|
||||
|
|
|
@ -11,19 +11,11 @@ incrementing the major version number resets both the minor and patch version
|
|||
numbers to 0.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate semver;
|
||||
|
||||
use semver::Version;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# SemVer(semver::SemVerError);
|
||||
# }
|
||||
# }
|
||||
use semver::{Version, SemVerError};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), SemVerError> {
|
||||
let mut parsed_version = Version::parse("0.2.6")?;
|
||||
|
||||
assert_eq!(
|
||||
|
@ -51,8 +43,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`semver::Version`]: https://docs.rs/semver/*/semver/struct.Version.html
|
||||
|
|
|
@ -5,19 +5,11 @@
|
|||
Given two versions, [`is_prerelease`] asserts that one is pre-release and the other is not.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate semver;
|
||||
|
||||
use semver::Version;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# SemVer(semver::SemVerError);
|
||||
# }
|
||||
# }
|
||||
use semver::{Version, SemVerError};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), SemVerError> {
|
||||
let version_1 = Version::parse("1.0.0-alpha")?;
|
||||
let version_2 = Version::parse("1.0.0")?;
|
||||
|
||||
|
@ -26,8 +18,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`is_prerelease`]: https://docs.rs/semver/*/semver/struct.Version.html#method.is_prerelease
|
||||
|
|
|
@ -7,25 +7,18 @@ be necessary when receiving information over the network, such that bytes
|
|||
received are from another system.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate byteorder;
|
||||
|
||||
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
|
||||
use std::io::Error;
|
||||
|
||||
#[derive(Default, PartialEq, Debug)]
|
||||
struct Payload {
|
||||
kind: u8,
|
||||
value: u16,
|
||||
}
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(std::io::Error);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let original_payload = Payload::default();
|
||||
let encoded_bytes = encode(&original_payload)?;
|
||||
let decoded_payload = decode(&encoded_bytes)?;
|
||||
|
@ -33,20 +26,18 @@ fn run() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn encode(payload: &Payload) -> Result<Vec<u8>> {
|
||||
fn encode(payload: &Payload) -> Result<Vec<u8>, Error> {
|
||||
let mut bytes = vec![];
|
||||
bytes.write_u8(payload.kind)?;
|
||||
bytes.write_u16::<LittleEndian>(payload.value)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn decode(mut bytes: &[u8]) -> Result<Payload> {
|
||||
fn decode(mut bytes: &[u8]) -> Result<Payload, Error> {
|
||||
let payload = Payload {
|
||||
kind: bytes.read_u8()?,
|
||||
value: bytes.read_u16::<LittleEndian>()?,
|
||||
};
|
||||
Ok(payload)
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
|
|
@ -11,20 +11,12 @@ 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 error_chain;
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
|
||||
use serde_json::Value;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Json(serde_json::Error);
|
||||
# }
|
||||
# }
|
||||
use serde_json::{Value, Error};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let j = r#"{
|
||||
"userid": 103609,
|
||||
"verified": true,
|
||||
|
@ -49,8 +41,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`from_str`]: https://docs.serde.rs/serde_json/fn.from_str.html
|
||||
|
|
|
@ -6,19 +6,11 @@ Parse some TOML into a universal `toml::Value` that is able to represent any
|
|||
valid TOML data.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate toml;
|
||||
|
||||
use toml::Value;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Toml(toml::de::Error);
|
||||
# }
|
||||
# }
|
||||
use toml::{Value, de::Error};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let toml_content = r#"
|
||||
[package]
|
||||
name = "your_package"
|
||||
|
@ -37,8 +29,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
Parse TOML into your own structs using [Serde].
|
||||
|
|
|
@ -5,9 +5,8 @@
|
|||
Reads CSV records with a tab [`delimiter`].
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate csv;
|
||||
use csv::Error;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
|
@ -20,17 +19,11 @@ struct Record {
|
|||
}
|
||||
|
||||
use csv::ReaderBuilder;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# CsvError(csv::Error);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let data = "name\tplace\tid
|
||||
Mark\tMelbourne\t46
|
||||
Ashley\tZurich\t92";
|
||||
Mark\tMelbourne\t46
|
||||
Ashley\tZurich\t92";
|
||||
|
||||
let mut reader = ReaderBuilder::new().delimiter(b'\t').from_reader(data.as_bytes());
|
||||
for result in reader.deserialize::<Record>() {
|
||||
|
@ -39,8 +32,6 @@ Ashley\tZurich\t92";
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`delimiter`]: https://docs.rs/csv/1.0.0-beta.3/csv/struct.ReaderBuilder.html#method.delimiter
|
||||
|
|
|
@ -7,9 +7,8 @@ provides a custom deserializer, [`csv::invalid_option`], which automatically
|
|||
converts invalid data to None values.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate csv;
|
||||
use csv::Error;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
|
@ -20,14 +19,8 @@ struct Record {
|
|||
#[serde(deserialize_with = "csv::invalid_option")]
|
||||
id: Option<u64>,
|
||||
}
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# CsvError(csv::Error);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let data = "name,place,id
|
||||
mark,sydney,46.5
|
||||
ashley,zurich,92
|
||||
|
@ -42,8 +35,6 @@ alisha,colombo,xyz";
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`csv::invalid_option`]: https://docs.rs/csv/*/csv/fn.invalid_option.html
|
||||
|
|
|
@ -8,19 +8,12 @@ data representation which expects valid UTF-8 rows. Alternatively,
|
|||
|
||||
```rust
|
||||
extern crate csv;
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Reader(csv::Error);
|
||||
# }
|
||||
# }
|
||||
use csv::Error;
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let csv = "year,make,model,description
|
||||
1948,Porsche,356,Luxury sports car
|
||||
1967,Ford,Mustang fastback 1967,American car";
|
||||
1948,Porsche,356,Luxury sports car
|
||||
1967,Ford,Mustang fastback 1967,American car";
|
||||
|
||||
let mut reader = csv::Reader::from_reader(csv.as_bytes());
|
||||
for record in reader.records() {
|
||||
|
@ -36,8 +29,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
Serde deserializes data into strongly type structures. See the
|
||||
|
|
|
@ -13,19 +13,11 @@ The example below coverts `&[u8]` data to hexadecimal equivalent. Compares this
|
|||
value to the expected value.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate data_encoding;
|
||||
|
||||
use data_encoding::{HEXUPPER, DecodeError};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Decode(DecodeError);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), DecodeError> {
|
||||
let original = b"The quick brown fox jumps over the lazy dog.";
|
||||
let expected = "54686520717569636B2062726F776E20666F78206A756D7073206F76\
|
||||
657220746865206C617A7920646F672E";
|
||||
|
@ -38,8 +30,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`data_encoding`]: https://docs.rs/data-encoding/*/data_encoding/
|
||||
|
|
|
@ -7,19 +7,12 @@ function from the `url` crate. Then decode using the [`percent_decode`]
|
|||
function.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate url;
|
||||
|
||||
use url::percent_encoding::{utf8_percent_encode, percent_decode, DEFAULT_ENCODE_SET};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Utf8(std::str::Utf8Error);
|
||||
# }
|
||||
# }
|
||||
use std::str::Utf8Error;
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Utf8Error> {
|
||||
let input = "confident, productive systems programming";
|
||||
|
||||
let iter = utf8_percent_encode(input, DEFAULT_ENCODE_SET);
|
||||
|
@ -32,8 +25,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
The encode set defines which bytes (in addition to non-ASCII and controls) need
|
||||
|
|
|
@ -11,21 +11,13 @@ behind the memory map is not being modified at the same time by another process
|
|||
or else a [race condition] occurs.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate memmap;
|
||||
|
||||
use memmap::Mmap;
|
||||
# use std::fs::File;
|
||||
# use std::io::Write;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(std::io::Error);
|
||||
# }
|
||||
# }
|
||||
use std::fs::File;
|
||||
use std::io::{Write, Error};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
# write!(File::create("content.txt")?, "My hovercraft is full of eels!")?;
|
||||
#
|
||||
let file = File::open("content.txt")?;
|
||||
|
@ -39,8 +31,6 @@ fn run() -> Result<()> {
|
|||
assert_eq!(&random_bytes[..], b"My loaf!");
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`Mmap::map`]: https://docs.rs/memmap/*/memmap/struct.Mmap.html#method.map
|
||||
|
|
|
@ -9,19 +9,10 @@ trait. [`File::create`] opens a [`File`] for writing, [`File::open`] for
|
|||
reading.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#
|
||||
use std::fs::File;
|
||||
use std::io::{Write, BufReader, BufRead};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(std::io::Error);
|
||||
# }
|
||||
# }
|
||||
use std::io::{Write, BufReader, BufRead, Error};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let path = "lines.txt";
|
||||
|
||||
let mut output = File::create(path)?;
|
||||
|
@ -36,8 +27,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`BufRead::lines`]: https://doc.rust-lang.org/std/io/trait.BufRead.html#method.lines
|
||||
|
|
|
@ -7,29 +7,24 @@ 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
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate same_file;
|
||||
|
||||
use same_file::Handle;
|
||||
use std::path::Path;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# IOError(::std::io::Error);
|
||||
# }
|
||||
# }
|
||||
use std::io::{BufRead, BufReader, Error, ErrorKind};
|
||||
use std::path::Path;
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let path_to_read = Path::new("new.txt");
|
||||
|
||||
let stdout_handle = Handle::stdout()?;
|
||||
let handle = Handle::from_path(path_to_read)?;
|
||||
|
||||
if stdout_handle == handle {
|
||||
bail!("You are reading and writing to the same file");
|
||||
return Err(Error::new(
|
||||
ErrorKind::Other,
|
||||
"You are reading and writing to the same file",
|
||||
));
|
||||
} else {
|
||||
let file = File::open(&path_to_read)?;
|
||||
let file = BufReader::new(file);
|
||||
|
@ -40,8 +35,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
```bash
|
||||
|
|
|
@ -7,19 +7,10 @@ listen until a request is made. `SocketAddrV4` assigns a random port when
|
|||
setting port to 0.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#
|
||||
use std::net::{SocketAddrV4, Ipv4Addr, TcpListener};
|
||||
use std::io::Read;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(::std::io::Error);
|
||||
# }
|
||||
# }
|
||||
use std::io::{Read, Error};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let loopback = Ipv4Addr::new(127, 0, 0, 1);
|
||||
let socket = SocketAddrV4::new(loopback, 0);
|
||||
let listener = TcpListener::bind(socket)?;
|
||||
|
@ -32,6 +23,4 @@ fn run() -> Result<()> {
|
|||
println!("{:?} says {}", addr, input);
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
|
17
src/os/external/continuous.md
vendored
17
src/os/external/continuous.md
vendored
|
@ -11,24 +11,15 @@ The below recipe is equivalent to the Unix shell command
|
|||
`journalctl | grep usb`.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#
|
||||
use std::process::{Command, Stdio};
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::io::{BufRead, BufReader, Error, ErrorKind};
|
||||
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(std::io::Error);
|
||||
# }
|
||||
# }
|
||||
#
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let stdout = Command::new("journalctl")
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?
|
||||
.stdout
|
||||
.ok_or_else(|| "Could not capture standard output.")?;
|
||||
.ok_or_else(|| Error::new(ErrorKind::Other,"Could not capture standard output."))?;
|
||||
|
||||
let reader = BufReader::new(stdout);
|
||||
|
||||
|
@ -40,8 +31,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`BufReader`]: https://doc.rust-lang.org/std/io/struct.BufReader.html
|
||||
|
|
14
src/os/external/error-file.md
vendored
14
src/os/external/error-file.md
vendored
|
@ -13,19 +13,11 @@ The below recipe is equivalent to run the Unix shell command `ls
|
|||
. oops >out.txt 2>&1`.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#
|
||||
use std::fs::File;
|
||||
use std::io::Error;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Io(std::io::Error);
|
||||
# }
|
||||
# }
|
||||
#
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let outputs = File::create("out.txt")?;
|
||||
let errors = outputs.try_clone()?;
|
||||
|
||||
|
@ -38,8 +30,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`File::try_clone`]: https://doc.rust-lang.org/std/fs/struct.File.html#method.try_clone
|
||||
|
|
|
@ -7,17 +7,10 @@ fetches the next page of results from the remote server as it arrives at the end
|
|||
of each page.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate reqwest;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Reqwest(reqwest::Error);
|
||||
# }
|
||||
# }
|
||||
use reqwest::Error;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ApiResponse {
|
||||
|
@ -45,7 +38,7 @@ struct ReverseDependencies {
|
|||
}
|
||||
|
||||
impl ReverseDependencies {
|
||||
fn of(crate_id: &str) -> Result<Self> {
|
||||
fn of(crate_id: &str) -> Result<Self, Error> {
|
||||
Ok(ReverseDependencies {
|
||||
crate_id: crate_id.to_owned(),
|
||||
dependencies: vec![].into_iter(),
|
||||
|
@ -56,7 +49,7 @@ impl ReverseDependencies {
|
|||
})
|
||||
}
|
||||
|
||||
fn try_next(&mut self) -> Result<Option<Dependency>> {
|
||||
fn try_next(&mut self) -> Result<Option<Dependency>, Error> {
|
||||
if let Some(dep) = self.dependencies.next() {
|
||||
return Ok(Some(dep));
|
||||
}
|
||||
|
@ -79,7 +72,7 @@ impl ReverseDependencies {
|
|||
}
|
||||
|
||||
impl Iterator for ReverseDependencies {
|
||||
type Item = Result<Dependency>;
|
||||
type Item = Result<Dependency, Error>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.try_next() {
|
||||
|
@ -90,12 +83,10 @@ impl Iterator for ReverseDependencies {
|
|||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
for dep in ReverseDependencies::of("serde")? {
|
||||
println!("reverse dependency: {}", dep?.crate_id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
|
|
@ -6,25 +6,18 @@ Queries GitHub [stargazers API v3](https://developer.github.com/v3/activity/star
|
|||
with [`reqwest::get`] to get list of all users who have marked a GitHub project with a star. [`reqwest::Response`] is deserialized with [`Response::json`] into `User` objects implementing [`serde::Deserialize`].
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate reqwest;
|
||||
use reqwest::Error;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct User {
|
||||
login: String,
|
||||
id: u32,
|
||||
}
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Reqwest(reqwest::Error);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), Error> {
|
||||
let request_url = format!("https://api.github.com/repos/{owner}/{repo}/stargazers",
|
||||
owner = "rust-lang-nursery",
|
||||
repo = "rust-cookbook");
|
||||
|
@ -35,8 +28,6 @@ fn run() -> Result<()> {
|
|||
println!("{:?}", users);
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`reqwest::get`]: https://docs.rs/reqwest/*/reqwest/fn.get.html
|
||||
|
|
|
@ -9,20 +9,14 @@ a body. [`reqwest::Client`] cofigured with [`ClientBuilder::timeout`] ensures
|
|||
a request will not last longer than a timeout.
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate reqwest;
|
||||
|
||||
use reqwest::Error;
|
||||
use std::time::Duration;
|
||||
use reqwest::ClientBuilder;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# Reqwest(reqwest::Error);
|
||||
# }
|
||||
# }
|
||||
|
||||
fn run() -> Result<()> {
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
let user = "ferris-the-crab";
|
||||
let request_url = format!("https://api.github.com/users/{}", user);
|
||||
println!("{}", request_url);
|
||||
|
@ -39,8 +33,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`Client::head`]: https://docs.rs/reqwest/*/reqwest/struct.Client.html#method.head
|
||||
|
|
|
@ -5,26 +5,17 @@
|
|||
Parses [`Url`] and slices it with [`url::Position`] to strip unneeded URL parts.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
|
||||
extern crate url;
|
||||
|
||||
use url::{Url, Position};
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# UrlParse(url::ParseError);
|
||||
# }
|
||||
# }
|
||||
use url::{Url, Position, ParseError};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let parsed = Url::parse("https://github.com/rust-lang/rust/issues?labels=E-easy&state=open")?;
|
||||
let cleaned: &str = &parsed[..Position::AfterPath];
|
||||
println!("cleaned: {}", cleaned);
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`url::Position`]: https://docs.rs/url/*/url/enum.Position.html
|
||||
|
|
|
@ -5,19 +5,11 @@
|
|||
The [`join`] method creates a new URL from a base and relative path.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate url;
|
||||
|
||||
use url::Url;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# UrlParse(url::ParseError);
|
||||
# }
|
||||
# }
|
||||
use url::{Url, ParseError};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let path = "/rust-lang/cargo";
|
||||
|
||||
let gh = build_github_url(path)?;
|
||||
|
@ -28,7 +20,7 @@ fn run() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn build_github_url(path: &str) -> Result<Url> {
|
||||
fn build_github_url(path: &str) -> Result<Url, ParseError> {
|
||||
const GITHUB: &'static str = "https://github.com";
|
||||
|
||||
let base = Url::parse(GITHUB).expect("hardcoded URL is known to be valid");
|
||||
|
@ -36,8 +28,6 @@ fn build_github_url(path: &str) -> Result<Url> {
|
|||
|
||||
Ok(joined)
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`join`]: https://docs.rs/url/*/url/struct.Url.html#method.join
|
||||
|
|
|
@ -6,19 +6,11 @@ The [`Url`] struct exposes various methods to extract information about the URL
|
|||
it represents.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate url;
|
||||
|
||||
use url::{Url, Host};
|
||||
use url::{Url, Host, ParseError};
|
||||
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# UrlParse(url::ParseError);
|
||||
# }
|
||||
# }
|
||||
#
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let s = "ftp://rust-lang.org/examples";
|
||||
|
||||
let url = Url::parse(s)?;
|
||||
|
@ -30,8 +22,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`origin`] produces the same result.
|
||||
|
|
|
@ -10,19 +10,11 @@ Once the URL has been parsed, it can be used with all of the methods in the
|
|||
`Url` type.
|
||||
|
||||
```rust
|
||||
# #[macro_use]
|
||||
# extern crate error_chain;
|
||||
extern crate url;
|
||||
|
||||
use url::Url;
|
||||
#
|
||||
# error_chain! {
|
||||
# foreign_links {
|
||||
# UrlParse(url::ParseError);
|
||||
# }
|
||||
# }
|
||||
use url::{Url, ParseError};
|
||||
|
||||
fn run() -> Result<()> {
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let s = "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open";
|
||||
|
||||
let parsed = Url::parse(s)?;
|
||||
|
@ -30,8 +22,6 @@ fn run() -> Result<()> {
|
|||
|
||||
Ok(())
|
||||
}
|
||||
#
|
||||
# quick_main!(run);
|
||||
```
|
||||
|
||||
[`parse`]: https://docs.rs/url/*/url/struct.Url.html#method.parse
|
||||
|
|
Loading…
Reference in a new issue