Skip to main content

use_stderr/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use std::io::{self, Write};
5
6/// Commonly used stderr primitives.
7pub mod prelude {
8    pub use crate::{
9        StderrDestination, write_error, write_error_line, write_stderr, write_stderr_line,
10    };
11}
12
13/// Marker type for the process standard error stream.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
15pub struct StderrDestination;
16
17impl StderrDestination {
18    /// Creates a stderr destination marker.
19    #[must_use]
20    pub const fn new() -> Self {
21        Self
22    }
23}
24
25/// Writes text to process stderr.
26///
27/// # Errors
28///
29/// Returns any I/O error reported while writing to stderr.
30pub fn write_stderr(text: &str) -> io::Result<()> {
31    let stderr = io::stderr();
32    write_error(stderr.lock(), text)
33}
34
35/// Writes text plus one newline to process stderr.
36///
37/// # Errors
38///
39/// Returns any I/O error reported while writing to stderr.
40pub fn write_stderr_line(text: &str) -> io::Result<()> {
41    let stderr = io::stderr();
42    write_error_line(stderr.lock(), text)
43}
44
45/// Writes error text to a generic writer.
46///
47/// # Errors
48///
49/// Returns any I/O error reported by `writer`.
50pub fn write_error(mut writer: impl Write, text: &str) -> io::Result<()> {
51    writer.write_all(text.as_bytes())
52}
53
54/// Writes error text plus one newline to a generic writer.
55///
56/// # Errors
57///
58/// Returns any I/O error reported by `writer`.
59pub fn write_error_line(mut writer: impl Write, text: &str) -> io::Result<()> {
60    writer.write_all(text.as_bytes())?;
61    writer.write_all(b"\n")
62}
63
64#[cfg(test)]
65mod tests {
66    use super::{StderrDestination, write_error, write_error_line};
67
68    #[test]
69    fn marker_is_copyable() {
70        let destination = StderrDestination::new();
71        let copied = destination;
72
73        assert_eq!(destination, copied);
74    }
75
76    #[test]
77    fn writes_to_generic_writer() -> Result<(), std::io::Error> {
78        let mut buffer = Vec::new();
79        write_error(&mut buffer, "warning")?;
80        write_error_line(&mut buffer, "!")?;
81
82        assert_eq!(buffer, b"warning!\n");
83        Ok(())
84    }
85}