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
26#[inline]
27pub fn wrap<T>(inner: T) -> Wrap<T> {
28    Wrap { inner }
29}
30
31#[cfg(feature = "std")]
32impl<W> crate::writer::IntoWriter for Wrap<W>
33where
34    W: std::io::Write,
35{
36    type Ok = ();
37    type Writer = Self;
38
39    #[inline]
40    fn into_writer(self) -> Self::Writer {
41        self
42    }
43}
44
45#[cfg(feature = "std")]
46impl<W> crate::writer::Writer for Wrap<W>
47where
48    W: std::io::Write,
49{
50    type Ok = ();
51    type Mut<'this>
52        = &'this mut Self
53    where
54        Self: 'this;
55
56    #[inline]
57    fn finish<C>(&mut self, _: C) -> Result<Self::Ok, C::Error>
58    where
59        C: Context,
60    {
61        Ok(())
62    }
63
64    #[inline]
65    fn borrow_mut(&mut self) -> Self::Mut<'_> {
66        self
67    }
68
69    #[inline]
70    fn extend<C>(&mut self, cx: C, buffer: Vec<u8, C::Allocator>) -> Result<(), C::Error>
71    where
72        C: Context,
73    {
74        // SAFETY: the buffer never outlives this function call.
75        self.write_bytes(cx, buffer.as_slice())
76    }
77
78    #[inline]
79    fn write_bytes<C>(&mut self, cx: C, bytes: &[u8]) -> Result<(), C::Error>
80    where
81        C: Context,
82    {
83        self.inner.write_all(bytes).map_err(cx.map())?;
84        cx.advance(bytes.len());
85        Ok(())
86    }
87}