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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
//! Module that defines [Encoding] whith allows for customization of the
//! encoding format, and the [DEFAULT] encoding configuration.

use core::marker;

#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "std")]
use std::io;

use musli::de::Decode;
use musli::en::Encode;
use musli::mode::{DefaultMode, Mode};
use musli::Context;

use crate::de::JsonDecoder;
use crate::en::JsonEncoder;
use crate::error::Error;
use crate::fixed_bytes::FixedBytes;
use crate::reader::{Parser, SliceParser};
use crate::writer::Writer;

/// The default configuration.
pub const DEFAULT: Encoding = Encoding::new();

/// Encode the given value to the given [Writer] using the [DEFAULT]
/// configuration.
#[inline]
pub fn encode<W, T>(writer: W, value: &T) -> Result<(), Error>
where
    W: Writer,
    Error: From<W::Error>,
    T: ?Sized + Encode<DefaultMode>,
{
    DEFAULT.encode(writer, value)
}

/// Encode the given value to the given [Write][io::Write] using the [DEFAULT]
/// configuration.
#[cfg(feature = "std")]
#[inline]
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<(), Error>
where
    W: io::Write,
    Error: From<io::Error>,
    T: ?Sized + Encode<DefaultMode>,
{
    DEFAULT.to_writer(writer, value)
}

/// Encode the given value to a [`Vec`] using the [DEFAULT] configuration.
#[cfg(feature = "alloc")]
#[inline]
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
where
    T: ?Sized + Encode<DefaultMode>,
{
    DEFAULT.to_vec(value)
}

/// Encode the given value to a [`String`] using the [DEFAULT] configuration.
#[cfg(feature = "alloc")]
#[inline]
pub fn to_string<T>(value: &T) -> Result<String, Error>
where
    T: ?Sized + Encode<DefaultMode>,
{
    DEFAULT.to_string(value)
}

/// Encode the given value to a fixed-size bytes using the [DEFAULT]
/// configuration.
#[inline]
pub fn to_fixed_bytes<const N: usize, T>(value: &T) -> Result<FixedBytes<N>, Error>
where
    T: ?Sized + Encode<DefaultMode>,
{
    DEFAULT.to_fixed_bytes::<N, _>(value)
}

/// Decode the given type `T` from the given [Parser] using the [DEFAULT]
/// configuration.
#[inline]
pub fn decode<'de, R, T>(reader: R) -> Result<T, Error>
where
    R: Parser<'de>,
    T: Decode<'de, DefaultMode>,
{
    DEFAULT.decode(reader)
}

/// Decode the given type `T` from the given string using the [DEFAULT]
/// configuration.
#[inline]
pub fn from_str<'de, T>(string: &'de str) -> Result<T, Error>
where
    T: Decode<'de, DefaultMode>,
{
    DEFAULT.from_str(string)
}

/// Decode the given type `T` from the given slice using the [DEFAULT]
/// configuration.
#[inline]
pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error>
where
    T: Decode<'de, DefaultMode>,
{
    DEFAULT.from_slice(bytes)
}

/// Setting up encoding with parameters.
pub struct Encoding<M = DefaultMode> {
    _marker: marker::PhantomData<M>,
}

impl Encoding<DefaultMode> {
    /// Construct a new [Encoding].
    ///
    /// You can modify this using the available factory methods:
    ///
    /// ```rust
    /// use musli_json::Encoding;
    /// use musli::{Encode, Decode, Mode};
    ///
    /// const CONFIG: Encoding<Json> = Encoding::new().with_mode();
    ///
    /// // Mode marker indicating that some attributes should
    /// // only apply when we're decoding in a JSON mode.
    /// enum Json {}
    ///
    /// impl Mode for Json {
    /// }
    ///
    /// #[derive(Debug, PartialEq, Encode, Decode)]
    /// #[musli(mode = Json, default_field_name = "name")]
    /// struct Struct<'a> {
    ///     name: &'a str,
    ///     age: u32,
    /// }
    ///
    /// let expected = Struct {
    ///     name: "Aristotle",
    ///     age: 61,
    /// };
    ///
    /// let out = CONFIG.to_vec(&expected).unwrap();
    /// println!("{}", core::str::from_utf8(out.as_slice()).unwrap());
    ///
    /// let out = musli_json::to_vec(&expected).unwrap();
    /// println!("{}", core::str::from_utf8(out.as_slice()).unwrap());
    /// let actual = musli_json::from_slice(out.as_slice()).unwrap();
    /// assert_eq!(expected, actual);
    /// ```
    #[inline]
    pub const fn new() -> Self {
        Encoding {
            _marker: marker::PhantomData,
        }
    }
}

