1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! Tools for implementing writer style serializers dedicated for `no_std` targets.
//!
//! Features a [trait][SerWrite] for objects which are byte-oriented sinks, akin to `std::io::Write`.
//!
//! Serializers can be implemented using this trait as a writer.
//!
//! Embedded or otherwise `no_std` projects can implement [`SerWrite`] for custom sinks.
//!
//! Some [implemenentations] for foreign types are provided depending on the enabled features.
//!
//! [implemenentations]: SerWrite#foreign-impls
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "std")]
extern crate std;

#[cfg(all(feature = "alloc",not(feature = "std")))]
extern crate alloc;

use core::fmt;

mod foreign;

pub type SerResult<T> = Result<T, SerError>;

/// A simple error type that can be used for [`SerWrite::Error`] implementations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SerError {
    /// Buffer is full
    BufferFull,
}

impl fmt::Display for SerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SerError::BufferFull => f.write_str("buffer is full"),
        }
    }
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for SerError {}

/// Serializers should write data to the implementations of this trait.
pub trait SerWrite {
    /// An error type returned from the trait methods.
    type Error;
    /// Write **all** bytes from `buf` to the internal buffer.
    ///
    /// Otherwise return an error.
    fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
    /// Write a single `byte` to the internal buffer.
    ///
    /// Return an error if the operation could not succeed.
    #[inline]
    fn write_byte(&mut self, byte: u8) -> Result<(), Self::Error> {
        self.write(core::slice::from_ref(&byte))
    }
    /// Write a **whole** string to the internal buffer.
    ///
    /// Otherwise return an error.
    #[inline]
    fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
        self.write(s.as_bytes())
    }
}

impl<T: SerWrite> SerWrite for &'_ mut T {
    type Error = T::Error;

    #[inline(always)]
    fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        (*self).write(buf)
    }

    #[inline(always)]
    fn write_byte(&mut self, byte: u8) -> Result<(), Self::Error> {
        (*self).write_byte(byte)
    }

    #[inline(always)]
    fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
        (*self).write_str(s)
    }
}

/// A simple slice writer (example implementation)
#[derive(Debug, PartialEq)]
pub struct SliceWriter<'a> {
    pub buf: &'a mut [u8],
    pub len: usize
}

impl<'a> AsRef<[u8]> for SliceWriter<'a> {
    /// Returns a populated portion of the slice
    fn as_ref(&self) -> &[u8] {
        &self.buf[..self.len]
    }
}

impl<'a> AsMut<[u8]> for SliceWriter<'a> {
    /// Returns a populated portion of the slice
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.buf[..self.len]
    }
}

impl<'a> SliceWriter<'a> {
    /// Create a new instance
    pub fn new(buf: &'a mut [u8]) -> Self {
        SliceWriter { buf, len: 0 }
    }
    /// Return populated length
    pub fn len(&self) -> usize {
        self.len
    }
    /// Return whether the output is not populated.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }
    /// Return total capacity of the container
    pub fn capacity(&self) -> usize {
        self.buf.len()
    }
    /// Return remaining free capacity
    pub fn rem_capacity(&self) -> usize {
        self.buf.len() - self.len
    }
    /// Reset cursor to the beginning of a container slice
    pub fn clear(&mut self) {
        self.len = 0;
    }
    /// Split the underlying buffer and return the portion of the populated buffer
    /// with an underlying buffer's borrowed lifetime.
    ///
    /// Once a [`SliceWriter`] is dropped the slice stays borrowed as long as the
    /// original container lives.
    pub fn split(self) -> (&'a mut[u8], Self) {
        let (res, buf) = self.buf.split_at_mut(self.len);
        (res, Self { buf, len: 0 })
    }
}

impl SerWrite for SliceWriter<'_> {
    type Error = SerError;

    fn write(&mut self, buf: &[u8]) -> SerResult<()> {
        let end = self.len + buf.len();
        match self.buf.get_mut(self.len..end) {
            Some(chunk) => {
                chunk.copy_from_slice(buf);
                self.len = end;
                Ok(())
            }
            None => Err(SerError::BufferFull)
        }
    }
}

impl<'a> fmt::Write for SliceWriter<'a> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        SerWrite::write_str(self, s).map_err(|_| fmt::Error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_slice_writer() {
        let mut buf = [0u8;22];
        let mut writer = SliceWriter::new(&mut buf);
        writer.write(b"Hello World!").unwrap();
        writer.write_byte(b' ').unwrap();
        writer.write_str("Good Bye!").unwrap();
        let expected = b"Hello World! Good Bye!";
        assert_eq!(writer.as_ref(), expected);
        let (head, mut writer) = writer.split();
        assert_eq!(head, expected);
        assert_eq!(writer.write_byte(b' ').unwrap_err(), SerError::BufferFull);
    }
}