]> git.proxmox.com Git - rustc.git/blob - vendor/failure/book/src/intro.md
New upstream version 1.42.0+dfsg0+pve1
[rustc.git] / vendor / failure / book / src / intro.md
1 # failure
2
3 This is the documentation for the failure crate, which provides a system for
4 creating and managing errors in Rust. Additional documentation is found here:
5
6 * [API documentation][api]
7 * [failure source code][repo]
8
9 [api]: https://docs.rs/failure
10 [repo]: https://github.com/rust-lang-nursery/failure
11
12 ```rust
13 extern crate serde;
14 extern crate toml;
15
16 #[macro_use] extern crate failure;
17 #[macro_use] extern crate serde_derive;
18
19 use std::collections::HashMap;
20 use std::path::PathBuf;
21 use std::str::FromStr;
22
23 use failure::Error;
24
25 // This is a new error type that you've created. It represents the ways a
26 // toolchain could be invalid.
27 //
28 // The custom derive for Fail derives an impl of both Fail and Display.
29 // We don't do any other magic like creating new types.
30 #[derive(Debug, Fail)]
31 enum ToolchainError {
32 #[fail(display = "invalid toolchain name: {}", name)]
33 InvalidToolchainName {
34 name: String,
35 },
36 #[fail(display = "unknown toolchain version: {}", version)]
37 UnknownToolchainVersion {
38 version: String,
39 }
40 }
41
42 pub struct ToolchainId {
43 // ... etc
44 }
45
46 impl FromStr for ToolchainId {
47 type Err = ToolchainError;
48
49 fn from_str(s: &str) -> Result<ToolchainId, ToolchainError> {
50 // ... etc
51 }
52 }
53
54 pub type Toolchains = HashMap<ToolchainId, PathBuf>;
55
56 // This opens a toml file containing associations between ToolchainIds and
57 // Paths (the roots of those toolchains).
58 //
59 // This could encounter an io Error, a toml parsing error, or a ToolchainError,
60 // all of them will be thrown into the special Error type
61 pub fn read_toolchains(path: PathBuf) -> Result<Toolchains, Error>
62 {
63 use std::fs::File;
64 use std::io::Read;
65
66 let mut string = String::new();
67 File::open(path)?.read_to_string(&mut string)?;
68
69 let toml: HashMap<String, PathBuf> = toml::from_str(&string)?;
70
71 let toolchains = toml.iter().map(|(key, path)| {
72 let toolchain_id = key.parse()?;
73 Ok((toolchain_id, path))
74 }).collect::<Result<Toolchains, ToolchainError>>()?;
75
76 Ok(toolchains)
77 }