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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//! This crate allows printing broken UTF-8 bytes to an output stream as
//! losslessly as possible.
//!
//! Usually, paths are printed by calling [`Path::display`] or
//! [`Path::to_string_lossy`] beforehand. However, both of these methods are
//! always lossy; they misrepresent some valid paths in output. The same is
//! true when using [`String::from_utf8_lossy`] to print any other UTF-8-like
//! byte sequence.
//!
//! Instead, this crate only performs a lossy conversion when the output device
//! is known to require unicode, to make output as accurate as possible. When
//! necessary, any character sequence that cannot be represented will be
//! replaced with [`REPLACEMENT_CHARACTER`]. That convention is shared with the
//! standard library, which uses the same character for its lossy conversion
//! functions.
//!
//! # Features
//!
//! These features are optional and can be enabled or disabled in a
//! "Cargo.toml" file. Nightly features are unstable, since they rely on
//! unstable Rust features.
//!
//! ### Default Features
//!
//! - **os_str** -
//!   Provides implementations of [`ToBytes`] for [`OsStr`] and other similar
//!   structs, such as [`Path`]. As a result, they can be output using
//!   functions in this crate.
//!
//! ### Nightly Features
//!
//! - **const_generics** -
//!   Provides an implementation of [`ToBytes`] for [`[u8; N]`][array]. As a
//!   result, it can be output using functions in this crate.
//!
//! - **specialization** -
//!   Provides [`write_bytes`].
//!
//! # Examples
//!
//! ```
//! use std::env;
//! # use std::io::Result as IoResult;
//!
//! use print_bytes::println_bytes;
//!
//! # fn main() -> IoResult<()> {
//! # #[cfg(feature = "os_str")]
//! # {
//! print!("exe: ");
//! println_bytes(&env::current_exe()?);
//! println!();
//!
//! println!("args:");
//! for arg in env::args_os().skip(1) {
//!     println_bytes(&arg);
//! }
//! # }
//! #     Ok(())
//! # }
//! ```
//!
//! [array]: https://doc.rust-lang.org/std/primitive.array.html
//! [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
//! [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html
//! [`Path::display`]: https://doc.rust-lang.org/std/path/struct.Path.html#method.display
//! [`Path::to_string_lossy`]: https://doc.rust-lang.org/std/path/struct.Path.html#method.to_string_lossy
//! [`REPLACEMENT_CHARACTER`]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html
//! [`String::from_utf8_lossy`]: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_lossy
//! [`ToBytes`]: trait.ToBytes.html
//! [`write_bytes`]: fn.write_bytes.html

#![cfg_attr(
    any(all(doc, not(doctest)), feature = "const_generics"),
    allow(incomplete_features)
)]
#![doc(html_root_url = "https://docs.rs/print_bytes/*")]
#![cfg_attr(
    any(all(doc, not(doctest)), feature = "const_generics"),
    feature(const_generics)
)]
#![cfg_attr(feature = "specialization", feature(specialization))]
#![warn(unused_results)]

use std::io;
use std::io::Result as IoResult;
use std::io::Stderr;
use std::io::StderrLock;
use std::io::Stdout;
use std::io::StdoutLock;
use std::io::Write;

mod bytes;
pub use bytes::Bytes;
pub use bytes::ToBytes;

#[cfg(unix)]
#[path = "unix.rs"]
mod imp;
#[cfg(windows)]
#[path = "windows.rs"]
mod imp;

trait WriteBytes: Write {
    fn is_console(&self) -> bool;

    #[inline]
    fn write_bytes<'a, TValue>(&mut self, value: &'a TValue) -> IoResult<()>
    where
        TValue: ?Sized + ToBytes<'a>,
    {
        imp::write(self, &value.to_bytes().0)
    }
}

#[cfg(feature = "specialization")]
impl<T> WriteBytes for T
where
    T: ?Sized + Write,
{
    default fn is_console(&self) -> bool {
        false
    }
}

macro_rules! r#impl {
    ( $($type:ty),* $(,)? ) => {
        $(
            impl WriteBytes for $type {
                fn is_console(&self) -> bool {
                    imp::is_console(self)
                }
            }
        )*
    };
}
r#impl!(Stderr, StderrLock<'_>, Stdout, StdoutLock<'_>);

/// Writes a value to a "writer".
///
/// This function is similar to [`write!`], but it does not take a format
/// parameter.
///
/// For more information, see [the module-level documentation][module].
///
/// *This function is only available with the `"specialization"` feature.*
///
/// # Errors
///
/// If writing fails, an error is returned.
///
/// [module]: index.html
/// [`write!`]: https://doc.rust-lang.org/std/macro.write.html
#[cfg(any(doc, feature = "specialization"))]
#[inline]
pub fn write_bytes<'a, TValue, TWriter>(
    writer: &mut TWriter,
    value: &'a TValue,
) -> IoResult<()>
where
    TValue: ?Sized + ToBytes<'a>,
    TWriter: ?Sized + Write,
{
    writer.write_bytes(value)
}

