Skip to main content

musli/
wrap.rs

1//! Wrapper for integrating musli with I/O types like [std::io].
2//!
3//! The main methods in this module is the [`wrap`] function which constructs an
4//! adapter around an I/O type to work with musli.
5
6#[cfg(feature = "std")]
7use crate::Context;
8#[cfg(feature = "std")]
9use crate::alloc::Vec;
10
11/// Wrap a type so that it implements [`Reader`] and [`Writer`].
12///
13/// See [`wrap()`].
14///
15/// [`Reader`]: crate::reader::Reader
16/// [`Writer`]: crate::writer::Writer
17///
18/// # Examples
19///
20/// ```
21/// use musli::wrap;
22///
23/// let buffer: Vec<u8> = Vec::new();
24/// let wrapped = wrap::wrap(buffer);
25/// ```
26pub struct Wrap<T> {
27    #[cfg_attr(not(feature = "std"), allow(unused))]
28    inner: T,
29}
30
31/// Wrap a type so that it implements [`Reader`] and [`Writer`].
32///
33/// [`Reader`]: crate::reader::Reader
34/// [`Writer`]: crate::writer::Writer
35///
36/// # Examples
37///
38/// ```
39/// use musli::wrap;
40///
41/// let buffer: Vec<u8> = Vec::new();
42/// let wrapped = wrap::wrap(buffer);
43/// ```
44#[inline]
45pub fn wrap<T>(inner: T) -> Wrap<T> {
46    Wrap { inner }
47}
48
49#[cfg(feature = "std")]
50impl<W> crate::writer::IntoWriter for Wrap<W>
51where
52    W: std::io::Write,
53{
54    type Ok = ();
55    type Writer = Self;
56
57    #[inline]
58    fn into_writer(self) -> Self::Writer {
59        self
60    }
61}
62
63#[cfg(feature = "std")]
64impl<W> crate::writer::Writer for Wrap<W>
65where
66    W: std::io::Write,
67{
68    type Ok = ();
69    type Mut<'this>
70        = &'this mut Self
71    where
72        Self: 'this;
73
74    #[inline]
75    fn finish<C>(&mut self, _: C) -> Result<Self::Ok, C::Error>
76    where
77        C: Context,
78    {
79        Ok(())
80    }
81
82    #[inline]
83    fn borrow_mut(&mut self) -> Self::Mut<'_> {
84        self
85    }
86
87    #[inline]
88    fn extend<C>(&mut self, cx: C, buffer: Vec<u8, C::Allocator>) -> Result<(), C::Error>
89    where
90        C: Context,
91    {
92        // SAFETY: the buffer never outlives this function call.
93        self.write_bytes(cx, buffer.as_slice())
94    }
95
96    #[inline]
97    fn write_bytes<C>(&mut self, cx: C, bytes: &[u8]) -> Result<(), C::Error>
98    where
99        C: Context,
100    {
101        self.inner.write_all(bytes).map_err(cx.map())?;
102        cx.advance(bytes.len());
103        Ok(())
104    }
105}