embedded_c_sdk_bind_hal/common/
format.rs

1//
2//The original code is from format_n_osd crate: https://crates.io/crates/format_no_std
3//
4
5use core::cmp::min;
6use core::fmt;
7use core::str::from_utf8;
8
9/// A struct representing a writer that appends formatted data to a byte buffer.
10pub struct WriteTo<'a> {
11    buf: &'a mut [u8],
12    len: usize,
13}
14
15impl<'a> WriteTo<'a> {
16    /// Constructs a new `WriteTo` instance wrapping the provided byte buffer.
17    pub fn new(buf: &'a mut [u8]) -> Self {
18        WriteTo { buf, len: 0 }
19    }
20
21    /// Converts the written portion of the buffer into a string slice, if possible.
22    pub fn as_str(self) -> Option<&'a str> {
23        let min_len;
24        if self.len > self.buf.len() {
25            min_len = self.buf.len();
26            let tail = &mut self.buf[min_len - 3..];
27            tail.fill(b'.');
28        } else {
29            min_len = min(self.len, self.buf.len())
30        };
31        from_utf8(&self.buf[..min_len]).ok()
32    }
33
34    /// Get the number of bytes written to buffer.
35    pub fn len(&self) -> usize {
36        min(self.len, self.buf.len())
37    }
38
39    /// Returns true if self has a length of zero bytes
40    pub fn is_empty(&self) -> bool {
41        self.len == 0
42    }
43}
44
45impl<'a> fmt::Write for WriteTo<'a> {
46    /// Writes a string slice into the buffer, updating the length accordingly.
47    fn write_str(&mut self, s: &str) -> fmt::Result {
48        if self.len >= self.buf.len() {
49            return Err(fmt::Error);
50        }
51
52        let rem = &mut self.buf[self.len..];
53        let raw_s = s.as_bytes();
54        let num = min(raw_s.len(), rem.len());
55
56        rem[..num].copy_from_slice(&raw_s[..num]);
57        self.len += raw_s.len();
58
59        Ok(())
60    }
61}
62
63/// Formats data using `format_args!` (`arg` argument) and writes it to a byte buffer `buf`.
64pub fn fmt_to_buf<'a>(buf: &'a mut [u8], arg: fmt::Arguments) -> Result<&'a str, fmt::Error> {
65    let mut w = WriteTo::new(buf);
66    if let Err(e) = fmt::write(&mut w, arg) {
67        if w.len() == 0 {
68            return Err(e);
69        }
70    }
71    w.as_str().ok_or(fmt::Error)
72}