musli_common/
macros.rs

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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/// Generate extensions assuming an encoding has implemented encode_with.
#[doc(hidden)]
#[macro_export]
macro_rules! encode_with_extensions {
    ($mode:ident) => {
        /// Encode the given value to the given [Writer] using the current
        /// configuration.
        #[inline]
        pub fn encode<W, T>(self, writer: W, value: &T) -> Result<(), Error>
        where
            W: Writer,
            T: ?Sized + Encode<$mode>,
        {
            let mut buf = $crate::exports::allocator::buffer();
            let alloc = $crate::exports::allocator::new(&mut buf);
            let cx = $crate::exports::context::Same::new(&alloc);
            self.encode_with(&cx, writer, value)
        }

        /// Encode the given value to the given [Write][io::Write] using the current
        /// configuration.
        #[cfg(feature = "std")]
        #[inline]
        pub fn to_writer<W, T>(self, write: W, value: &T) -> Result<(), Error>
        where
            W: io::Write,
            T: ?Sized + Encode<$mode>,
        {
            let writer = $crate::exports::wrap::wrap(write);
            self.encode(writer, value)
        }

        /// Encode the given value to the given [Write][io::Write] using the current
        /// configuration and context `C`.
        #[cfg(feature = "std")]
        #[inline]
        pub fn to_writer_with<C, W, T>(self, cx: &C, write: W, value: &T) -> Result<(), C::Error>
        where
            C: ?Sized + Context<Mode = $mode>,
            W: io::Write,
            T: ?Sized + Encode<$mode>,
        {
            let writer = $crate::exports::wrap::wrap(write);
            self.encode_with(cx, writer, value)
        }

        /// Encode the given value to a [`Vec`] using the current configuration.
        #[cfg(feature = "alloc")]
        #[inline]
        pub fn to_vec<T>(self, value: &T) -> Result<Vec<u8>, Error>
        where
            T: ?Sized + Encode<$mode>,
        {
            let mut vec = Vec::new();
            self.encode(&mut vec, value)?;
            Ok(vec)
        }

        /// Encode the given value to a [`Vec`] using the current configuration.
        ///
        /// This is the same as [`Encoding::to_vec`], but allows for using a
        /// configurable [`Context`].
        #[cfg(feature = "alloc")]
        #[inline]
        pub fn to_vec_with<C, T>(self, cx: &C, value: &T) -> Result<Vec<u8>, C::Error>
        where
            C: ?Sized + Context<Mode = $mode>,
            T: ?Sized + Encode<$mode>,
        {
            let mut vec = Vec::new();
            self.encode_with(cx, &mut vec, value)?;
            Ok(vec)
        }

        /// Encode the given value to a fixed-size bytes using the current
        /// configuration.
        #[inline]
        pub fn to_fixed_bytes<const N: usize, T>(self, value: &T) -> Result<FixedBytes<N>, Error>
        where
            T: ?Sized + Encode<$mode>,
        {
            let mut buf = $crate::exports::allocator::buffer();
            let alloc = $crate::exports::allocator::new(&mut buf);
            let cx = $crate::exports::context::Same::new(&alloc);
            self.to_fixed_bytes_with(&cx, value)
        }

        /// Encode the given value to a fixed-size bytes using the current
        /// configuration.
        #[inline]
        pub fn to_fixed_bytes_with<C, const N: usize, T>(
            self,
            cx: &C,
            value: &T,
        ) -> Result<FixedBytes<N>, C::Error>
        where
            C: ?Sized + Context<Mode = $mode>,
            T: ?Sized + Encode<$mode>,
        {
            let mut bytes = FixedBytes::new();
            self.encode_with(cx, &mut bytes, value)?;
            Ok(bytes)
        }
    };
}

