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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/// 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>,
{
$crate::allocator::with(|alloc| {
let cx = $crate::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::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::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>,
{
$crate::allocator::with(|alloc| {
let cx = $crate::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) => {
/// 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>,
{
$crate::allocator::with(|alloc| {
let cx = $crate::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 = $crate::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>,
{
cx.clear();
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>,
{
cx.clear();
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>,
{
$crate::allocator::with(|alloc| {
let cx = $crate::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, $mode:ty $(, $(#[$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<$mode> + ::musli::de::DecodeOwned<$mode>,
T: ::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, "\" (0-{})", self.0.len())?;
Ok(())
}
}
$crate::allocator::with(|alloc| {
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 = cx.report();
panic!("{WHAT}: {}: failed to encode:\n{error}", 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 = cx.report();
panic!("{WHAT}: {}: failed to decode:\nValue: {value:?}\nBytes: {out}\n{error}", type_name::<T>())
}
};
assert_eq!(decoded, value, "{WHAT}: {}: roundtrip does not match\nValue: {value:?}", 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 = cx.report();
panic!("{WHAT}: {}: failed to decode to value type:\nValue: {value:?}\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 = cx.report();
panic!("{WHAT}: {}: failed to decode from value type:\nValue: {value:?}\nBytes: {out}\nBuffered value: {value_decode:?}\n{error}", type_name::<T>())
}
};
assert_eq!(value_decoded, value, "{WHAT}: {}: musli-value roundtrip does not match\nValue: {value:?}", 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>, expected: &U) -> U
where
T: ::musli::en::Encode<$mode>,
T: ::core::fmt::Debug + ::core::cmp::PartialEq,
U: ::musli::de::Decode<'de, $mode>,
U: ::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, "\" (0-{})", self.0.len())?;
Ok(())
}
}
$crate::allocator::with(|alloc| {
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 = cx.report();
panic!("{WHAT}: {}: failed to encode:\n{error}", type_name::<T>())
}
};
let actual = match ENCODING.from_slice_with(&cx, &*out) {
Ok(decoded) => decoded,
Err(error) => {
let out = FormatBytes(&*out);
let error = cx.report();
panic!("{WHAT}: {}: failed to decode:\nValue: {value:?}\nBytes: {out}\n{error}", type_name::<T>())
}
};
assert_eq!(
actual,
*expected,
"{WHAT}: decoded value does not match expected\nBytes: {}",
FormatBytes(&*out),
);
actual
})
}
/// 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<$mode>,
{
const WHAT: &str = $what;
const ENCODING: crate::Encoding = crate::Encoding::new();
use ::core::any::type_name;
use ::alloc::string::ToString;
$crate::allocator::with(|alloc| {
let mut cx = $crate::context::SystemContext::new(alloc);
cx.include_type();
match ENCODING.to_vec_with(&cx, &value) {
Ok(out) => out,
Err(..) => {
let error = cx.report();
panic!("{WHAT}: {}: failed to encode:\n{error}", type_name::<T>())
}
}
})
}
}
}
/// Expands to a `str` module which provides local and lightweight simdutf8
/// compatibility functions.
#[doc(hidden)]
#[macro_export]
macro_rules! simdutf8 {
() => {
pub(crate) mod str {
//! Functions for working with strings. The exported implementations change
//! depending on if the `simdutf8` feature is enabled.
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::fmt;
#[cfg(not(feature = "simdutf8"))]
#[doc(inline)]
pub use core::str::from_utf8;
#[cfg(feature = "simdutf8")]
#[doc(inline)]
pub use simdutf8::basic::from_utf8;
/// Error raised in case the UTF-8 sequence could not be decoded.
#[non_exhaustive]
#[derive(Debug)]
pub struct Utf8Error;
#[cfg(feature = "std")]
impl std::error::Error for Utf8Error {}
impl fmt::Display for Utf8Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid or incomplete utf-8 sequence")
}
}
/// The same as [`String::from_utf8`], but the implementation can different
/// depending on if the `simdutf8` feature is enabled.
///
/// [`String::from_utf8`]: alloc::string::String::from_utf8
#[inline(always)]
#[cfg(all(feature = "alloc", not(feature = "simdutf8")))]
pub fn from_utf8_owned(bytes: Vec<u8>) -> Result<String, Utf8Error> {
match String::from_utf8(bytes) {
Ok(string) => Ok(string),
Err(..) => Err(Utf8Error),
}
}
/// The same as [`String::from_utf8`], but the implementation can different
/// depending on if the `simdutf8` feature is enabled.
///
/// [`String::from_utf8`]: alloc::string::String::from_utf8
#[inline(always)]
#[cfg(all(feature = "alloc", feature = "simdutf8"))]
pub fn from_utf8_owned(bytes: Vec<u8>) -> Result<String, Utf8Error> {
if from_utf8(&bytes).is_err() {
return Err(Utf8Error);
}
// SAFETY: String was checked above.
Ok(unsafe { String::from_utf8_unchecked(bytes) })
}
}
};
}