From 1b6a04ca5504955c571d1c97504fb45ea0befee4 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Mon, 8 Jan 2024 01:21:28 +0400 Subject: Initial vendor packages Signed-off-by: Valentin Popov --- vendor/anstream/src/adapter/mod.rs | 15 + vendor/anstream/src/adapter/strip.rs | 513 ++++++++++++++++++++++++++++++++++ vendor/anstream/src/adapter/wincon.rs | 320 +++++++++++++++++++++ vendor/anstream/src/auto.rs | 263 +++++++++++++++++ vendor/anstream/src/buffer.rs | 68 +++++ vendor/anstream/src/fmt.rs | 54 ++++ vendor/anstream/src/lib.rs | 79 ++++++ vendor/anstream/src/macros.rs | 389 ++++++++++++++++++++++++++ vendor/anstream/src/stream.rs | 261 +++++++++++++++++ vendor/anstream/src/strip.rs | 219 +++++++++++++++ vendor/anstream/src/wincon.rs | 210 ++++++++++++++ 11 files changed, 2391 insertions(+) create mode 100644 vendor/anstream/src/adapter/mod.rs create mode 100644 vendor/anstream/src/adapter/strip.rs create mode 100644 vendor/anstream/src/adapter/wincon.rs create mode 100644 vendor/anstream/src/auto.rs create mode 100644 vendor/anstream/src/buffer.rs create mode 100644 vendor/anstream/src/fmt.rs create mode 100644 vendor/anstream/src/lib.rs create mode 100644 vendor/anstream/src/macros.rs create mode 100644 vendor/anstream/src/stream.rs create mode 100644 vendor/anstream/src/strip.rs create mode 100644 vendor/anstream/src/wincon.rs (limited to 'vendor/anstream/src') diff --git a/vendor/anstream/src/adapter/mod.rs b/vendor/anstream/src/adapter/mod.rs new file mode 100644 index 0000000..f266b68 --- /dev/null +++ b/vendor/anstream/src/adapter/mod.rs @@ -0,0 +1,15 @@ +//! Gracefully degrade styled output + +mod strip; +mod wincon; + +pub use strip::strip_bytes; +pub use strip::strip_str; +pub use strip::StripBytes; +pub use strip::StripBytesIter; +pub use strip::StripStr; +pub use strip::StripStrIter; +pub use strip::StrippedBytes; +pub use strip::StrippedStr; +pub use wincon::WinconBytes; +pub use wincon::WinconBytesIter; diff --git a/vendor/anstream/src/adapter/strip.rs b/vendor/anstream/src/adapter/strip.rs new file mode 100644 index 0000000..5078c51 --- /dev/null +++ b/vendor/anstream/src/adapter/strip.rs @@ -0,0 +1,513 @@ +use anstyle_parse::state::state_change; +use anstyle_parse::state::Action; +use anstyle_parse::state::State; + +/// Strip ANSI escapes from a `&str`, returning the printable content +/// +/// This can be used to take output from a program that includes escape sequences and write it +/// somewhere that does not easily support them, such as a log file. +/// +/// For non-contiguous data, see [`StripStr`]. +/// +/// # Example +/// +/// ```rust +/// use std::io::Write as _; +/// +/// let styled_text = "\x1b[32mfoo\x1b[m bar"; +/// let plain_str = anstream::adapter::strip_str(&styled_text).to_string(); +/// assert_eq!(plain_str, "foo bar"); +/// ``` +#[inline] +pub fn strip_str(data: &str) -> StrippedStr<'_> { + StrippedStr::new(data) +} + +/// See [`strip_str`] +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct StrippedStr<'s> { + bytes: &'s [u8], + state: State, +} + +impl<'s> StrippedStr<'s> { + #[inline] + fn new(data: &'s str) -> Self { + Self { + bytes: data.as_bytes(), + state: State::Ground, + } + } + + /// Create a [`String`] of the printable content + #[inline] + #[allow(clippy::inherent_to_string_shadow_display)] // Single-allocation implementation + pub fn to_string(&self) -> String { + use std::fmt::Write as _; + let mut stripped = String::with_capacity(self.bytes.len()); + let _ = write!(&mut stripped, "{}", self); + stripped + } +} + +impl<'s> std::fmt::Display for StrippedStr<'s> { + /// **Note:** this does *not* exhaust the [`Iterator`] + #[inline] + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let iter = Self { + bytes: self.bytes, + state: self.state, + }; + for printable in iter { + printable.fmt(f)?; + } + Ok(()) + } +} + +impl<'s> Iterator for StrippedStr<'s> { + type Item = &'s str; + + #[inline] + fn next(&mut self) -> Option { + next_str(&mut self.bytes, &mut self.state) + } +} + +/// Incrementally strip non-contiguous data +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct StripStr { + state: State, +} + +impl StripStr { + /// Initial state + pub fn new() -> Self { + Default::default() + } + + /// Strip the next segment of data + pub fn strip_next<'s>(&'s mut self, data: &'s str) -> StripStrIter<'s> { + StripStrIter { + bytes: data.as_bytes(), + state: &mut self.state, + } + } +} + +/// See [`StripStr`] +#[derive(Debug, PartialEq, Eq)] +pub struct StripStrIter<'s> { + bytes: &'s [u8], + state: &'s mut State, +} + +impl<'s> Iterator for StripStrIter<'s> { + type Item = &'s str; + + #[inline] + fn next(&mut self) -> Option { + next_str(&mut self.bytes, self.state) + } +} + +#[inline] +fn next_str<'s>(bytes: &mut &'s [u8], state: &mut State) -> Option<&'s str> { + let offset = bytes.iter().copied().position(|b| { + let (next_state, action) = state_change(*state, b); + if next_state != State::Anywhere { + *state = next_state; + } + is_printable_str(action, b) + }); + let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len())); + *bytes = next; + *state = State::Ground; + + let offset = bytes.iter().copied().position(|b| { + let (_next_state, action) = state_change(State::Ground, b); + !is_printable_str(action, b) + }); + let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len())); + *bytes = next; + if printable.is_empty() { + None + } else { + let printable = unsafe { + from_utf8_unchecked( + printable, + "`bytes` was validated as UTF-8, the parser preserves UTF-8 continuations", + ) + }; + Some(printable) + } +} + +#[inline] +unsafe fn from_utf8_unchecked<'b>(bytes: &'b [u8], safety_justification: &'static str) -> &'b str { + if cfg!(debug_assertions) { + // Catch problems more quickly when testing + std::str::from_utf8(bytes).expect(safety_justification) + } else { + std::str::from_utf8_unchecked(bytes) + } +} + +#[inline] +fn is_printable_str(action: Action, byte: u8) -> bool { + // VT320 considered 0x7f to be `Print`able but we expect to be working in UTF-8 systems and not + // ISO Latin-1, making it DEL and non-printable + const DEL: u8 = 0x7f; + (action == Action::Print && byte != DEL) + || action == Action::BeginUtf8 + // since we know the input is valid UTF-8, the only thing we can do with + // continuations is to print them + || is_utf8_continuation(byte) + || (action == Action::Execute && byte.is_ascii_whitespace()) +} + +#[inline] +fn is_utf8_continuation(b: u8) -> bool { + matches!(b, 0x80..=0xbf) +} + +/// Strip ANSI escapes from bytes, returning the printable content +/// +/// This can be used to take output from a program that includes escape sequences and write it +/// somewhere that does not easily support them, such as a log file. +/// +/// # Example +/// +/// ```rust +/// use std::io::Write as _; +/// +/// let styled_text = "\x1b[32mfoo\x1b[m bar"; +/// let plain_str = anstream::adapter::strip_bytes(styled_text.as_bytes()).into_vec(); +/// assert_eq!(plain_str.as_slice(), &b"foo bar"[..]); +/// ``` +#[inline] +pub fn strip_bytes(data: &[u8]) -> StrippedBytes<'_> { + StrippedBytes::new(data) +} + +/// See [`strip_bytes`] +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct StrippedBytes<'s> { + bytes: &'s [u8], + state: State, + utf8parser: Utf8Parser, +} + +impl<'s> StrippedBytes<'s> { + /// See [`strip_bytes`] + #[inline] + pub fn new(bytes: &'s [u8]) -> Self { + Self { + bytes, + state: State::Ground, + utf8parser: Default::default(), + } + } + + /// Strip the next slice of bytes + /// + /// Used when the content is in several non-contiguous slices + /// + /// # Panic + /// + /// May panic if it is not exhausted / empty + #[inline] + pub fn extend(&mut self, bytes: &'s [u8]) { + debug_assert!( + self.is_empty(), + "current bytes must be processed to ensure we end at the right state" + ); + self.bytes = bytes; + } + + /// Report the bytes has been exhausted + #[inline] + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// Create a [`Vec`] of the printable content + #[inline] + pub fn into_vec(self) -> Vec { + let mut stripped = Vec::with_capacity(self.bytes.len()); + for printable in self { + stripped.extend(printable); + } + stripped + } +} + +impl<'s> Iterator for StrippedBytes<'s> { + type Item = &'s [u8]; + + #[inline] + fn next(&mut self) -> Option { + next_bytes(&mut self.bytes, &mut self.state, &mut self.utf8parser) + } +} + +/// Incrementally strip non-contiguous data +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct StripBytes { + state: State, + utf8parser: Utf8Parser, +} + +impl StripBytes { + /// Initial state + pub fn new() -> Self { + Default::default() + } + + /// Strip the next segment of data + pub fn strip_next<'s>(&'s mut self, bytes: &'s [u8]) -> StripBytesIter<'s> { + StripBytesIter { + bytes, + state: &mut self.state, + utf8parser: &mut self.utf8parser, + } + } +} + +/// See [`StripBytes`] +#[derive(Debug, PartialEq, Eq)] +pub struct StripBytesIter<'s> { + bytes: &'s [u8], + state: &'s mut State, + utf8parser: &'s mut Utf8Parser, +} + +impl<'s> Iterator for StripBytesIter<'s> { + type Item = &'s [u8]; + + #[inline] + fn next(&mut self) -> Option { + next_bytes(&mut self.bytes, self.state, self.utf8parser) + } +} + +#[inline] +fn next_bytes<'s>( + bytes: &mut &'s [u8], + state: &mut State, + utf8parser: &mut Utf8Parser, +) -> Option<&'s [u8]> { + let offset = bytes.iter().copied().position(|b| { + if *state == State::Utf8 { + true + } else { + let (next_state, action) = state_change(*state, b); + if next_state != State::Anywhere { + *state = next_state; + } + is_printable_bytes(action, b) + } + }); + let (_, next) = bytes.split_at(offset.unwrap_or(bytes.len())); + *bytes = next; + + let offset = bytes.iter().copied().position(|b| { + if *state == State::Utf8 { + if utf8parser.add(b) { + *state = State::Ground; + } + false + } else { + let (next_state, action) = state_change(State::Ground, b); + if next_state != State::Anywhere { + *state = next_state; + } + if *state == State::Utf8 { + utf8parser.add(b); + false + } else { + !is_printable_bytes(action, b) + } + } + }); + let (printable, next) = bytes.split_at(offset.unwrap_or(bytes.len())); + *bytes = next; + if printable.is_empty() { + None + } else { + Some(printable) + } +} + +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct Utf8Parser { + utf8_parser: utf8parse::Parser, +} + +impl Utf8Parser { + fn add(&mut self, byte: u8) -> bool { + let mut b = false; + let mut receiver = VtUtf8Receiver(&mut b); + self.utf8_parser.advance(&mut receiver, byte); + b + } +} + +struct VtUtf8Receiver<'a>(&'a mut bool); + +impl<'a> utf8parse::Receiver for VtUtf8Receiver<'a> { + fn codepoint(&mut self, _: char) { + *self.0 = true; + } + + fn invalid_sequence(&mut self) { + *self.0 = true; + } +} + +#[inline] +fn is_printable_bytes(action: Action, byte: u8) -> bool { + // VT320 considered 0x7f to be `Print`able but we expect to be working in UTF-8 systems and not + // ISO Latin-1, making it DEL and non-printable + const DEL: u8 = 0x7f; + + // Continuations aren't included as they may also be control codes, requiring more context + (action == Action::Print && byte != DEL) + || action == Action::BeginUtf8 + || (action == Action::Execute && byte.is_ascii_whitespace()) +} + +#[cfg(test)] +mod test { + use super::*; + use proptest::prelude::*; + + /// Model based off full parser + fn parser_strip(bytes: &[u8]) -> String { + #[derive(Default)] + struct Strip(String); + impl Strip { + fn with_capacity(capacity: usize) -> Self { + Self(String::with_capacity(capacity)) + } + } + impl anstyle_parse::Perform for Strip { + fn print(&mut self, c: char) { + self.0.push(c); + } + + fn execute(&mut self, byte: u8) { + if byte.is_ascii_whitespace() { + self.0.push(byte as char); + } + } + } + + let mut stripped = Strip::with_capacity(bytes.len()); + let mut parser = anstyle_parse::Parser::::new(); + for byte in bytes { + parser.advance(&mut stripped, *byte); + } + stripped.0 + } + + /// Model verifying incremental parsing + fn strip_char(mut s: &str) -> String { + let mut result = String::new(); + let mut state = StripStr::new(); + while !s.is_empty() { + let mut indices = s.char_indices(); + indices.next(); // current + let offset = indices.next().map(|(i, _)| i).unwrap_or_else(|| s.len()); + let (current, remainder) = s.split_at(offset); + for printable in state.strip_next(current) { + result.push_str(printable); + } + s = remainder; + } + result + } + + /// Model verifying incremental parsing + fn strip_byte(s: &[u8]) -> Vec { + let mut result = Vec::new(); + let mut state = StripBytes::default(); + for start in 0..s.len() { + let current = &s[start..=start]; + for printable in state.strip_next(current) { + result.extend(printable); + } + } + result + } + + #[test] + fn test_strip_bytes_multibyte() { + let bytes = [240, 145, 141, 139]; + let expected = parser_strip(&bytes); + let actual = String::from_utf8(strip_bytes(&bytes).into_vec()).unwrap(); + assert_eq!(expected, actual); + } + + #[test] + fn test_strip_byte_multibyte() { + let bytes = [240, 145, 141, 139]; + let expected = parser_strip(&bytes); + let actual = String::from_utf8(strip_byte(&bytes).to_vec()).unwrap(); + assert_eq!(expected, actual); + } + + #[test] + fn test_strip_str_del() { + let input = std::str::from_utf8(&[0x7f]).unwrap(); + let expected = ""; + let actual = strip_str(input).to_string(); + assert_eq!(expected, actual); + } + + #[test] + fn test_strip_byte_del() { + let bytes = [0x7f]; + let expected = ""; + let actual = String::from_utf8(strip_byte(&bytes).to_vec()).unwrap(); + assert_eq!(expected, actual); + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn strip_str_no_escapes(s in "\\PC*") { + let expected = parser_strip(s.as_bytes()); + let actual = strip_str(&s).to_string(); + assert_eq!(expected, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn strip_char_no_escapes(s in "\\PC*") { + let expected = parser_strip(s.as_bytes()); + let actual = strip_char(&s); + assert_eq!(expected, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn strip_bytes_no_escapes(s in "\\PC*") { + dbg!(&s); + dbg!(s.as_bytes()); + let expected = parser_strip(s.as_bytes()); + let actual = String::from_utf8(strip_bytes(s.as_bytes()).into_vec()).unwrap(); + assert_eq!(expected, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn strip_byte_no_escapes(s in "\\PC*") { + dbg!(&s); + dbg!(s.as_bytes()); + let expected = parser_strip(s.as_bytes()); + let actual = String::from_utf8(strip_byte(s.as_bytes()).to_vec()).unwrap(); + assert_eq!(expected, actual); + } + } +} diff --git a/vendor/anstream/src/adapter/wincon.rs b/vendor/anstream/src/adapter/wincon.rs new file mode 100644 index 0000000..de3da65 --- /dev/null +++ b/vendor/anstream/src/adapter/wincon.rs @@ -0,0 +1,320 @@ +/// Incrementally convert to wincon calls for non-contiguous data +#[derive(Default, Clone, Debug, PartialEq, Eq)] +pub struct WinconBytes { + parser: anstyle_parse::Parser, + capture: WinconCapture, +} + +impl WinconBytes { + /// Initial state + pub fn new() -> Self { + Default::default() + } + + /// Strip the next segment of data + pub fn extract_next<'s>(&'s mut self, bytes: &'s [u8]) -> WinconBytesIter<'s> { + self.capture.reset(); + self.capture.printable.reserve(bytes.len()); + WinconBytesIter { + bytes, + parser: &mut self.parser, + capture: &mut self.capture, + } + } +} + +/// See [`WinconBytes`] +#[derive(Debug, PartialEq, Eq)] +pub struct WinconBytesIter<'s> { + bytes: &'s [u8], + parser: &'s mut anstyle_parse::Parser, + capture: &'s mut WinconCapture, +} + +impl<'s> Iterator for WinconBytesIter<'s> { + type Item = (anstyle::Style, String); + + #[inline] + fn next(&mut self) -> Option { + next_bytes(&mut self.bytes, self.parser, self.capture) + } +} + +#[inline] +fn next_bytes( + bytes: &mut &[u8], + parser: &mut anstyle_parse::Parser, + capture: &mut WinconCapture, +) -> Option<(anstyle::Style, String)> { + capture.reset(); + while capture.ready.is_none() { + let byte = if let Some((byte, remainder)) = (*bytes).split_first() { + *bytes = remainder; + *byte + } else { + break; + }; + parser.advance(capture, byte); + } + if capture.printable.is_empty() { + return None; + } + + let style = capture.ready.unwrap_or(capture.style); + Some((style, std::mem::take(&mut capture.printable))) +} + +#[derive(Default, Clone, Debug, PartialEq, Eq)] +struct WinconCapture { + style: anstyle::Style, + printable: String, + ready: Option, +} + +impl WinconCapture { + fn reset(&mut self) { + self.ready = None; + } +} + +impl anstyle_parse::Perform for WinconCapture { + /// Draw a character to the screen and update states. + fn print(&mut self, c: char) { + self.printable.push(c); + } + + /// Execute a C0 or C1 control function. + fn execute(&mut self, byte: u8) { + if byte.is_ascii_whitespace() { + self.printable.push(byte as char); + } + } + + fn csi_dispatch( + &mut self, + params: &anstyle_parse::Params, + _intermediates: &[u8], + ignore: bool, + action: u8, + ) { + if ignore { + return; + } + if action != b'm' { + return; + } + + let mut style = self.style; + // param/value differences are dependent on the escape code + let mut state = State::Normal; + let mut r = None; + let mut g = None; + let mut is_bg = false; + for param in params { + for value in param { + match (state, *value) { + (State::Normal, 0) => { + style = anstyle::Style::default(); + break; + } + (State::Normal, 1) => { + style = style.bold(); + break; + } + (State::Normal, 4) => { + style = style.underline(); + break; + } + (State::Normal, 30..=37) => { + let color = to_ansi_color(value - 30).unwrap(); + style = style.fg_color(Some(color.into())); + break; + } + (State::Normal, 38) => { + is_bg = false; + state = State::PrepareCustomColor; + } + (State::Normal, 39) => { + style = style.fg_color(None); + break; + } + (State::Normal, 40..=47) => { + let color = to_ansi_color(value - 40).unwrap(); + style = style.bg_color(Some(color.into())); + break; + } + (State::Normal, 48) => { + is_bg = true; + state = State::PrepareCustomColor; + } + (State::Normal, 49) => { + style = style.bg_color(None); + break; + } + (State::Normal, 90..=97) => { + let color = to_ansi_color(value - 90).unwrap().bright(true); + style = style.fg_color(Some(color.into())); + break; + } + (State::Normal, 100..=107) => { + let color = to_ansi_color(value - 100).unwrap().bright(true); + style = style.bg_color(Some(color.into())); + break; + } + (State::PrepareCustomColor, 5) => { + state = State::Ansi256; + } + (State::PrepareCustomColor, 2) => { + state = State::Rgb; + r = None; + g = None; + } + (State::Ansi256, n) => { + let color = anstyle::Ansi256Color(n as u8); + if is_bg { + style = style.bg_color(Some(color.into())); + } else { + style = style.fg_color(Some(color.into())); + } + break; + } + (State::Rgb, b) => match (r, g) { + (None, _) => { + r = Some(b); + } + (Some(_), None) => { + g = Some(b); + } + (Some(r), Some(g)) => { + let color = anstyle::RgbColor(r as u8, g as u8, b as u8); + if is_bg { + style = style.bg_color(Some(color.into())); + } else { + style = style.fg_color(Some(color.into())); + } + break; + } + }, + _ => { + break; + } + } + } + } + + if style != self.style && !self.printable.is_empty() { + self.ready = Some(self.style); + } + self.style = style; + } +} + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +enum State { + Normal, + PrepareCustomColor, + Ansi256, + Rgb, +} + +fn to_ansi_color(digit: u16) -> Option { + match digit { + 0 => Some(anstyle::AnsiColor::Black), + 1 => Some(anstyle::AnsiColor::Red), + 2 => Some(anstyle::AnsiColor::Green), + 3 => Some(anstyle::AnsiColor::Yellow), + 4 => Some(anstyle::AnsiColor::Blue), + 5 => Some(anstyle::AnsiColor::Magenta), + 6 => Some(anstyle::AnsiColor::Cyan), + 7 => Some(anstyle::AnsiColor::White), + _ => None, + } +} + +#[cfg(test)] +mod test { + use super::*; + use owo_colors::OwoColorize as _; + use proptest::prelude::*; + + #[track_caller] + fn verify(input: &str, expected: Vec<(anstyle::Style, &str)>) { + let expected = expected + .into_iter() + .map(|(style, value)| (style, value.to_owned())) + .collect::>(); + let mut state = WinconBytes::new(); + let actual = state.extract_next(input.as_bytes()).collect::>(); + assert_eq!(expected, actual, "{input:?}"); + } + + #[test] + fn start() { + let input = format!("{} world!", "Hello".green().on_red()); + let expected = vec![ + ( + anstyle::AnsiColor::Green.on(anstyle::AnsiColor::Red), + "Hello", + ), + (anstyle::Style::default(), " world!"), + ]; + verify(&input, expected); + } + + #[test] + fn middle() { + let input = format!("Hello {}!", "world".green().on_red()); + let expected = vec![ + (anstyle::Style::default(), "Hello "), + ( + anstyle::AnsiColor::Green.on(anstyle::AnsiColor::Red), + "world", + ), + (anstyle::Style::default(), "!"), + ]; + verify(&input, expected); + } + + #[test] + fn end() { + let input = format!("Hello {}", "world!".green().on_red()); + let expected = vec![ + (anstyle::Style::default(), "Hello "), + ( + anstyle::AnsiColor::Green.on(anstyle::AnsiColor::Red), + "world!", + ), + ]; + verify(&input, expected); + } + + #[test] + fn ansi256_colors() { + // termcolor only supports "brights" via these + let input = format!( + "Hello {}!", + "world".color(owo_colors::XtermColors::UserBrightYellow) + ); + let expected = vec![ + (anstyle::Style::default(), "Hello "), + (anstyle::Ansi256Color(11).on_default(), "world"), + (anstyle::Style::default(), "!"), + ]; + verify(&input, expected); + } + + proptest! { + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn wincon_no_escapes(s in "\\PC*") { + let expected = if s.is_empty() { + vec![] + } else { + vec![(anstyle::Style::default(), s.clone())] + }; + let mut state = WinconBytes::new(); + let actual = state.extract_next(s.as_bytes()).collect::>(); + assert_eq!(expected, actual); + } + } +} diff --git a/vendor/anstream/src/auto.rs b/vendor/anstream/src/auto.rs new file mode 100644 index 0000000..7aaac6a --- /dev/null +++ b/vendor/anstream/src/auto.rs @@ -0,0 +1,263 @@ +use crate::stream::AsLockedWrite; +use crate::stream::RawStream; +#[cfg(feature = "auto")] +use crate::ColorChoice; +use crate::StripStream; +#[cfg(all(windows, feature = "wincon"))] +use crate::WinconStream; + +/// [`std::io::Write`] that adapts ANSI escape codes to the underlying `Write`s capabilities +#[derive(Debug)] +pub struct AutoStream { + inner: StreamInner, +} + +#[derive(Debug)] +enum StreamInner { + PassThrough(S), + Strip(StripStream), + #[cfg(all(windows, feature = "wincon"))] + Wincon(WinconStream), +} + +impl AutoStream +where + S: RawStream, +{ + /// Runtime control over styling behavior + #[cfg(feature = "auto")] + #[inline] + pub fn new(raw: S, choice: ColorChoice) -> Self { + match choice { + ColorChoice::Auto => Self::auto(raw), + ColorChoice::AlwaysAnsi => Self::always_ansi(raw), + ColorChoice::Always => Self::always(raw), + ColorChoice::Never => Self::never(raw), + } + } + + /// Auto-adapt for the stream's capabilities + #[cfg(feature = "auto")] + #[inline] + pub fn auto(raw: S) -> Self { + let choice = Self::choice(&raw); + debug_assert_ne!(choice, ColorChoice::Auto); + Self::new(raw, choice) + } + + /// Report the desired choice for the given stream + #[cfg(feature = "auto")] + pub fn choice(raw: &S) -> ColorChoice { + choice(raw) + } + + /// Force ANSI escape codes to be passed through as-is, no matter what the inner `Write` + /// supports. + #[inline] + pub fn always_ansi(raw: S) -> Self { + #[cfg(feature = "auto")] + { + if raw.is_terminal() { + let _ = anstyle_query::windows::enable_ansi_colors(); + } + } + Self::always_ansi_(raw) + } + + #[inline] + fn always_ansi_(raw: S) -> Self { + let inner = StreamInner::PassThrough(raw); + AutoStream { inner } + } + + /// Force color, no matter what the inner `Write` supports. + #[inline] + pub fn always(raw: S) -> Self { + if cfg!(windows) { + #[cfg(feature = "auto")] + let use_wincon = raw.is_terminal() + && !anstyle_query::windows::enable_ansi_colors().unwrap_or(true) + && !anstyle_query::term_supports_ansi_color(); + #[cfg(not(feature = "auto"))] + let use_wincon = true; + if use_wincon { + Self::wincon(raw).unwrap_or_else(|raw| Self::always_ansi_(raw)) + } else { + Self::always_ansi_(raw) + } + } else { + Self::always_ansi(raw) + } + } + + /// Only pass printable data to the inner `Write`. + #[inline] + pub fn never(raw: S) -> Self { + let inner = StreamInner::Strip(StripStream::new(raw)); + AutoStream { inner } + } + + #[inline] + fn wincon(raw: S) -> Result { + #[cfg(all(windows, feature = "wincon"))] + { + Ok(Self { + inner: StreamInner::Wincon(WinconStream::new(raw)), + }) + } + #[cfg(not(all(windows, feature = "wincon")))] + { + Err(raw) + } + } + + /// Get the wrapped [`RawStream`] + #[inline] + pub fn into_inner(self) -> S { + match self.inner { + StreamInner::PassThrough(w) => w, + StreamInner::Strip(w) => w.into_inner(), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => w.into_inner(), + } + } + + #[inline] + pub fn is_terminal(&self) -> bool { + match &self.inner { + StreamInner::PassThrough(w) => w.is_terminal(), + StreamInner::Strip(w) => w.is_terminal(), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(_) => true, // its only ever a terminal + } + } + + /// Prefer [`AutoStream::choice`] + /// + /// This doesn't report what is requested but what is currently active. + #[inline] + #[cfg(feature = "auto")] + pub fn current_choice(&self) -> ColorChoice { + match &self.inner { + StreamInner::PassThrough(_) => ColorChoice::AlwaysAnsi, + StreamInner::Strip(_) => ColorChoice::Never, + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(_) => ColorChoice::Always, + } + } +} + +#[cfg(feature = "auto")] +fn choice(raw: &dyn RawStream) -> ColorChoice { + let choice = ColorChoice::global(); + match choice { + ColorChoice::Auto => { + let clicolor = anstyle_query::clicolor(); + let clicolor_enabled = clicolor.unwrap_or(false); + let clicolor_disabled = !clicolor.unwrap_or(true); + if raw.is_terminal() + && !anstyle_query::no_color() + && !clicolor_disabled + && (anstyle_query::term_supports_color() + || clicolor_enabled + || anstyle_query::is_ci()) + || anstyle_query::clicolor_force() + { + ColorChoice::Always + } else { + ColorChoice::Never + } + } + ColorChoice::AlwaysAnsi | ColorChoice::Always | ColorChoice::Never => choice, + } +} + +impl AutoStream { + /// Get exclusive access to the `AutoStream` + /// + /// Why? + /// - Faster performance when writing in a loop + /// - Avoid other threads interleaving output with the current thread + #[inline] + pub fn lock(self) -> AutoStream> { + let inner = match self.inner { + StreamInner::PassThrough(w) => StreamInner::PassThrough(w.lock()), + StreamInner::Strip(w) => StreamInner::Strip(w.lock()), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => StreamInner::Wincon(w.lock()), + }; + AutoStream { inner } + } +} + +impl AutoStream { + /// Get exclusive access to the `AutoStream` + /// + /// Why? + /// - Faster performance when writing in a loop + /// - Avoid other threads interleaving output with the current thread + #[inline] + pub fn lock(self) -> AutoStream> { + let inner = match self.inner { + StreamInner::PassThrough(w) => StreamInner::PassThrough(w.lock()), + StreamInner::Strip(w) => StreamInner::Strip(w.lock()), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => StreamInner::Wincon(w.lock()), + }; + AutoStream { inner } + } +} + +impl std::io::Write for AutoStream +where + S: RawStream + AsLockedWrite, +{ + // Must forward all calls to ensure locking happens appropriately + #[inline] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + match &mut self.inner { + StreamInner::PassThrough(w) => w.as_locked_write().write(buf), + StreamInner::Strip(w) => w.write(buf), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => w.write(buf), + } + } + #[inline] + fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { + match &mut self.inner { + StreamInner::PassThrough(w) => w.as_locked_write().write_vectored(bufs), + StreamInner::Strip(w) => w.write_vectored(bufs), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => w.write_vectored(bufs), + } + } + // is_write_vectored: nightly only + #[inline] + fn flush(&mut self) -> std::io::Result<()> { + match &mut self.inner { + StreamInner::PassThrough(w) => w.as_locked_write().flush(), + StreamInner::Strip(w) => w.flush(), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => w.flush(), + } + } + #[inline] + fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> { + match &mut self.inner { + StreamInner::PassThrough(w) => w.as_locked_write().write_all(buf), + StreamInner::Strip(w) => w.write_all(buf), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => w.write_all(buf), + } + } + // write_all_vectored: nightly only + #[inline] + fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> { + match &mut self.inner { + StreamInner::PassThrough(w) => w.as_locked_write().write_fmt(args), + StreamInner::Strip(w) => w.write_fmt(args), + #[cfg(all(windows, feature = "wincon"))] + StreamInner::Wincon(w) => w.write_fmt(args), + } + } +} diff --git a/vendor/anstream/src/buffer.rs b/vendor/anstream/src/buffer.rs new file mode 100644 index 0000000..9846bb7 --- /dev/null +++ b/vendor/anstream/src/buffer.rs @@ -0,0 +1,68 @@ +#![allow(deprecated)] + +/// In-memory [`RawStream`][crate::stream::RawStream] +#[derive(Clone, Default, Debug, PartialEq, Eq)] +#[deprecated(since = "0.6.2", note = "Use Vec")] +#[doc(hidden)] +pub struct Buffer(Vec); + +impl Buffer { + #[inline] + pub fn new() -> Self { + Default::default() + } + + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Self(Vec::with_capacity(capacity)) + } + + #[inline] + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } +} + +impl AsRef<[u8]> for Buffer { + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + +impl std::io::Write for Buffer { + #[inline] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.extend(buf); + Ok(buf.len()) + } + + #[inline] + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[cfg(all(windows, feature = "wincon"))] +impl anstyle_wincon::WinconStream for Buffer { + fn write_colored( + &mut self, + fg: Option, + bg: Option, + data: &[u8], + ) -> std::io::Result { + self.0.write_colored(fg, bg, data) + } +} + +#[cfg(all(windows, feature = "wincon"))] +impl anstyle_wincon::WinconStream for &'_ mut Buffer { + fn write_colored( + &mut self, + fg: Option, + bg: Option, + data: &[u8], + ) -> std::io::Result { + (**self).write_colored(fg, bg, data) + } +} diff --git a/vendor/anstream/src/fmt.rs b/vendor/anstream/src/fmt.rs new file mode 100644 index 0000000..e673c26 --- /dev/null +++ b/vendor/anstream/src/fmt.rs @@ -0,0 +1,54 @@ +/// A shim which allows a [`std::io::Write`] to be implemented in terms of a [`std::fmt::Write`] +/// +/// This saves off I/O errors. instead of discarding them +pub(crate) struct Adapter +where + W: FnMut(&[u8]) -> std::io::Result<()>, +{ + writer: W, + error: std::io::Result<()>, +} + +impl Adapter +where + W: FnMut(&[u8]) -> std::io::Result<()>, +{ + pub(crate) fn new(writer: W) -> Self { + Adapter { + writer, + error: Ok(()), + } + } + + pub(crate) fn write_fmt(mut self, fmt: std::fmt::Arguments<'_>) -> std::io::Result<()> { + match std::fmt::write(&mut self, fmt) { + Ok(()) => Ok(()), + Err(..) => { + // check if the error came from the underlying `Write` or not + if self.error.is_err() { + self.error + } else { + Err(std::io::Error::new( + std::io::ErrorKind::Other, + "formatter error", + )) + } + } + } + } +} + +impl std::fmt::Write for Adapter +where + W: FnMut(&[u8]) -> std::io::Result<()>, +{ + fn write_str(&mut self, s: &str) -> std::fmt::Result { + match (self.writer)(s.as_bytes()) { + Ok(()) => Ok(()), + Err(e) => { + self.error = Err(e); + Err(std::fmt::Error) + } + } + } +} diff --git a/vendor/anstream/src/lib.rs b/vendor/anstream/src/lib.rs new file mode 100644 index 0000000..9721139 --- /dev/null +++ b/vendor/anstream/src/lib.rs @@ -0,0 +1,79 @@ +//! **Auto-adapting [`stdout`] / [`stderr`] streams** +//! +//! *A portmanteau of "ansi stream"* +//! +//! [`AutoStream`] always accepts [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code), +//! adapting to the user's terminal's capabilities. +//! +//! Benefits +//! - Allows the caller to not be concerned with the terminal's capabilities +//! - Semver safe way of passing styled text between crates as ANSI escape codes offer more +//! compatibility than most crate APIs. +//! +//! Available styling crates: +//! - [anstyle](https://docs.rs/anstyle) for minimal runtime styling, designed to go in public APIs +//! (once it hits 1.0) +//! - [owo-colors](https://docs.rs/owo-colors) for feature-rich runtime styling +//! - [color-print](https://docs.rs/color-print) for feature-rich compile-time styling +//! +//! # Example +//! +//! ``` +//! # #[cfg(feature = "auto")] { +//! use anstream::println; +//! use owo_colors::OwoColorize as _; +//! +//! // Foreground colors +//! println!("My number is {:#x}!", 10.green()); +//! // Background colors +//! println!("My number is not {}!", 4.on_red()); +//! # } +//! ``` +//! +//! And this will correctly handle piping to a file, etc + +#![cfg_attr(docsrs, feature(doc_auto_cfg))] + +pub mod adapter; +pub mod stream; + +mod buffer; +#[macro_use] +mod macros; +mod auto; +mod fmt; +mod strip; +#[cfg(all(windows, feature = "wincon"))] +mod wincon; + +pub use auto::AutoStream; +pub use strip::StripStream; +#[cfg(all(windows, feature = "wincon"))] +pub use wincon::WinconStream; + +#[allow(deprecated)] +pub use buffer::Buffer; + +/// Create an ANSI escape code compatible stdout +/// +/// **Note:** Call [`AutoStream::lock`] in loops to avoid the performance hit of acquiring/releasing +/// from the implicit locking in each [`std::io::Write`] call +#[cfg(feature = "auto")] +pub fn stdout() -> AutoStream { + let stdout = std::io::stdout(); + AutoStream::auto(stdout) +} + +/// Create an ANSI escape code compatible stderr +/// +/// **Note:** Call [`AutoStream::lock`] in loops to avoid the performance hit of acquiring/releasing +/// from the implicit locking in each [`std::io::Write`] call +#[cfg(feature = "auto")] +pub fn stderr() -> AutoStream { + let stderr = std::io::stderr(); + AutoStream::auto(stderr) +} + +/// Selection for overriding color output +#[cfg(feature = "auto")] +pub use colorchoice::ColorChoice; diff --git a/vendor/anstream/src/macros.rs b/vendor/anstream/src/macros.rs new file mode 100644 index 0000000..bd1accb --- /dev/null +++ b/vendor/anstream/src/macros.rs @@ -0,0 +1,389 @@ +/// Prints to [`stdout`][crate::stdout]. +/// +/// Equivalent to the [`println!`] macro except that a newline is not printed at +/// the end of the message. +/// +/// Note that stdout is frequently line-buffered by default so it may be +/// necessary to use [`std::io::Write::flush()`] to ensure the output is emitted +/// immediately. +/// +/// **NOTE:** The `print!` macro will lock the standard output on each call. If you call +/// `print!` within a hot loop, this behavior may be the bottleneck of the loop. +/// To avoid this, lock stdout with [`AutoStream::lock`][crate::AutoStream::lock]: +/// ``` +/// # #[cfg(feature = "auto")] { +/// use std::io::Write as _; +/// +/// let mut lock = anstream::stdout().lock(); +/// write!(lock, "hello world").unwrap(); +/// # } +/// ``` +/// +/// Use `print!` only for the primary output of your program. Use +/// [`eprint!`] instead to print error and progress messages. +/// +/// **NOTE:** Not all `print!` calls will be captured in tests like [`std::print!`] +/// - Capturing will automatically be activated in test binaries +/// - Otherwise, only when the `test` feature is enabled +/// +/// # Panics +/// +/// Panics if writing to `stdout` fails for any reason **except** broken pipe. +/// +/// Writing to non-blocking stdout can cause an error, which will lead +/// this macro to panic. +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "auto")] { +/// use std::io::Write as _; +/// use anstream::print; +/// use anstream::stdout; +/// +/// print!("this "); +/// print!("will "); +/// print!("be "); +/// print!("on "); +/// print!("the "); +/// print!("same "); +/// print!("line "); +/// +/// stdout().flush().unwrap(); +/// +/// print!("this string has a newline, why not choose println! instead?\n"); +/// +/// stdout().flush().unwrap(); +/// # } +/// ``` +#[cfg(feature = "auto")] +#[macro_export] +macro_rules! print { + ($($arg:tt)*) => {{ + if cfg!(any(feature = "test", test)) { + use std::io::Write as _; + + let stdio = std::io::stdout(); + let choice = $crate::AutoStream::choice(&stdio); + let buffer = Vec::new(); + let mut stream = $crate::AutoStream::new(buffer, choice); + // Ignore errors rather than panic + let _ = ::std::write!(&mut stream, $($arg)*); + let buffer = stream.into_inner(); + // Should be UTF-8 but not wanting to panic + let buffer = String::from_utf8_lossy(&buffer); + ::std::print!("{}", buffer) + } else { + use std::io::Write as _; + + let mut stream = $crate::stdout(); + match ::std::write!(&mut stream, $($arg)*) { + Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => { + ::std::panic!("failed printing to stdout: {e}"); + } + Err(_) | Ok(_) => {} + } + } + }}; +} + +/// Prints to [`stdout`][crate::stdout], with a newline. +/// +/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone +/// (no additional CARRIAGE RETURN (`\r`/`U+000D`)). +/// +/// This macro uses the same syntax as [`format!`], but writes to the standard output instead. +/// See [`std::fmt`] for more information. +/// +/// **NOTE:** The `println!` macro will lock the standard output on each call. If you call +/// `println!` within a hot loop, this behavior may be the bottleneck of the loop. +/// To avoid this, lock stdout with [`AutoStream::lock`][crate::AutoStream::lock]: +/// ``` +/// # #[cfg(feature = "auto")] { +/// use std::io::Write as _; +/// +/// let mut lock = anstream::stdout().lock(); +/// writeln!(lock, "hello world").unwrap(); +/// # } +/// ``` +/// +/// Use `println!` only for the primary output of your program. Use +/// [`eprintln!`] instead to print error and progress messages. +/// +/// **NOTE:** Not all `println!` calls will be captured in tests like [`std::println!`] +/// - Capturing will automatically be activated in test binaries +/// - Otherwise, only when the `test` feature is enabled +/// +/// # Panics +/// +/// Panics if writing to `stdout` fails for any reason **except** broken pipe. +/// +/// Writing to non-blocking stdout can cause an error, which will lead +/// this macro to panic. +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "auto")] { +/// use anstream::println; +/// +/// println!(); // prints just a newline +/// println!("hello there!"); +/// println!("format {} arguments", "some"); +/// let local_variable = "some"; +/// println!("format {local_variable} arguments"); +/// # } +/// ``` +#[cfg(feature = "auto")] +#[macro_export] +macro_rules! println { + () => { + $crate::print!("\n") + }; + ($($arg:tt)*) => {{ + if cfg!(any(feature = "test", test)) { + use std::io::Write as _; + + let stdio = std::io::stdout(); + let choice = $crate::AutoStream::choice(&stdio); + let buffer = Vec::new(); + let mut stream = $crate::AutoStream::new(buffer, choice); + // Ignore errors rather than panic + let _ = ::std::write!(&mut stream, $($arg)*); + let buffer = stream.into_inner(); + // Should be UTF-8 but not wanting to panic + let buffer = String::from_utf8_lossy(&buffer); + ::std::println!("{}", buffer) + } else { + use std::io::Write as _; + + let mut stream = $crate::stdout(); + match ::std::writeln!(&mut stream, $($arg)*) { + Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => { + ::std::panic!("failed printing to stdout: {e}"); + } + Err(_) | Ok(_) => {} + } + } + }}; +} + +/// Prints to [`stderr`][crate::stderr]. +/// +/// Equivalent to the [`print!`] macro, except that output goes to +/// `stderr` instead of `stdout`. See [`print!`] for +/// example usage. +/// +/// Use `eprint!` only for error and progress messages. Use `print!` +/// instead for the primary output of your program. +/// +/// **NOTE:** Not all `eprint!` calls will be captured in tests like [`std::eprint!`] +/// - Capturing will automatically be activated in test binaries +/// - Otherwise, only when the `test` feature is enabled +/// +/// # Panics +/// +/// Panics if writing to `stderr` fails for any reason **except** broken pipe. +/// +/// Writing to non-blocking stdout can cause an error, which will lead +/// this macro to panic. +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "auto")] { +/// use anstream::eprint; +/// +/// eprint!("Error: Could not complete task"); +/// # } +/// ``` +#[cfg(feature = "auto")] +#[macro_export] +macro_rules! eprint { + ($($arg:tt)*) => {{ + if cfg!(any(feature = "test", test)) { + use std::io::Write as _; + + let stdio = std::io::stderr(); + let choice = $crate::AutoStream::choice(&stdio); + let buffer = Vec::new(); + let mut stream = $crate::AutoStream::new(buffer, choice); + // Ignore errors rather than panic + let _ = ::std::write!(&mut stream, $($arg)*); + let buffer = stream.into_inner(); + // Should be UTF-8 but not wanting to panic + let buffer = String::from_utf8_lossy(&buffer); + ::std::eprint!("{}", buffer) + } else { + use std::io::Write as _; + + let mut stream = $crate::stderr(); + match ::std::write!(&mut stream, $($arg)*) { + Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => { + ::std::panic!("failed printing to stdout: {e}"); + } + Err(_) | Ok(_) => {} + } + } + }}; +} + +/// Prints to [`stderr`][crate::stderr], with a newline. +/// +/// Equivalent to the [`println!`] macro, except that output goes to +/// `stderr` instead of `stdout`. See [`println!`] for +/// example usage. +/// +/// Use `eprintln!` only for error and progress messages. Use `println!` +/// instead for the primary output of your program. +/// +/// **NOTE:** Not all `eprintln!` calls will be captured in tests like [`std::eprintln!`] +/// - Capturing will automatically be activated in test binaries +/// - Otherwise, only when the `test` feature is enabled +/// +/// # Panics +/// +/// Panics if writing to `stderr` fails for any reason **except** broken pipe. +/// +/// Writing to non-blocking stdout can cause an error, which will lead +/// this macro to panic. +/// +/// # Examples +/// +/// ``` +/// # #[cfg(feature = "auto")] { +/// use anstream::eprintln; +/// +/// eprintln!("Error: Could not complete task"); +/// # } +/// ``` +#[cfg(feature = "auto")] +#[macro_export] +macro_rules! eprintln { + () => { + $crate::eprint!("\n") + }; + ($($arg:tt)*) => {{ + if cfg!(any(feature = "test", test)) { + use std::io::Write as _; + + let stdio = std::io::stderr(); + let choice = $crate::AutoStream::choice(&stdio); + let buffer = Vec::new(); + let mut stream = $crate::AutoStream::new(buffer, choice); + // Ignore errors rather than panic + let _ = ::std::write!(&mut stream, $($arg)*); + let buffer = stream.into_inner(); + // Should be UTF-8 but not wanting to panic + let buffer = String::from_utf8_lossy(&buffer); + ::std::eprintln!("{}", buffer) + } else { + use std::io::Write as _; + + let mut stream = $crate::stderr(); + match ::std::writeln!(&mut stream, $($arg)*) { + Err(e) if e.kind() != ::std::io::ErrorKind::BrokenPipe => { + ::std::panic!("failed printing to stdout: {e}"); + } + Err(_) | Ok(_) => {} + } + } + }}; +} + +/// Panics the current thread. +/// +/// This allows a program to terminate immediately and provide feedback +/// to the caller of the program. +/// +/// This macro is the perfect way to assert conditions in example code and in +/// tests. `panic!` is closely tied with the `unwrap` method of both +/// [`Option`][ounwrap] and [`Result`][runwrap] enums. Both implementations call +/// `panic!` when they are set to [`None`] or [`Err`] variants. +/// +/// When using `panic!()` you can specify a string payload, that is built using +/// the [`format!`] syntax. That payload is used when injecting the panic into +/// the calling Rust thread, causing the thread to panic entirely. +/// +/// The behavior of the default `std` hook, i.e. the code that runs directly +/// after the panic is invoked, is to print the message payload to +/// `stderr` along with the file/line/column information of the `panic!()` +/// call. You can override the panic hook using [`std::panic::set_hook()`]. +/// Inside the hook a panic can be accessed as a `&dyn Any + Send`, +/// which contains either a `&str` or `String` for regular `panic!()` invocations. +/// To panic with a value of another other type, [`panic_any`] can be used. +/// +/// See also the macro [`compile_error!`], for raising errors during compilation. +/// +/// # When to use `panic!` vs `Result` +/// +/// The Rust language provides two complementary systems for constructing / +/// representing, reporting, propagating, reacting to, and discarding errors. These +/// responsibilities are collectively known as "error handling." `panic!` and +/// `Result` are similar in that they are each the primary interface of their +/// respective error handling systems; however, the meaning these interfaces attach +/// to their errors and the responsibilities they fulfill within their respective +/// error handling systems differ. +/// +/// The `panic!` macro is used to construct errors that represent a bug that has +/// been detected in your program. With `panic!` you provide a message that +/// describes the bug and the language then constructs an error with that message, +/// reports it, and propagates it for you. +/// +/// `Result` on the other hand is used to wrap other types that represent either +/// the successful result of some computation, `Ok(T)`, or error types that +/// represent an anticipated runtime failure mode of that computation, `Err(E)`. +/// `Result` is used alongside user defined types which represent the various +/// anticipated runtime failure modes that the associated computation could +/// encounter. `Result` must be propagated manually, often with the the help of the +/// `?` operator and `Try` trait, and they must be reported manually, often with +/// the help of the `Error` trait. +/// +/// For more detailed information about error handling check out the [book] or the +/// [`std::result`] module docs. +/// +/// [ounwrap]: Option::unwrap +/// [runwrap]: Result::unwrap +/// [`std::panic::set_hook()`]: ../std/panic/fn.set_hook.html +/// [`panic_any`]: ../std/panic/fn.panic_any.html +/// [`Box`]: ../std/boxed/struct.Box.html +/// [`Any`]: crate::any::Any +/// [`format!`]: ../std/macro.format.html +/// [book]: ../book/ch09-00-error-handling.html +/// [`std::result`]: ../std/result/index.html +/// +/// # Current implementation +/// +/// If the main thread panics it will terminate all your threads and end your +/// program with code `101`. +/// +/// # Examples +/// +/// ```should_panic +/// # #![allow(unreachable_code)] +/// use anstream::panic; +/// panic!(); +/// panic!("this is a terrible mistake!"); +/// panic!("this is a {} {message}", "fancy", message = "message"); +/// ``` +#[cfg(feature = "auto")] +#[macro_export] +macro_rules! panic { + () => { + ::std::panic!() + }; + ($($arg:tt)*) => {{ + use std::io::Write as _; + + let panic_stream = std::io::stderr(); + let choice = $crate::AutoStream::choice(&panic_stream); + let buffer = Vec::new(); + let mut stream = $crate::AutoStream::new(buffer, choice); + // Ignore errors rather than panic + let _ = ::std::write!(&mut stream, $($arg)*); + let buffer = stream.into_inner(); + // Should be UTF-8 but not wanting to panic + let buffer = String::from_utf8_lossy(&buffer).into_owned(); + ::std::panic!("{}", buffer) + }}; +} diff --git a/vendor/anstream/src/stream.rs b/vendor/anstream/src/stream.rs new file mode 100644 index 0000000..e2f7e68 --- /dev/null +++ b/vendor/anstream/src/stream.rs @@ -0,0 +1,261 @@ +//! Higher-level traits to describe writeable streams + +/// Required functionality for underlying [`std::io::Write`] for adaptation +#[cfg(not(all(windows, feature = "wincon")))] +pub trait RawStream: std::io::Write + IsTerminal + private::Sealed {} + +/// Required functionality for underlying [`std::io::Write`] for adaptation +#[cfg(all(windows, feature = "wincon"))] +pub trait RawStream: + std::io::Write + IsTerminal + anstyle_wincon::WinconStream + private::Sealed +{ +} + +impl RawStream for std::io::Stdout {} + +impl RawStream for std::io::StdoutLock<'_> {} + +impl RawStream for &'_ mut std::io::StdoutLock<'_> {} + +impl RawStream for std::io::Stderr {} + +impl RawStream for std::io::StderrLock<'_> {} + +impl RawStream for &'_ mut std::io::StderrLock<'_> {} + +impl RawStream for Box {} + +impl RawStream for &'_ mut Box {} + +impl RawStream for Vec {} + +impl RawStream for &'_ mut Vec {} + +impl RawStream for std::fs::File {} + +impl RawStream for &'_ mut std::fs::File {} + +#[allow(deprecated)] +impl RawStream for crate::Buffer {} + +#[allow(deprecated)] +impl RawStream for &'_ mut crate::Buffer {} + +pub trait IsTerminal: private::Sealed { + fn is_terminal(&self) -> bool; +} + +impl IsTerminal for std::io::Stdout { + #[inline] + fn is_terminal(&self) -> bool { + std::io::IsTerminal::is_terminal(self) + } +} + +impl IsTerminal for std::io::StdoutLock<'_> { + #[inline] + fn is_terminal(&self) -> bool { + std::io::IsTerminal::is_terminal(self) + } +} + +impl IsTerminal for &'_ mut std::io::StdoutLock<'_> { + #[inline] + fn is_terminal(&self) -> bool { + (**self).is_terminal() + } +} + +impl IsTerminal for std::io::Stderr { + #[inline] + fn is_terminal(&self) -> bool { + std::io::IsTerminal::is_terminal(self) + } +} + +impl IsTerminal for std::io::StderrLock<'_> { + #[inline] + fn is_terminal(&self) -> bool { + std::io::IsTerminal::is_terminal(self) + } +} + +impl IsTerminal for &'_ mut std::io::StderrLock<'_> { + #[inline] + fn is_terminal(&self) -> bool { + (**self).is_terminal() + } +} + +impl IsTerminal for Box { + #[inline] + fn is_terminal(&self) -> bool { + false + } +} + +impl IsTerminal for &'_ mut Box { + #[inline] + fn is_terminal(&self) -> bool { + false + } +} + +impl IsTerminal for Vec { + #[inline] + fn is_terminal(&self) -> bool { + false + } +} + +impl IsTerminal for &'_ mut Vec { + #[inline] + fn is_terminal(&self) -> bool { + false + } +} + +impl IsTerminal for std::fs::File { + #[inline] + fn is_terminal(&self) -> bool { + std::io::IsTerminal::is_terminal(self) + } +} + +impl IsTerminal for &'_ mut std::fs::File { + #[inline] + fn is_terminal(&self) -> bool { + (**self).is_terminal() + } +} + +#[allow(deprecated)] +impl IsTerminal for crate::Buffer { + #[inline] + fn is_terminal(&self) -> bool { + false + } +} + +#[allow(deprecated)] +impl IsTerminal for &'_ mut crate::Buffer { + #[inline] + fn is_terminal(&self) -> bool { + (**self).is_terminal() + } +} + +pub trait AsLockedWrite: private::Sealed { + type Write<'w>: RawStream + 'w + where + Self: 'w; + + fn as_locked_write(&mut self) -> Self::Write<'_>; +} + +impl AsLockedWrite for std::io::Stdout { + type Write<'w> = std::io::StdoutLock<'w>; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self.lock() + } +} + +impl AsLockedWrite for std::io::StdoutLock<'static> { + type Write<'w> = &'w mut Self; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self + } +} + +impl AsLockedWrite for std::io::Stderr { + type Write<'w> = std::io::StderrLock<'w>; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self.lock() + } +} + +impl AsLockedWrite for std::io::StderrLock<'static> { + type Write<'w> = &'w mut Self; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self + } +} + +impl AsLockedWrite for Box { + type Write<'w> = &'w mut Self; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self + } +} + +impl AsLockedWrite for Vec { + type Write<'w> = &'w mut Self; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self + } +} + +impl AsLockedWrite for std::fs::File { + type Write<'w> = &'w mut Self; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self + } +} + +#[allow(deprecated)] +impl AsLockedWrite for crate::Buffer { + type Write<'w> = &'w mut Self; + + #[inline] + fn as_locked_write(&mut self) -> Self::Write<'_> { + self + } +} + +mod private { + pub trait Sealed {} + + impl Sealed for std::io::Stdout {} + + impl Sealed for std::io::StdoutLock<'_> {} + + impl Sealed for &'_ mut std::io::StdoutLock<'_> {} + + impl Sealed for std::io::Stderr {} + + impl Sealed for std::io::StderrLock<'_> {} + + impl Sealed for &'_ mut std::io::StderrLock<'_> {} + + impl Sealed for Box {} + + impl Sealed for &'_ mut Box {} + + impl Sealed for Vec {} + + impl Sealed for &'_ mut Vec {} + + impl Sealed for std::fs::File {} + + impl Sealed for &'_ mut std::fs::File {} + + #[allow(deprecated)] + impl Sealed for crate::Buffer {} + + #[allow(deprecated)] + impl Sealed for &'_ mut crate::Buffer {} +} diff --git a/vendor/anstream/src/strip.rs b/vendor/anstream/src/strip.rs new file mode 100644 index 0000000..d7fda04 --- /dev/null +++ b/vendor/anstream/src/strip.rs @@ -0,0 +1,219 @@ +use crate::adapter::StripBytes; +use crate::stream::AsLockedWrite; +use crate::stream::RawStream; + +/// Only pass printable data to the inner `Write` +#[derive(Debug)] +pub struct StripStream +where + S: RawStream, +{ + raw: S, + state: StripBytes, +} + +impl StripStream +where + S: RawStream, +{ + /// Only pass printable data to the inner `Write` + #[inline] + pub fn new(raw: S) -> Self { + Self { + raw, + state: Default::default(), + } + } + + /// Get the wrapped [`RawStream`] + #[inline] + pub fn into_inner(self) -> S { + self.raw + } + + #[inline] + pub fn is_terminal(&self) -> bool { + self.raw.is_terminal() + } +} + +impl StripStream { + /// Get exclusive access to the `StripStream` + /// + /// Why? + /// - Faster performance when writing in a loop + /// - Avoid other threads interleaving output with the current thread + #[inline] + pub fn lock(self) -> StripStream> { + StripStream { + raw: self.raw.lock(), + state: self.state, + } + } +} + +impl StripStream { + /// Get exclusive access to the `StripStream` + /// + /// Why? + /// - Faster performance when writing in a loop + /// - Avoid other threads interleaving output with the current thread + #[inline] + pub fn lock(self) -> StripStream> { + StripStream { + raw: self.raw.lock(), + state: self.state, + } + } +} + +impl std::io::Write for StripStream +where + S: RawStream + AsLockedWrite, +{ + // Must forward all calls to ensure locking happens appropriately + #[inline] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + write(&mut self.raw.as_locked_write(), &mut self.state, buf) + } + #[inline] + fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { + let buf = bufs + .iter() + .find(|b| !b.is_empty()) + .map(|b| &**b) + .unwrap_or(&[][..]); + self.write(buf) + } + // is_write_vectored: nightly only + #[inline] + fn flush(&mut self) -> std::io::Result<()> { + self.raw.as_locked_write().flush() + } + #[inline] + fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> { + write_all(&mut self.raw.as_locked_write(), &mut self.state, buf) + } + // write_all_vectored: nightly only + #[inline] + fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> { + write_fmt(&mut self.raw.as_locked_write(), &mut self.state, args) + } +} + +fn write( + raw: &mut dyn std::io::Write, + state: &mut StripBytes, + buf: &[u8], +) -> std::io::Result { + let initial_state = state.clone(); + + for printable in state.strip_next(buf) { + let possible = printable.len(); + let written = raw.write(printable)?; + if possible != written { + let divergence = &printable[written..]; + let offset = offset_to(buf, divergence); + let consumed = &buf[offset..]; + *state = initial_state; + state.strip_next(consumed).last(); + return Ok(offset); + } + } + Ok(buf.len()) +} + +fn write_all( + raw: &mut dyn std::io::Write, + state: &mut StripBytes, + buf: &[u8], +) -> std::io::Result<()> { + for printable in state.strip_next(buf) { + raw.write_all(printable)?; + } + Ok(()) +} + +fn write_fmt( + raw: &mut dyn std::io::Write, + state: &mut StripBytes, + args: std::fmt::Arguments<'_>, +) -> std::io::Result<()> { + let write_all = |buf: &[u8]| write_all(raw, state, buf); + crate::fmt::Adapter::new(write_all).write_fmt(args) +} + +#[inline] +fn offset_to(total: &[u8], subslice: &[u8]) -> usize { + let total = total.as_ptr(); + let subslice = subslice.as_ptr(); + + debug_assert!( + total <= subslice, + "`Offset::offset_to` only accepts slices of `self`" + ); + subslice as usize - total as usize +} + +#[cfg(test)] +mod test { + use super::*; + use proptest::prelude::*; + use std::io::Write as _; + + proptest! { + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_all_no_escapes(s in "\\PC*") { + let buffer = Vec::new(); + let mut stream = StripStream::new(buffer); + stream.write_all(s.as_bytes()).unwrap(); + let buffer = stream.into_inner(); + let actual = std::str::from_utf8(buffer.as_ref()).unwrap(); + assert_eq!(s, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_byte_no_escapes(s in "\\PC*") { + let buffer = Vec::new(); + let mut stream = StripStream::new(buffer); + for byte in s.as_bytes() { + stream.write_all(&[*byte]).unwrap(); + } + let buffer = stream.into_inner(); + let actual = std::str::from_utf8(buffer.as_ref()).unwrap(); + assert_eq!(s, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_all_random(s in any::>()) { + let buffer = Vec::new(); + let mut stream = StripStream::new(buffer); + stream.write_all(s.as_slice()).unwrap(); + let buffer = stream.into_inner(); + if let Ok(actual) = std::str::from_utf8(buffer.as_ref()) { + for char in actual.chars() { + assert!(!char.is_ascii() || !char.is_control() || char.is_ascii_whitespace(), "{:?} -> {:?}: {:?}", String::from_utf8_lossy(&s), actual, char); + } + } + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_byte_random(s in any::>()) { + let buffer = Vec::new(); + let mut stream = StripStream::new(buffer); + for byte in s.as_slice() { + stream.write_all(&[*byte]).unwrap(); + } + let buffer = stream.into_inner(); + if let Ok(actual) = std::str::from_utf8(buffer.as_ref()) { + for char in actual.chars() { + assert!(!char.is_ascii() || !char.is_control() || char.is_ascii_whitespace(), "{:?} -> {:?}: {:?}", String::from_utf8_lossy(&s), actual, char); + } + } + } + } +} diff --git a/vendor/anstream/src/wincon.rs b/vendor/anstream/src/wincon.rs new file mode 100644 index 0000000..a5aa5e7 --- /dev/null +++ b/vendor/anstream/src/wincon.rs @@ -0,0 +1,210 @@ +use crate::adapter::WinconBytes; +use crate::stream::AsLockedWrite; +use crate::stream::RawStream; + +/// Only pass printable data to the inner `Write` +#[cfg(feature = "wincon")] // here mostly for documentation purposes +#[derive(Debug)] +pub struct WinconStream +where + S: RawStream, +{ + raw: S, + // `WinconBytes` is especially large compared to other variants of `AutoStream`, so boxing it + // here so `AutoStream` doesn't have to discard one allocation and create another one when + // calling `AutoStream::lock` + state: Box, +} + +impl WinconStream +where + S: RawStream, +{ + /// Only pass printable data to the inner `Write` + #[inline] + pub fn new(raw: S) -> Self { + Self { + raw, + state: Default::default(), + } + } + + /// Get the wrapped [`RawStream`] + #[inline] + pub fn into_inner(self) -> S { + self.raw + } + + #[inline] + pub fn is_terminal(&self) -> bool { + self.raw.is_terminal() + } +} + +impl WinconStream { + /// Get exclusive access to the `WinconStream` + /// + /// Why? + /// - Faster performance when writing in a loop + /// - Avoid other threads interleaving output with the current thread + #[inline] + pub fn lock(self) -> WinconStream> { + WinconStream { + raw: self.raw.lock(), + state: self.state, + } + } +} + +impl WinconStream { + /// Get exclusive access to the `WinconStream` + /// + /// Why? + /// - Faster performance when writing in a loop + /// - Avoid other threads interleaving output with the current thread + #[inline] + pub fn lock(self) -> WinconStream> { + WinconStream { + raw: self.raw.lock(), + state: self.state, + } + } +} + +impl std::io::Write for WinconStream +where + S: RawStream + AsLockedWrite, +{ + // Must forward all calls to ensure locking happens appropriately + #[inline] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + write(&mut self.raw.as_locked_write(), &mut self.state, buf) + } + #[inline] + fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { + let buf = bufs + .iter() + .find(|b| !b.is_empty()) + .map(|b| &**b) + .unwrap_or(&[][..]); + self.write(buf) + } + // is_write_vectored: nightly only + #[inline] + fn flush(&mut self) -> std::io::Result<()> { + self.raw.as_locked_write().flush() + } + #[inline] + fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> { + write_all(&mut self.raw.as_locked_write(), &mut self.state, buf) + } + // write_all_vectored: nightly only + #[inline] + fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) -> std::io::Result<()> { + write_fmt(&mut self.raw.as_locked_write(), &mut self.state, args) + } +} + +fn write(raw: &mut dyn RawStream, state: &mut WinconBytes, buf: &[u8]) -> std::io::Result { + for (style, printable) in state.extract_next(buf) { + let fg = style.get_fg_color().and_then(cap_wincon_color); + let bg = style.get_bg_color().and_then(cap_wincon_color); + let written = raw.write_colored(fg, bg, printable.as_bytes())?; + let possible = printable.len(); + if possible != written { + // HACK: Unsupported atm + break; + } + } + Ok(buf.len()) +} + +fn write_all(raw: &mut dyn RawStream, state: &mut WinconBytes, buf: &[u8]) -> std::io::Result<()> { + for (style, printable) in state.extract_next(buf) { + let mut buf = printable.as_bytes(); + let fg = style.get_fg_color().and_then(cap_wincon_color); + let bg = style.get_bg_color().and_then(cap_wincon_color); + while !buf.is_empty() { + match raw.write_colored(fg, bg, buf) { + Ok(0) => { + return Err(std::io::Error::new( + std::io::ErrorKind::WriteZero, + "failed to write whole buffer", + )); + } + Ok(n) => buf = &buf[n..], + Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + } + Ok(()) +} + +fn write_fmt( + raw: &mut dyn RawStream, + state: &mut WinconBytes, + args: std::fmt::Arguments<'_>, +) -> std::io::Result<()> { + let write_all = |buf: &[u8]| write_all(raw, state, buf); + crate::fmt::Adapter::new(write_all).write_fmt(args) +} + +fn cap_wincon_color(color: anstyle::Color) -> Option { + match color { + anstyle::Color::Ansi(c) => Some(c), + anstyle::Color::Ansi256(c) => c.into_ansi(), + anstyle::Color::Rgb(_) => None, + } +} + +#[cfg(test)] +mod test { + use super::*; + use proptest::prelude::*; + use std::io::Write as _; + + proptest! { + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_all_no_escapes(s in "\\PC*") { + let buffer = Vec::new(); + let mut stream = WinconStream::new(buffer); + stream.write_all(s.as_bytes()).unwrap(); + let buffer = stream.into_inner(); + let actual = std::str::from_utf8(buffer.as_ref()).unwrap(); + assert_eq!(s, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_byte_no_escapes(s in "\\PC*") { + let buffer = Vec::new(); + let mut stream = WinconStream::new(buffer); + for byte in s.as_bytes() { + stream.write_all(&[*byte]).unwrap(); + } + let buffer = stream.into_inner(); + let actual = std::str::from_utf8(buffer.as_ref()).unwrap(); + assert_eq!(s, actual); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_all_random(s in any::>()) { + let buffer = Vec::new(); + let mut stream = WinconStream::new(buffer); + stream.write_all(s.as_slice()).unwrap(); + } + + #[test] + #[cfg_attr(miri, ignore)] // See https://github.com/AltSysrq/proptest/issues/253 + fn write_byte_random(s in any::>()) { + let buffer = Vec::new(); + let mut stream = WinconStream::new(buffer); + for byte in s.as_slice() { + stream.write_all(&[*byte]).unwrap(); + } + } + } +} -- cgit v1.2.3