impl<M> Encoding<M>
where
    M: Mode,
{
    /// Change the mode of the encoding.
    pub const fn with_mode<T>(self) -> Encoding<T>
    where
        T: Mode,
    {
        Encoding {
            _marker: marker::PhantomData,
        }
    }

    /// Encode the given value to the given [`Writer`] using the current
    /// configuration.
    ///
    /// This is the same as [`Encoding::encode`] but allows for using a
    /// configurable [`Context`].
    #[inline]
    pub fn encode_with<C, W, T>(self, cx: &mut C, writer: W, value: &T) -> Result<(), C::Error>
    where
        C: Context<Input = Error>,
        W: Writer,
        Error: From<W::Error>,
        T: ?Sized + Encode<M>,
    {
        T::encode(value, cx, JsonEncoder::<M, _>::new(writer))
    }

    /// Encode the given value to a [`String`] using the current configuration.
    #[cfg(feature = "alloc")]
    #[inline]
    pub fn to_string<T>(self, value: &T) -> Result<String, Error>
    where
        T: ?Sized + Encode<M>,
    {
        let alloc = musli_common::allocator::Default::default();
        let mut cx = musli_common::context::Same::new(&alloc);
        self.to_string_with(&mut cx, value)
    }

    /// Encode the given value to a [`String`] using the current configuration.
    ///
    /// This is the same as [`Encoding::to_string`] but allows for using a
    /// configurable [`Context`].
    #[cfg(feature = "alloc")]
    #[inline]
    pub fn to_string_with<T, C>(self, cx: &mut C, value: &T) -> Result<String, C::Error>
    where
        C: Context<Input = Error>,
        T: ?Sized + Encode<M>,
    {
        let mut data = Vec::with_capacity(128);
        T::encode(value, cx, JsonEncoder::<M, _>::new(&mut data))?;
        // SAFETY: Encoder is guaranteed to produce valid UTF-8.
        Ok(unsafe { String::from_utf8_unchecked(data) })
    }

    /// Decode the given type `T` from the given [Parser] using the current
    /// configuration.
    #[inline]
    pub fn decode<'de, P, T>(self, parser: P) -> Result<T, Error>
    where
        P: Parser<'de>,
        T: Decode<'de, M>,
    {
        let alloc = musli_common::allocator::Default::default();
        let mut cx = musli_common::context::Same::new(&alloc);
        self.decode_with(&mut cx, parser)
    }

    /// Decode the given type `T` from the given [Parser] using the current
    /// configuration.
    ///
    /// This is the same as [`Encoding::decode`] but allows for using a
    /// configurable [`Context`].
    #[inline]
    pub fn decode_with<'de, C, P, T>(self, cx: &mut C, parser: P) -> Result<T, C::Error>
    where
        C: Context<Input = Error>,
        P: Parser<'de>,
        T: Decode<'de, M>,
    {
        T::decode(cx, JsonDecoder::new(parser))
    }

    /// Decode the given type `T` from the given string using the current
    /// configuration.
    #[inline]
    pub fn from_str<'de, T>(self, string: &'de str) -> Result<T, Error>
    where
        T: Decode<'de, M>,
    {
        self.from_slice(string.as_bytes())
    }

    /// Decode the given type `T` from the given string using the current
    /// configuration.
    ///
    /// This is the same as [`Encoding::from_str`] but allows for using a
    /// configurable [`Context`].
    #[inline]
    pub fn from_str_with<'de, C, T>(self, cx: &mut C, string: &'de str) -> Result<T, C::Error>
    where
        C: Context<Input = Error>,
        T: Decode<'de, M>,
    {
        self.from_slice_with(cx, string.as_bytes())
    }

    /// Decode the given type `T` from the given slice using the current
    /// configuration.
    #[inline]
    pub fn from_slice<'de, T>(self, bytes: &'de [u8]) -> Result<T, Error>
    where
        T: Decode<'de, M>,
    {
        let alloc = musli_common::allocator::Default::default();
        let mut cx = musli_common::context::Same::new(&alloc);
        self.from_slice_with(&mut cx, bytes)
    }

    /// Decode the given type `T` from the given slice using the current
    /// configuration.
    ///
    /// This is the same as [`Encoding::from_slice`] but allows for using a
    /// configurable [`Context`].
    #[inline]
    pub fn from_slice_with<'de, C, T>(self, cx: &mut C, bytes: &'de [u8]) -> Result<T, C::Error>
    where
        C: Context<Input = Error>,
        T: Decode<'de, M>,
    {
        let mut reader = SliceParser::new(bytes);
        T::decode(cx, JsonDecoder::new(&mut reader))
    }

    musli_common::encode_with_extensions!();
}

impl<M> Clone for Encoding<M> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<M> Copy for Encoding<M> {}