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::alloc::Vec;
8#[cfg(feature = "std")]
9use crate::Context;
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
17pub struct Wrap<T> {
18    #[cfg_attr(not(feature = "std"), allow(unused))]
19    inner: T,
20}
21
22/// Wrap a type so that it implements [`Reader`] and [`Writer`].
23///
24/// [`Reader`]: crate::reader::Reader
25/// [`Writer`]: crate::writer::Writer
26pub fn wrap<T>(inner: T) -> Wrap<T> {
27    Wrap { inner }
28}
29
30#[cfg(feature = "std")]
31impl<W> crate::writer::Writer for Wrap<W>
32where
33    W: std::io::Write,
34{
35    type Mut<'this> = &'this mut Self where Self: 'this;
36
37    #[inline]
38    fn borrow_mut(&mut self) -> Self::Mut<'_> {
39        self
40    }
41
42    #[inline]
43    fn extend<C>(&mut self, cx: &C, buffer: Vec<'_, u8, C::Allocator>) -> Result<(), C::Error>
44    where
45        C: ?Sized + Context,
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}