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
//! `μfmt` utilities
//!
//! # Minimum Supported Rust Version (MSRV)
//!
//! This crate is guaranteed to compile on stable Rust 1.36 and up. It *might* compile on older
//! versions but that may change in any new patch release.

#![deny(missing_docs)]
#![deny(warnings)]
#![no_std]

use core::{convert::Infallible, fmt, str};

use heapless::String;
use ufmt_write::uWrite;

macro_rules! assume_unreachable {
    () => {
        if cfg!(debug_assertions) {
            panic!()
        } else {
            core::hint::unreachable_unchecked()
        }
    };
}

/// A write adapter that ignores all errors
pub struct Ignore<W>
where
    W: uWrite,
{
    writer: W,
}

impl<W> Ignore<W>
where
    W: uWrite,
{
    /// Creates a new `Ignore` adapter
    pub fn new(writer: W) -> Self {
        Self { writer }
    }

    /// Destroys the adapter and returns the underlying writer
    pub fn free(self) -> W {
        self.writer
    }
}

impl<W> uWrite for Ignore<W>
where
    W: uWrite,
{
    type Error = Infallible;

    fn write_str(&mut self, s: &str) -> Result<(), Infallible> {
        let _ = self.writer.write_str(s);
        Ok(())
    }
}

/// A write adapter that buffers writes and automatically flushes on newlines
pub struct LineBuffered<W, const N: usize>
where
    W: uWrite,
{
    buffer: String<N>,
    writer: W,
}

impl<W, const N: usize> LineBuffered<W, N>
where
    W: uWrite,
{
    /// Creates a new `LineBuffered` adapter
    pub fn new(writer: W) -> Self {
        Self {
            buffer: String::new(),
            writer,
        }
    }

    /// Flushes the contents of the buffer
    pub fn flush(&mut self) -> Result<(), W::Error> {
        let ret = self.writer.write_str(&self.buffer);
        self.buffer.clear();
        ret
    }

    /// Destroys the adapter and returns the underlying writer
    pub fn free(self) -> W {
        self.writer
    }

    fn push_str(&mut self, s: &str) -> Result<(), W::Error> {
        let len = s.as_bytes().len();
        if self.buffer.len() + len > self.buffer.capacity() {
            self.flush()?;
        }

        if len > self.buffer.capacity() {
            self.writer.write_str(s)?;
        } else {
            self.buffer
                .push_str(s)
                .unwrap_or_else(|_| unsafe { assume_unreachable!() })
        }

        Ok(())
    }
}

impl<W, const N: usize> uWrite for LineBuffered<W, N>
where
    W: uWrite,
{
    type Error = W::Error;

    fn write_str(&mut self, mut s: &str) -> Result<(), W::Error> {
        while let Some(pos) = s.as_bytes().iter().position(|b| *b == b'\n') {
            let line = s
                .get(..pos + 1)
                .unwrap_or_else(|| unsafe { assume_unreachable!() });

            self.push_str(line)?;
            self.flush()?;

            s = s
                .get(pos + 1..)
                .unwrap_or_else(|| unsafe { assume_unreachable!() });
        }

        self.push_str(s)
    }
}

/// An adapter struct allowing to use `ufmt` on types which implement `core::fmt::Write`
///
/// For example:
///
/// ```
/// use ufmt::uwrite;
/// use ufmt_write::uWrite;
/// use ufmt_utils::WriteAdapter;
///
/// let fancy_number: u8 = 42;
///
/// let mut s = String::new();
/// uwrite!(WriteAdapter(&mut s), "{:?}", fancy_number);
/// ```
pub struct WriteAdapter<W>(pub W)
where
    W: fmt::Write;

impl<W> uWrite for WriteAdapter<W>
where
    W: fmt::Write,
{
    type Error = fmt::Error;

    fn write_char(&mut self, c: char) -> Result<(), Self::Error> {
        self.0.write_char(c)
    }

    fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
        self.0.write_str(s)
    }
}