musli 0.0.149

Müsli is a flexible and efficient serialization framework.
Documentation
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
use core::error::Error;
use core::fmt;

#[cfg(feature = "alloc")]
use crate::alloc::Global;
use crate::{Allocator, Context};

use super::{
    Capture, ContextError, Emit, ErrorMode, Errors, Ignore, NoTrace, Report, Trace, TraceImpl,
    TraceMode,
};

/// The default context which uses an allocator to track the location of errors.
///
/// This is typically constructed using [`new`] and by default uses the
/// [`Global`] allocator to allocate memory. To customized the allocator to use
/// [`new_in`] can be used during construction.
///
/// The default constructor is only available when the `alloc` feature is
/// enabled, and will use the [`Global`] allocator.
///
/// [`new`]: super::new
/// [`new_in`]: super::new_in
pub struct DefaultContext<A, T, C>
where
    A: Allocator,
    T: TraceMode,
{
    alloc: A,
    trace: T::Impl<A>,
    capture: C,
}

#[cfg(feature = "alloc")]
impl DefaultContext<Global, NoTrace, Ignore> {
    /// Construct the default context which uses the [`Global`] allocator for
    /// memory.
    #[inline]
    pub(super) fn new() -> Self {
        Self::new_in(Global::new())
    }
}

impl<A> DefaultContext<A, NoTrace, Ignore>
where
    A: Allocator,
{
    /// Construct a new context which uses allocations to a fixed but
    /// configurable number of diagnostics.
    #[inline]
    pub(super) fn new_in(alloc: A) -> Self {
        let trace = NoTrace::new_in(alloc);
        Self {
            alloc,
            trace,
            capture: Ignore,
        }
    }
}

#[cfg(feature = "alloc")]
impl Default for DefaultContext<Global, NoTrace, Ignore> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<A, T, C> DefaultContext<A, T, C>
where
    A: Allocator,
    T: TraceMode,
    C: ErrorMode<A>,
{
    /// Enable tracing through the current allocator `A`.
    ///
    /// Note that this makes diagnostics methods such as [`report`] and
    /// [`errors`] available on the type.
    ///
    /// Tracing requires the configured allocator to work, if for example the
    /// [`Disabled`] allocator was in use, no diagnostics would be collected.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::context;
    ///
    /// let cx = context::new().with_trace();
    /// // Use cx for encoding/decoding to get detailed error information
    /// ```
    ///
    /// [`report`]: DefaultContext::report
    /// [`errors`]: DefaultContext::errors
    /// [`Disabled`]: crate::alloc::Disabled
    #[inline]
    pub fn with_trace(self) -> DefaultContext<A, Trace, C> {
        let trace = Trace::new_in(self.alloc);

        DefaultContext {
            alloc: self.alloc,
            trace,
            capture: self.capture,
        }
    }

    /// Capture the specified error type.
    ///
    /// This gives access to the last captured error through
    /// [`DefaultContext::unwrap`] and [`DefaultContext::result`].
    ///
    /// Capturing instead of forwarding the error might be beneficial if the
    /// error type is large.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::{Decode, Encode};
    /// use musli::alloc::Global;
    /// use musli::context;
    /// use musli::json::{Encoding, Error};
    ///
    /// const ENCODING: Encoding = Encoding::new();
    ///
    /// #[derive(Decode, Encode)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let cx = context::new().with_capture::<Error>();
    ///
    /// let mut data = Vec::new();
    ///
    /// ENCODING.encode_with(&cx, &mut data, &Person {
    ///     name: "Aristotle".to_string(),
    ///     age: 61,
    /// })?;
    ///
    /// assert!(cx.result().is_ok());
    ///
    /// let _: Result<Person, _> = ENCODING.from_slice_with(&cx, &data[..data.len() - 2]);
    /// assert!(cx.result().is_err());
    /// Ok::<_, musli::context::ErrorMarker>(())
    /// ```
    #[inline]
    pub fn with_capture<E>(self) -> DefaultContext<A, T, Capture<E>>
    where
        E: ContextError<A>,
    {
        DefaultContext {
            alloc: self.alloc,
            trace: self.trace,
            capture: Capture::new(),
        }
    }

    /// Emit the specified error type `E`.
    ///
    /// This causes the method receiving the context to return the specified
    /// error type directly instead through [`Context::Error`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::{Decode, Encode};
    /// use musli::alloc::Global;
    /// use musli::context;
    /// use musli::json::{Encoding, Error};
    ///
    /// const ENCODING: Encoding = Encoding::new();
    ///
    /// #[derive(Decode, Encode)]
    /// struct Person {
    ///     name: String,
    ///     age: u32,
    /// }
    ///
    /// let cx = context::new().with_error();
    ///
    /// let mut data = Vec::new();
    ///
    /// ENCODING.encode_with(&cx, &mut data, &Person {
    ///     name: "Aristotle".to_string(),
    ///     age: 61,
    /// })?;
    ///
    /// let person: Person = ENCODING.from_slice_with(&cx, &data[..])?;
    /// assert_eq!(person.name, "Aristotle");
    /// assert_eq!(person.age, 61);
    /// Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn with_error<E>(self) -> DefaultContext<A, T, Emit<E>>
    where
        E: ContextError<A>,
    {
        DefaultContext {
            alloc: self.alloc,
            trace: self.trace,
            capture: Emit::new(),
        }
    }
}