macro_rules! r#impl {
    (
        $writer:expr ,
        $(#[ $print_fn_attr:meta ])* $print_fn:ident ,
        $(#[ $println_fn_attr:meta ])* $println_fn:ident ,
        $label:literal $(,)?
    ) => {
        $(#[$print_fn_attr])*
        #[inline]
        pub fn $print_fn<'a, TValue>(value: &'a TValue)
        where
            TValue: ?Sized + ToBytes<'a>,
        {
            if let Err(error) = $writer.write_bytes(value) {
                panic!("failed writing to {}: {}", $label, error);
            }
        }

        $(#[$println_fn_attr])*
        #[inline]
        pub fn $println_fn<'a, TValue>(value: &'a TValue)
        where
            TValue: ?Sized + ToBytes<'a>,
        {
            let _ = $writer.lock();
            $print_fn(value);
            $print_fn(b"\n".as_ref());
        }
    };
}
r#impl!(
    io::stdout(),
    /// Prints a value to the standard output stream.
    ///
    /// This function is similar to [`print!`], but it does not take a format
    /// parameter.
    ///
    /// For more information, see [the module-level documentation][module].
    ///
    /// # Panics
    ///
    /// Panics if writing to the stream fails.
    ///
    /// [module]: index.html
    /// [`print!`]: https://doc.rust-lang.org/std/macro.print.html
    print_bytes,
    /// Prints a value to the standard output stream, followed by a newline.
    ///
    /// This function is similar to [`println!`], but it does not take a format
    /// parameter. A line feed (`\n`) is still used for the newline, with no
    /// additional carriage return (`\r`) printed.
    ///
    /// For more information, see [the module-level documentation][module].
    ///
    /// # Panics
    ///
    /// Panics if writing to the stream fails.
    ///
    /// [module]: index.html
    /// [`println!`]: https://doc.rust-lang.org/std/macro.println.html
    println_bytes,
    "stdout",
);
r#impl!(
    io::stderr(),
    /// Prints a value to the standard error stream.
    ///
    /// This function is similar to [`eprint!`], but it does not take a format
    /// parameter.
    ///
    /// For more information, see [the module-level documentation][module].
    ///
    /// # Panics
    ///
    /// Panics if writing to the stream fails.
    ///
    /// [`eprint!`]: https://doc.rust-lang.org/std/macro.eprint.html
    /// [module]: index.html
    eprint_bytes,
    /// Prints a value to the standard error stream, followed by a newline.
    ///
    /// This function is similar to [`eprintln!`], but it does not take a
    /// format parameter. A line feed (`\n`) is still used for the newline,
    /// with no additional carriage return (`\r`) printed.
    ///
    /// For more information, see [the module-level documentation][module].
    ///
    /// # Panics
    ///
    /// Panics if writing to the stream fails.
    ///
    /// [`eprintln!`]: https://doc.rust-lang.org/std/macro.eprintln.html
    /// [module]: index.html
    eprintln_bytes,
    "stderr",
);

#[cfg(test)]
mod tests {
    use std::io::Result as IoResult;
    use std::io::Write;

    use super::imp;
    use super::WriteBytes;

    const INVALID_STRING: &[u8] = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";

    struct Writer {
        buffer: Vec<u8>,
        is_console: bool,
    }

    impl Writer {
        fn new(is_console: bool) -> Self {
            Self {
                buffer: Vec::new(),
                is_console,
            }
        }
    }

    impl Write for Writer {
        fn flush(&mut self) -> IoResult<()> {
            self.buffer.flush()
        }

        fn write(&mut self, bytes: &[u8]) -> IoResult<usize> {
            self.buffer.write(bytes)
        }
    }

    impl WriteBytes for Writer {
        fn is_console(&self) -> bool {
            self.is_console
        }
    }

    fn assert_invalid_string(writer: &Writer, lossy: bool) {
        let bytes = writer.buffer.as_slice();
        assert_ne!(lossy, INVALID_STRING == bytes);
        if lossy {
            assert_eq!(
                String::from_utf8_lossy(INVALID_STRING).as_bytes(),
                bytes,
            );
        }
    }

    fn test<TWriteFn>(mut write_fn: TWriteFn) -> IoResult<()>
    where
        TWriteFn: FnMut(&mut Writer, &[u8]) -> IoResult<()>,
    {
        let mut writer = Writer::new(true);
        write_fn(&mut writer, INVALID_STRING)?;
        assert_invalid_string(&writer, cfg!(windows));

        writer = Writer::new(false);
        write_fn(&mut writer, INVALID_STRING)?;
        assert_invalid_string(&writer, false);

        Ok(())
    }

    #[test]
    fn test_write() -> IoResult<()> {
        test(imp::write)
    }

    #[cfg(feature = "specialization")]
    #[test]
    fn test_write_bytes() -> IoResult<()> {
        test(|writer, bytes| super::write_bytes(writer, bytes))
    }
}