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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use core::{fmt, marker::PhantomData};

use serde::{
    de::{Error, SeqAccess, Unexpected, Visitor},
    ser::SerializeSeq,
    Deserialize, Deserializer, Serialize, Serializer,
};

use crate::{Btrit, RawEncoding, RawEncodingBuf, TritBuf, Trits, Utrit};

// Serialisation

impl Serialize for Btrit {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_i8((*self).into())
    }
}

impl Serialize for Utrit {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_i8((*self).into())
    }
}

impl<'a, T: RawEncoding> Serialize for &'a Trits<T>
where
    T::Trit: Serialize,
    T: serde::Serialize,
{
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for trit in self.iter() {
            seq.serialize_element(&trit)?;
        }
        seq.end()
    }
}

impl<T: RawEncodingBuf> Serialize for TritBuf<T>
where
    <T::Slice as RawEncoding>::Trit: Serialize,
{
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for trit in self.iter() {
            seq.serialize_element(&trit)?;
        }
        seq.end()
    }
}

// Deserialisation

struct BtritVisitor;

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

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a value between -1 and 1 inclusive")
    }

    fn visit_u64<E: Error>(self, trit: u64) -> Result<Self::Value, E> {
        i8::try_from(trit)
            .map_err(|_| ())
            .and_then(|trit| Btrit::try_from(trit).map_err(|_| ()))
            .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit), &self))
    }

    fn visit_i64<E: Error>(self, trit: i64) -> Result<Self::Value, E> {
        i8::try_from(trit)
            .map_err(|_| ())
            .and_then(|trit| Btrit::try_from(trit).map_err(|_| ()))
            .map_err(|_| E::invalid_value(Unexpected::Signed(trit), &self))
    }

    fn visit_u8<E: Error>(self, trit: u8) -> Result<Self::Value, E> {
        i8::try_from(trit)
            .map_err(|_| ())
            .and_then(|trit| Btrit::try_from(trit).map_err(|_| ()))
            .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit as u64), &self))
    }

    fn visit_i8<E: Error>(self, trit: i8) -> Result<Self::Value, E> {
        Btrit::try_from(trit).map_err(|_| E::invalid_value(Unexpected::Signed(trit as i64), &self))
    }
}

impl<'de> Deserialize<'de> for Btrit {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_i8(BtritVisitor)
    }
}

struct UtritVisitor;

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

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a value between 0 and 2 inclusive")
    }

    fn visit_u64<E: Error>(self, trit: u64) -> Result<Self::Value, E> {
        u8::try_from(trit)
            .map_err(|_| ())
            .and_then(|trit| Utrit::try_from(trit).map_err(|_| ()))
            .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit), &self))
    }

    fn visit_i64<E: Error>(self, trit: i64) -> Result<Self::Value, E> {
        i8::try_from(trit)
            .map_err(|_| ())
            .and_then(|trit| Utrit::try_from(trit).map_err(|_| ()))
            .map_err(|_| E::invalid_value(Unexpected::Signed(trit), &self))
    }

    fn visit_u8<E: Error>(self, trit: u8) -> Result<Self::Value, E> {
        Ok(trit)
            .and_then(|trit| Utrit::try_from(trit).map_err(|_| ()))
            .map_err(|_| E::invalid_value(Unexpected::Unsigned(trit as u64), &self))
    }

    fn visit_i8<E: Error>(self, trit: i8) -> Result<Self::Value, E> {
        Utrit::try_from(trit).map_err(|_| E::invalid_value(Unexpected::Signed(trit as i64), &self))
    }
}

impl<'de> Deserialize<'de> for Utrit {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_i8(UtritVisitor)
    }
}

struct TritBufVisitor<T>(PhantomData<T>);

impl<'de, T: RawEncodingBuf> Visitor<'de> for TritBufVisitor<T>
where
    <T::Slice as RawEncoding>::Trit: Deserialize<'de>,
{
    type Value = TritBuf<T>;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a sequence of trits")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let mut buf = TritBuf::with_capacity(seq.size_hint().unwrap_or(0));

        while let Some(trit) = seq.next_element()? {
            buf.push(trit);
        }

        Ok(buf)
    }
}

impl<'de, T: RawEncodingBuf> Deserialize<'de> for TritBuf<T>
where
    <T::Slice as RawEncoding>::Trit: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_seq(TritBufVisitor::<T>(PhantomData))
    }
}