musli/context/
mod.rs

1//! [`Context`] implementations.
2//!
3//! [`Context`]: crate::Context
4
5mod access;
6use self::access::{Access, Shared};
7
8mod trace;
9#[doc(inline)]
10pub use self::trace::{Error, Errors, NoTrace, Report, Trace, TraceImpl, TraceMode};
11
12mod capture;
13#[doc(inline)]
14pub use self::capture::{Capture, Emit, ErrorMode, Ignore};
15
16mod error_marker;
17#[doc(inline)]
18pub use self::error_marker::ErrorMarker;
19
20mod default_context;
21#[doc(inline)]
22pub use self::default_context::DefaultContext;
23
24mod context_error;
25#[doc(inline)]
26pub use self::context_error::ContextError;
27
28#[cfg(feature = "alloc")]
29use crate::alloc::System;
30use crate::Allocator;
31
32/// Construct a new default context using the [`System`] allocator.
33///
34/// # Examples
35///
36/// ```
37/// use musli::context;
38///
39/// musli::alloc::default(|alloc| {
40///     let cx = context::new();
41///     let encoding = musli::json::Encoding::new();
42///     let string = encoding.to_string_with(&cx, &42)?;
43///     assert_eq!(string, "42");
44///     Ok(())
45/// })?;
46/// # Ok::<_, musli::context::ErrorMarker>(())
47/// ```
48#[cfg(feature = "alloc")]
49#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
50#[inline]
51pub fn new() -> DefaultContext<System, NoTrace, Ignore> {
52    DefaultContext::new()
53}
54
55/// Construct a new default context using the provided allocator.
56///
57/// # Examples
58///
59/// The `default` macro provides access to the default allocator. This is how it
60/// can be used with this method:
61///
62/// ```
63/// use musli::context;
64///
65/// musli::alloc::default(|alloc| {
66///     let cx = context::new_in(alloc);
67///     let encoding = musli::json::Encoding::new();
68///     let string = encoding.to_string_with(&cx, &42)?;
69///     assert_eq!(string, "42");
70///     Ok(())
71/// })?;
72/// # Ok::<_, musli::context::ErrorMarker>(())
73/// ```
74///
75/// We can also very conveniently set up an allocator which uses an existing
76/// buffer:
77///
78/// ```
79/// use musli::{alloc, context};
80///
81/// let mut buf = alloc::ArrayBuffer::new();
82/// let alloc = alloc::Slice::new(&mut buf);
83/// let cx = context::new_in(&alloc);
84///
85/// let encoding = musli::json::Encoding::new();
86/// let string = encoding.to_string_with(&cx, &42)?;
87/// assert_eq!(string, "42");
88/// # Ok::<_, musli::context::ErrorMarker>(())
89/// ```
90#[inline]
91pub fn new_in<A>(alloc: A) -> DefaultContext<A, NoTrace, Ignore>
92where
93    A: Allocator,
94{
95    DefaultContext::new_in(alloc)
96}