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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
use core::fmt;

use crate::error::Error;

struct RefVisitorExpected<T>(T);

impl<'de, T> fmt::Display for RefVisitorExpected<T>
where
    T: ReferenceVisitor<'de>,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.expected(f)
    }
}

/// A visitor for data where it might be possible to borrow it without copying
/// from the underlying [Decoder].
///
/// A visitor is required with [Decoder::decode_bytes] and
/// [Decoder::decode_string] because the caller doesn't know if the encoding
/// format is capable of producing references to the underlying data directly or
/// if it needs to be processed.
///
/// By requiring a visitor we ensure that the caller has to handle both
/// scenarios, even if one involves erroring. A type like
/// [Cow][std::borrow::Cow] is an example of a type which can comfortably handle
/// both.
pub trait ReferenceVisitor<'de>: Sized {
    /// The value being visited.
    type Target: ?Sized;
    /// The value produced.
    type Ok;
    /// The error produced.
    type Error: Error;

    /// Format an error indicating what was expected.
    ///
    /// Override to be more specific about the type that failed.
    fn expected(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;

    /// Visit a string that is borrowed directly from the source data.
    #[inline]
    fn visit_ref(self, string: &'de Self::Target) -> Result<Self::Ok, Self::Error> {
        self.visit(string)
    }

    /// Visit a string that is provided from the decoder in any manner possible.
    /// Which might require additional decoding work.
    #[inline]
    fn visit(self, _: &Self::Target) -> Result<Self::Ok, Self::Error> {
        Err(Self::Error::collect_from_display(RefVisitorExpected(self)))
    }
}

/// A pack that can construct encoders.
pub trait PackDecoder<'de> {
    /// Error type raised by this unpack.
    type Error: Error;

    /// The encoder to use for the pack.
    type Decoder<'this>: Decoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// Return decoder to unpack the next element.
    fn next(&mut self) -> Result<Self::Decoder<'_>, Self::Error>;

    /// Finish unpacking.
    fn finish(self) -> Result<(), Self::Error>;
}

/// Trait governing how to decode a sequence.
pub trait SequenceDecoder<'de> {
    /// Error type.
    type Error: Error;

    /// The decoder for individual items.
    type Next<'this>: Decoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// Get a size hint of known remaining elements.
    fn size_hint(&self) -> Option<usize>;

    /// Decode the next element.
    fn decode_next(&mut self) -> Result<Option<Self::Next<'_>>, Self::Error>;
}

/// Trait governing how to decode a map entry.
pub trait MapEntryDecoder<'de> {
    /// Error type.
    type Error: Error;

    /// The decoder to use for a key.
    type Key<'this>: Decoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// The decoder to use for a key.
    type Value<'this>: Decoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// Decode the next key.
    fn decode_key(&mut self) -> Result<Self::Key<'_>, Self::Error>;

    /// Follow up the decoding of a key by decoding a value.
    fn decode_value(&mut self) -> Result<Self::Value<'_>, Self::Error>;
}

/// Trait governing how to decode a map.
pub trait MapDecoder<'de> {
    /// Error type.
    type Error: Error;

    /// The decoder to use for a key.
    type Entry<'this>: MapEntryDecoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// Get a size hint of known remaining elements.
    fn size_hint(&self) -> Option<usize>;

    /// Decode the next key. This returns `Ok(None)` where there are no more elements to decode.
    fn decode_entry(&mut self) -> Result<Option<Self::Entry<'_>>, Self::Error>;
}

/// Trait governing how to decode a map.
pub trait StructDecoder<'de> {
    /// Error type.
    type Error: Error;

    /// The decoder to use for a key.
    type Field<'this>: PairDecoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// Get a size hint of known remaining elements.
    fn size_hint(&self) -> Option<usize>;

    /// Decode the next key. This returns `Ok(None)` where there are no more elements to decode.
    fn decode_field(&mut self) -> Result<Option<Self::Field<'_>>, Self::Error>;
}

/// Trait governing how to decode a field.
pub trait PairDecoder<'de> {
    /// Error type.
    type Error: Error;

    /// The decoder to use for a tuple field index.
    type First<'this>: Decoder<'de, Error = Self::Error>
    where
        Self: 'this;

    /// The decoder to use for a tuple field value.
    type Second: Decoder<'de, Error = Self::Error>;

    /// Decoder for the next index.
    fn decode_first(&mut self) -> Result<Self::First<'_>, Self::Error>;

    /// Decoder for the next value.
    fn decode_second(self) -> Result<Self::Second, Self::Error>;

    /// Indicate that the second element is not compatible with the current
    /// struct and skip it.
    ///
    /// Returns a boolean indicating if the second value was successfully
    /// skipped.
    fn skip_second(self) -> Result<bool, Self::Error>;
}

