aboutsummaryrefslogtreecommitdiff
path: root/tests/decoder.rs
blob: fe6db3f5e5118e6dfa641975a1de4048f7a0d74d (plain)
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
#![cfg(all(feature = "parse", feature = "display"))]

#[derive(Copy, Clone)]
pub struct Decoder;

impl toml_test_harness::Decoder for Decoder {
    fn name(&self) -> &str {
        "toml"
    }

    fn decode(&self, data: &[u8]) -> Result<toml_test_harness::Decoded, toml_test_harness::Error> {
        let data = std::str::from_utf8(data).map_err(toml_test_harness::Error::new)?;
        let document = data
            .parse::<toml::Value>()
            .map_err(toml_test_harness::Error::new)?;
        value_to_decoded(&document)
    }
}

fn value_to_decoded(
    value: &toml::Value,
) -> Result<toml_test_harness::Decoded, toml_test_harness::Error> {
    match value {
        toml::Value::Integer(v) => Ok(toml_test_harness::Decoded::Value(
            toml_test_harness::DecodedValue::from(*v),
        )),
        toml::Value::String(v) => Ok(toml_test_harness::Decoded::Value(
            toml_test_harness::DecodedValue::from(v),
        )),
        toml::Value::Float(v) => Ok(toml_test_harness::Decoded::Value(
            toml_test_harness::DecodedValue::from(*v),
        )),
        toml::Value::Datetime(v) => {
            let value = v.to_string();
            let value = match (v.date.is_some(), v.time.is_some(), v.offset.is_some()) {
                (true, true, true) => toml_test_harness::DecodedValue::Datetime(value),
                (true, true, false) => toml_test_harness::DecodedValue::DatetimeLocal(value),
                (true, false, false) => toml_test_harness::DecodedValue::DateLocal(value),
                (false, true, false) => toml_test_harness::DecodedValue::TimeLocal(value),
                _ => unreachable!("Unsupported case"),
            };
            Ok(toml_test_harness::Decoded::Value(value))
        }
        toml::Value::Boolean(v) => Ok(toml_test_harness::Decoded::Value(
            toml_test_harness::DecodedValue::from(*v),
        )),
        toml::Value::Array(v) => {
            let v: Result<_, toml_test_harness::Error> = v.iter().map(value_to_decoded).collect();
            Ok(toml_test_harness::Decoded::Array(v?))
        }
        toml::Value::Table(v) => table_to_decoded(v),
    }
}

fn table_to_decoded(
    value: &toml::value::Table,
) -> Result<toml_test_harness::Decoded, toml_test_harness::Error> {
    let table: Result<_, toml_test_harness::Error> = value
        .iter()
        .map(|(k, v)| {
            let k = k.to_owned();
            let v = value_to_decoded(v)?;
            Ok((k, v))
        })
        .collect();
    Ok(toml_test_harness::Decoded::Table(table?))
}