facet_core/
write.rs

1//! A `no_std` compatible `Write` trait for serialization.
2//!
3//! This trait is used by facet serializers (like `facet-json`) to write output
4//! without depending on `std::io::Write`, enabling `no_std` support.
5
6#[cfg(feature = "alloc")]
7use alloc::vec::Vec;
8
9/// A `no_std` compatible write trait used by facet serializers.
10///
11/// This trait provides a simple interface for writing bytes, designed to work
12/// in `no_std` environments while remaining compatible with standard library types.
13pub trait Write {
14    /// Write all bytes from the buffer to the writer.
15    fn write(&mut self, buf: &[u8]);
16
17    /// If the writer supports it, reserve space for `additional` bytes.
18    ///
19    /// This is an optimization hint and may be ignored by implementations.
20    fn reserve(&mut self, additional: usize);
21}
22
23#[cfg(feature = "alloc")]
24impl Write for Vec<u8> {
25    #[inline]
26    fn write(&mut self, buf: &[u8]) {
27        self.extend_from_slice(buf);
28    }
29
30    #[inline]
31    fn reserve(&mut self, additional: usize) {
32        Vec::reserve(self, additional);
33    }
34}
35
36#[cfg(feature = "alloc")]
37impl Write for &mut Vec<u8> {
38    #[inline]
39    fn write(&mut self, buf: &[u8]) {
40        self.extend_from_slice(buf);
41    }
42
43    #[inline]
44    fn reserve(&mut self, additional: usize) {
45        Vec::reserve(self, additional);
46    }
47}
48
49#[cfg(feature = "bytes")]
50impl Write for bytes::BytesMut {
51    #[inline]
52    fn write(&mut self, buf: &[u8]) {
53        self.extend_from_slice(buf);
54    }
55
56    #[inline]
57    fn reserve(&mut self, additional: usize) {
58        bytes::BytesMut::reserve(self, additional);
59    }
60}
61
62#[cfg(feature = "bytes")]
63impl Write for &mut bytes::BytesMut {
64    #[inline]
65    fn write(&mut self, buf: &[u8]) {
66        self.extend_from_slice(buf);
67    }
68
69    #[inline]
70    fn reserve(&mut self, additional: usize) {
71        bytes::BytesMut::reserve(self, additional);
72    }
73}