Debian Codegraph @

debian/rust-vendor/rstest/src/magic_conversion.rs

raw
1 pub struct Magic<T>(pub std::marker::PhantomData<T>);
2
3 pub trait ViaParseDebug<'a, T> {
4 fn magic_conversion(&self, input: &'a str) -> T;
5 }
6
7 impl<'a, T> ViaParseDebug<'a, T> for &&Magic<T>
8 where
9 T: std::str::FromStr,
10 T::Err: std::fmt::Debug,
11 {
12 fn magic_conversion(&self, input: &'a str) -> T {
13 T::from_str(input).unwrap()
14 }
15 }
16
17 pub trait ViaParse<'a, T> {
18 fn magic_conversion(&self, input: &'a str) -> T;
19 }
20
21 impl<'a, T> ViaParse<'a, T> for &Magic<T>
22 where
23 T: std::str::FromStr,
24 {
25 fn magic_conversion(&self, input: &'a str) -> T {
26 match T::from_str(input) {
27 Ok(v) => v,
28 Err(_) => {
29 panic!(
30 "Cannot parse '{}' to get {}",
31 input,
32 std::any::type_name::<T>()
33 );
34 }
35 }
36 }
37 }
38
39 pub trait ViaIdent<'a, T> {
40 fn magic_conversion(&self, input: &'a str) -> T;
41 }
42
43 impl<'a> ViaIdent<'a, &'a str> for &&Magic<&'a str> {
44 fn magic_conversion(&self, input: &'a str) -> &'a str {
45 input
46 }
47 }
48
49 #[cfg(test)]
50 mod test {
51 use super::*;
52 use std::str::FromStr;
53
54 #[test]
55 fn should_return_the_same_slice_string() {
56 assert_eq!(
57 "something",
58 (&&&Magic::<&str>(std::marker::PhantomData)).magic_conversion("something")
59 );
60 }
61
62 #[test]
63 fn should_parse_via_parse_debug() {
64 assert_eq!(
65 42u32,
66 (&&&Magic::<u32>(std::marker::PhantomData)).magic_conversion("42")
67 );
68 }
69
70 #[test]
71 fn should_parse_via_parse_no_error_debug() {
72 struct S(String);
73 struct E;
74 impl FromStr for S {
75 type Err = E;
76
77 fn from_str(s: &str) -> Result<Self, Self::Err> {
78 Ok(S(s.to_owned()))
79 }
80 }
81
82 assert_eq!(
83 "some",
84 (&&&Magic::<S>(std::marker::PhantomData))
85 .magic_conversion("some")
86 .0
87 );
88 }
89
90 #[test]
91 #[should_panic(expected = "MyTypeName")]
92 fn should_show_error() {
93 struct MyTypeName;
94 struct E;
95 impl FromStr for MyTypeName {
96 type Err = E;
97
98 fn from_str(_s: &str) -> Result<Self, Self::Err> {
99 Err(E)
100 }
101 }
102 (&&&Magic::<MyTypeName>(std::marker::PhantomData)).magic_conversion("");
103 }
104 }