1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Project: grippo
// File: src/format/w3c.rs
// Purpose: The W3C extended log format, read a line at a time
// Language: Rust
//
// License: Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED
//! W3C extended log files, as web and proxy servers write them.
//!
//! A `#Fields:` directive names the columns of the lines after it, other `#`
//! lines are directives that write nothing, and a record's values are split
//! on ASCII whitespace, with `-` written as an empty field.
//!
//! The names carry from one line to the next, so a reader is kept per file.
//! [`W3c::names`] and [`W3c::with_names`] save and restore them, for a reader
//! that picks a file up where it stopped.
use std::borrow::Cow;
use thiserror::Error;
use crate::parse::{FieldSink, FieldValue, Hint};
use crate::path::key_part;
/// Why a record line can't be read.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum W3cError {
/// A record came before any `#Fields:` line.
#[error("no #Fields line was found for this file")]
NoFields,
/// A record has a different number of values from the names.
#[error("expected {expected} fields, got {got}")]
Columns {
/// The number of names.
expected: usize,
/// The number of values the line holds.
got: usize,
},
}
/// What one line was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line {
/// A `#` directive. A `#Fields:` line sets the names.
Directive,
/// A record, and the number of fields it wrote.
Record(usize),
}
/// One file's reader: the names its last `#Fields:` line gave.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct W3c {
names: Option<Vec<String>>,
}
impl W3c {
/// A reader with no names yet.
#[must_use]
pub const fn new() -> Self {
Self { names: None }
}
/// A reader that goes on with names saved from an earlier one.
#[must_use]
pub const fn with_names(names: Vec<String>) -> Self {
Self { names: Some(names) }
}
/// The names the last `#Fields:` line gave, if one has been read.
#[must_use]
pub fn names(&self) -> Option<&[String]> {
self.names.as_deref()
}
/// Reads one line, without its line end. A directive writes nothing, and
/// a record writes one field per name, in order.
///
/// # Errors
///
/// [`W3cError::NoFields`] for a record before any `#Fields:` line, and
/// [`W3cError::Columns`] when its value count differs from the names'.
/// Either way nothing is written.
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))
}
}
/// The runs of `text` between ASCII whitespace.
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"
);
}
}