/// Trait governing the implementation of a decoder.
pub trait Decoder<'de>: Sized {
    /// Error type raised by the decoder.
    type Error: Error;

    /// Trait for an unpack.
    type Pack: PackDecoder<'de, Error = Self::Error>;

    /// The type of a sequence decoder.
    type Sequence: SequenceDecoder<'de, Error = Self::Error>;

    /// The type of a map decoder.
    type Map: MapDecoder<'de, Error = Self::Error>;

    /// Decoder to use when an optional value is present.
    type Some: Decoder<'de, Error = Self::Error>;

    /// Decoder returned to decode a struct variant.
    type Struct: StructDecoder<'de, Error = Self::Error>;

    /// Decoder returned to decode a tuple struct.
    type Tuple: StructDecoder<'de, Error = Self::Error>;

    /// Decode a variant.
    type Variant: PairDecoder<'de, Error = Self::Error>;

    /// Decode a unit, or something that is empty.
    fn decode_unit(self) -> Result<(), Self::Error>;

    /// Construct an unpack that can decode more than one element at a time.
    ///
    /// This hints to the format that it should attempt to decode all of the
    /// elements in the packed sequence from an as compact format as possible
    /// compatible with what's being returned by
    /// [Encoder::pack][crate::Encoder::encode_pack].
    fn decode_pack(self) -> Result<Self::Pack, Self::Error>;

    /// Decode a fixed-length array.
    fn decode_array<const N: usize>(self) -> Result<[u8; N], Self::Error>;

    /// Decode a sequence of bytes whos length is encoded in the payload.
    fn decode_bytes<V>(self, visitor: V) -> Result<V::Ok, V::Error>
    where
        V: ReferenceVisitor<'de, Target = [u8], Error = Self::Error>;

    /// Decode a string slice from the current decoder.
    fn decode_string<V>(self, visitor: V) -> Result<V::Ok, V::Error>
    where
        V: ReferenceVisitor<'de, Target = str, Error = Self::Error>;

    /// Decode a boolean.
    fn decode_bool(self) -> Result<bool, Self::Error>;

    /// Decode a character.
    fn decode_char(self) -> Result<char, Self::Error>;

    /// Decode a 8-bit unsigned integer (a.k.a. a byte).
    fn decode_u8(self) -> Result<u8, Self::Error>;

    /// Decode a 16-bit unsigned integer.
    fn decode_u16(self) -> Result<u16, Self::Error>;

    /// Decode a 32-bit unsigned integer.
    fn decode_u32(self) -> Result<u32, Self::Error>;

    /// Decode a 64-bit unsigned integer.
    fn decode_u64(self) -> Result<u64, Self::Error>;

    /// Decode a 128-bit unsigned integer.
    fn decode_u128(self) -> Result<u128, Self::Error>;

    /// Decode a 8-bit signed integer.
    fn decode_i8(self) -> Result<i8, Self::Error>;

    /// Decode a 16-bit signed integer.
    fn decode_i16(self) -> Result<i16, Self::Error>;

    /// Decode a 32-bit signed integer.
    fn decode_i32(self) -> Result<i32, Self::Error>;

    /// Decode a 64-bit signed integer.
    fn decode_i64(self) -> Result<i64, Self::Error>;

    /// Decode a 128-bit signed integer.
    fn decode_i128(self) -> Result<i128, Self::Error>;

    /// Decode a usize value.
    fn decode_usize(self) -> Result<usize, Self::Error>;

    /// Decode a isize value.
    fn decode_isize(self) -> Result<isize, Self::Error>;

    /// Decode a 32-bit floating point value.
    ///
    /// Default to reading the 32-bit in-memory IEEE 754 encoding byte-by-byte.
    fn decode_f32(self) -> Result<f32, Self::Error>;

    /// Decode a 64-bit floating point value.
    ///
    /// Default to reading the 64-bit in-memory IEEE 754 encoding byte-by-byte.
    fn decode_f64(self) -> Result<f64, Self::Error>;

    /// Decode an optional value.
    fn decode_option(self) -> Result<Option<Self::Some>, Self::Error>;

    /// Decode a sequence, this returns a decoder that can be used to define the structure of the sequence.
    fn decode_sequence(self) -> Result<Self::Sequence, Self::Error>;

    /// Decode a map, this returns a decoder that can be used to extract map-like values.
    fn decode_map(self) -> Result<Self::Map, Self::Error>;

    /// Return a helper to decode a struct with named fields.
    fn decode_struct(self, fields: usize) -> Result<Self::Struct, Self::Error>;

    /// Return a helper to decode a tuple struct.
    fn decode_tuple(self, fields: usize) -> Result<Self::Tuple, Self::Error>;

    /// Decode a unit variant.
    fn decode_unit_struct(self) -> Result<(), Self::Error>;

    /// Return decoder for a variant.
    fn decode_variant(self) -> Result<Self::Variant, Self::Error>;
}