File: basic.rs

package info (click to toggle)
rust-snafu 0.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 664 kB
  • sloc: sh: 15; makefile: 4
file content (49 lines) | stat: -rw-r--r-- 1,333 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#![cfg(feature="std")]
use snafu::prelude::*;
use std::{
    fs, io,
    path::{Path, PathBuf},
};

#[derive(Debug, Snafu)]
enum Error {
    #[snafu(display("Could not open config file at {}: {}", filename.display(), source))]
    OpenConfig {
        filename: PathBuf,
        source: io::Error,
    },
    #[snafu(display("Could not open config file at {}", source))]
    SaveConfig { source: io::Error },
    #[snafu(display("User ID {} is invalid", user_id))]
    InvalidUser { user_id: i32 },
    #[snafu(display("No user available"))]
    MissingUser,
}

type Result<T, E = Error> = std::result::Result<T, E>;

const CONFIG_FILENAME: &str = "/tmp/config";

fn example(root: impl AsRef<Path>, user_id: Option<i32>) -> Result<()> {
    let root = root.as_ref();
    let filename = &root.join(CONFIG_FILENAME);

    let config = fs::read(filename).context(OpenConfigSnafu { filename })?;

    let _user_id = match user_id {
        None => MissingUserSnafu.fail()?,
        Some(user_id) if user_id != 42 => InvalidUserSnafu { user_id }.fail()?,
        Some(user_id) => user_id,
    };

    fs::write(filename, config).context(SaveConfigSnafu)?;

    Ok(())
}

#[test]
fn implements_error() {
    fn check<T: std::error::Error>() {}
    check::<Error>();
    example("/some/directory/that/does/not/exist", None).unwrap_err();
}