formatting_nostd/
borrowed_fd_writer.rs

1use rustix::fd::BorrowedFd;
2
3/// A `core::fmt::Writer` that writes to a file descriptor via direct syscalls.
4///
5/// Its `core::fmt::Write` implementation retries if interrupted by a signal,
6/// and returns errors if the file is closed or the write returns other errors
7/// (including `EWOULDBLOCK`). In such cases, partial writes can occur.
8///
9/// To format a message with Rust's formatting:
10/// ```
11/// # // Can't create pipes under miri.
12/// # #[cfg(not(miri))]
13/// # {
14/// # use formatting_nostd::BorrowedFdWriter;
15/// use rustix::fd::AsFd;
16/// use core::fmt::Write;
17/// let (_reader_fd, writer_fd) = rustix::pipe::pipe().unwrap();
18/// let mut writer = BorrowedFdWriter::new(writer_fd.as_fd());
19/// let x = 42;
20/// write!(&mut writer, "{x}").unwrap();
21/// # }
22/// ```
23pub struct BorrowedFdWriter<'fd> {
24    fd: BorrowedFd<'fd>,
25}
26
27impl<'fd> BorrowedFdWriter<'fd> {
28    pub fn new(fd: BorrowedFd<'fd>) -> Self {
29        Self { fd }
30    }
31}
32
33impl core::fmt::Write for BorrowedFdWriter<'_> {
34    fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> {
35        let mut bytes_slice = s.as_bytes();
36        while !bytes_slice.is_empty() {
37            let Ok(written) = rustix::io::retry_on_intr(|| rustix::io::write(self.fd, bytes_slice))
38            else {
39                return Err(core::fmt::Error);
40            };
41            if written == 0 {
42                // Not making forward progress; e.g. file may be closed.
43                return Err(core::fmt::Error);
44            }
45            bytes_slice = &bytes_slice[written..];
46        }
47        Ok(())
48    }
49}
50
51// We can't test without going through FFI, which miri doesn't support.
52#[cfg(all(test, not(miri)))]
53mod test {
54    use core::fmt::Write;
55
56    use rustix::fd::AsFd;
57
58    use super::*;
59
60    #[test]
61    fn test_write() {
62        let (reader, writer) = rustix::pipe::pipe().unwrap();
63
64        BorrowedFdWriter::new(writer.as_fd())
65            .write_str("123")
66            .unwrap();
67
68        let mut buf = [0xff; 4];
69        assert_eq!(rustix::io::read(reader.as_fd(), &mut buf), Ok(3));
70        assert_eq!(buf, [b'1', b'2', b'3', 0xff]);
71    }
72}