print_bytes-1.2.0/.cargo_vcs_info.json0000644000000001360000000000100133760ustar { "git": { "sha1": "fdaa3d9202ebe41c5c2f83240de5228262597fa2" }, "path_in_vcs": "" }print_bytes-1.2.0/COPYRIGHT000064400000000000000000000004161046102023000134620ustar 00000000000000Copyright (c) 2020 dylni (https://github.com/dylni) Licensed under the Apache License, Version 2.0 or the MIT license , at your option. All files in this project may not be copied, modified, or distributed except according to those terms. print_bytes-1.2.0/Cargo.lock0000644000000051650000000000100113600ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "memchr" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "os_str_bytes" version = "6.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ceedf44fb00f2d1984b0bc98102627ce622e083e49a5bacdb3e514fa4238e267" dependencies = [ "memchr", ] [[package]] name = "print_bytes" version = "1.2.0" dependencies = [ "os_str_bytes", "windows-sys", ] [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" [[package]] name = "windows_x86_64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" print_bytes-1.2.0/Cargo.toml0000644000000025200000000000100113730ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.63.0" name = "print_bytes" version = "1.2.0" authors = ["dylni"] exclude = [ ".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests", ] description = """ Print bytes as losslessly as possible """ readme = "README.md" keywords = [ "bytes", "osstr", "path", "print", "windows", ] categories = [ "command-line-interface", "os", "wasm", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dylni/print_bytes" [package.metadata.docs.rs] all-features = true rustc-args = [ "--cfg", "print_bytes_docs_rs", ] rustdoc-args = [ "--cfg", "print_bytes_docs_rs", ] [dev-dependencies.os_str_bytes] version = "6.3" [features] specialization = [] [target."cfg(windows)".dependencies.windows-sys] version = "0.48" features = [ "Win32_Foundation", "Win32_System_Console", ] print_bytes-1.2.0/Cargo.toml.orig000064400000000000000000000014361046102023000150610ustar 00000000000000[package] name = "print_bytes" version = "1.2.0" authors = ["dylni"] edition = "2021" rust-version = "1.63.0" description = """ Print bytes as losslessly as possible """ readme = "README.md" repository = "https://github.com/dylni/print_bytes" license = "MIT OR Apache-2.0" keywords = ["bytes", "osstr", "path", "print", "windows"] categories = ["command-line-interface", "os", "wasm"] exclude = [".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests"] [package.metadata.docs.rs] all-features = true rustc-args = ["--cfg", "print_bytes_docs_rs"] rustdoc-args = ["--cfg", "print_bytes_docs_rs"] [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.48", features = ["Win32_Foundation", "Win32_System_Console"] } [dev-dependencies] os_str_bytes = "6.3" [features] specialization = [] print_bytes-1.2.0/LICENSE-APACHE000064400000000000000000000236751046102023000141270ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS print_bytes-1.2.0/LICENSE-MIT000064400000000000000000000021011046102023000136140ustar 00000000000000MIT License Copyright (c) 2020 dylni (https://github.com/dylni) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. print_bytes-1.2.0/README.md000064400000000000000000000045401046102023000134500ustar 00000000000000# print\_bytes 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. [![GitHub Build Status](https://github.com/dylni/print_bytes/workflows/build/badge.svg?branch=master)](https://github.com/dylni/print_bytes/actions?query=branch%3Amaster) ## Usage Add the following lines to your "Cargo.toml" file: ```toml [dependencies] print_bytes = "1.2" ``` See the [documentation] for available functionality and examples. ## Rust version support The minimum supported Rust toolchain version is currently Rust 1.63.0. Minor version updates may increase this version requirement. However, the previous two Rust releases will always be supported. If the minimum Rust version must not be increased, use a tilde requirement to prevent updating this crate's minor version: ```toml [dependencies] print_bytes = "~1.2" ``` ## License Licensing terms are specified in [COPYRIGHT]. Unless you explicitly state otherwise, any contribution submitted for inclusion in this crate, as defined in [LICENSE-APACHE], shall be licensed according to [COPYRIGHT], without any additional terms or conditions. [COPYRIGHT]: https://github.com/dylni/print_bytes/blob/master/COPYRIGHT [documentation]: https://docs.rs/print_bytes [LICENSE-APACHE]: https://github.com/dylni/print_bytes/blob/master/LICENSE-APACHE [`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 print_bytes-1.2.0/src/bytes.rs000064400000000000000000000131231046102023000144510ustar 00000000000000use std::borrow::Cow; use std::ffi::CStr; use std::ffi::CString; use std::ops::Deref; #[derive(Debug)] pub(super) enum ByteStrInner<'a> { Bytes(&'a [u8]), #[cfg(windows)] Str(Cow<'a, str>), } /// A value returned by [`ToBytes::to_bytes`]. /// /// This struct is usually initialized by calling the above method for /// [`[u8]`][slice]. #[derive(Debug)] pub struct ByteStr<'a>(pub(super) ByteStrInner<'a>); #[cfg(any(doc, windows))] #[cfg_attr(print_bytes_docs_rs, doc(cfg(windows)))] impl<'a> ByteStr<'a> { /// Wraps a byte string lossily. /// /// This method can be used to implement [`ToBytes::to_bytes`] when /// [`ToBytes::to_wide`] is the better way to represent the string. #[inline] #[must_use] pub fn from_utf8_lossy(string: &'a [u8]) -> Self { Self(ByteStrInner::Str(String::from_utf8_lossy(string))) } } /// A value returned by [`ToBytes::to_wide`]. #[cfg(any(doc, windows))] #[cfg_attr(print_bytes_docs_rs, doc(cfg(windows)))] #[derive(Debug)] pub struct WideStr(pub(super) Vec); #[cfg(any(doc, windows))] impl WideStr { /// Wraps a wide character string. /// /// This method can be used to implement [`ToBytes::to_wide`]. #[inline] #[must_use] pub fn new(string: Vec) -> Self { Self(string) } } /// Represents a type similarly to [`Display`]. /// /// Implement this trait to allow printing a type that cannot guarantee UTF-8 /// output. It is used to bound values accepted by functions in this crate. /// /// # Examples /// /// ``` /// use print_bytes::println_lossy; /// use print_bytes::ByteStr; /// use print_bytes::ToBytes; /// #[cfg(windows)] /// use print_bytes::WideStr; /// /// struct ByteSlice<'a>(&'a [u8]); /// /// impl ToBytes for ByteSlice<'_> { /// fn to_bytes(&self) -> ByteStr<'_> { /// self.0.to_bytes() /// } /// /// #[cfg(windows)] /// fn to_wide(&self) -> Option { /// self.0.to_wide() /// } /// } /// /// println_lossy(&ByteSlice(b"Hello, world!")); /// ``` /// /// [`Display`]: ::std::fmt::Display /// [`to_bytes`]: Self::to_bytes /// [`ToString`]: ::std::string::ToString pub trait ToBytes { /// Returns a byte string that will be used to represent the instance. #[must_use] fn to_bytes(&self) -> ByteStr<'_>; /// Returns a wide character string that will be used to represent the /// instance. /// /// The Windows API frequently uses wide character strings. This method /// allows them to be printed losslessly in some cases, even when they /// cannot be converted to UTF-8. /// /// Returning [`None`] causes [`to_bytes`] to be used instead. /// /// [`to_bytes`]: Self::to_bytes #[cfg(any(doc, windows))] #[cfg_attr(print_bytes_docs_rs, doc(cfg(windows)))] #[must_use] fn to_wide(&self) -> Option; } impl ToBytes for [u8] { #[inline] fn to_bytes(&self) -> ByteStr<'_> { ByteStr(ByteStrInner::Bytes(self)) } #[cfg(any(doc, windows))] #[inline] fn to_wide(&self) -> Option { None } } macro_rules! defer_methods { ( $convert_method:ident ) => { #[inline] fn to_bytes(&self) -> ByteStr<'_> { ToBytes::to_bytes(self.$convert_method()) } #[cfg(any(doc, windows))] #[inline] fn to_wide(&self) -> Option { self.$convert_method().to_wide() } }; } impl ToBytes for [u8; N] { defer_methods!(as_slice); } impl ToBytes for Cow<'_, T> where T: ?Sized + ToBytes + ToOwned, T::Owned: ToBytes, { defer_methods!(deref); } macro_rules! defer_impl { ( $type:ty , $convert_method:ident ) => { impl ToBytes for $type { defer_methods!($convert_method); } }; } defer_impl!(CStr, to_bytes); defer_impl!(CString, as_c_str); defer_impl!(Vec, as_slice); #[cfg(any( all(target_vendor = "fortanix", target_env = "sgx"), target_os = "hermit", target_os = "solid_asp3", target_os = "wasi", target_os = "xous", unix, windows, ))] mod os_str { use std::ffi::OsStr; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; use super::ByteStr; use super::ToBytes; #[cfg(any(doc, windows))] use super::WideStr; impl ToBytes for OsStr { #[inline] fn to_bytes(&self) -> ByteStr<'_> { #[cfg(windows)] { use super::ByteStrInner; ByteStr(ByteStrInner::Str(self.to_string_lossy())) } #[cfg(not(windows))] { #[cfg(all( target_vendor = "fortanix", target_env = "sgx", ))] use std::os::fortanix_sgx as os; #[cfg(target_os = "hermit")] use std::os::hermit as os; #[cfg(target_os = "solid_asp3")] use std::os::solid as os; #[cfg(unix)] use std::os::unix as os; #[cfg(target_os = "wasi")] use std::os::wasi as os; #[cfg(target_os = "xous")] use std::os::xous as os; use os::ffi::OsStrExt; self.as_bytes().to_bytes() } } #[cfg(any(doc, windows))] #[inline] fn to_wide(&self) -> Option { #[cfg(windows)] use std::os::windows::ffi::OsStrExt; Some(WideStr(self.encode_wide().collect())) } } defer_impl!(OsString, as_os_str); defer_impl!(Path, as_os_str); defer_impl!(PathBuf, as_path); } print_bytes-1.2.0/src/console.rs000064400000000000000000000055531046102023000147750ustar 00000000000000use std::convert::TryInto; use std::io; use std::os::windows::io::AsHandle; use std::os::windows::io::AsRawHandle; use std::os::windows::io::BorrowedHandle; use std::ptr; use windows_sys::Win32::Foundation::BOOL; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::System::Console::GetConsoleMode; use windows_sys::Win32::System::Console::WriteConsoleW; const TRUE: BOOL = 1; fn check_syscall(result: BOOL) -> io::Result<()> { if result == TRUE { Ok(()) } else { Err(io::Error::last_os_error()) } } fn raw_handle(handle: BorrowedHandle<'_>) -> HANDLE { handle.as_raw_handle() as _ } #[derive(Clone, Copy)] pub struct Console<'a>(BorrowedHandle<'a>); impl<'a> Console<'a> { pub(super) fn from_handle(handle: &'a T) -> Option where T: AsHandle + ?Sized, { let handle = handle.as_handle(); let raw_handle = raw_handle(handle); if matches!(raw_handle, 0 | INVALID_HANDLE_VALUE) { return None; } // The mode is not important, since this call only succeeds for Windows // Console. Other streams usually do not require Unicode writes. let mut mode = 0; check_syscall(unsafe { GetConsoleMode(raw_handle, &mut mode) }) .ok() .map(|()| Self(handle)) } // Writing to the returned instance causes undefined behavior. #[cfg(test)] pub(super) const unsafe fn null() -> Self { // SAFETY: Null pointers can be passed to this method. Self(unsafe { BorrowedHandle::borrow_raw(ptr::null_mut()) }) } fn write_wide(&mut self, string: &[u16]) -> io::Result { let length = string.len().try_into().unwrap_or(u32::MAX); let mut written_length = 0; check_syscall(unsafe { WriteConsoleW( raw_handle(self.0), string.as_ptr().cast(), length, &mut written_length, ptr::null_mut(), ) }) .map(|()| written_length as usize) } pub(super) fn write_wide_all( &mut self, mut string: &[u16], ) -> io::Result<()> { while !string.is_empty() { match self.write_wide(string) { Ok(written_length) => { if written_length == 0 { return Err(io::Error::new( io::ErrorKind::WriteZero, "failed to write whole buffer", )); } string = &string[written_length..]; } Err(error) => { if error.kind() != io::ErrorKind::Interrupted { return Err(error); } } } } Ok(()) } } print_bytes-1.2.0/src/lib.rs000064400000000000000000000201061046102023000140700ustar 00000000000000//! 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. //! //! ### Note: Windows Compatibility //! //! [`OsStr`] and related structs may be printed lossily on Windows. Paths are //! not represented using bytes on that platform, so it may be confusing to //! display them in that manner. Plus, the encoding most often used to account //! for the difference is [not permitted to be written to files][wtf-8 //! audience], so it would not make sense for this crate to use it. //! //! Windows Console can display these paths, so this crate will output them //! losslessly when writing to that terminal. //! //! # 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. //! //! ### Nightly Features //! //! - **specialization** - //! Provides an implementation of [`WriteLossy`] for all types. //! //! # Examples //! //! ``` //! use std::env; //! # use std::io; //! //! use print_bytes::println_lossy; //! //! print!("exe: "); //! println_lossy(&env::current_exe()?); //! println!(); //! //! println!("args:"); //! for arg in env::args_os().skip(1) { //! println_lossy(&arg); //! } //! # //! # Ok::<_, io::Error>(()) //! ``` //! //! [`OsStr`]: ::std::ffi::OsStr //! [`Path::display`]: ::std::path::Path::display //! [`Path::to_string_lossy`]: ::std::path::Path::to_string_lossy //! [`REPLACEMENT_CHARACTER`]: ::std::char::REPLACEMENT_CHARACTER //! [wtf-8 audience]: https://simonsapin.github.io/wtf-8/#intended-audience #![cfg_attr(feature = "specialization", allow(incomplete_features))] // Only require a nightly compiler when building documentation for docs.rs. // This is a private option that should not be used. // https://github.com/rust-lang/docs.rs/issues/147#issuecomment-389544407 #![cfg_attr(print_bytes_docs_rs, feature(doc_cfg))] // Nightly is also currently required for the SGX platform. #![cfg_attr( all(target_vendor = "fortanix", target_env = "sgx"), feature(sgx_platform) )] #![cfg_attr(feature = "specialization", feature(specialization))] #![warn(unused_results)] use std::io; use std::io::Write; mod bytes; pub use bytes::ByteStr; use bytes::ByteStrInner; pub use bytes::ToBytes; #[cfg(any(doc, windows))] pub use bytes::WideStr; #[cfg(windows)] mod console; #[cfg_attr(test, macro_use)] mod writer; pub use writer::WriteLossy; #[cfg(test)] mod tests; /// Writes a value to a "writer". /// /// This function is similar to [`write!`] but does not take a format /// parameter. /// /// For more information, see [the module-level documentation][module]. /// /// # Errors /// /// Returns an error if writing to the writer fails. /// /// # Examples /// /// ``` /// use std::env; /// use std::ffi::OsStr; /// /// use print_bytes::write_lossy; /// /// let string = "foobar"; /// let os_string = OsStr::new(string); /// /// let mut lossy_string = Vec::new(); /// write_lossy(&mut lossy_string, os_string) /// .expect("failed writing to vector"); /// assert_eq!(string.as_bytes(), lossy_string); /// ``` /// /// [module]: self #[inline] pub fn write_lossy(mut writer: W, value: &T) -> io::Result<()> where T: ?Sized + ToBytes, W: Write + WriteLossy, { #[cfg_attr(not(windows), allow(unused_mut))] let mut lossy = false; #[cfg(windows)] if let Some(mut console) = writer.__to_console() { if let Some(string) = value.to_wide() { return console.write_wide_all(&string.0); } lossy = true; } let buffer; let string = value.to_bytes(); let string = match &string.0 { ByteStrInner::Bytes(string) => { if lossy { buffer = String::from_utf8_lossy(string); buffer.as_bytes() } else { string } } #[cfg(windows)] ByteStrInner::Str(string) => string.as_bytes(), }; writer.write_all(string) } macro_rules! expect_print { ( $label:literal , $result:expr ) => { $result .unwrap_or_else(|x| panic!("failed writing to {}: {}", $label, x)) }; } macro_rules! r#impl { ( $writer:expr , $(#[ $print_fn_attr:meta ])* $print_fn:ident , $(#[ $println_fn_attr:meta ])* $println_fn:ident , $label:literal $(,)? ) => { #[inline] $(#[$print_fn_attr])* pub fn $print_fn(value: &T) where T: ?Sized + ToBytes, { expect_print!($label, write_lossy($writer, value)); } #[inline] $(#[$println_fn_attr])* pub fn $println_fn(value: &T) where T: ?Sized + ToBytes, { let mut writer = $writer.lock(); expect_print!($label, write_lossy(&mut writer, value)); expect_print!($label, writer.write_all(b"\n")); } }; } r#impl!( io::stderr(), /// Prints a value to the standard error stream. /// /// This function is similar to [`eprint!`] but does not take a format /// parameter. /// /// For more information, see [the module-level documentation][module]. /// /// # Panics /// /// Panics if writing to the stream fails. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use print_bytes::eprint_lossy; /// /// eprint_lossy(&env::current_exe()?); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [module]: self eprint_lossy, /// Prints a value to the standard error stream, followed by a newline. /// /// This function is similar to [`eprintln!`] but does not take a format /// parameter. /// /// For more information, see [the module-level documentation][module]. /// /// # Panics /// /// Panics if writing to the stream fails. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use print_bytes::eprintln_lossy; /// /// eprintln_lossy(&env::current_exe()?); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [module]: self eprintln_lossy, "stderr", ); r#impl!( io::stdout(), /// Prints a value to the standard output stream. /// /// This function is similar to [`print!`] but does not take a format /// parameter. /// /// For more information, see [the module-level documentation][module]. /// /// # Panics /// /// Panics if writing to the stream fails. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use print_bytes::print_lossy; /// /// print_lossy(&env::current_exe()?); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [module]: self print_lossy, /// Prints a value to the standard output stream, followed by a newline. /// /// This function is similar to [`println!`] but does not take a format /// parameter. /// /// For more information, see [the module-level documentation][module]. /// /// # Panics /// /// Panics if writing to the stream fails. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use print_bytes::println_lossy; /// /// println_lossy(&env::current_exe()?); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [module]: self println_lossy, "stdout", ); print_bytes-1.2.0/src/writer.rs000064400000000000000000000065041046102023000146440ustar 00000000000000use std::io::BufWriter; use std::io::LineWriter; #[cfg(any(doc, not(feature = "specialization")))] use std::io::Stderr; #[cfg(any(doc, not(feature = "specialization")))] use std::io::StderrLock; #[cfg(any(doc, not(feature = "specialization")))] use std::io::Stdout; #[cfg(any(doc, not(feature = "specialization")))] use std::io::StdoutLock; use std::io::Write; #[cfg(all(feature = "specialization", windows))] use std::os::windows::io::AsHandle; #[cfg(windows)] use super::console::Console; pub(super) trait ToConsole { #[cfg(windows)] fn to_console(&self) -> Option>; } #[cfg(feature = "specialization")] impl ToConsole for T where T: ?Sized, { #[cfg(windows)] default fn to_console(&self) -> Option> { None } } #[cfg(all(feature = "specialization", windows))] impl ToConsole for T where T: AsHandle + ?Sized + Write, { fn to_console(&self) -> Option> { Console::from_handle(self) } } /// A bound for [`write_lossy`] that allows it to be used for some types /// without specialization. /// /// When the "specialization" feature is enabled, this trait is implemented for /// all types. /// /// [`write_lossy`]: super::write_lossy pub trait WriteLossy { #[cfg(windows)] #[doc(hidden)] fn __to_console(&self) -> Option>; } #[cfg(feature = "specialization")] #[cfg_attr(print_bytes_docs_rs, doc(cfg(feature = "specialization")))] impl WriteLossy for T where T: ?Sized, { #[cfg(windows)] default fn __to_console(&self) -> Option> { self.to_console() } } macro_rules! r#impl { ( $generic:ident , $type:ty ) => { impl<$generic> WriteLossy for $type where $generic: ?Sized + WriteLossy, { #[cfg(windows)] fn __to_console(&self) -> Option> { (**self).__to_console() } } }; } r#impl!(T, &mut T); r#impl!(T, Box); macro_rules! r#impl { ( $generic:ident , $type:ty ) => { impl<$generic> WriteLossy for $type where $generic: Write + WriteLossy, { #[cfg(windows)] fn __to_console(&self) -> Option> { self.get_ref().__to_console() } } }; } r#impl!(T, BufWriter); r#impl!(T, LineWriter); macro_rules! impl_to_console { ( $(#[ $attr:meta ])* $type:ty , $to_console_fn:expr , ) => { #[cfg(any(doc, not(feature = "specialization")))] impl $crate::WriteLossy for $type { #[cfg(windows)] fn __to_console(&self) -> Option> { $crate::writer::ToConsole::to_console(self) } } $(#[$attr])* impl $crate::writer::ToConsole for $type { #[cfg(windows)] fn to_console<'a>(&'a self) -> Option> { let to_console_fn: fn(&'a Self) -> _ = $to_console_fn; to_console_fn(self) } } }; } macro_rules! r#impl { ( $($type:ty),+ ) => { $(impl_to_console! { #[cfg(not(feature = "specialization"))] $type, Console::from_handle, })+ }; } r#impl!(Stderr, StderrLock<'_>, Stdout, StdoutLock<'_>); impl_to_console! { #[cfg(not(feature = "specialization"))] Vec, |_| None, }