use std::ops::Range;
use crate::field::{Scan, field};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
const MARKER_BY: usize = 64;
#[derive(Debug, Clone)]
pub struct Cri {
signature: Signature,
}
impl Default for Cri {
fn default() -> Self {
Self::new()
}
}
impl Cri {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.any_of([" stdout ", " stderr "])
.verify(flag_follows)
.within(MARKER_BY)
.build()
.unwrap_or_else(|_| unreachable!("invariant: the CRI literals are non-empty"));
Self { signature }
}
}
fn flag_follows(span: &[u8], at: usize) -> bool {
at + 10 <= MARKER_BY && matches!(span.get(at + 8..at + 10), Some(b"F " | b"P "))
}
impl Parser for Cri {
fn name(&self) -> &'static str {
"cri"
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.signature
}
fn escape_value(
&self,
_input: &[u8],
_field: usize,
at: Range<usize>,
value: &[u8],
out: &mut Vec<u8>,
) -> Option<Range<usize>> {
out.extend_from_slice(value);
Some(at)
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let Some(Scan::Match(t)) = field("TIMESTAMP_ISO8601").map(|f| (f.scan)(input, 0)) else {
return Ok(Parsed::NoMatch);
};
let rest = &input[t..];
let stream_len = if rest.starts_with(b" stdout ") || rest.starts_with(b" stderr ") {
6
} else {
return Ok(Parsed::NoMatch);
};
let flag_at = t + 1 + stream_len + 1;
let partial = match input.get(flag_at..flag_at + 2) {
Some(b"F ") => false,
Some(b"P ") => true,
_ => return Ok(Parsed::NoMatch),
};
let body = flag_at + 2;
if body > MARKER_BY {
return Ok(Parsed::NoMatch);
}
let trail = input[body..]
.iter()
.rev()
.take_while(|&&b| b == b'\n')
.count();
let end = input.len() - trail;
out.field(
"timestamp",
FieldValue::borrowed(&input[..t], Hint::Timestamp),
);
out.field(
"stream",
FieldValue::borrowed(&input[t + 1..t + 1 + stream_len], Hint::Text),
);
let flag: &'static [u8] = if partial { b"true" } else { b"false" };
out.field("partial", FieldValue::borrowed(flag, Hint::Bool));
out.body_field(
"message",
FieldValue::borrowed(&input[body..end], Hint::Text),
);
Ok(Parsed::Body {
span: body..end,
hint: (input.get(body) == Some(&b'{')).then_some("ndjson"),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse::Fields;
#[test]
fn a_full_and_a_partial_line() {
let line = b"2026-11-26T00:22:33.123456789Z stdout F {\"level\":\"info\"}\n";
let mut out = Fields::new();
let Parsed::Body { span, hint } = Cri::new().parse(line, &mut out).unwrap() else {
panic!("no body")
};
assert_eq!(&line[span], b"{\"level\":\"info\"}");
assert_eq!(hint, Some("ndjson"));
assert_eq!(&*out.get("stream").unwrap().bytes, b"stdout");
assert_eq!(&*out.get("partial").unwrap().bytes, b"false");
let mut out = Fields::new();
Cri::new()
.parse(b"2026-11-26T00:22:33Z stderr P half a li", &mut out)
.unwrap();
assert_eq!(&*out.get("partial").unwrap().bytes, b"true");
assert_eq!(&*out.get("message").unwrap().bytes, b"half a li");
}
proptest::proptest! {
#[test]
fn a_written_message_reads_back(value in "[a-z {}\"\t]{0,12}") {
let line = b"2026-11-26T00:22:33Z stdout F old message\n";
let mut text = Vec::new();
let span = Cri::new().escape_value(line, 3, 30..41, value.as_bytes(), &mut text).unwrap();
let after = [&line[..span.start], &text, &line[span.end..]].concat();
let mut out = Fields::new();
let parsed = Cri::new().parse(&after, &mut out).unwrap();
let body = matches!(parsed, Parsed::Body { .. });
proptest::prop_assert!(body);
proptest::prop_assert_eq!(&*out.get("message").unwrap().bytes, value.as_bytes());
}
}
#[test]
fn other_lines_are_no_match() {
for line in [
&b"2026-11-26T00:22:33Z stdin F x"[..],
b"stdout F x",
b"2026-11-26T00:22:33Z stdout X y",
] {
let mut out = Fields::new();
assert_eq!(Cri::new().parse(line, &mut out).unwrap(), Parsed::NoMatch);
assert!(out.is_empty());
}
}
#[test]
fn the_parser_and_its_signature_agree_on_where_the_marker_may_sit() {
let cri = Cri::new();
let longest = b"2026-11-26T00:22:33.123456789+10:00 stdout F m";
assert!(cri.signature().may_match(longest));
assert!(matches!(
cri.parse(longest, &mut Fields::new()),
Ok(Parsed::Body { .. })
));
let late = b"2026-11-26T00:22:33.12345678901234567890123456789012345Z stdout F m";
assert!(!cri.signature().may_match(late));
assert!(matches!(
cri.parse(late, &mut Fields::new()),
Ok(Parsed::NoMatch)
));
for (pad, fits) in [(54, true), (55, false)] {
let line = format!("{} stderr P m", "x".repeat(pad));
assert_eq!(cri.signature().may_match(line.as_bytes()), fits, "{pad}");
}
assert!(
!cri.signature()
.may_match(b"2026-11-26T00:22:33Z stdout X m")
);
}
}