File: with_source.rs

package info (click to toggle)
rust-snafu 0.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, trixie
  • size: 664 kB
  • sloc: sh: 15; makefile: 4
file content (48 lines) | stat: -rw-r--r-- 1,197 bytes parent folder | download | duplicates (3)
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
#![cfg(feature="std")]
use snafu::prelude::*;
use std::{
    error::Error as StdError,
    fs, io,
    path::{Path, PathBuf},
    ptr,
};

#[derive(Debug, Snafu)]
#[snafu(display("filename: {}, source: {}", filename.display(), source))]
struct Error {
    filename: PathBuf,
    source: io::Error,
}

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

fn example(filename: impl AsRef<Path>) -> Result<()> {
    let filename = filename.as_ref();

    let _config = fs::read(filename).context(Snafu { filename })?;

    Ok(())
}

#[test]
fn implements_error() {
    fn check<T: StdError>() {}
    check::<Error>();

    let path = "/some/directory/that/does/not/exist";
    let e = example(path).unwrap_err();
    assert_eq!(e.filename, Path::new(path));

    let source = e.source().expect("Source must be present");
    let source_as_io_error = source
        .downcast_ref::<io::Error>()
        .expect("Source must be io::Error");
    assert!(ptr::eq(source_as_io_error, &e.source));

    let display = e.to_string();
    assert!(
        display.starts_with("filename: /some/directory/that/does/not/exist, source: "),
        "Display string incorrect, is: {}",
        display,
    );
}