/rust/registry/src/index.crates.io-1949cf8c6b5b557f/anstream-0.6.21/src/fmt.rs
Line | Count | Source |
1 | | /// A shim which allows a [`std::io::Write`] to be implemented in terms of a [`std::fmt::Write`] |
2 | | /// |
3 | | /// This saves off I/O errors. instead of discarding them |
4 | | pub(crate) struct Adapter<W> |
5 | | where |
6 | | W: FnMut(&[u8]) -> std::io::Result<()>, |
7 | | { |
8 | | writer: W, |
9 | | error: std::io::Result<()>, |
10 | | } |
11 | | |
12 | | impl<W> Adapter<W> |
13 | | where |
14 | | W: FnMut(&[u8]) -> std::io::Result<()>, |
15 | | { |
16 | 0 | pub(crate) fn new(writer: W) -> Self { |
17 | 0 | Adapter { |
18 | 0 | writer, |
19 | 0 | error: Ok(()), |
20 | 0 | } |
21 | 0 | } |
22 | | |
23 | 0 | pub(crate) fn write_fmt(mut self, fmt: std::fmt::Arguments<'_>) -> std::io::Result<()> { |
24 | 0 | match std::fmt::write(&mut self, fmt) { |
25 | 0 | Ok(()) => Ok(()), |
26 | | Err(..) => { |
27 | | // check if the error came from the underlying `Write` or not |
28 | 0 | if self.error.is_err() { |
29 | 0 | self.error |
30 | | } else { |
31 | 0 | Err(std::io::Error::new( |
32 | 0 | std::io::ErrorKind::Other, |
33 | 0 | "formatter error", |
34 | 0 | )) |
35 | | } |
36 | | } |
37 | | } |
38 | 0 | } |
39 | | } |
40 | | |
41 | | impl<W> std::fmt::Write for Adapter<W> |
42 | | where |
43 | | W: FnMut(&[u8]) -> std::io::Result<()>, |
44 | | { |
45 | 0 | fn write_str(&mut self, s: &str) -> std::fmt::Result { |
46 | 0 | match (self.writer)(s.as_bytes()) { |
47 | 0 | Ok(()) => Ok(()), |
48 | 0 | Err(e) => { |
49 | 0 | self.error = Err(e); |
50 | 0 | Err(std::fmt::Error) |
51 | | } |
52 | | } |
53 | 0 | } |
54 | | } |