use std::borrow::Cow;
use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::io::{self, IsTerminal, Read, Write};
use std::path::Path;
use std::process::ExitCode;
use std::time::{Duration, Instant};
use termlens::{Screen, ScreenDiff, Terminal};
const USAGE: &str = "\
usage: termlens <command> [options]
commands:
inspect [options] <program> [args…] run a program in a PTY and print its screen
diff [--color WHEN] [--] <a> <b> compare two saved screens; exit 1 when they differ
render --svg|--html|--ansi|--text|--json [--out PATH] [--] <a> render a saved screen
A saved screen is the snapshot text format termlens prints — what `inspect`
writes to stdout, an insta .snap with or without its header, the block a
wait error prints, a TERMLENS_ARTIFACT_DIR file — or the JSON the crate's
`serde` feature writes. `diff` and `render` read `-` as standard input; only
one of diff's two operands can be, since stdin is read once. Either refuses
a screen in the text format larger than 1 GiB; JSON has no size limit.
Exit code 0: the command ran (diff: the screens are the same picture).
Exit code 1: diff found a difference. Exit code 2: termlens itself could not
run — bad arguments, an unreadable file, a program that could not be spawned.
-h, --help print this text (also after a command)
--version print the version";
const INSPECT_USAGE: &str = "\
usage: termlens inspect [--size COLSxROWS] [--timeout SECONDS] [--idle MILLIS]
[--cwd DIR] [--inherit-env] [--ansi]
[--env KEY=VALUE]... [--] <program> [args…]
Runs <program> in an 80x24 pseudo-terminal (or --size) and prints the
rendered screen. The wait ends on whichever comes first: the program
exits, or, once it has drawn something, its output has been silent for
--idle milliseconds (default 300). --timeout (default 5 seconds) bounds
both, and a program still running when the wait ends is killed.
The child environment is cleared except for PATH, and gets
TERM=xterm-256color and SHELL=/bin/sh; --inherit-env keeps the caller's
environment instead, but for TERM, COLUMNS and LINES, and repeatable
--env sets selected values, those three included.
--cwd runs the program in DIR, which must be an existing directory. A
relative DIR is taken from where inspect runs, and a relative program
path such as ./myapp is then found inside DIR.
--ansi paints the screen in colour on a terminal.
-- ends the options; the program name follows. Options already stop at
the first argument that does not begin with `-`, so this matters only for
a program whose name does. Every option that takes a value also accepts
it attached with `=`, as in --size=100x30 or --env=KEY=VALUE.
What goes to stdout depends on where stdout goes. A terminal gets what
you came to look at: the plain text, or the painted screen with --ansi.
Anything else — a redirect, a pipe — gets a saved screen with its
styles: block, because that is the rendering that carries colour and the
one `termlens diff` and `termlens render` read back. So a redirect never
loses a style, and never writes an escape those two would refuse.
The screen goes to stdout and nothing else does, so `inspect … > file`
saves a screen that `termlens diff` and `termlens render` read back. The
trailer that says what the program did — its exit status, or that it was
still running when the wait ended — goes to stderr. Exit code 2 means inspect
itself could not run: bad arguments, or a program that could not be spawned.";
const DIFF_USAGE: &str = "\
usage: termlens diff [--color auto|always|never] [--] <a> <b>
Either <a> or <b> may be `-`, meaning standard input — not both, since
stdin is read once. -- ends the options, so a file whose name begins with
`-` can follow it; a `-` after it is still standard input. A text-format
input larger than 1 GiB is refused, since no screen in that format is that
large; JSON has no size limit.
Parses two saved screens and prints what changed from <a> to <b>: the rows
that differ side by side, the size and cursor deltas, the style runs before
and after. On a terminal the changed cells are coloured (red in <a>, green
in <b>) unless --color never or NO_COLOR is set; in a pipe the rendering is
the plain one Screen::diff prints in a CI log. Every option that takes a
value also accepts it attached with `=`, as in --color=never.
Exit code 0 when the two are the same picture, 1 when they differ, 2 when
diff itself could not run — bad arguments, or a file that is missing or not
a saved screen.";
const RENDER_USAGE: &str = "\
usage: termlens render (--svg | --html | --ansi | --text | --json) [--out PATH] [--] <a>
Prints a saved screen as an SVG image, an HTML fragment, the screen in ANSI
colour for a terminal, the plain text format with its styles: block, or the
format-1 JSON document the crate's `serde` feature writes.
<a> may be `-`, meaning standard input. -- ends the options, so a file
whose name begins with `-` can follow it; a `-` after it is still standard
input. A text-format input larger than 1 GiB is refused, since no screen in
that format is that large; JSON has no size limit. --out writes to PATH
instead of stdout; `--out -` is standard output, and a file named `-` is
still `./-`.
--out creates nothing when the render fails — unlike a shell redirect,
which truncates the file before termlens runs. Every option that takes a
value also accepts it attached with `=`, as in --out=screen.svg.
Exit code 0: the screen was rendered. Exit code 2: render itself could not
run — bad arguments, a file that is missing or not a saved screen, or an
--out path that cannot be written.";
fn print(out: &str) -> ExitCode {
emit(|stdout| stdout.write_all(out.as_bytes()))
}
fn emit(write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> ExitCode {
let mut stdout = io::BufWriter::new(io::stdout().lock());
match write(&mut stdout).and_then(|()| stdout.flush()) {
Ok(()) => ExitCode::SUCCESS,
Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
Err(e) => fail(&format!("writing the output failed: {e}")),
}
}
fn fail(message: &str) -> ExitCode {
let _ = report(&format!("termlens: {message}"));
ExitCode::from(2)
}
fn report(line: &str) -> io::Result<()> {
let mut stderr = io::stderr().lock();
writeln!(stderr, "{line}").and_then(|()| stderr.flush())
}
fn usage_error(usage: &str) -> ExitCode {
let _ = report(usage);
ExitCode::from(2)
}
fn utf8(arg: OsString) -> Result<String, String> {
arg.into_string()
.map_err(|arg| format!("{arg:?} is not valid UTF-8; termlens's own arguments must be"))
}
fn version() -> String {
format!("termlens {}\n", env!("CARGO_PKG_VERSION"))
}
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let Some(command) = args.next() else {
return usage_error(USAGE);
};
let command = match utf8(command) {
Ok(command) => command,
Err(e) => return fail(&e),
};
let rest: Vec<OsString> = args.collect();
if command == "inspect" {
return inspect(rest);
}
let rest = match rest.into_iter().map(utf8).collect::<Result<Vec<_>, _>>() {
Ok(rest) => rest,
Err(e) => return fail(&e),
};
match command.as_str() {
"-h" | "--help" => print(&format!("{USAGE}\n")),
"--version" => print(&version()),
"diff" => diff(&rest),
"render" => render(&rest),
other if other.starts_with('-') && other != STDIN => {
fail(&format!("unknown option {other:?} (try --help)"))
}
other => fail(&format!("unknown command {other:?} (try --help)")),
}
}
fn load(path: &str) -> Result<Screen, String> {
read(open(path, MAX_INPUT)?, MAX_INPUT)
}
struct Source<'a> {
name: &'a str,
input: Box<dyn Read + 'a>,
len: usize,
head: Option<Head>,
}
fn too_large(name: &str, limit: usize, as_utf8: &str) -> String {
format!(
"{name}: larger than {}{as_utf8}, which no screen in the text format is",
size(limit)
)
}
fn size(limit: usize) -> String {
if limit % (1 << 30) == 0 {
format!("{} GiB", limit >> 30)
} else {
format!("{limit} bytes")
}
}
fn open(path: &str, limit: usize) -> Result<Source<'_>, String> {
if path == STDIN {
return Ok(Source {
name: STDIN_NAME,
input: Box::new(io::stdin().lock()),
len: 0,
head: None,
});
}
let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
let (len, head) = match file.metadata() {
Ok(meta) if meta.is_file() => {
let head = Head::read(&mut file).map_err(|e| format!("{path}: {e}"))?;
(meta.len(), Some(head))
}
Ok(meta) if meta.is_dir() => match (&file).read(&mut [0; 1]) {
Ok(_) => (0, None),
Err(e) => return Err(format!("{path}: {e}")),
},
_ => (0, None),
};
if len > limit as u64 && head.as_ref().is_some_and(|head| head.json().is_none()) {
return Err(too_large(path, limit, ""));
}
Ok(Source {
name: path,
input: Box::new(file),
len: usize::try_from(len).unwrap_or(usize::MAX),
head,
})
}
fn read(source: Source<'_>, limit: usize) -> Result<Screen, String> {
let Source {
name,
mut input,
len,
head,
} = source;
let head = match head {
Some(head) => head,
None => Head::read(&mut input).map_err(|e| format!("{name}: {e}"))?,
};
if let Some((encoding, skip)) = head.json() {
return read_json(name, head.bytes, encoding, skip, input);
}
let raw = read_bounded(io::Cursor::new(head.bytes).chain(input), len, limit);
let Some(raw) = raw.map_err(|e| format!("{name}: {e}"))? else {
return Err(too_large(name, limit, ""));
};
let text = decode(raw, limit).map_err(|e| match e {
NotText::Utf8 => format!("{name}: stream did not contain valid UTF-8"),
NotText::Utf16 => format!("{name}: stream did not contain valid UTF-16"),
NotText::Utf32 => format!(
"{name}: the byte-order mark says UTF-32, which termlens does not read \
(it reads UTF-8 and UTF-16)"
),
NotText::TooLarge => too_large(name, limit, " as UTF-8"),
NotText::Memory => format!("{name}: {}", io::Error::from(io::ErrorKind::OutOfMemory)),
})?;
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let text = if text.contains("\r\n") {
Cow::Owned(text.replace("\r\n", "\n"))
} else {
Cow::Borrowed(text)
};
let body = strip_insta_header(&text).trim_start_matches('\n');
if body.trim_start().starts_with('{') {
return serde_json::from_str(body)
.map_err(|e| format!("{name}: not a termlens Screen: {e}"));
}
Screen::parse(strip_inspect_trailer(body)).map_err(|e| format!("{name}: {e}"))
}
#[derive(Debug, PartialEq, Eq)]
enum NotText {
Utf8,
Utf16,
Utf32,
TooLarge,
Memory,
}
fn decode(raw: Vec<u8>, limit: usize) -> Result<String, NotText> {
let big_endian = match encoding(&raw) {
Encoding::Utf8 => return String::from_utf8(raw).map_err(|_| NotText::Utf8),
Encoding::Utf16 { big_endian } => big_endian,
Encoding::Utf32 => return Err(NotText::Utf32),
};
if raw.len() % 2 != 0 {
return Err(NotText::Utf16);
}
let units = || {
raw.chunks_exact(2).map(|unit| {
let unit = [unit[0], unit[1]];
if big_endian {
u16::from_be_bytes(unit)
} else {
u16::from_le_bytes(unit)
}
})
};
let mut len = 0;
for decoded in char::decode_utf16(units()) {
len += decoded.map_err(|_| NotText::Utf16)?.len_utf8();
if len > limit {
return Err(NotText::TooLarge);
}
}
let mut text = String::new();
text.try_reserve_exact(len).map_err(|_| NotText::Memory)?;
text.extend(char::decode_utf16(units()).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)));
Ok(text)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Encoding {
Utf8,
Utf16 {
big_endian: bool,
},
Utf32,
}
fn encoding(bytes: &[u8]) -> Encoding {
if let Some([0xff, 0xfe, 0, 0] | [0, 0, 0xfe, 0xff]) = bytes.get(..4) {
return Encoding::Utf32;
}
match bytes.get(..2) {
Some([0xff, 0xfe]) => Encoding::Utf16 { big_endian: false },
Some([0xfe, 0xff]) => Encoding::Utf16 { big_endian: true },
_ => Encoding::Utf8,
}
}
const HEAD: usize = 64 * 1024;
struct Head {
bytes: Vec<u8>,
ended: bool,
}
impl Head {
fn read(input: &mut impl Read) -> io::Result<Head> {
let mut bytes = Vec::new();
input.take(HEAD as u64).read_to_end(&mut bytes)?;
Ok(Head {
ended: bytes.len() < HEAD,
bytes,
})
}
fn json(&self) -> Option<(Encoding, usize)> {
let encoding = encoding(&self.bytes);
let (text, whole) = match encoding {
Encoding::Utf8 => match std::str::from_utf8(&self.bytes) {
Ok(text) => (Cow::Borrowed(text), self.ended),
Err(e) => (
Cow::Borrowed(std::str::from_utf8(&self.bytes[..e.valid_up_to()]).ok()?),
false,
),
},
Encoding::Utf32 => return None,
Encoding::Utf16 { big_endian } => {
let units = self.bytes.chunks_exact(2).map(|unit| {
let unit = [unit[0], unit[1]];
if big_endian {
u16::from_be_bytes(unit)
} else {
u16::from_le_bytes(unit)
}
});
let mut text = String::new();
let mut whole = self.ended && self.bytes.len() % 2 == 0;
for decoded in char::decode_utf16(units) {
let Ok(ch) = decoded else {
whole = false;
break;
};
text.push(ch);
}
(Cow::Owned(text), whole)
}
};
json_body(&text, whole).map(|skip| (encoding, skip))
}
}
fn json_body(text: &str, whole: bool) -> Option<usize> {
let mut rest = text.strip_prefix('\u{feff}').unwrap_or(text);
if let Some(header) = rest
.strip_prefix("---\n")
.or_else(|| rest.strip_prefix("---\r\n"))
{
let close = header.match_indices("\n---").find_map(|(at, _)| {
let after = &header[at + 4..];
after
.strip_prefix('\n')
.or_else(|| after.strip_prefix("\r\n"))
});
match close {
Some(body) => rest = body,
None if whole => {}
None => return None,
}
}
let body = rest.trim_start_matches('\n');
let first = body.trim_start();
if first.is_empty() && !whole {
return None;
}
first.starts_with('{').then_some(text.len() - body.len())
}
fn read_json(
name: &str,
head: Vec<u8>,
encoding: Encoding,
skip: usize,
rest: impl Read,
) -> Result<Screen, String> {
let input = io::Cursor::new(head).chain(rest);
let mut text: Box<dyn Read + '_> = match encoding {
Encoding::Utf8 | Encoding::Utf32 => Box::new(Utf8Text::new(input)),
Encoding::Utf16 { big_endian } => Box::new(Utf16Text::new(input, big_endian)),
};
io::copy(&mut text.by_ref().take(skip as u64), &mut io::sink())
.map_err(|e| format!("{name}: {e}"))?;
let document = io::BufReader::with_capacity(HEAD, JsonText::new(text));
serde_json::from_reader(document).map_err(|e| {
if e.is_io() {
format!("{name}: {e}")
} else {
format!("{name}: not a termlens Screen: {e}")
}
})
}
const MAX_STRING: usize = 1 << 20;
const MAX_DEPTH: usize = 128;
struct JsonText<R> {
inner: R,
in_string: bool,
escaped: bool,
run: usize,
depth: usize,
}
impl<R> JsonText<R> {
fn new(inner: R) -> Self {
Self {
inner,
in_string: false,
escaped: false,
run: 0,
depth: 0,
}
}
fn refuse(what: String) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, what)
}
}
impl<R: Read> Read for JsonText<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let read = self.inner.read(buf)?;
for &byte in &buf[..read] {
if self.in_string {
if self.escaped {
self.escaped = false;
} else if byte == b'\\' {
self.escaped = true;
} else if byte == b'"' {
self.in_string = false;
continue;
}
self.run += 1;
if self.run > MAX_STRING {
return Err(Self::refuse(format!(
"a string in the JSON runs past {} MiB, longer than any a saved screen holds",
MAX_STRING >> 20
)));
}
continue;
}
match byte {
b'"' => {
self.in_string = true;
self.run = 0;
}
b'[' | b'{' => {
self.depth += 1;
if self.depth > MAX_DEPTH {
return Err(Self::refuse(format!(
"the JSON nests deeper than {MAX_DEPTH}, which no saved screen does"
)));
}
}
b']' | b'}' => self.depth = self.depth.saturating_sub(1),
_ => {}
}
}
Ok(read)
}
}
struct Utf8Text<R> {
inner: R,
carry: [u8; 3],
carried: usize,
out: Vec<u8>,
at: usize,
}
impl<R: Read> Utf8Text<R> {
fn new(inner: R) -> Self {
Self {
inner,
carry: [0; 3],
carried: 0,
out: Vec::new(),
at: 0,
}
}
fn invalid() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
)
}
fn fill(&mut self) -> io::Result<bool> {
let mut raw = [0; 8 * 1024];
let mut have = self.carried;
raw[..have].copy_from_slice(&self.carry[..have]);
loop {
let read = loop {
match self.inner.read(&mut raw[have..]) {
Ok(read) => break read,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
};
if read == 0 {
return if have > 0 {
Err(Self::invalid())
} else {
Ok(false)
};
}
have += read;
let valid = match std::str::from_utf8(&raw[..have]) {
Ok(_) => have,
Err(e) if e.error_len().is_none() => e.valid_up_to(),
Err(_) => return Err(Self::invalid()),
};
if valid == 0 {
continue;
}
self.carried = have - valid;
self.carry[..self.carried].copy_from_slice(&raw[valid..have]);
self.out.clear();
self.out.extend_from_slice(&raw[..valid]);
self.at = 0;
return Ok(true);
}
}
}
impl<R: Read> Read for Utf8Text<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while self.at == self.out.len() {
if !self.fill()? {
return Ok(0);
}
}
let n = buf.len().min(self.out.len() - self.at);
buf[..n].copy_from_slice(&self.out[self.at..self.at + n]);
self.at += n;
Ok(n)
}
}
struct Utf16Text<R> {
inner: R,
big_endian: bool,
odd: Option<u8>,
high: Option<u16>,
out: Vec<u8>,
at: usize,
}
impl<R: Read> Utf16Text<R> {
fn new(inner: R, big_endian: bool) -> Self {
Self {
inner,
big_endian,
odd: None,
high: None,
out: Vec::new(),
at: 0,
}
}
fn invalid() -> io::Error {
io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-16",
)
}
fn fill(&mut self) -> io::Result<bool> {
let mut raw = [0; 8 * 1024];
let mut have = 0;
if let Some(byte) = self.odd.take() {
raw[0] = byte;
have = 1;
}
let read = loop {
match self.inner.read(&mut raw[have..]) {
Ok(read) => break read,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
};
if read == 0 {
return if have > 0 || self.high.is_some() {
Err(Self::invalid())
} else {
Ok(false)
};
}
have += read;
if have % 2 == 1 {
have -= 1;
self.odd = Some(raw[have]);
}
self.out.clear();
self.at = 0;
for unit in raw[..have].chunks_exact(2) {
let unit = [unit[0], unit[1]];
let unit = if self.big_endian {
u16::from_be_bytes(unit)
} else {
u16::from_le_bytes(unit)
};
let ch = match (self.high.take(), unit) {
(None, 0xd800..=0xdbff) => {
self.high = Some(unit);
continue;
}
(Some(high), 0xdc00..=0xdfff) => {
let code =
0x10000 + ((u32::from(high) - 0xd800) << 10) + (u32::from(unit) - 0xdc00);
char::from_u32(code).ok_or_else(Self::invalid)?
}
(None, unit) => char::from_u32(u32::from(unit)).ok_or_else(Self::invalid)?,
(Some(_), _) => return Err(Self::invalid()),
};
let mut encoded = [0; 4];
self.out
.extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());
}
Ok(true)
}
}
impl<R: Read> Read for Utf16Text<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while self.at == self.out.len() {
if !self.fill()? {
return Ok(0);
}
}
let n = buf.len().min(self.out.len() - self.at);
buf[..n].copy_from_slice(&self.out[self.at..self.at + n]);
self.at += n;
Ok(n)
}
}
const STDIN: &str = "-";
const STDIN_NAME: &str = "<stdin>";
const MAX_INPUT: usize = 1 << 30;
fn read_bounded(mut reader: impl Read, hint: usize, limit: usize) -> io::Result<Option<Vec<u8>>> {
let cap = limit + 1;
let mut buf: Vec<u8> = Vec::new();
buf.try_reserve_exact(hint.saturating_add(1).max(8 * 1024).min(cap))?;
loop {
let room = buf.capacity() - buf.len();
let read = (&mut reader).take(room as u64).read_to_end(&mut buf)?;
if buf.len() > limit {
return Ok(None);
}
if read < room {
return Ok(Some(buf));
}
let grown = buf.capacity().saturating_mul(2).min(cap);
buf.try_reserve_exact(grown - buf.len())?;
}
}
const REAP_GRACE: Duration = if cfg!(windows) {
Duration::from_secs(2)
} else {
Duration::from_millis(500)
};
fn strip_insta_header(text: &str) -> &str {
text.strip_prefix("---\n")
.and_then(|rest| rest.find("\n---\n").map(|end| &rest[end + 5..]))
.unwrap_or(text)
}
fn strip_inspect_trailer(text: &str) -> &str {
let trimmed = text.trim_end_matches('\n');
let start = trimmed.rfind('\n').map_or(0, |at| at + 1);
let last = &trimmed[start..];
let is_trailer = last.ends_with(" ---")
&& [
"--- exited: ",
"--- still running",
"--- waiting for the program failed: ",
]
.iter()
.any(|prefix| last.starts_with(prefix));
if is_trailer {
&trimmed[..start]
} else {
text
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColorWhen {
Auto,
Always,
Never,
}
impl ColorWhen {
fn enabled(self) -> bool {
match self {
ColorWhen::Always => true,
ColorWhen::Never => false,
ColorWhen::Auto => {
io::stdout().is_terminal()
&& std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
}
}
}
}
fn color_when(word: &str) -> Result<ColorWhen, String> {
match word {
"auto" => Ok(ColorWhen::Auto),
"always" => Ok(ColorWhen::Always),
"never" => Ok(ColorWhen::Never),
other => Err(format!(
"--color takes auto, always or never, got {other:?}"
)),
}
}
fn diff(args: &[String]) -> ExitCode {
let mut color = ColorWhen::Auto;
let mut files = Vec::new();
let mut args = args.iter();
while let Some(arg) = args.next() {
match arg.as_str() {
"-h" | "--help" => return print(&format!("{DIFF_USAGE}\n")),
"--version" => return print(&version()),
"--color" => {
let Some(word) = args.next() else {
return fail("--color needs a WHEN argument");
};
match color_when(word) {
Ok(when) => color = when,
Err(e) => return fail(&e),
}
}
other if other.starts_with("--color=") => {
match color_when(&other["--color=".len()..]) {
Ok(when) => color = when,
Err(e) => return fail(&e),
}
}
"--" => {
files.extend(args.by_ref());
break;
}
other if other.starts_with('-') && other != STDIN => {
return fail(&format!(
"unknown option {other:?} (try `termlens diff --help`)"
));
}
_ => files.push(arg),
}
}
let [a, b] = files.as_slice() else {
return usage_error(DIFF_USAGE);
};
if a.as_str() == STDIN && b.as_str() == STDIN {
return fail("only one of the two screens can be `-`: stdin is read once");
}
let right = if a.as_str() == STDIN {
match open(b, MAX_INPUT) {
Ok(source) => Some(source),
Err(e) => return fail(&e),
}
} else {
None
};
let before = match load(a) {
Ok(screen) => screen,
Err(e) => return fail(&e),
};
let after = match right.map_or_else(|| load(b), |source| read(source, MAX_INPUT)) {
Ok(screen) => screen,
Err(e) => return fail(&e),
};
let diff = before.diff(&after);
let rendered = if color.enabled() {
colored(&before, &after, &diff)
} else {
diff.to_string()
};
let code = emit(|out| {
out.write_all(rendered.as_bytes())?;
if rendered.ends_with('\n') {
Ok(())
} else {
out.write_all(b"\n")
}
});
if code != ExitCode::SUCCESS {
return code;
}
if diff.is_empty() {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn is_row_line(line: &str) -> bool {
let Some((number, _)) = line.split_once('│') else {
return false;
};
let Some(number) = number.strip_suffix(' ') else {
return false;
};
number.chars().any(|c| c.is_ascii_digit())
&& number.chars().all(|c| c.is_ascii_digit() || c == ' ')
}
fn colored(before: &Screen, after: &Screen, diff: &ScreenDiff) -> String {
let plain = diff.to_string();
if diff.is_empty() {
return plain;
}
let mut lines = plain.lines();
let mut out = String::new();
for line in lines.by_ref() {
if is_row_line(line) {
break;
}
if !out.is_empty() {
out.push('\n');
}
out.push_str(line);
}
let mut changed_rows: Vec<u16> = diff.cells().map(|(row, _, _, _)| row).collect();
changed_rows.dedup();
let changed: HashSet<(u16, u16)> = diff.cells().map(|(row, col, _, _)| (row, col)).collect();
let cols = before.cols().min(after.cols());
for row in changed_rows {
let cells = |screen: &Screen| -> Vec<(String, bool)> {
let mut cells = Vec::new();
for col in 0..cols {
let Some(cell) = screen.cell(row, col) else {
continue;
};
if cell.is_wide_continuation() {
continue;
}
let stranded = cell.is_wide()
&& (col + 1 >= cols
|| !screen
.cell(row, col + 1)
.is_some_and(termlens::Cell::is_wide_continuation));
let text = if cell.contents().is_empty() || stranded {
" "
} else {
cell.contents()
};
cells.push((text.to_owned(), changed.contains(&(row, col))));
}
cells
};
let paint = |cells: &[(String, bool)], sgr: &str| -> String {
cells
.iter()
.map(|(text, changed)| {
if *changed {
format!("\x1b[{sgr}m{text}\x1b[0m")
} else {
text.clone()
}
})
.collect()
};
let mut after_cells = cells(after);
while after_cells.last().is_some_and(|(text, _)| text == " ") {
after_cells.pop();
}
out.push_str(&format!(
"\n{row:>3} │{}│{}",
paint(&cells(before), "31"),
paint(&after_cells, "32")
));
}
for line in lines.filter(|l| l.starts_with('…') || l.starts_with("styles:")) {
out.push('\n');
out.push_str(line);
}
out
}
fn render_usage_error(reason: &str) -> ExitCode {
let _ = report(&format!("termlens: {reason}\n\n{RENDER_USAGE}"));
ExitCode::from(2)
}
fn render(args: &[String]) -> ExitCode {
let mut format: Option<&str> = None;
let mut files = Vec::new();
let mut out_path: Option<&str> = None;
let mut args = args.iter();
while let Some(arg) = args.next() {
match arg.as_str() {
"-h" | "--help" => return print(&format!("{RENDER_USAGE}\n")),
"--version" => return print(&version()),
"--svg" | "--html" | "--ansi" | "--text" | "--json" => {
if let Some(first) = format {
return render_usage_error(&if first == arg {
format!("{arg} is given twice; render writes one format")
} else {
format!("{first} and {arg} are two formats; render writes one")
});
}
format = Some(arg.as_str());
}
"--out" => match args.next() {
Some(path) if path.is_empty() => return fail("--out needs a PATH argument"),
Some(path) => {
if out_path.is_some() {
return render_usage_error("--out is given twice; render writes one file");
}
out_path = Some(path.as_str());
}
None => return fail("--out needs a PATH argument"),
},
other if other.starts_with("--out=") => {
let path = &other["--out=".len()..];
if path.is_empty() {
return fail("--out needs a PATH argument");
}
if out_path.is_some() {
return render_usage_error("--out is given twice; render writes one file");
}
out_path = Some(path);
}
"--" => {
files.extend(args.by_ref());
break;
}
other if other.starts_with('-') && other != STDIN => {
return fail(&format!(
"unknown option {other:?} (try `termlens render --help`)"
));
}
_ => files.push(arg),
}
}
let (Some(format), [file]) = (format, files.as_slice()) else {
return usage_error(RENDER_USAGE);
};
let screen = match load(file) {
Ok(screen) => screen,
Err(e) => return fail(&e),
};
let write = |out: &mut dyn Write| -> io::Result<()> {
match format {
"--svg" => out.write_all(screen.to_svg().as_bytes()),
"--html" => out.write_all(screen.to_html().as_bytes()),
"--ansi" => out.write_all(screen.to_ansi().as_bytes()),
"--json" => {
serde_json::to_writer_pretty(&mut *out, &screen)?;
out.write_all(b"\n")
}
_ => writeln!(out, "{}", screen.with_styles()),
}
};
match out_path {
Some(STDIN) | None => emit(write),
Some(path) => {
let written = std::fs::File::create(path).and_then(|file| {
let mut file = io::BufWriter::new(file);
write(&mut file)?;
file.flush()
});
match written {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&format!("{path}: {e}")),
}
}
}
}
fn take<T>(
args: &mut impl Iterator<Item = OsString>,
flag: &str,
kind: &str,
example: &str,
parse: impl Fn(&str) -> Option<T>,
) -> Result<T, String> {
let Some(raw) = args.next() else {
return Err(format!("{flag} needs a {kind} argument"));
};
let raw = utf8(raw)?;
parse(&raw).ok_or_else(|| format!("bad {flag} {raw:?}, expected e.g. {example}"))
}
fn timeout_secs(spec: &str) -> Option<Duration> {
let timeout = Duration::from_secs(spec.parse().ok()?);
Instant::now().checked_add(timeout.checked_add(Duration::from_secs(3600))?)?;
Some(timeout)
}
fn is_option(arg: &OsStr) -> bool {
arg.as_encoded_bytes().starts_with(b"-") && arg != STDIN
}
fn inspect_render(screen: &Screen, ansi: bool) -> String {
if !io::stdout().is_terminal() {
screen.with_styles().to_string()
} else if ansi {
let header = screen.to_string();
let header = header.lines().next().unwrap_or_default();
format!("{header}\n{}", screen.to_ansi())
} else {
screen.to_string()
}
}
fn shows_something(screen: &termlens::Screen) -> bool {
let (row, col, _) = screen.cursor();
(row, col) != (0, 0) || !screen.text().trim().is_empty()
}
fn inspect(args: Vec<OsString>) -> ExitCode {
let artifact_dir = std::env::var_os("TERMLENS_ARTIFACT_DIR");
std::env::remove_var("TERMLENS_ARTIFACT_DIR");
let mut args = args.into_iter().peekable();
let mut size = (80u16, 24u16);
let mut timeout = Duration::from_secs(5);
let mut idle = Duration::from_millis(300);
let mut inherit_env = false;
let mut ansi = false;
let mut env = Vec::new();
let mut cwd: Option<String> = None;
while args.peek().is_some_and(|a| is_option(a)) {
let flag = match utf8(args.next().unwrap_or_default()) {
Ok(flag) => flag,
Err(e) => return fail(&e),
};
let (name, inline) = match flag.split_once('=') {
Some((name, value))
if matches!(name, "--size" | "--timeout" | "--idle" | "--cwd" | "--env") =>
{
(name, Some(value))
}
_ => (flag.as_str(), None),
};
let mut args = inline.map(OsString::from).into_iter().chain(args.by_ref());
let parsed = match name {
"-h" | "--help" => return print(&format!("{INSPECT_USAGE}\n")),
"--version" => return print(&version()),
"--" => break,
"--size" => take(&mut args, "--size", "COLSxROWS", "120x40", |spec| {
let (c, r) = spec.split_once('x')?;
Some((c.parse().ok()?, r.parse().ok()?))
})
.map(|s| size = s),
"--timeout" => {
take(&mut args, "--timeout", "SECONDS", "30", timeout_secs).map(|t| timeout = t)
}
"--idle" => take(&mut args, "--idle", "MILLIS", "1000", |s| s.parse().ok())
.map(|millis| idle = Duration::from_millis(millis)),
"--inherit-env" => {
inherit_env = true;
Ok(())
}
"--ansi" => {
ansi = true;
Ok(())
}
"--cwd" => {
take(&mut args, "--cwd", "DIR", "/tmp", |s| Some(s.to_owned())).and_then(|dir| {
if Path::new(&dir).is_dir() {
cwd = Some(dir);
Ok(())
} else {
Err(format!("bad --cwd {dir:?}, not an existing directory"))
}
})
}
"--env" => take(&mut args, "--env", "KEY=VALUE", "NO_COLOR=1", |s| {
let (key, value) = s.split_once('=')?;
(!key.is_empty()).then(|| (key.to_owned(), value.to_owned()))
})
.map(|pair| env.push(pair)),
_ => Err(format!(
"unknown option {flag:?} (try `termlens inspect --help`)"
)),
};
if let Err(message) = parsed {
return fail(&message);
}
}
let Some(program) = args.next() else {
return usage_error(INSPECT_USAGE);
};
let bare = Path::new(&program)
.parent()
.is_none_or(|dir| dir.as_os_str().is_empty());
if bare && std::env::var_os("PATH").is_none() && !env.iter().any(|(key, _)| key == "PATH") {
return fail(&format!(
"`{}` is a bare program name and there is no PATH to find it in, \
since termlens has none to pass on, with --inherit-env or without; \
give the program's absolute path, or a PATH with --env PATH=DIR",
program.to_string_lossy()
));
}
let mut builder = Terminal::builder()
.size(size.0, size.1)
.timeout(timeout)
.args(args);
if !inherit_env {
builder = builder.env_clear();
if let Some(path) = std::env::var_os("PATH") {
builder = builder.env("PATH", path);
}
} else if let Some(dir) = artifact_dir {
builder = builder.env("TERMLENS_ARTIFACT_DIR", dir);
}
for (key, value) in env {
builder = builder.env(key, value);
}
if let Some(dir) = cwd {
builder = builder.current_dir(dir);
}
let mut t = match builder.spawn(&program) {
Ok(t) => t,
Err(e) => return fail(&e.to_string()),
};
let still_running = "--- still running (killed on exit) ---";
let at_the_deadline = "--- still running at the deadline (killed on exit) ---";
let reap = |t: &mut termlens::Terminal| match t.wait_exit_for(REAP_GRACE) {
Ok(status) => format!("--- exited: {status} ---"),
Err(termlens::Error::Timeout { .. }) => still_running.to_owned(),
Err(e) => format!("--- waiting for the program failed: {e} ---"),
};
let deadline = Instant::now() + timeout;
let trailer = match t.wait_until_for(shows_something, timeout) {
Ok(()) => {
let remaining = deadline.saturating_duration_since(Instant::now());
match t.wait_idle_for(idle, remaining) {
Ok(()) => reap(&mut t),
Err(termlens::Error::Timeout { .. }) => at_the_deadline.to_owned(),
Err(e) => format!("--- waiting for the program failed: {e} ---"),
}
}
Err(termlens::Error::Eof { .. }) => reap(&mut t),
Err(termlens::Error::Timeout { .. }) => at_the_deadline.to_owned(),
Err(e) => format!("--- waiting for the program failed: {e} ---"),
};
let code = emit(|out| writeln!(out, "{}", inspect_render(&t.screen(), ansi)));
if report(&trailer).is_err() {
return ExitCode::from(2);
}
code
}
#[cfg(test)]
mod tests {
use std::io::Read as _;
use super::{
decode, json_body, open, read, read_bounded, Encoding, Head, JsonText, NotText, Source,
Utf16Text, Utf8Text, MAX_DEPTH, MAX_STRING,
};
use termlens::Screen;
fn utf16(text: &str, big_endian: bool) -> Vec<u8> {
std::iter::once(0xfeff)
.chain(text.encode_utf16())
.flat_map(|unit| {
if big_endian {
unit.to_be_bytes()
} else {
unit.to_le_bytes()
}
})
.collect()
}
#[test]
fn decode_reads_utf8_and_utf16_behind_its_mark() {
let text = "size: 4x1 cursor: 0,0\n汉字 \u{1f600}";
assert_eq!(
decode(text.as_bytes().to_vec(), 1 << 20).as_deref(),
Ok(text)
);
let marked = format!("\u{feff}{text}");
assert_eq!(
decode(marked.as_bytes().to_vec(), 1 << 20).as_deref(),
Ok(marked.as_str())
);
for big_endian in [false, true] {
assert_eq!(
decode(utf16(text, big_endian), 1 << 20).as_deref(),
Ok(marked.as_str()),
"big-endian: {big_endian}"
);
}
assert_eq!(
decode(utf16(text, false)[2..].to_vec(), 1 << 20),
Err(NotText::Utf8)
);
assert_eq!(decode(vec![b'a', 0xff], 1 << 20), Err(NotText::Utf8));
assert_eq!(decode(Vec::new(), 1 << 20).as_deref(), Ok(""));
assert_eq!(decode(vec![0xff, 0xfe], 1 << 20).as_deref(), Ok("\u{feff}"));
for mark in [[0xff, 0xfe, 0, 0], [0, 0, 0xfe, 0xff]] {
let bytes = [&mark[..], b"s\0\0\0"].concat();
assert_eq!(super::encoding(&bytes), Encoding::Utf32);
assert_eq!(decode(bytes.clone(), 1 << 20), Err(NotText::Utf32));
let head = Head { bytes, ended: true };
assert_eq!(head.json(), None);
}
assert_eq!(
super::encoding(&[0xff, 0xfe, b's', 0]),
Encoding::Utf16 { big_endian: false }
);
}
#[test]
fn decode_refuses_broken_utf16() {
let mut odd = utf16("ok", false);
odd.push(b'!');
assert_eq!(decode(odd, 1 << 20), Err(NotText::Utf16));
for lone in [[0x3d, 0xd8], [0x00, 0xde]] {
let mut bytes = utf16("ok", false);
bytes.extend(lone);
bytes.extend(utf16("ok", false).split_off(2));
assert_eq!(decode(bytes, 1 << 20), Err(NotText::Utf16), "{lone:02x?}");
}
}
#[test]
fn decode_bounds_utf16_by_its_utf8_length() {
let bytes = utf16(&"汉".repeat(10), false);
assert_eq!(bytes.len(), 22);
assert_eq!(decode(bytes.clone(), 32), Err(NotText::TooLarge));
let text = decode(bytes, 33).expect("exactly the limit is read");
assert_eq!(text.len(), 33);
let ascii = decode(utf16("abcdefgh", false), 1 << 20).expect("ASCII");
assert!(ascii.capacity() <= 11, "{}", ascii.capacity());
}
struct Trickle<'a> {
data: &'a [u8],
chunk: usize,
}
impl std::io::Read for Trickle<'_> {
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
let n = self.data.len().min(self.chunk).min(out.len());
out[..n].copy_from_slice(&self.data[..n]);
self.data = &self.data[n..];
Ok(n)
}
}
#[test]
fn read_bounded_takes_the_limit_and_refuses_one_byte_more() {
let limit = 100_000;
let data = vec![b'x'; limit + 1];
for chunk in [1, 7, 4096, limit + 1] {
for hint in [0, limit, limit + 1, usize::MAX] {
let whole = read_bounded(
Trickle {
data: &data[..limit],
chunk,
},
hint,
limit,
)
.expect("an in-memory read")
.expect("exactly the limit is read");
assert_eq!(whole.len(), limit);
assert!(
whole.capacity() <= limit + 1,
"{} for {hint}",
whole.capacity()
);
let over = read_bounded(Trickle { data: &data, chunk }, hint, limit)
.expect("an in-memory read");
assert!(over.is_none(), "{chunk}/{hint}");
}
}
let empty = read_bounded(&b""[..], 0, limit).unwrap().unwrap();
assert!(empty.is_empty());
let small = read_bounded(&b"size"[..], 4, limit).unwrap().unwrap();
assert_eq!(small, b"size");
}
fn screen_json() -> String {
let screen = Screen::parse("size: 6x2 cursor: 1,2\nab 汉\ncd").expect("a screen");
serde_json::to_string_pretty(&screen).expect("the JSON")
}
fn source(bytes: Vec<u8>, chunk: usize) -> Source<'static> {
struct Owned {
data: Vec<u8>,
at: usize,
chunk: usize,
}
impl std::io::Read for Owned {
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
let n = (self.data.len() - self.at).min(self.chunk).min(out.len());
out[..n].copy_from_slice(&self.data[self.at..self.at + n]);
self.at += n;
Ok(n)
}
}
Source {
name: "t",
input: Box::new(Owned {
data: bytes,
at: 0,
chunk,
}),
len: 0,
head: None,
}
}
#[test]
fn json_is_told_from_its_head() {
assert_eq!(json_body("{\"format\":1}", true), Some(0));
assert_eq!(json_body("\u{feff}\n\n {}", true), Some(5));
assert_eq!(json_body(" \t\r\n{}", true), Some(0));
assert_eq!(json_body("\u{a0}{}", true), Some(0));
let snap = "---\nsource: tests/a.rs\nexpression: screen\n---\n{}";
assert_eq!(json_body(snap, true), Some(snap.len() - 2));
let crlf = "---\r\nsource: a\r\n---x\r\n---\r\n\r\n{}";
assert_eq!(json_body(crlf, true), Some(crlf.len() - 4));
assert_eq!(json_body("size: 2x1 cursor: 0,0\n{}", true), None);
assert_eq!(
json_body("---\n{}", true),
None,
"a header that never closes"
);
assert_eq!(json_body("---\nsource: a\n", false), None);
assert_eq!(json_body("\n\n ", false), None);
assert_eq!(json_body("\n\n {", false), Some(2));
let head = |bytes: &[u8]| Head {
bytes: bytes.to_vec(),
ended: true,
};
assert_eq!(head(b"{}").json(), Some((Encoding::Utf8, 0)));
assert_eq!(head(b"\xef\xbb\xbf{}").json(), Some((Encoding::Utf8, 3)));
assert_eq!(
head(&utf16("\n{}", false)).json(),
Some((Encoding::Utf16 { big_endian: false }, 4))
);
assert_eq!(
head(&utf16("{}", true)).json(),
Some((Encoding::Utf16 { big_endian: true }, 3))
);
assert_eq!(head(b"size: 1x1 cursor: 0,0\nx").json(), None);
assert_eq!(head(b"\xff\n{}").json(), None);
}
#[test]
fn json_is_not_held_to_the_text_limit() {
let limit = 16 * 1024;
let json = screen_json();
assert!(json.len() < limit);
let padded = format!("{json}{}", " \n".repeat(5 * limit));
let expected = Screen::parse("size: 6x2 cursor: 1,2\nab 汉\ncd").unwrap();
for chunk in [1, 7, 4096] {
let screen = read(source(padded.clone().into_bytes(), chunk), limit)
.expect("JSON past the limit reads");
assert_eq!(screen, expected, "chunk {chunk}");
let marked = [&[0xef, 0xbb, 0xbf][..], padded.as_bytes()].concat();
assert_eq!(read(source(marked, chunk), limit), Ok(expected.clone()));
let wide = utf16(&padded, chunk % 2 == 0);
assert_eq!(read(source(wide, chunk), limit), Ok(expected.clone()));
}
let text = format!("size: 6x2 cursor: 1,2\nab 汉\ncd\n{}", "\n".repeat(limit));
assert_eq!(
read(source(text.clone().into_bytes(), 7), limit).unwrap_err(),
"t: larger than 16384 bytes, which no screen in the text format is"
);
let fits = &text[..limit];
assert!(read(source(fits.as_bytes().to_vec(), 7), limit).is_ok());
let dir = std::env::temp_dir().join(format!("termlens-unit-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (big_text, big_json) = (dir.join("big.txt"), dir.join("big.json"));
std::fs::write(&big_text, &text).unwrap();
std::fs::write(&big_json, &padded).unwrap();
let path = big_text.to_str().unwrap();
let refused = open(path, limit).err().expect("refused by its length");
assert_eq!(
refused,
format!("{path}: larger than 16384 bytes, which no screen in the text format is")
);
let source = open(big_json.to_str().unwrap(), limit).expect("JSON opens");
assert_eq!(read(source, limit), Ok(expected));
let _ = std::fs::remove_dir_all(&dir);
}
fn pass(input: &[u8]) -> std::io::Result<Vec<u8>> {
let mut out = Vec::new();
JsonText::new(input).read_to_end(&mut out).map(|_| out)
}
#[test]
fn json_text_bounds_strings_and_nesting() {
let string = |len: usize| format!("{{\"title\":\"{}\"}}", "a".repeat(len));
assert_eq!(
pass(string(MAX_STRING).as_bytes()).unwrap().len(),
MAX_STRING + 12
);
let err = pass(string(MAX_STRING + 1).as_bytes()).unwrap_err();
assert_eq!(
err.to_string(),
"a string in the JSON runs past 1 MiB, longer than any a saved screen holds"
);
let escaped = format!("\"{}\\\"\"", "a".repeat(MAX_STRING - 2));
assert!(
pass(escaped.as_bytes()).is_ok(),
"the escape is two bytes of the string"
);
let escaped = format!("\"{}\\\"a\"", "a".repeat(MAX_STRING - 2));
assert!(
pass(escaped.as_bytes()).is_err(),
"and the quote it escapes does not end it"
);
let many = "\"aaaa\",".repeat(MAX_STRING);
assert!(
pass(format!("[{many}\"\"]").as_bytes()).is_ok(),
"each string counts alone"
);
let outside = format!("[{}0]", " ".repeat(3 * MAX_STRING));
assert!(pass(outside.as_bytes()).is_ok());
let nested = |depth: usize| format!("{}{}", "[".repeat(depth), "]".repeat(depth));
assert!(pass(nested(MAX_DEPTH).as_bytes()).is_ok());
let err = pass(nested(MAX_DEPTH + 1).as_bytes()).unwrap_err();
assert_eq!(
err.to_string(),
"the JSON nests deeper than 128, which no saved screen does"
);
assert!(
pass(format!("\"{}\"", "[".repeat(1000)).as_bytes()).is_ok(),
"inside a string"
);
let long = format!("{{\"title\":\"{}\"}}", "a".repeat(MAX_STRING + 1));
let err = read(source(long.into_bytes(), 4096), 1 << 30).unwrap_err();
assert!(
err.starts_with(
"t: a string in the JSON runs past 1 MiB, longer than any a saved screen holds"
),
"{err}"
);
}
#[test]
fn utf16_text_streams_as_utf8() {
let text = "{\"汉字\": \"\u{1f600} ok\"}";
for big_endian in [false, true] {
let bytes = utf16(text, big_endian);
for chunk in [1, 2, 3, 5, 4096] {
let mut out = Vec::new();
let mut reader =
Utf16Text::new(super::tests::source(bytes.clone(), chunk).input, big_endian);
reader.read_to_end(&mut out).expect("valid UTF-16");
assert_eq!(
String::from_utf8(out).unwrap(),
format!("\u{feff}{text}"),
"big-endian {big_endian}, chunk {chunk}"
);
}
}
let mut odd = utf16("ok", false);
odd.push(b'!');
let mut lone = utf16("ok", false);
lone.extend([0x3d, 0xd8, b'!', 0]);
let mut unpaired = utf16("ok", false);
unpaired.extend([0x3d, 0xd8]);
for bytes in [odd, lone, unpaired] {
let err = Utf16Text::new(&bytes[..], false)
.read_to_end(&mut Vec::new())
.unwrap_err();
assert_eq!(err.to_string(), "stream did not contain valid UTF-16");
}
let mut json = utf16(&screen_json(), false);
json.extend([0x3d, 0xd8]);
assert_eq!(
read(source(json, 4096), 1 << 30),
Err("t: stream did not contain valid UTF-16".into())
);
}
#[test]
fn utf8_text_streams_checked() {
let text = "{\"汉字\": \"\u{1f600} é ok\"}";
for chunk in [1, 2, 3, 5, 4096] {
let mut out = Vec::new();
Utf8Text::new(source(text.as_bytes().to_vec(), chunk).input)
.read_to_end(&mut out)
.expect("valid UTF-8");
assert_eq!(out, text.as_bytes(), "chunk {chunk}");
}
let emoji = "\u{1f600}".as_bytes();
for bytes in [
&b"{\"t\": \"caf\xe9\"}"[..],
&b"{\"t\": \"\x80\"}"[..],
&b"{\"t\": \"\xc0\xaf\"}"[..],
&b"{\"t\": \"\xed\xa0\x80\"}"[..],
&[b"{} ".as_slice(), &emoji[..3]].concat(),
] {
for chunk in [1, 4096] {
let err = Utf8Text::new(source(bytes.to_vec(), chunk).input)
.read_to_end(&mut Vec::new())
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert_eq!(err.to_string(), "stream did not contain valid UTF-8");
}
}
for tail in [&b"\xe9\n"[..], b""] {
let json = screen_json().replacen("\"title\": \"\"", "\"title\": \"caf\u{e9}\"", 1);
let mut bytes = json.into_bytes();
if tail.is_empty() {
let at = bytes.windows(2).position(|w| w == b"\xc3\xa9").unwrap();
bytes.splice(at..at + 2, [0xe9]);
} else {
bytes.extend_from_slice(tail);
}
assert_eq!(
read(source(bytes, 4096), 1 << 30),
Err("t: stream did not contain valid UTF-8".into())
);
}
}
}