musli_utils/
wrap.rs

1//! Helpers for integrating musli with I/O types like [std::io] and
2//! [std::io::Write].
3//!
4//! The central function in this module is the [wrap] function which constructs
5//! an adapter around an I/O type to work with musli.
6
7#[cfg(feature = "std")]
8use musli::{Buf, Context};
9
10/// Wrap a type so that it implements [`Reader`] and [`Writer`].
11///
12/// See [`wrap()`].
13///
14/// [`Reader`]: crate::reader::Reader
15/// [`Writer`]: crate::writer::Writer
16pub struct Wrap<T> {
17    #[cfg_attr(not(feature = "std"), allow(unused))]
18    inner: T,
19}
20
21/// Wrap a type so that it implements [`Reader`] and [`Writer`].
22///
23/// [`Reader`]: crate::reader::Reader
24/// [`Writer`]: crate::writer::Writer
25pub fn wrap<T>(inner: T) -> Wrap<T> {
26    Wrap { inner }
27}
28
29#[cfg(feature = "std")]
30impl<W> crate::writer::Writer for Wrap<W>
31where
32    W: std::io::Write,
33{
34    type Mut<'this> = &'this mut Self where Self: 'this;
35
36    #[inline]
37    fn borrow_mut(&mut self) -> Self::Mut<'_> {
38        self
39    }
40
41    #[inline]
42    fn write_buffer<C, B>(&mut self, cx: &C, buffer: B) -> Result<(), C::Error>
43    where
44        C: ?Sized + Context,
45        B: Buf,
46    {
47        // SAFETY: the buffer never outlives this function call.
48        self.write_bytes(cx, buffer.as_slice())
49    }
50
51    #[inline]
52    fn write_bytes<C>(&mut self, cx: &C, bytes: &[u8]) -> Result<(), C::Error>
53    where
54        C: ?Sized + Context,
55    {
56        self.inner.write_all(bytes).map_err(cx.map())?;
57        cx.advance(bytes.len());
58        Ok(())
59    }
60}