├── rustfmt.toml ├── .gitignore ├── .github ├── dependabot.yml └── workflows │ └── build.yml ├── COPYRIGHT ├── src ├── bin │ └── writer.rs ├── tests.rs ├── console.rs ├── writer.rs ├── bytes.rs └── lib.rs ├── Cargo.toml ├── LICENSE-MIT ├── tests ├── bin_writer.rs └── specialization.rs ├── README.md └── LICENSE-APACHE /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 79 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 dylni (https://github.com/dylni) 2 | 3 | Licensed under the Apache License, Version 2.0 or the MIT 4 | license , at your option. All files in this project may not be 5 | copied, modified, or distributed except according to those terms. 6 | -------------------------------------------------------------------------------- /src/bin/writer.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "os_str_bytes")] 2 | use std::env; 3 | 4 | #[cfg(feature = "os_str_bytes")] 5 | use print_bytes::print_lossy; 6 | 7 | fn main() { 8 | #[cfg(feature = "os_str_bytes")] 9 | print_lossy(&env::args_os().nth(1).expect("missing argument")); 10 | } 11 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "print_bytes" 3 | version = "2.1.0" 4 | authors = ["dylni"] 5 | edition = "2021" 6 | rust-version = "1.77.0" 7 | description = """ 8 | Print bytes as losslessly as possible 9 | """ 10 | readme = "README.md" 11 | repository = "https://github.com/dylni/print_bytes" 12 | license = "MIT OR Apache-2.0" 13 | keywords = ["bytes", "osstr", "path", "print", "windows"] 14 | categories = ["command-line-interface", "os"] 15 | exclude = [".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests"] 16 | 17 | [package.metadata.docs.rs] 18 | all-features = true 19 | rustc-args = ["--cfg", "print_bytes_docs_rs"] 20 | rustdoc-args = ["--cfg", "print_bytes_docs_rs"] 21 | 22 | [target.'cfg(windows)'.dependencies] 23 | windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] } 24 | 25 | [target.'cfg(not(windows))'.dependencies] 26 | os_str_bytes = { version = "7.0", default-features = false, optional = true } 27 | 28 | [features] 29 | specialization = [] 30 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 dylni (https://github.com/dylni) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /tests/bin_writer.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "os_str_bytes")] 2 | 3 | use std::char::REPLACEMENT_CHARACTER; 4 | use std::io; 5 | use std::process::Command; 6 | use std::process::Stdio; 7 | 8 | #[test] 9 | fn test_wtf8() -> io::Result<()> { 10 | let string = { 11 | #[cfg(unix)] 12 | { 13 | use std::ffi::OsStr; 14 | use std::os::unix::ffi::OsStrExt; 15 | 16 | OsStr::from_bytes(b"\x66\x6F\x80\x6F") 17 | } 18 | #[cfg(windows)] 19 | { 20 | use std::ffi::OsString; 21 | use std::os::windows::ffi::OsStringExt; 22 | 23 | &OsString::from_wide(&[0x66, 0x6F, 0xD800, 0x6F]) 24 | } 25 | }; 26 | assert_eq!(None, string.to_str()); 27 | 28 | let output = Command::new(env!("CARGO_BIN_EXE_writer")) 29 | .arg(string) 30 | .stderr(Stdio::inherit()) 31 | .output()?; 32 | 33 | if cfg!(windows) { 34 | assert_eq!( 35 | format!("\x66\x6F{}\x6F", REPLACEMENT_CHARACTER).as_bytes(), 36 | output.stdout, 37 | ); 38 | } else { 39 | assert_eq!(&b"\x66\x6F\x80\x6F"[..], output.stdout); 40 | } 41 | 42 | assert!(output.status.success()); 43 | 44 | Ok(()) 45 | } 46 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | schedule: 9 | - cron: 0 0 * * FRI 10 | 11 | jobs: 12 | build: 13 | runs-on: ${{ matrix.platform }} 14 | steps: 15 | - uses: dylni/build-actions/build@master 16 | with: 17 | nightly-features: 'specialization' 18 | timeout-minutes: 10 19 | strategy: 20 | matrix: 21 | platform: [ubuntu-latest, windows-latest] 22 | build-other: 23 | needs: [build] 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: dylni/build-actions/build-other@master 27 | with: 28 | nightly-features: 'specialization' 29 | target: ${{ matrix.target }} 30 | version: ${{ matrix.version }} 31 | timeout-minutes: 10 32 | strategy: 33 | matrix: 34 | target: [wasm32-unknown-unknown, wasm32-wasip1] 35 | version: [1.78.0, stable, beta, nightly] 36 | test: 37 | needs: [build] 38 | runs-on: ${{ matrix.platform }} 39 | steps: 40 | - uses: dylni/build-actions/test@master 41 | with: 42 | nightly-features: 'specialization' 43 | version: ${{ matrix.version }} 44 | timeout-minutes: 10 45 | strategy: 46 | matrix: 47 | platform: [macos-latest, ubuntu-latest, windows-latest] 48 | version: [1.77.0, stable, beta, nightly] 49 | -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | #![cfg(windows)] 2 | 3 | use std::io; 4 | use std::io::Write; 5 | 6 | use super::console::Console; 7 | 8 | const INVALID_STRING: &[u8] = b"\xF1foo\xF1\x80bar\xF1\x80\x80"; 9 | 10 | struct Writer { 11 | buffer: Vec, 12 | is_console: bool, 13 | } 14 | 15 | impl Writer { 16 | const fn new(is_console: bool) -> Self { 17 | Self { 18 | buffer: Vec::new(), 19 | is_console, 20 | } 21 | } 22 | } 23 | 24 | impl Write for Writer { 25 | fn write(&mut self, buf: &[u8]) -> io::Result { 26 | self.buffer.write(buf) 27 | } 28 | 29 | fn flush(&mut self) -> io::Result<()> { 30 | self.buffer.flush() 31 | } 32 | } 33 | 34 | impl_to_console! { 35 | Writer, 36 | // SAFETY: Since no platform strings are being written, no test should ever 37 | // write to this console. 38 | |x| x.is_console.then(|| unsafe { Console::null() }), 39 | } 40 | 41 | fn assert_invalid_string(writer: &Writer, lossy: bool) { 42 | let lossy_string = String::from_utf8_lossy(INVALID_STRING); 43 | let lossy_string = lossy_string.as_bytes(); 44 | assert_ne!(INVALID_STRING, lossy_string); 45 | 46 | let string = &*writer.buffer; 47 | if lossy { 48 | assert_eq!(lossy_string, string); 49 | } else { 50 | assert_eq!(INVALID_STRING, string); 51 | } 52 | } 53 | 54 | #[test] 55 | fn test_write_lossy() -> io::Result<()> { 56 | let mut writer = Writer::new(false); 57 | super::write_lossy(&mut writer, INVALID_STRING)?; 58 | assert_invalid_string(&writer, false); 59 | 60 | writer = Writer::new(true); 61 | super::write_lossy(&mut writer, INVALID_STRING)?; 62 | assert_invalid_string(&writer, true); 63 | 64 | Ok(()) 65 | } 66 | -------------------------------------------------------------------------------- /tests/specialization.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::ffi::CStr; 3 | #[cfg(feature = "os_str_bytes")] 4 | use std::ffi::OsStr; 5 | use std::io; 6 | #[cfg(feature = "os_str_bytes")] 7 | use std::path::Path; 8 | 9 | use print_bytes::write_lossy; 10 | 11 | const INVALID_STRING: &[u8] = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz"; 12 | 13 | fn test_write(bytes: &[u8]) -> io::Result<()> { 14 | let mut writer = Vec::new(); 15 | write_lossy(&mut writer, bytes)?; 16 | assert_eq!(bytes, writer); 17 | Ok(()) 18 | } 19 | 20 | #[test] 21 | fn test_empty_write() -> io::Result<()> { 22 | test_write(b"") 23 | } 24 | 25 | #[test] 26 | fn test_invalid_write() -> io::Result<()> { 27 | test_write(INVALID_STRING) 28 | } 29 | 30 | #[test] 31 | fn test_multiple_writes() -> io::Result<()> { 32 | let mut writer = Vec::new(); 33 | 34 | write_lossy(&mut writer, &b"Hello, "[..])?; 35 | writer.extend_from_slice(b"world"); 36 | write_lossy(&mut writer, &b"!"[..])?; 37 | 38 | assert_eq!(b"Hello, world!", &*writer); 39 | 40 | Ok(()) 41 | } 42 | 43 | #[test] 44 | fn test_implementations() -> io::Result<()> { 45 | const C_STRING: &CStr = c"foobar"; 46 | const STRING: &str = if let Ok(string) = &C_STRING.to_str() { 47 | string 48 | } else { 49 | unreachable!(); 50 | }; 51 | const STRING_BYTES: &[u8] = STRING.as_bytes(); 52 | 53 | macro_rules! test_one { 54 | ( $value:expr ) => {{ 55 | let mut writer = Vec::new(); 56 | write_lossy(&mut writer, $value)?; 57 | assert_eq!(STRING_BYTES, &*writer); 58 | }}; 59 | } 60 | 61 | macro_rules! test { 62 | ( $value:expr ) => {{ 63 | let value = $value; 64 | test_one!(value); 65 | test_one!(&value.to_owned()); 66 | }}; 67 | } 68 | 69 | test!(C_STRING); 70 | test!(STRING_BYTES); 71 | #[cfg(feature = "os_str_bytes")] 72 | { 73 | test!(OsStr::new(STRING)); 74 | test!(Path::new(STRING)); 75 | } 76 | 77 | test_one!(&Cow::Borrowed(STRING_BYTES)); 78 | test_one!(&Cow::<[_]>::Owned(STRING_BYTES.to_owned())); 79 | 80 | Ok(()) 81 | } 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # print\_bytes 2 | 3 | This crate allows printing broken UTF-8 bytes to an output stream as losslessly 4 | as possible. 5 | 6 | Usually, paths are printed by calling [`Path::display`] or 7 | [`Path::to_string_lossy`] beforehand. However, both of these methods are always 8 | lossy; they misrepresent some valid paths in output. The same is true when 9 | using [`String::from_utf8_lossy`] to print any other UTF-8–like byte sequence. 10 | 11 | Instead, this crate only performs a lossy conversion when the output device is 12 | known to require Unicode, to make output as accurate as possible. When 13 | necessary, any character sequence that cannot be represented will be replaced 14 | with [`REPLACEMENT_CHARACTER`]. That convention is shared with the standard 15 | library, which uses the same character for its lossy conversion functions. 16 | 17 | [![GitHub Build Status](https://github.com/dylni/print_bytes/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/dylni/print_bytes/actions/workflows/build.yml?query=branch%3Amaster) 18 | 19 | ## Usage 20 | 21 | Add the following lines to your "Cargo.toml" file: 22 | 23 | ```toml 24 | [dependencies] 25 | print_bytes = "2.1" 26 | ``` 27 | 28 | See the [documentation] for available functionality and examples. 29 | 30 | ## Rust version support 31 | 32 | The minimum supported Rust toolchain version is currently Rust 1.77.0. 33 | 34 | Minor version updates may increase this version requirement. However, the 35 | previous two Rust releases will always be supported. If the minimum Rust 36 | version must not be increased, use a tilde requirement to prevent updating this 37 | crate's minor version: 38 | 39 | ```toml 40 | [dependencies] 41 | print_bytes = "~2.1" 42 | ``` 43 | 44 | ## License 45 | 46 | Licensing terms are specified in [COPYRIGHT]. 47 | 48 | Unless you explicitly state otherwise, any contribution submitted for inclusion 49 | in this crate, as defined in [LICENSE-APACHE], shall be licensed according to 50 | [COPYRIGHT], without any additional terms or conditions. 51 | 52 | [COPYRIGHT]: https://github.com/dylni/print_bytes/blob/master/COPYRIGHT 53 | [documentation]: https://docs.rs/print_bytes 54 | [LICENSE-APACHE]: https://github.com/dylni/print_bytes/blob/master/LICENSE-APACHE 55 | [`Path::display`]: https://doc.rust-lang.org/std/path/struct.Path.html#method.display 56 | [`Path::to_string_lossy`]: https://doc.rust-lang.org/std/path/struct.Path.html#method.to_string_lossy 57 | [`REPLACEMENT_CHARACTER`]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html 58 | [`String::from_utf8_lossy`]: https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_lossy 59 | -------------------------------------------------------------------------------- /src/console.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::os::windows::io::AsHandle; 3 | use std::os::windows::io::AsRawHandle; 4 | use std::os::windows::io::BorrowedHandle; 5 | use std::ptr; 6 | 7 | use windows_sys::core::BOOL; 8 | use windows_sys::Win32::Foundation::HANDLE; 9 | use windows_sys::Win32::Foundation::TRUE; 10 | use windows_sys::Win32::System::Console::GetConsoleMode; 11 | use windows_sys::Win32::System::Console::WriteConsoleW; 12 | 13 | fn check_syscall(result: BOOL) -> io::Result<()> { 14 | if result == TRUE { 15 | Ok(()) 16 | } else { 17 | Err(io::Error::last_os_error()) 18 | } 19 | } 20 | 21 | fn raw_handle(handle: BorrowedHandle<'_>) -> HANDLE { 22 | handle.as_raw_handle() as _ 23 | } 24 | 25 | #[derive(Clone, Copy)] 26 | pub(super) struct Console<'a>(BorrowedHandle<'a>); 27 | 28 | impl<'a> Console<'a> { 29 | pub(super) fn from_handle(handle: &'a T) -> Option 30 | where 31 | T: AsHandle + ?Sized, 32 | { 33 | let handle = handle.as_handle(); 34 | // The mode is not important, since this call only succeeds for Windows 35 | // Console. Other streams usually do not require Unicode writes. 36 | let mut mode = 0; 37 | check_syscall(unsafe { GetConsoleMode(raw_handle(handle), &mut mode) }) 38 | .ok() 39 | .map(|()| Self(handle)) 40 | } 41 | 42 | // Writing to the returned instance causes undefined behavior. 43 | #[cfg(test)] 44 | pub(super) const unsafe fn null() -> Self { 45 | // SAFETY: Null pointers can be passed to this method. 46 | Self(unsafe { BorrowedHandle::borrow_raw(ptr::null_mut()) }) 47 | } 48 | 49 | fn write_wide(&mut self, string: &[u16]) -> io::Result { 50 | let length = string.len().try_into().unwrap_or(u32::MAX); 51 | let mut written_length = 0; 52 | check_syscall(unsafe { 53 | WriteConsoleW( 54 | raw_handle(self.0), 55 | string.as_ptr().cast(), 56 | length, 57 | &mut written_length, 58 | ptr::null_mut(), 59 | ) 60 | }) 61 | .map(|()| written_length as usize) 62 | } 63 | 64 | pub(super) fn write_wide_all( 65 | &mut self, 66 | mut string: &[u16], 67 | ) -> io::Result<()> { 68 | while !string.is_empty() { 69 | match self.write_wide(string) { 70 | Ok(written_length) => { 71 | if written_length == 0 { 72 | return Err(io::Error::new( 73 | io::ErrorKind::WriteZero, 74 | "failed to write whole buffer", 75 | )); 76 | } 77 | string = &string[written_length..]; 78 | } 79 | Err(error) => { 80 | if error.kind() != io::ErrorKind::Interrupted { 81 | return Err(error); 82 | } 83 | } 84 | } 85 | } 86 | Ok(()) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/writer.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(windows, allow(private_interfaces))] 2 | 3 | use std::io::BufWriter; 4 | use std::io::LineWriter; 5 | #[cfg(any(doc, not(feature = "specialization")))] 6 | use std::io::Stderr; 7 | #[cfg(any(doc, not(feature = "specialization")))] 8 | use std::io::StderrLock; 9 | #[cfg(any(doc, not(feature = "specialization")))] 10 | use std::io::Stdout; 11 | #[cfg(any(doc, not(feature = "specialization")))] 12 | use std::io::StdoutLock; 13 | use std::io::Write; 14 | #[cfg(all(feature = "specialization", windows))] 15 | use std::os::windows::io::AsHandle; 16 | 17 | #[cfg(windows)] 18 | use super::console::Console; 19 | 20 | #[cfg(windows)] 21 | pub(super) trait ToConsole { 22 | fn to_console(&self) -> Option>; 23 | } 24 | 25 | #[cfg(all(feature = "specialization", windows))] 26 | impl ToConsole for T 27 | where 28 | T: ?Sized, 29 | { 30 | default fn to_console(&self) -> Option> { 31 | None 32 | } 33 | } 34 | 35 | #[cfg(all(feature = "specialization", windows))] 36 | impl ToConsole for T 37 | where 38 | T: AsHandle + ?Sized + Write, 39 | { 40 | fn to_console(&self) -> Option> { 41 | Console::from_handle(self) 42 | } 43 | } 44 | 45 | /// A bound for [`write_lossy`] that allows it to be used for some types 46 | /// without specialization. 47 | /// 48 | /// When the "specialization" feature is enabled, this trait is implemented for 49 | /// all types. 50 | /// 51 | /// [`write_lossy`]: super::write_lossy 52 | pub trait WriteLossy { 53 | #[cfg(windows)] 54 | #[doc(hidden)] 55 | fn __to_console(&self) -> Option>; 56 | } 57 | 58 | #[cfg(feature = "specialization")] 59 | #[cfg_attr(print_bytes_docs_rs, doc(cfg(feature = "specialization")))] 60 | impl WriteLossy for T 61 | where 62 | T: ?Sized, 63 | { 64 | #[cfg(windows)] 65 | default fn __to_console(&self) -> Option> { 66 | self.to_console() 67 | } 68 | } 69 | 70 | macro_rules! r#impl { 71 | ( $generic:ident , $type:ty ) => { 72 | impl<$generic> WriteLossy for $type 73 | where 74 | $generic: ?Sized + WriteLossy, 75 | { 76 | #[cfg(windows)] 77 | fn __to_console(&self) -> Option> { 78 | (**self).__to_console() 79 | } 80 | } 81 | }; 82 | } 83 | r#impl!(T, &mut T); 84 | r#impl!(T, Box); 85 | 86 | macro_rules! r#impl { 87 | ( $generic:ident , $type:ty ) => { 88 | impl<$generic> WriteLossy for $type 89 | where 90 | $generic: Write + WriteLossy, 91 | { 92 | #[cfg(windows)] 93 | fn __to_console(&self) -> Option> { 94 | self.get_ref().__to_console() 95 | } 96 | } 97 | }; 98 | } 99 | r#impl!(T, BufWriter); 100 | r#impl!(T, LineWriter); 101 | 102 | macro_rules! impl_to_console { 103 | ( $(#[ $attr:meta ])* $type:ty , $to_console_fn:expr , ) => { 104 | #[cfg(any(doc, not(feature = "specialization")))] 105 | impl $crate::WriteLossy for $type { 106 | #[cfg(windows)] 107 | fn __to_console(&self) -> Option> { 108 | $crate::writer::ToConsole::to_console(self) 109 | } 110 | } 111 | 112 | #[cfg(windows)] 113 | $(#[$attr])* 114 | impl $crate::writer::ToConsole for $type { 115 | fn to_console<'a>(&'a self) -> Option> { 116 | let to_console_fn: fn(&'a Self) -> _ = $to_console_fn; 117 | to_console_fn(self) 118 | } 119 | } 120 | }; 121 | } 122 | 123 | macro_rules! r#impl { 124 | ( $($type:ty),+ ) => { 125 | $( 126 | impl_to_console! { 127 | #[cfg(not(feature = "specialization"))] 128 | $type, Console::from_handle, 129 | } 130 | )+ 131 | }; 132 | } 133 | r#impl!(Stderr, StderrLock<'_>, Stdout, StdoutLock<'_>); 134 | 135 | impl_to_console! { 136 | #[cfg(not(feature = "specialization"))] 137 | Vec, |_| None, 138 | } 139 | -------------------------------------------------------------------------------- /src/bytes.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::ffi::CStr; 3 | use std::ffi::CString; 4 | use std::ops::Deref; 5 | 6 | #[cfg(windows)] 7 | type Bytes<'a> = &'a [u8]; 8 | #[cfg(not(windows))] 9 | type Bytes<'a> = Cow<'a, [u8]>; 10 | 11 | #[derive(Debug)] 12 | pub(super) enum ByteStrInner<'a> { 13 | Bytes(Bytes<'a>), 14 | #[cfg(windows)] 15 | Str(Cow<'a, str>), 16 | } 17 | 18 | /// A value returned by [`ToBytes::to_bytes`]. 19 | /// 20 | /// This struct is usually initialized by calling the above method for 21 | /// [`[u8]`][slice]. 22 | #[derive(Debug)] 23 | pub struct ByteStr<'a>(pub(super) ByteStrInner<'a>); 24 | 25 | #[cfg(any(doc, windows))] 26 | impl<'a> ByteStr<'a> { 27 | /// Wraps a byte string lossily. 28 | /// 29 | /// This method can be used to implement [`ToBytes::to_bytes`] when 30 | /// [`ToBytes::to_wide`] is the better way to represent the string. 31 | #[cfg_attr(print_bytes_docs_rs, doc(cfg(windows)))] 32 | #[inline] 33 | #[must_use] 34 | pub fn from_utf8_lossy(string: &'a [u8]) -> Self { 35 | Self(ByteStrInner::Str(String::from_utf8_lossy(string))) 36 | } 37 | } 38 | 39 | /// A value returned by [`ToBytes::to_wide`]. 40 | #[cfg(any(doc, windows))] 41 | #[cfg_attr(print_bytes_docs_rs, doc(cfg(windows)))] 42 | #[derive(Debug)] 43 | pub struct WideStr(pub(super) Vec); 44 | 45 | #[cfg(any(doc, windows))] 46 | impl WideStr { 47 | /// Wraps a wide character string. 48 | /// 49 | /// This method can be used to implement [`ToBytes::to_wide`]. 50 | #[inline] 51 | #[must_use] 52 | pub fn new(string: Vec) -> Self { 53 | Self(string) 54 | } 55 | } 56 | 57 | /// Represents a type similarly to [`Display`]. 58 | /// 59 | /// Implement this trait to allow printing a type that cannot guarantee UTF-8 60 | /// output. It is used to bound values accepted by functions in this crate. 61 | /// 62 | /// # Examples 63 | /// 64 | /// ``` 65 | /// use print_bytes::println_lossy; 66 | /// use print_bytes::ByteStr; 67 | /// use print_bytes::ToBytes; 68 | /// #[cfg(windows)] 69 | /// use print_bytes::WideStr; 70 | /// 71 | /// struct ByteSlice<'a>(&'a [u8]); 72 | /// 73 | /// impl ToBytes for ByteSlice<'_> { 74 | /// fn to_bytes(&self) -> ByteStr<'_> { 75 | /// self.0.to_bytes() 76 | /// } 77 | /// 78 | /// #[cfg(windows)] 79 | /// fn to_wide(&self) -> Option { 80 | /// self.0.to_wide() 81 | /// } 82 | /// } 83 | /// 84 | /// println_lossy(&ByteSlice(b"Hello, world!")); 85 | /// ``` 86 | /// 87 | /// [`Display`]: ::std::fmt::Display 88 | /// [`to_bytes`]: Self::to_bytes 89 | /// [`ToString`]: ::std::string::ToString 90 | pub trait ToBytes { 91 | /// Returns a byte string that will be used to represent the instance. 92 | #[must_use] 93 | fn to_bytes(&self) -> ByteStr<'_>; 94 | 95 | /// Returns a wide character string that will be used to represent the 96 | /// instance. 97 | /// 98 | /// The Windows API frequently uses wide character strings. This method 99 | /// allows them to be printed losslessly in some cases, even when they 100 | /// cannot be converted to UTF-8. 101 | /// 102 | /// Returning [`None`] causes [`to_bytes`] to be used instead. 103 | /// 104 | /// [`to_bytes`]: Self::to_bytes 105 | #[cfg(any(doc, windows))] 106 | #[cfg_attr(print_bytes_docs_rs, doc(cfg(windows)))] 107 | #[must_use] 108 | fn to_wide(&self) -> Option; 109 | } 110 | 111 | impl ToBytes for [u8] { 112 | #[cfg_attr(windows, allow(clippy::useless_conversion))] 113 | #[inline] 114 | fn to_bytes(&self) -> ByteStr<'_> { 115 | ByteStr(ByteStrInner::Bytes(self.into())) 116 | } 117 | 118 | #[cfg(any(doc, windows))] 119 | #[inline] 120 | fn to_wide(&self) -> Option { 121 | None 122 | } 123 | } 124 | 125 | macro_rules! defer_methods { 126 | ( $convert_method:ident ) => { 127 | #[inline] 128 | fn to_bytes(&self) -> ByteStr<'_> { 129 | ToBytes::to_bytes(self.$convert_method()) 130 | } 131 | 132 | #[cfg(any(doc, windows))] 133 | #[inline] 134 | fn to_wide(&self) -> Option { 135 | self.$convert_method().to_wide() 136 | } 137 | }; 138 | } 139 | 140 | impl ToBytes for [u8; N] { 141 | defer_methods!(as_slice); 142 | } 143 | 144 | impl ToBytes for Cow<'_, T> 145 | where 146 | T: ?Sized + ToBytes + ToOwned, 147 | T::Owned: ToBytes, 148 | { 149 | defer_methods!(deref); 150 | } 151 | 152 | macro_rules! defer_impl { 153 | ( $type:ty , $convert_method:ident ) => { 154 | impl ToBytes for $type { 155 | defer_methods!($convert_method); 156 | } 157 | }; 158 | } 159 | defer_impl!(CStr, to_bytes); 160 | defer_impl!(CString, as_c_str); 161 | defer_impl!(Vec, as_slice); 162 | 163 | #[cfg(feature = "os_str_bytes")] 164 | #[cfg_attr(print_bytes_docs_rs, doc(cfg(feature = "os_str_bytes")))] 165 | mod os_str_bytes { 166 | use std::ffi::OsStr; 167 | use std::ffi::OsString; 168 | #[cfg(windows)] 169 | use std::os::windows::ffi::OsStrExt; 170 | use std::path::Path; 171 | use std::path::PathBuf; 172 | 173 | #[cfg(not(windows))] 174 | use os_str_bytes::OsStrBytes; 175 | 176 | use super::ByteStr; 177 | use super::ByteStrInner; 178 | use super::ToBytes; 179 | #[cfg(any(doc, windows))] 180 | use super::WideStr; 181 | 182 | impl ToBytes for OsStr { 183 | #[inline] 184 | fn to_bytes(&self) -> ByteStr<'_> { 185 | #[cfg(windows)] 186 | { 187 | ByteStr(ByteStrInner::Str(self.to_string_lossy())) 188 | } 189 | #[cfg(not(windows))] 190 | ByteStr(ByteStrInner::Bytes(self.to_io_bytes_lossy())) 191 | } 192 | 193 | #[cfg(any(doc, windows))] 194 | #[inline] 195 | fn to_wide(&self) -> Option { 196 | Some(WideStr(self.encode_wide().collect())) 197 | } 198 | } 199 | 200 | defer_impl!(OsString, as_os_str); 201 | defer_impl!(Path, as_os_str); 202 | defer_impl!(PathBuf, as_path); 203 | } 204 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate allows printing broken UTF-8 bytes to an output stream as 2 | //! losslessly as possible. 3 | //! 4 | //! Usually, paths are printed by calling [`Path::display`] or 5 | //! [`Path::to_string_lossy`] beforehand. However, both of these methods are 6 | //! always lossy; they misrepresent some valid paths in output. The same is 7 | //! true when using [`String::from_utf8_lossy`] to print any other 8 | //! UTF-8–like byte sequence. 9 | //! 10 | //! Instead, this crate only performs a lossy conversion when the output device 11 | //! is known to require Unicode, to make output as accurate as possible. When 12 | //! necessary, any character sequence that cannot be represented will be 13 | //! replaced with [`REPLACEMENT_CHARACTER`]. That convention is shared with the 14 | //! standard library, which uses the same character for its lossy conversion 15 | //! functions. 16 | //! 17 | //! ### Note: Windows Compatibility 18 | //! 19 | //! [`OsStr`] and related structs may be printed lossily on Windows. Paths are 20 | //! not represented using bytes on that platform, so it may be confusing to 21 | //! display them in that manner. Plus, the encoding most often used to account 22 | //! for the difference is [not permitted to be written to 23 | //! files][wtf8_audience], so it would not make sense for this crate to use it. 24 | //! 25 | //! Windows Console can display these paths, so this crate will output them 26 | //! losslessly when writing to that terminal. 27 | //! 28 | //! # Features 29 | //! 30 | //! These features are optional and can be enabled or disabled in a 31 | //! "Cargo.toml" file. 32 | //! 33 | //! ### Optional Features 34 | //! 35 | //! - **os\_str\_bytes** - 36 | //! Provides implementations of [`ToBytes`] for: 37 | //! - [`OsStr`] 38 | //! - [`OsString`] 39 | //! - [`Path`] 40 | //! - [`PathBuf`] 41 | //! 42 | //! ### Nightly Features 43 | //! 44 | //! These features are unstable, since they rely on unstable Rust features. 45 | //! 46 | //! - **specialization** - 47 | //! Provides an implementation of [`WriteLossy`] for all types. 48 | //! 49 | //! # Examples 50 | //! 51 | //! ``` 52 | //! use std::env; 53 | //! # use std::io; 54 | //! 55 | //! use print_bytes::println_lossy; 56 | //! 57 | //! print!("exe: "); 58 | //! # #[cfg(feature = "os_str_bytes")] 59 | //! println_lossy(&env::current_exe()?); 60 | //! println!(); 61 | //! 62 | //! println!("args:"); 63 | //! for arg in env::args_os().skip(1) { 64 | //! # #[cfg(feature = "os_str_bytes")] 65 | //! println_lossy(&arg); 66 | //! } 67 | //! # 68 | //! # Ok::<_, io::Error>(()) 69 | //! ``` 70 | //! 71 | //! [`OsStr`]: ::std::ffi::OsStr 72 | //! [`OsString`]: ::std::ffi::OsString 73 | //! [`Path`]: ::std::path::Path 74 | //! [`Path::display`]: ::std::path::Path::display 75 | //! [`Path::to_string_lossy`]: ::std::path::Path::to_string_lossy 76 | //! [`PathBuf`]: ::std::path::PathBuf 77 | //! [`REPLACEMENT_CHARACTER`]: char::REPLACEMENT_CHARACTER 78 | //! [wtf8_audience]: https://simonsapin.github.io/wtf-8/#intended-audience 79 | 80 | #![cfg_attr(feature = "specialization", allow(incomplete_features))] 81 | // Only require a nightly compiler when building documentation for docs.rs. 82 | // This is a private option that should not be used. 83 | // https://github.com/rust-lang/docs.rs/issues/147#issuecomment-389544407 84 | #![cfg_attr(print_bytes_docs_rs, feature(doc_cfg))] 85 | #![cfg_attr(feature = "specialization", feature(specialization))] 86 | #![warn(unused_results)] 87 | 88 | use std::io; 89 | use std::io::Write; 90 | 91 | mod bytes; 92 | pub use bytes::ByteStr; 93 | use bytes::ByteStrInner; 94 | pub use bytes::ToBytes; 95 | #[cfg(any(doc, windows))] 96 | pub use bytes::WideStr; 97 | 98 | #[cfg(windows)] 99 | mod console; 100 | 101 | #[cfg_attr(test, macro_use)] 102 | mod writer; 103 | pub use writer::WriteLossy; 104 | 105 | #[cfg(test)] 106 | mod tests; 107 | 108 | /// Writes a value to a "writer". 109 | /// 110 | /// This function is similar to [`write!`] but does not take a format 111 | /// parameter. 112 | /// 113 | /// For more information, see [the module-level documentation][module]. 114 | /// 115 | /// # Errors 116 | /// 117 | /// Returns an error if writing to the writer fails. 118 | /// 119 | /// # Examples 120 | /// 121 | /// ``` 122 | /// use std::env; 123 | /// use std::ffi::OsStr; 124 | /// 125 | /// use print_bytes::write_lossy; 126 | /// 127 | /// let string = "foobar"; 128 | /// let os_string = OsStr::new(string); 129 | /// 130 | /// # #[cfg(feature = "os_str_bytes")] 131 | /// # { 132 | /// let mut lossy_string = Vec::new(); 133 | /// write_lossy(&mut lossy_string, os_string) 134 | /// .expect("failed writing to vector"); 135 | /// assert_eq!(string.as_bytes(), lossy_string); 136 | /// # } 137 | /// ``` 138 | /// 139 | /// [module]: self 140 | #[inline] 141 | pub fn write_lossy(mut writer: W, value: &T) -> io::Result<()> 142 | where 143 | T: ?Sized + ToBytes, 144 | W: Write + WriteLossy, 145 | { 146 | #[cfg(windows)] 147 | let lossy = if let Some(mut console) = writer.__to_console() { 148 | if let Some(string) = value.to_wide() { 149 | return console.write_wide_all(&string.0); 150 | } 151 | true 152 | } else { 153 | false 154 | }; 155 | 156 | #[cfg(windows)] 157 | let buffer; 158 | let string = value.to_bytes().0; 159 | #[cfg_attr(not(windows), allow(clippy::infallible_destructuring_match))] 160 | let string = match &string { 161 | ByteStrInner::Bytes(string) => { 162 | #[cfg(windows)] 163 | if lossy { 164 | buffer = String::from_utf8_lossy(string); 165 | buffer.as_bytes() 166 | } else { 167 | string 168 | } 169 | #[cfg(not(windows))] 170 | string 171 | } 172 | #[cfg(windows)] 173 | ByteStrInner::Str(string) => string.as_bytes(), 174 | }; 175 | writer.write_all(string) 176 | } 177 | 178 | macro_rules! expect_print { 179 | ( $label:literal , $result:expr ) => { 180 | $result 181 | .unwrap_or_else(|x| panic!("failed writing to {}: {}", $label, x)) 182 | }; 183 | } 184 | 185 | macro_rules! r#impl { 186 | ( 187 | $writer:expr , 188 | $(#[ $print_fn_attr:meta ])* $print_fn:ident , 189 | $(#[ $println_fn_attr:meta ])* $println_fn:ident , 190 | $label:literal , 191 | ) => { 192 | #[inline] 193 | $(#[$print_fn_attr])* 194 | pub fn $print_fn(value: &T) 195 | where 196 | T: ?Sized + ToBytes, 197 | { 198 | expect_print!($label, write_lossy($writer, value)); 199 | } 200 | 201 | #[inline] 202 | $(#[$println_fn_attr])* 203 | pub fn $println_fn(value: &T) 204 | where 205 | T: ?Sized + ToBytes, 206 | { 207 | let mut writer = $writer.lock(); 208 | expect_print!($label, write_lossy(&mut writer, value)); 209 | expect_print!($label, writer.write_all(b"\n")); 210 | } 211 | }; 212 | } 213 | r#impl!( 214 | io::stderr(), 215 | /// Prints a value to the standard error stream. 216 | /// 217 | /// This function is similar to [`eprint!`] but does not take a format 218 | /// parameter. 219 | /// 220 | /// For more information, see [the module-level documentation][module]. 221 | /// 222 | /// # Panics 223 | /// 224 | /// Panics if writing to the stream fails. 225 | /// 226 | /// # Examples 227 | /// 228 | /// ``` 229 | /// use std::env; 230 | /// # use std::io; 231 | /// 232 | /// use print_bytes::eprint_lossy; 233 | /// 234 | /// # #[cfg(feature = "os_str_bytes")] 235 | /// eprint_lossy(&env::current_exe()?); 236 | /// # 237 | /// # Ok::<_, io::Error>(()) 238 | /// ``` 239 | /// 240 | /// [module]: self 241 | eprint_lossy, 242 | /// Prints a value to the standard error stream, followed by a newline. 243 | /// 244 | /// This function is similar to [`eprintln!`] but does not take a format 245 | /// parameter. 246 | /// 247 | /// For more information, see [the module-level documentation][module]. 248 | /// 249 | /// # Panics 250 | /// 251 | /// Panics if writing to the stream fails. 252 | /// 253 | /// # Examples 254 | /// 255 | /// ``` 256 | /// use std::env; 257 | /// # use std::io; 258 | /// 259 | /// use print_bytes::eprintln_lossy; 260 | /// 261 | /// # #[cfg(feature = "os_str_bytes")] 262 | /// eprintln_lossy(&env::current_exe()?); 263 | /// # 264 | /// # Ok::<_, io::Error>(()) 265 | /// ``` 266 | /// 267 | /// [module]: self 268 | eprintln_lossy, 269 | "stderr", 270 | ); 271 | r#impl!( 272 | io::stdout(), 273 | /// Prints a value to the standard output stream. 274 | /// 275 | /// This function is similar to [`print!`] but does not take a format 276 | /// parameter. 277 | /// 278 | /// For more information, see [the module-level documentation][module]. 279 | /// 280 | /// # Panics 281 | /// 282 | /// Panics if writing to the stream fails. 283 | /// 284 | /// # Examples 285 | /// 286 | /// ``` 287 | /// use std::env; 288 | /// # use std::io; 289 | /// 290 | /// use print_bytes::print_lossy; 291 | /// 292 | /// # #[cfg(feature = "os_str_bytes")] 293 | /// print_lossy(&env::current_exe()?); 294 | /// # 295 | /// # Ok::<_, io::Error>(()) 296 | /// ``` 297 | /// 298 | /// [module]: self 299 | print_lossy, 300 | /// Prints a value to the standard output stream, followed by a newline. 301 | /// 302 | /// This function is similar to [`println!`] but does not take a format 303 | /// parameter. 304 | /// 305 | /// For more information, see [the module-level documentation][module]. 306 | /// 307 | /// # Panics 308 | /// 309 | /// Panics if writing to the stream fails. 310 | /// 311 | /// # Examples 312 | /// 313 | /// ``` 314 | /// use std::env; 315 | /// # use std::io; 316 | /// 317 | /// use print_bytes::println_lossy; 318 | /// 319 | /// # #[cfg(feature = "os_str_bytes")] 320 | /// println_lossy(&env::current_exe()?); 321 | /// # 322 | /// # Ok::<_, io::Error>(()) 323 | /// ``` 324 | /// 325 | /// [module]: self 326 | println_lossy, 327 | "stdout", 328 | ); 329 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | --------------------------------------------------------------------------------