use std::io::Read;
#[cfg(doc)]
use super::config::compile_inputs;
#[cfg(doc)]
use super::out_paths::resolve_output_path_for_kind;
use crate::output::WriteTarget;
use crate::write::{write_compiled, Inputs};
use mds::{MdsError, MAX_FILE_SIZE};
use miette::Result;
pub(crate) fn read_stdin() -> Result<String, MdsError> {
read_stdin_from(&mut std::io::stdin().lock())
}
fn read_stdin_from(reader: &mut impl Read) -> Result<String, MdsError> {
let bytes = mds::read_at_most(reader, MAX_FILE_SIZE + 1, 0).map_err(|e| MdsError::Io {
message: format!(
"cannot read stdin: {}",
crate::output::safe_inline(crate::output::io_cause(&e))
),
})?;
if bytes.len() as u64 > MAX_FILE_SIZE {
return Err(MdsError::ResourceLimit {
message: "stdin input exceeds maximum size of 10 MiB".to_owned(),
});
}
String::from_utf8(bytes).map_err(|_| MdsError::Io {
message: "cannot read stdin: stream did not contain valid UTF-8".to_owned(),
})
}
pub(crate) fn write_output(
target: Option<&WriteTarget>,
compiled: &str,
inputs: &Inputs,
quiet: bool,
announce: bool,
) -> Result<()> {
match target {
Some(target) => {
write_compiled(target, compiled, inputs)?;
if !quiet && announce {
crate::output::ewriteln!("Compiled to {}", crate::output::safe_path(&target.shown));
}
}
None => crate::output::write_stdout(compiled.as_bytes()).into_batch_result()?,
}
Ok(())
}
#[cfg(test)]
pub(super) mod tests {
use super::super::exit_code;
use super::*;
pub(crate) struct Stream {
left: Option<u64>,
pub(crate) served: u64,
}
impl Stream {
pub(crate) fn sized(len: u64) -> Self {
Self {
left: Some(len),
served: 0,
}
}
fn endless() -> Self {
Self {
left: None,
served: 0,
}
}
}
impl Read for Stream {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = buf.len().min(64 * 1024);
let n = self
.left
.map_or(n, |left| n.min(usize::try_from(left).unwrap_or(n)));
buf[..n].fill(b'x');
if let Some(left) = self.left.as_mut() {
*left -= n as u64;
}
self.served += n as u64;
Ok(n)
}
}
#[test]
fn read_stdin_holds_at_most_the_cap_plus_one_byte() {
let at_cap = read_stdin_from(&mut Stream::sized(MAX_FILE_SIZE)).unwrap();
assert_eq!(
at_cap.len() as u64,
MAX_FILE_SIZE,
"exactly the cap is read"
);
assert!(
at_cap.capacity() as u64 <= MAX_FILE_SIZE + 1,
"capacity {} for {MAX_FILE_SIZE} bytes, over the cap plus one byte",
at_cap.capacity()
);
let over_cap = "resource limit exceeded: stdin input exceeds maximum size of 10 MiB";
let over: miette::Report = read_stdin_from(&mut Stream::sized(MAX_FILE_SIZE + 1))
.unwrap_err()
.into();
assert_eq!(
(exit_code(&over), over.to_string()),
(3, over_cap.to_owned())
);
let mut endless = Stream::endless();
let err: miette::Report = read_stdin_from(&mut endless).unwrap_err().into();
assert_eq!((exit_code(&err), err.to_string()), (3, over_cap.to_owned()));
assert_eq!(endless.served, MAX_FILE_SIZE + 1, "read no further");
let err: miette::Report = read_stdin_from(&mut &b"ok \xff"[..]).unwrap_err().into();
assert_eq!(
(exit_code(&err), err.to_string()),
(
2,
"cannot read stdin: stream did not contain valid UTF-8".to_owned()
)
);
let err: miette::Report = read_stdin_from(&mut Unreadable).unwrap_err().into();
assert_eq!(
(exit_code(&err), err.to_string()),
(
2,
format!("cannot read stdin: {}", std::io::ErrorKind::Other)
),
"the error's kind, not the text it carries (#390)"
);
assert_eq!(read_stdin_from(&mut &b"Hello!\n"[..]).unwrap(), "Hello!\n");
}
struct Unreadable;
impl Read for Unreadable {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("stream broke"))
}
}
}