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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "loose_deserialization")]
use crate::loose_deserializer::EnumData;
use crate::value::Value;
use serde::de::MapAccess;
use serde::de::SeqAccess;
use serde::de::Visitor;
#[cfg(feature = "loose_deserialization")]
use serde::de::{EnumAccess, VariantAccess};
use serde::Deserialize;

pub struct ValueVisitor;

impl<'de> Visitor<'de> for ValueVisitor {
    type Value = Value;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("any valid OCaml value")
    }

    #[inline]
    fn visit_bool<E>(self, value: bool) -> Result<Value, E> {
        Ok(Value::Bool(value))
    }

    #[inline]
    fn visit_char<E>(self, value: char) -> Result<Value, E> {
        Ok(Value::Char(value as u8))
    }

    #[inline]
    fn visit_i64<E>(self, value: i64) -> Result<Value, E> {
        Ok(Value::Int(value))
    }

    #[inline]
    fn visit_f64<E>(self, value: f64) -> Result<Value, E> {
        Ok(Value::Float(value))
    }

    #[inline]
    fn visit_str<E>(self, value: &str) -> Result<Value, E>
    where
        E: serde::de::Error,
    {
        self.visit_string(String::from(value))
    }

    #[inline]
    fn visit_bytes<E>(self, value: &[u8]) -> Result<Value, E> {
        // Represent bytes as a list of chars
        // Chars are always 1 byte in BinProt so this fits
        let bytes = value.iter().map(|x| Value::Char(*x)).collect();
        Ok(Value::List(bytes))
    }

    #[inline]
    fn visit_none<E>(self) -> Result<Value, E> {
        Ok(Value::Option(None))
    }

    #[inline]
    fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(Value::Option(Some(Box::new(Deserialize::deserialize(
            deserializer,
        )?))))
    }

    #[inline]
    fn visit_unit<E>(self) -> Result<Value, E> {
        Ok(Value::Unit)
    }

    #[inline]
    fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error>
    where
        V: SeqAccess<'de>,
    {
        let mut vec = Vec::new();
        while let Some(elem) = visitor.next_element()? {
            vec.push(elem);
        }

        if visitor.size_hint().is_some() {
            Ok(Value::List(vec))
        } else {
            Ok(Value::Tuple(vec))
        }
    }

    fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error>
    where
        V: MapAccess<'de>,
    {
        let mut values = Vec::new();
        while let Some((k, v)) = visitor.next_entry()? {
            values.push((k, v));
        }
        Ok(Value::Record(values))
    }

    #[cfg(feature = "loose_deserialization")]
    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
    where
        A: EnumAccess<'de>,
    {
        let (payload, variant_access) = data.variant::<EnumData>()?;

        // payload must encode the index and name in a deserializer
        // the variant access can be used to retrieve the correct content based on this

        match payload {
            EnumData::Sum { index, name, len } => {
                let body = variant_access.tuple_variant(len, self)?;
                Ok(Value::Sum {
                    name,
                    index,
                    value: Box::new(body),
                })
            }
            EnumData::Polyvar {
                index: _,
                tag,
                name,
                len,
            } => {
                let body = variant_access.tuple_variant(len, self)?;
                Ok(Value::Polyvar {
                    name,
                    tag,
                    value: Box::new(body),
                })
            }
        }
    }
}