use std::{borrow::Cow, ffi::OsStr, io};
use tokio::io::{AsyncRead, AsyncReadExt};
#[cfg(windows)]
mod windows;
pub fn os_text(value: &OsStr) -> Cow<'_, str> {
value.to_string_lossy()
}
pub fn os_unicode(value: &OsStr) -> Option<&str> {
value.to_str()
}
pub fn output_text(bytes: &[u8]) -> Cow<'_, str> {
Encoding::detect(bytes).decode(bytes)
}
#[derive(Clone, Copy)]
enum Encoding {
Bytes,
#[cfg(windows)]
Wide(windows::Endian),
}
impl Encoding {
#[cfg(unix)]
fn detect(_: &[u8]) -> Self {
Self::Bytes
}
#[cfg(windows)]
fn detect(bytes: &[u8]) -> Self {
windows::wide_encoding(bytes).map_or(Self::Bytes, Self::Wide)
}
#[cfg(unix)]
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
String::from_utf8_lossy(bytes)
}
#[cfg(windows)]
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
let text = match self {
Self::Bytes => windows::byte_text(bytes),
Self::Wide(order) => Cow::Owned(order.decode(bytes)),
};
if text.contains("\r\n") {
Cow::Owned(text.replace("\r\n", "\n"))
} else {
text
}
}
fn ends_line(self, bytes: &[u8]) -> bool {
match self {
Self::Bytes => bytes.ends_with(b"\n"),
#[cfg(windows)]
Self::Wide(order) => order.ends_line(bytes),
}
}
#[cfg(unix)]
fn probe(_: &[u8]) -> Option<Self> {
Some(Self::Bytes)
}
#[cfg(windows)]
fn probe(prefix: &[u8]) -> Option<Self> {
match Self::detect(prefix) {
wide @ Self::Wide(_) => Some(wide),
Self::Bytes if prefix.ends_with(b"\n") || prefix.len() >= windows::ENCODING_PREFIX => {
Some(Self::Bytes)
}
Self::Bytes => None,
}
}
}
pub struct ProgramLines<R> {
reader: R,
limit: usize,
line: Vec<u8>,
encoding: Option<Encoding>,
}
#[derive(Debug, thiserror::Error)]
pub enum ProgramLineError {
#[error("Cannot read program output: {0}")]
Read(#[from] io::Error),
#[error("Program output line exceeds the byte limit")]
TooLong,
}
impl<R: AsyncRead + Unpin> ProgramLines<R> {
pub fn new(reader: R, limit: usize) -> Self {
Self {
reader,
limit,
line: Vec::new(),
encoding: None,
}
}
pub fn into_inner(self) -> R {
self.reader
}
pub async fn next_line(&mut self) -> Result<Option<String>, ProgramLineError> {
loop {
match self.reader.read_u8().await {
Ok(byte) => {
if self.line.len() == self.limit {
return Err(ProgramLineError::TooLong);
}
self.line.push(byte);
let encoding = self.encoding.or_else(|| Encoding::probe(&self.line));
self.encoding = encoding;
if encoding.is_some_and(|encoding| encoding.ends_line(&self.line)) {
break;
}
}
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
Err(error) => return Err(error.into()),
}
}
if self.line.is_empty() {
return Ok(None);
}
let encoding = self
.encoding
.unwrap_or_else(|| Encoding::detect(&self.line));
let text = encoding.decode(&self.line).into_owned();
self.line.clear();
Ok(Some(text))
}
}
#[cfg(test)]
mod tests;