impl<A, C> DefaultContext<A, Trace, C>
where
    A: Allocator,
{
    /// If tracing is enabled through [`DefaultContext::with_trace`], this
    /// configured the context to visualize type information, and not just
    /// variant and fields.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::context;
    ///
    /// let cx = context::new().with_trace().with_type();
    /// ```
    #[inline]
    pub fn with_type(mut self) -> Self {
        self.trace.include_type();
        self
    }

    /// Generate a line-separated report of all reported errors.
    ///
    /// This can be useful if you want a quick human-readable overview of
    /// errors. The line separator used will be platform dependent.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::context::{self, ErrorMarker};
    /// use musli::value::Value;
    /// use musli::json::Encoding;
    ///
    /// const ENCODING: Encoding = Encoding::new();
    ///
    /// let cx = context::new().with_trace();
    ///
    /// let ErrorMarker = ENCODING.from_str_with::<_, Value<_>>(&cx, "not json").unwrap_err();
    /// let report = cx.report();
    /// println!("{report}");
    /// ```
    #[inline]
    pub fn report(&self) -> Report<'_, A> {
        self.trace.report()
    }

    /// Iterate over all reported errors.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::context::{self, ErrorMarker};
    /// use musli::value::Value;
    /// use musli::json::Encoding;
    ///
    /// const ENCODING: Encoding = Encoding::new();
    ///
    /// let cx = context::new().with_trace();
    ///
    /// let ErrorMarker = ENCODING.from_str_with::<_, Value<_>>(&cx, "not json").unwrap_err();
    /// assert!(cx.errors().count() > 0);
    /// ```
    #[inline]
    pub fn errors(&self) -> Errors<'_, A> {
        self.trace.errors()
    }
}

impl<A, T, E> DefaultContext<A, T, Capture<E>>
where
    A: Allocator,
    T: TraceMode,
    E: ContextError<A>,
{
    /// Unwrap the error marker or panic if there is no error.
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// use musli::context;
    ///
    /// let cx = context::new().with_capture::<String>();
    /// // This will panic since no error has been captured
    /// let error = cx.unwrap();
    /// ```
    #[inline]
    pub fn unwrap(&self) -> E {
        self.capture.unwrap()
    }

    /// Coerce a captured error into a result.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli::context;
    ///
    /// let cx = context::new().with_capture::<String>();
    /// let result = cx.result();
    /// assert!(result.is_ok());
    /// ```
    #[inline]
    pub fn result(&self) -> Result<(), E> {
        self.capture.result()
    }
}

impl<A, T, C> Context for &DefaultContext<A, T, C>
where
    A: Allocator,
    T: TraceMode,
    C: ErrorMode<A>,
{
    type Error = C::Error;
    type Mark = <<T as TraceMode>::Impl<A> as TraceImpl<A>>::Mark;
    type Allocator = A;

    #[inline]
    fn clear(self) {
        self.trace.clear();
        self.capture.clear();
    }

    #[inline]
    fn alloc(self) -> Self::Allocator {
        self.alloc
    }

    #[inline]
    fn custom<E>(self, message: E) -> Self::Error
    where
        E: 'static + Send + Sync + Error,
    {
        self.trace.custom(self.alloc, &message);
        self.capture.custom(self.alloc, message)
    }

    #[inline]
    fn message<M>(self, message: M) -> Self::Error
    where
        M: fmt::Display,
    {
        self.trace.message(self.alloc, &message);
        self.capture.message(self.alloc, message)
    }

    #[inline]
    fn message_at<M>(self, mark: &Self::Mark, message: M) -> Self::Error
    where
        M: fmt::Display,
    {
        self.trace.message_at(self.alloc, mark, &message);
        self.capture.message(self.alloc, message)
    }

    #[inline]
    fn custom_at<E>(self, mark: &Self::Mark, message: E) -> Self::Error
    where
        E: 'static + Send + Sync + Error,
    {
        self.trace.custom_at(self.alloc, mark, &message);
        self.capture.custom(self.alloc, message)
    }

    #[inline]
    fn mark(self) -> Self::Mark {
        self.trace.mark()
    }

    #[inline]
    fn restore(self, mark: &Self::Mark) {
        self.trace.restore(mark);
    }

    #[inline]
    fn advance(self, n: usize) {
        self.trace.advance(n);
    }

    #[inline]
    fn enter_named_field<F>(self, name: &'static str, field: F)
    where
        F: fmt::Display,
    {
        self.trace.enter_named_field(name, &field);
    }

    #[inline]
    fn enter_unnamed_field<F>(self, index: u32, name: F)
    where
        F: fmt::Display,
    {
        self.trace.enter_unnamed_field(index, &name);
    }

    #[inline]
    fn leave_field(self) {
        self.trace.leave_field();
    }

    #[inline]
    fn enter_struct(self, name: &'static str) {
        self.trace.enter_struct(name);
    }

    #[inline]
    fn leave_struct(self) {
        self.trace.leave_struct();
    }

    #[inline]
    fn enter_enum(self, name: &'static str) {
        self.trace.enter_enum(name);
    }

    #[inline]
    fn leave_enum(self) {
        self.trace.leave_enum();
    }

    #[inline]
    fn enter_variant<V>(self, name: &'static str, tag: V)
    where
        V: fmt::Display,
    {
        self.trace.enter_variant(name, &tag);
    }

    #[inline]
    fn leave_variant(self) {
        self.trace.leave_variant();
    }

    #[inline]
    fn enter_sequence_index(self, index: usize) {
        self.trace.enter_sequence_index(index);
    }

    #[inline]
    fn leave_sequence_index(self) {
        self.trace.leave_sequence_index();
    }

    #[inline]
    fn enter_map_key<F>(self, field: F)
    where
        F: fmt::Display,
    {
        self.trace.enter_map_key(self.alloc, &field);
    }

    #[inline]
    fn leave_map_key(self) {
        self.trace.leave_map_key();
    }
}