use std::borrow::Cow;
use thiserror::Error;
use crate::parse::{FieldSink, FieldValue, Hint};
use crate::path::key_part;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum W3cError {
#[error("no #Fields line was found for this file")]
NoFields,
#[error("expected {expected} fields, got {got}")]
Columns {
expected: usize,
got: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line {
Directive,
Record(usize),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct W3c {
names: Option<Vec<String>>,
}
impl W3c {
#[must_use]
pub const fn new() -> Self {
Self { names: None }
}
#[must_use]
pub const fn with_names(names: Vec<String>) -> Self {
Self { names: Some(names) }
}
#[must_use]
pub fn names(&self) -> Option<&[String]> {
self.names.as_deref()
}
pub fn line<'a>(
&mut self,
line: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Line, W3cError> {
if let Some(directive) = line.strip_prefix(b"#") {
if let Some(fields) = directive.strip_prefix(b"Fields:") {
self.names = Some(
words(fields)
.map(|name| String::from_utf8_lossy(name).into_owned())
.collect(),
);
}
return Ok(Line::Directive);
}
let names = self.names.as_deref().ok_or(W3cError::NoFields)?;
let got = words(line).count();
if got != names.len() {
return Err(W3cError::Columns {
expected: names.len(),
got,
});
}
for (name, value) in names.iter().zip(words(line)) {
let value: &[u8] = if value == b"-" { b"" } else { value };
out.field(
&key_part(Cow::Borrowed(name)),
FieldValue::borrowed(value, Hint::Text),
);
}
Ok(Line::Record(got))
}
}
fn words(text: &[u8]) -> impl Iterator<Item = &[u8]> {
text.split(u8::is_ascii_whitespace)
.filter(|w| !w.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse::Fields;
type Row = (String, String);
fn read(w3c: &mut W3c, line: &str) -> (Result<Line, W3cError>, Vec<Row>) {
let mut out = Fields::new();
let got = w3c.line(line.as_bytes(), &mut out);
let rows = out
.as_slice()
.iter()
.map(|(k, v)| (k.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect();
(got, rows)
}
#[test]
fn a_dotted_column_name_is_written_quoted_and_reads_back_whole() {
for (name, value) in [(r#"["a.b"]"#, "1"), ("c", "2")] {
let mut w3c = W3c::new();
let mut out = Fields::new();
w3c.line(b"#Fields: a.b c", &mut out).unwrap();
w3c.line(b"1 2", &mut out).unwrap();
let got = out
.get(name)
.map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
assert_eq!(got.as_deref(), Some(value), "{name}");
#[cfg(feature = "record")]
{
use crate::record::Record;
let keys: Vec<_> = crate::path::keys(name).collect();
let at = (&out).find(&keys[..]).unwrap();
assert_eq!((&out).text(at).unwrap(), value, "{name}");
}
}
}
#[test]
fn directives_set_names_and_records_read_by_them() {
use W3cError::{Columns, NoFields};
let mut w3c = W3c::new();
let lines: &[(&str, Result<Line, W3cError>, &[(&str, &str)])] = &[
("a b c", Err(NoFields), &[]),
("#Software: IIS", Ok(Line::Directive), &[]),
("#Version: 1.0", Ok(Line::Directive), &[]),
("#Date: 2024-01-01 00:00:00", Ok(Line::Directive), &[]),
(
"#Fields: date time cs-method cs(User-Agent)",
Ok(Line::Directive),
&[],
),
(
"2024-01-01 00:00:01 GET Mozilla/5.0+(X11)",
Ok(Line::Record(4)),
&[
("date", "2024-01-01"),
("time", "00:00:01"),
("cs-method", "GET"),
("cs(User-Agent)", "Mozilla/5.0+(X11)"),
],
),
(
"2024-01-01\t00:00:02 - -",
Ok(Line::Record(4)),
&[
("date", "2024-01-01"),
("time", "00:00:02"),
("cs-method", ""),
("cs(User-Agent)", ""),
],
),
(
"2024-01-01 00:00:01",
Err(Columns {
expected: 4,
got: 2,
}),
&[],
),
(
"a b c d e",
Err(Columns {
expected: 4,
got: 5,
}),
&[],
),
("# Fields: x", Ok(Line::Directive), &[]),
("#Fields: x y", Ok(Line::Directive), &[]),
("1 --", Ok(Line::Record(2)), &[("x", "1"), ("y", "--")]),
("#Fields:", Ok(Line::Directive), &[]),
("", Ok(Line::Record(0)), &[]),
(
"1",
Err(Columns {
expected: 0,
got: 1,
}),
&[],
),
];
for (line, want, fields) in lines {
let (got, rows) = read(&mut w3c, line);
assert_eq!(&got, want, "{line:?}");
let want_rows: Vec<Row> = fields
.iter()
.map(|&(k, v)| (k.to_owned(), v.to_owned()))
.collect();
assert_eq!(rows, want_rows, "{line:?}");
}
}
#[test]
fn names_carry_over_to_a_reader_that_goes_on() {
let mut first = W3c::new();
assert_eq!(
read(&mut first, "#Fields: date time").0,
Ok(Line::Directive)
);
assert_eq!(
first.names(),
Some(&["date".to_owned(), "time".to_owned()][..])
);
let mut next = W3c::with_names(first.names().unwrap_or_default().to_vec());
assert_eq!(read(&mut next, "2024-01-01 -").0, Ok(Line::Record(2)));
assert_eq!(
W3cError::Columns {
expected: 3,
got: 2
}
.to_string(),
"expected 3 fields, got 2"
);
assert_eq!(
W3cError::NoFields.to_string(),
"no #Fields line was found for this file"
);
}
}