File: generics.rs

package info (click to toggle)
rust-snafu 0.7.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 724 kB
  • sloc: sh: 15; makefile: 4
file content (97 lines) | stat: -rw-r--r-- 2,098 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
mod lifetimes {
    use snafu::prelude::*;

    #[derive(Debug, Snafu)]
    struct Error<'a> {
        key: &'a i32,
    }

    #[test]
    fn are_allowed() {
        let key = 42;
        let e = Snafu { key: &key }.build();
        assert_eq!(*e.key, key);
    }
}

mod types {
    use snafu::prelude::*;

    #[derive(Debug, Snafu)]
    struct Error<T> {
        key: T,
    }

    #[test]
    fn are_allowed() {
        let key = 42;
        let e: Error<i32> = Snafu { key }.build();
        assert_eq!(e.key, key);
    }

    #[cfg(feature="std")]
    mod with_defaults {
        use snafu::{prelude::*, AsErrorSource};
        use std::{error::Error as StdError, fmt::Debug, io};

        #[derive(Debug, Snafu)]
        struct Error<S = io::Error, T = String>
        where
            S: StdError + AsErrorSource,
            T: Debug,
        {
            source: S,
            key: T,
        }

        #[test]
        fn allows_non_default_types() {
            #[derive(Debug, Snafu)]
            struct AnotherError;

            let r = AnotherSnafu.fail::<()>();
            let _e: Error<_, u8> = r.context(Snafu { key: 42 }).unwrap_err();
        }
    }
}

mod bounds {
    mod inline {
        use snafu::prelude::*;
        use std::fmt::Display;

        #[derive(Debug, Snafu)]
        #[snafu(display("key: {}", key))]
        struct Error<T: Display> {
            key: T,
        }

        #[test]
        fn are_preserved() {
            let e: Error<bool> = Snafu { key: true }.build();
            let display = e.to_string();
            assert_eq!(display, "key: true");
        }
    }

    mod where_clause {
        use snafu::prelude::*;
        use std::fmt::Display;

        #[derive(Debug, Snafu)]
        #[snafu(display("key: {}", key))]
        struct Error<T>
        where
            T: Display,
        {
            key: T,
        }

        #[test]
        fn are_preserved() {
            let e: Error<bool> = Snafu { key: true }.build();
            let display = e.to_string();
            assert_eq!(display, "key: true");
        }
    }
}