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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use core::cmp::min;
use core::fmt::{self, Write};
#[cfg(windows)]
use {
    std::ptr::null_mut,
    windows_sys::Win32::Foundation::{GetLastError, SetLastError},
    windows_sys::Win32::Storage::FileSystem::WriteFile,
    windows_sys::Win32::System::Console::GetStdHandle,
    windows_sys::Win32::System::Console::STD_ERROR_HANDLE,
};

struct Writer {
    pos: usize,

    // `PIPE_BUF` is the biggest buffer we can write atomically.
    #[cfg(unix)]
    buf: [u8; rustix::io::PIPE_BUF],

    // No specific size is documented, so just pick a number.
    #[cfg(windows)]
    buf: [u8; 4096],

    #[cfg(unix)]
    saved_errno: errno::Errno,

    #[cfg(windows)]
    saved_error: u32,
}

impl Writer {
    fn new() -> Self {
        Self {
            pos: 0,

            #[cfg(unix)]
            buf: [0_u8; rustix::io::PIPE_BUF],

            #[cfg(windows)]
            buf: [0_u8; 4096],

            #[cfg(unix)]
            saved_errno: errno::errno(),

            #[cfg(windows)]
            saved_error: unsafe { GetLastError() },
        }
    }

    fn flush(&mut self) -> fmt::Result {
        let mut s = &self.buf[..self.pos];

        // Safety: Users using `dbg`/`eprintln`/`eprint` APIs should be aware
        // that these assume that the stderr file descriptor is open and valid
        // to write to.
        #[cfg(unix)]
        let stderr = unsafe { rustix::io::stderr() };

        #[cfg(windows)]
        let stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) };

        while !s.is_empty() {
            #[cfg(unix)]
            match rustix::io::write(stderr, s) {
                Ok(n) => s = &s[n..],
                Err(rustix::io::Error::INTR) => (),
                Err(_) => return Err(fmt::Error),
            }

            #[cfg(windows)]
            unsafe {
                let mut n = 0;
                if WriteFile(
                    stderr,
                    s.as_ptr().cast(),
                    min(s.len(), u32::MAX as usize) as u32,
                    &mut n,
                    null_mut(),
                ) == 0
                {
                    return Err(fmt::Error);
                }
                s = &s[n as usize..];
            }
        }

        self.pos = 0;
        Ok(())
    }
}

impl Drop for Writer {
    fn drop(&mut self) {
        #[cfg(unix)]
        errno::set_errno(self.saved_errno);

        #[cfg(windows)]
        unsafe {
            SetLastError(self.saved_error);
        }
    }
}

impl fmt::Write for Writer {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let mut bytes = s.as_bytes();
        while !bytes.is_empty() {
            let mut sink = &mut self.buf[self.pos..];
            if sink.is_empty() {
                self.flush()?;
                sink = &mut self.buf;
            }

            let len = min(sink.len(), bytes.len());
            let (now, later) = bytes.split_at(len);
            sink[..len].copy_from_slice(now);

            self.pos += len;
            bytes = later;
        }
        Ok(())
    }
}

#[doc(hidden)]
pub fn _eprint(args: fmt::Arguments<'_>) {
    let mut writer = Writer::new();
    writer.write_fmt(args).unwrap();
    writer.flush().unwrap();
}

#[doc(hidden)]
pub fn _eprintln(args: fmt::Arguments<'_>) {
    let mut writer = Writer::new();
    writer.write_fmt(args).unwrap();
    writer.write_fmt(format_args!("\n")).unwrap();
    writer.flush().unwrap();
}

#[doc(hidden)]
pub struct _Dbg(Writer);

#[doc(hidden)]
pub fn _dbg_start() -> _Dbg {
    _Dbg(Writer::new())
}

#[doc(hidden)]
pub fn _dbg_write(dbg: &mut _Dbg, file: &str, line: u32, name: &str, args: fmt::Arguments<'_>) {
    writeln!(&mut dbg.0, "[{}:{}] {} = {}", file, line, name, args).unwrap();
}

#[doc(hidden)]
pub fn _dbg_finish(mut dbg: _Dbg) {
    dbg.0.flush().unwrap();
}

/// Prints to the standard error.
///
/// Similar to [`std::eprint`], except it:
///  - Writes atomically, up to the greatest length supported on the platform.
///  - Doesn't use locks (in userspace).
///  - Preserve libc's `errno` and Windows' last-error code value.
///
/// This allows it to be used to debug allocators, multi-threaded code,
/// synchronization routines, startup code, and more.
#[macro_export]
macro_rules! eprint {
    ($($arg:tt)*) => {
        $crate::_eprint(core::format_args!($($arg)*))
    };
}

/// Prints to the standard error, with a newline.
///
/// Similar to [`std::eprintln`], except it:
///  - Writes atomically, up to the greatest length supported on the platform.
///  - Doesn't use locks (in userspace).
///  - Preserve libc's `errno` and Windows' last-error code value.
///
/// This allows it to be used to debug allocators, multi-threaded code,
/// synchronization routines, startup code, and more.
#[macro_export]
macro_rules! eprintln {
    () => {
        $crate::eprint!("\n")
    };
    ($($arg:tt)*) => {
        // TODO: Use `format_args_nl` when it's stabilized.
        $crate::_eprintln(core::format_args!($($arg)*))
    };
}

/// Prints and returns the value of a given expression for quick and dirty debugging.
///
/// Similar to [`std::dbg`], except it:
///  - Writes atomically, up to the greatest length supported on the platform.
///  - Doesn't use locks (in userspace).
///  - Preserve libc's `errno` and Windows' last-error code value.
///
/// This allows it to be used to debug allocators, multi-threaded code,
/// synchronization routines, startup code, and more.
#[macro_export]
macro_rules! dbg {
    () => {
        $crate::eprintln!("[{}:{}]", core::file!(), core::line!())
    };
    ($val:expr $(,)?) => {
        // Use the same `match` trick that `std` does.
        match $val {
            tmp => {
                $crate::eprintln!("[{}:{}] {} = {:#?}",
                    core::file!(), core::line!(), core::stringify!($val), &tmp);
                tmp
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        let mut dbg = $crate::_dbg_start();

        // Use the same `match` trick that `std` does.
        ($(match $val {
            tmp => {
                $crate::_dbg_write(
                    &mut dbg,
                    core::file!(),
                    core::line!(),
                    core::stringify!($val),
                    core::format_args!("{:#?}", &tmp),
                );
                tmp
            }
        }),+);

        $crate::_dbg_finish(dbg);
    };
}