/// Generate all public encoding helpers.
#[doc(hidden)]
#[macro_export]
macro_rules! encoding_from_slice_impls {
    ($mode:ident, $decoder_new:path) => {
        /// 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, $mode>,
        {
            let mut buf = $crate::exports::allocator::buffer();
            let alloc = $crate::exports::allocator::new(&mut buf);
            let cx = $crate::exports::context::Same::new(&alloc);
            self.from_slice_with(&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: &C, bytes: &'de [u8]) -> Result<T, C::Error>
        where
            C: ?Sized + Context<Mode = $mode>,
            T: Decode<'de, $mode>,
        {
            let reader = SliceReader::new(bytes);
            self.decode_with(cx, reader)
        }
    };
}

/// Generate all public encoding helpers.
#[doc(hidden)]
#[macro_export]
macro_rules! encoding_impls {
    ($mode:ident, $encoder_new:path, $decoder_new:path) => {
        /// 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: &C, writer: W, value: &T) -> Result<(), C::Error>
        where
            C: ?Sized + Context<Mode = $mode>,
            W: Writer,
            T: ?Sized + Encode<$mode>,
        {
            T::encode(value, cx, $encoder_new(cx, writer))
        }

        /// Decode the given type `T` from the given [Reader] 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, R, T>(self, cx: &C, reader: R) -> Result<T, C::Error>
        where
            C: ?Sized + Context<Mode = $mode>,
            R: Reader<'de>,
            T: Decode<'de, $mode>,
        {
            T::decode(cx, $decoder_new(cx, reader))
        }

        /// Decode the given type `T` from the given [Reader] using the current
        /// configuration.
        #[inline]
        pub fn decode<'de, R, T>(self, reader: R) -> Result<T, Error>
        where
            R: Reader<'de>,
            T: Decode<'de, $mode>,
        {
            let mut buf = $crate::exports::allocator::buffer();
            let alloc = $crate::exports::allocator::new(&mut buf);
            let cx = $crate::exports::context::Same::new(&alloc);
            self.decode_with(&cx, reader)
        }

        $crate::encode_with_extensions!($mode);
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! test_include_if {
    (#[musli_value] => $($rest:tt)*) => { $($rest)* };
    (=> $($_:tt)*) => {};
}

/// Generate test functions which provides rich diagnostics when they fail.
#[doc(hidden)]
#[macro_export]
#[allow(clippy::crate_in_macro_def)]
macro_rules! test_fns {
    ($what:expr $(, $(#[$option:ident])*)?) => {
        /// Roundtrip encode the given value.
        #[doc(hidden)]
        #[track_caller]
        #[cfg(feature = "test")]
        pub fn rt<T>(value: T) -> T
        where
            T: ::musli::en::Encode + ::musli::de::DecodeOwned + ::core::fmt::Debug + ::core::cmp::PartialEq,
        {
            const WHAT: &str = $what;
            const ENCODING: crate::Encoding = crate::Encoding::new();

            use ::core::any::type_name;
            use ::alloc::string::ToString;

            struct FormatBytes<'a>(&'a [u8]);

            impl ::core::fmt::Display for FormatBytes<'_> {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    write!(f, "b\"")?;

                    for b in self.0 {
                        if b.is_ascii_graphic() {
                            write!(f, "{}", *b as char)?;
                        } else {
                            write!(f, "\\x{b:02x}")?;
                        }
                    }

                    write!(f, "\"")?;
                    Ok(())
                }
            }

            let format_error = |cx: &crate::context::SystemContext<_, _>| {
                use ::alloc::vec::Vec;

                let mut errors = Vec::new();

                for error in cx.errors() {
                    errors.push(error.to_string());
                }

                errors.join("\n")
            };

            let mut buf = crate::allocator::buffer();
            let alloc = crate::allocator::new(&mut buf);
            let mut cx = crate::context::SystemContext::new(&alloc);
            cx.include_type();

            let out = match ENCODING.to_vec_with(&cx, &value) {
                Ok(out) => out,
                Err(..) => {
                    let error = format_error(&cx);
                    panic!("{WHAT}: {}: failed to encode:\n{error}", type_name::<T>())
                }
            };

            $crate::test_include_if! {
                $($(#[$option])*)* =>
                let value_decode: ::musli_value::Value = match ENCODING.from_slice_with(&cx, out.as_slice()) {
                    Ok(decoded) => decoded,
                    Err(..) => {
                        let out = FormatBytes(&out);
                        let error = format_error(&cx);
                        panic!("{WHAT}: {}: failed to decode to value type:\nBytes:{out}\n{error}", type_name::<T>())
                    }
                };

                let value_decoded: T = match ::musli_value::decode_with(&cx, &value_decode) {
                    Ok(decoded) => decoded,
                    Err(..) => {
                        let out = FormatBytes(&out);
                        let error = format_error(&cx);
                        panic!("{WHAT}: {}: failed to decode from value type:\nBytes: {out}\nValue: {value_decode:?}\n{error}", type_name::<T>())
                    }
                };

                assert_eq!(value_decoded, value, "{WHAT}: {}: musli-value roundtrip does not match", type_name::<T>());
            }

            let decoded: T = match ENCODING.from_slice_with(&cx, out.as_slice()) {
                Ok(decoded) => decoded,
                Err(..) => {
                    let out = FormatBytes(&out);
                    let error = format_error(&cx);
                    panic!("{WHAT}: {}: failed to decode:\nBytes: {out}\n{error}", type_name::<T>())
                }
            };

            assert_eq!(decoded, value, "{WHAT}: {}: roundtrip does not match", type_name::<T>());

            decoded
        }

        /// Encode and then decode the given value once.
        #[doc(hidden)]
        #[track_caller]
        #[cfg(feature = "test")]
        pub fn decode<'de, T, U>(value: T, out: &'de mut ::alloc::vec::Vec<u8>, _hint: &U) -> U
        where
            T: ::musli::en::Encode + ::core::fmt::Debug + ::core::cmp::PartialEq,
            U: ::musli::de::Decode<'de>,
        {
            const WHAT: &str = $what;
            const ENCODING: crate::Encoding = crate::Encoding::new();

            use ::core::any::type_name;
            use ::alloc::string::ToString;

            let format_error = |cx: &crate::context::SystemContext<_, _>| {
                use ::alloc::vec::Vec;

                let mut errors = Vec::new();

                for error in cx.errors() {
                    errors.push(error.to_string());
                }

                errors.join("\n")
            };

            let mut buf = crate::allocator::buffer();
            let alloc = crate::allocator::new(&mut buf);
            let mut cx = crate::context::SystemContext::new(&alloc);
            cx.include_type();

            out.clear();

            match ENCODING.to_writer_with(&cx, &mut *out, &value) {
                Ok(()) => (),
                Err(..) => {
                    let error = format_error(&cx);
                    panic!("{WHAT}: {}: failed to encode:\n{error}", type_name::<T>())
                }
            };

            match ENCODING.from_slice_with(&cx, out) {
                Ok(decoded) => decoded,
                Err(error) => {
                    let error = format_error(&cx);
                    panic!("{WHAT}: {}: failed to decode:\n{error}", type_name::<T>())
                }
            }
        }

        /// Encode a value to bytes.
        #[doc(hidden)]
        #[track_caller]
        #[cfg(feature = "test")]
        pub fn to_vec<T>(value: T) -> ::alloc::vec::Vec<u8>
        where
            T: ::musli::en::Encode,
        {
            const WHAT: &str = $what;
            const ENCODING: crate::Encoding = crate::Encoding::new();

            use ::core::any::type_name;
            use ::alloc::string::ToString;

            let format_error = |cx: &crate::context::SystemContext<_, _>| {
                use ::alloc::vec::Vec;

                let mut errors = Vec::new();

                for error in cx.errors() {
                    errors.push(error.to_string());
                }

                errors.join("\n")
            };

            let mut buf = crate::allocator::buffer();
            let alloc = crate::allocator::new(&mut buf);
            let mut cx = crate::context::SystemContext::new(&alloc);
            cx.include_type();

            match ENCODING.to_vec_with(&cx, &value) {
                Ok(out) => out,
                Err(..) => {
                    let error = format_error(&cx);
                    panic!("{WHAT}: {}: failed to encode:\n{error}", type_name::<T>())
                }
            }
        }
    }
}