1
#[test]
2
4
fn test_deserialize_seed() {
3
    // Test adapted from David Tolnay's serde-yaml:
4
    // https://github.com/dtolnay/serde-yaml/blob/8a806e316302fd2e6541dccee6d166dd51b689d6/tests/test_de.rs#L357-L392
5

            
6
    struct Seed(i64);
7

            
8
    impl<'de> serde::de::DeserializeSeed<'de> for Seed {
9
        type Value = i64;
10

            
11
16
        fn deserialize<D>(self, deserializer: D) -> Result<i64, D::Error>
12
16
        where
13
16
            D: serde::de::Deserializer<'de>,
14
16
        {
15
            struct Visitor(i64);
16

            
17
            impl<'de> serde::de::Visitor<'de> for Visitor {
18
                type Value = i64;
19

            
20
4
                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
21
4
                    write!(formatter, "an integer")
22
4
                }
23

            
24
4
                fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<i64, E> {
25
4
                    Ok(v * self.0)
26
4
                }
27

            
28
8
                fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<i64, E> {
29
8
                    Ok(v as i64 * self.0)
30
8
                }
31
            }
32

            
33
16
            deserializer.deserialize_any(Visitor(self.0))
34
16
        }
35
    }
36

            
37
4
    let cases = [("3", 5, 15), ("6", 7, 42), ("-5", 9, -45)];
38

            
39
16
    for &(ron, seed, expected) in &cases {
40
12
        let deserialized = ron::Options::default()
41
12
            .from_str_seed(ron, Seed(seed))
42
12
            .unwrap();
43
12

            
44
12
        assert_eq!(expected, deserialized);
45
    }
46

            
47
4
    assert_eq!(
48
4
        ron::Options::default().from_str_seed("'a'", Seed(42)),
49
4
        Err(ron::error::SpannedError {
50
4
            code: ron::Error::InvalidValueForType {
51
4
                expected: String::from("an integer"),
52
4
                found: String::from("the string \"a\""),
53
4
            },
54
4
            position: ron::error::Position { line: 1, col: 4 },
55
4
        })
56
4
    );
57
4
}