1use crate::*;
25use std::borrow::Cow;
26use std::collections::HashMap;
27use std::fs::{self, File, OpenOptions};
28use std::io::{self, Write};
29use std::path::Path;
30
31pub struct StreamReader<'a> {
35 buf: &'a [u8],
36 committed_end: usize,
37 blocks: Vec<(usize, usize)>,
38 damaged: Vec<usize>,
39 torn_regions: Vec<(usize, usize)>,
42 torn: bool,
43 continue_past_damage: bool,
44 container: Result<Container<'a>>,
47}
48
49impl<'a> StreamReader<'a> {
50 pub fn new(buf: &'a [u8]) -> Self {
52 Self::with_options(buf, false)
53 }
54
55 pub fn continuing(buf: &'a [u8]) -> Self {
57 Self::with_options(buf, true)
58 }
59
60 fn with_options(buf: &'a [u8], continue_past_damage: bool) -> Self {
61 let mut r = StreamReader {
62 buf,
63 committed_end: 0,
64 blocks: Vec::new(),
65 damaged: Vec::new(),
66 torn_regions: Vec::new(),
67 torn: false,
68 continue_past_damage,
69 container: Err(Error::other("unparsed")),
70 };
71 r.scan();
72 r.container = r.parse_committed();
73 r
74 }
75
76 pub fn buf(&self) -> &'a [u8] {
77 self.buf
78 }
79
80 pub fn committed_end(&self) -> usize {
82 self.committed_end
83 }
84
85 pub fn committed(&self) -> &'a [u8] {
87 &self.buf[..self.committed_end]
88 }
89
90 pub fn tail(&self) -> &'a [u8] {
92 &self.buf[self.committed_end..]
93 }
94
95 pub fn torn(&self) -> bool {
98 self.torn
99 }
100
101 pub fn torn_regions(&self) -> &[(usize, usize)] {
107 &self.torn_regions
108 }
109
110 pub fn continue_past_damage(&self) -> bool {
112 self.continue_past_damage
113 }
114
115 pub fn block_count(&self) -> usize {
116 self.blocks.len()
117 }
118
119 pub fn block(&self, i: usize) -> &'a [u8] {
122 let (s, e) = self.blocks[i];
123 &self.buf[s..e]
124 }
125
126 pub fn block_ranges(&self) -> &[(usize, usize)] {
128 &self.blocks
129 }
130
131 pub fn blocks(&self) -> impl Iterator<Item = &'a [u8]> + '_ {
132 (0..self.blocks.len()).map(move |i| self.block(i))
133 }
134
135 pub fn block_end(&self, i: usize) -> usize {
137 self.blocks
138 .get(i + 1)
139 .map_or(self.committed_end, |&(s, _)| s)
140 }
141
142 pub fn damaged(&self) -> &[usize] {
144 &self.damaged
145 }
146
147 pub fn is_damaged(&self, i: usize) -> bool {
148 self.damaged.contains(&i)
149 }
150
151 pub fn undamaged(&self) -> Cow<'a, [u8]> {
154 if self.damaged.is_empty() {
155 return Cow::Borrowed(self.committed());
156 }
157 let mut out = Vec::new();
158 for (i, &(s, e)) in self.blocks.iter().enumerate() {
159 if !self.damaged.contains(&i) {
160 out.extend_from_slice(&self.buf[s..e]);
161 }
162 }
163 Cow::Owned(out)
164 }
165
166 pub fn container(&self) -> Result<&Container<'a>> {
170 self.check_damage()?;
171 self.container.as_ref().map_err(Clone::clone)
172 }
173
174 pub fn document(&self) -> Result<&Document<'a>> {
176 self.container()?
177 .first()
178 .ok_or_else(|| Error::other("the committed region holds no document"))
179 }
180
181 pub fn each_record<F: FnMut(&Record<'a>)>(&self, mut f: F) -> Result<()> {
185 let c = self.container.as_ref().map_err(Clone::clone)?;
186 let limit = if self.continue_past_damage {
187 usize::MAX
188 } else {
189 self.damaged
190 .first()
191 .map_or(usize::MAX, |&d| self.blocks[d].0)
192 };
193 for doc in c.documents() {
194 for g in doc.body().groups() {
195 for r in g.records() {
196 if r.offset() >= limit {
197 self.check_damage()?;
198 }
199 f(r);
200 }
201 }
202 }
203 self.check_damage()
204 }
205
206 pub fn records(&self) -> Result<Vec<Vec<Vec<u8>>>> {
209 let mut out = Vec::new();
210 let mut err = None;
211 self.each_record(|r| match r.values() {
212 Ok(vs) => out.push(vs.into_iter().map(|v| v.into_owned()).collect()),
213 Err(e) => err = Some(e),
214 })?;
215 match err {
216 Some(e) => Err(e),
217 None => Ok(out),
218 }
219 }
220
221 fn check_damage(&self) -> Result<()> {
222 if self.continue_past_damage {
223 return Ok(());
224 }
225 match self.damaged.first() {
226 Some(&d) => Err(Error::DamagedBlock {
227 index: d,
228 resume_offset: self.block_end(d),
229 }),
230 None => Ok(()),
231 }
232 }
233
234 fn parse_committed(&mut self) -> Result<Container<'a>> {
239 let mut skip: HashMap<usize, usize> = self.torn_regions.iter().copied().collect();
240 let container = loop {
241 let mut parser = Parser::with_skip(self.buf, skip.clone());
242 match Container::parse(self.buf, self.committed_end, &mut parser) {
243 Ok(c) => break c,
244 Err(e) => {
245 let Some(pos) = e.position() else {
246 return Err(e);
247 };
248 let Some(i) = self.block_at(pos) else {
249 return Err(e);
250 };
251 if skip.contains_key(&self.blocks[i].0) {
252 return Err(e);
253 }
254 self.damaged.push(i);
255 skip.insert(self.blocks[i].0, self.block_end(i));
256 }
257 }
258 };
259 self.damaged.sort_unstable();
260 Ok(container)
261 }
262
263 fn block_at(&self, pos: usize) -> Option<usize> {
265 self.blocks.iter().rposition(|&(s, _)| s <= pos)
266 }
267
268 fn scan(&mut self) {
269 let buf = self.buf;
270 let len = buf.len();
271 let mut pos = 0;
272 let mut block_start = 0;
273 let mut in_text = false;
274 while pos < len {
275 let b = buf[pos];
276 if in_text {
277 if b == DLE {
278 pos += 2;
279 continue;
280 } else if b == ETX {
281 in_text = false;
282 } else if b == ETB {
283 self.blocks.push((block_start, pos));
284 pos = self.payload_end(pos + 1);
285 block_start = pos;
286 in_text = false;
287 continue;
288 } else if b == SYN || b == EOT || b == EM {
289 in_text = false;
291 if b == SYN {
292 self.tear(block_start, pos);
293 block_start = pos;
294 }
295 }
296 pos += 1;
297 } else {
298 if b == STX {
299 in_text = true;
300 } else if b == ETB {
301 self.blocks.push((block_start, pos));
302 pos = self.payload_end(pos + 1);
303 block_start = pos;
304 continue;
305 } else if b == SYN && pos > 0 {
306 self.tear(block_start, pos);
308 block_start = pos;
309 }
310 pos += 1;
311 }
312 }
313 self.torn = self.torn_tail();
314 }
315
316 fn tear(&mut self, start: usize, end: usize) {
319 if scan::layout(self.buf, start, end) < end {
320 self.torn_regions.push((start, end));
321 }
322 }
323
324 fn payload_end(&mut self, pos: usize) -> usize {
327 let buf = self.buf;
328 let len = buf.len();
329 let mut p = scan::layout(buf, pos, len);
330 if p < len && buf[p] >= 0x20 {
331 p = scan::plain(buf, p, len);
332 while p > pos && buf[p - 1] == SP {
334 p -= 1;
335 }
336 } else {
337 p = pos; }
339 self.committed_end = p;
340 p
341 }
342
343 fn torn_tail(&self) -> bool {
345 let buf = self.buf;
346 let len = buf.len();
347 let mut pos = self.committed_end;
348 loop {
349 pos = scan::layout(buf, pos, len);
350 if pos >= len {
351 return false;
352 }
353 let b = buf[pos];
354 if b == EOT {
355 pos += 1;
356 } else if b == EM {
357 return false; } else if b == BEL {
359 let p2 = scan::layout(buf, pos + 1, len);
360 if p2 < len && buf[p2] < 0x20 && buf[p2] != STX {
361 return true; }
363 match scan::comment(buf, pos, len) {
364 Ok(p) => pos = p,
365 Err(_) => return true,
366 }
367 } else {
368 return true;
369 }
370 }
371 }
372}
373
374pub fn last_commit_end(buf: &[u8]) -> usize {
378 let mut i = buf.len();
379 while i > 0 {
380 i -= 1;
381 if buf[i] != ETB {
382 continue;
383 }
384 let dles = buf[..i].iter().rev().take_while(|&&b| b == DLE).count();
385 if dles % 2 == 0 {
386 return scan::plain(buf, i + 1, buf.len());
387 }
388 }
389 0
390}
391
392fn commit_bytes<F: FnOnce(&mut Builder)>(f: F) -> Vec<u8> {
394 let mut b = Builder::new();
395 f(&mut b);
396 b.etb();
397 b.into_bytes()
398}
399
400pub struct StreamWriter<W: Write> {
405 sink: W,
406}
407
408impl<W: Write> StreamWriter<W> {
409 pub fn new(sink: W) -> Self {
410 StreamWriter { sink }
411 }
412
413 pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
415 self.batch(|b| {
416 b.syn();
417 for (k, v) in heading {
418 b.heading(k, v);
419 }
420 })
421 }
422
423 pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
425 self.batch(|b| {
426 b.record(fields);
427 })
428 }
429
430 pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
432 self.batch(|b| {
433 b.map(pairs);
434 })
435 }
436
437 pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
439 self.batch(|b| {
440 b.header(names);
441 })
442 }
443
444 pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
446 self.batch(|b| {
447 b.group(name, headers);
448 })
449 }
450
451 pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
453 self.sink.write_all(&commit_bytes(f))?;
454 self.sink.flush()
455 }
456
457 pub fn get_ref(&self) -> &W {
458 &self.sink
459 }
460
461 pub fn get_mut(&mut self) -> &mut W {
462 &mut self.sink
463 }
464
465 pub fn into_inner(self) -> W {
467 self.sink
468 }
469}
470
471pub struct FileLog {
474 w: StreamWriter<File>,
475 sync: bool,
476}
477
478impl FileLog {
479 pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
481 self.w.start(heading)?;
482 self.sync()
483 }
484
485 pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
486 self.w.record(fields)?;
487 self.sync()
488 }
489
490 pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
491 self.w.map(pairs)?;
492 self.sync()
493 }
494
495 pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
496 self.w.header(names)?;
497 self.sync()
498 }
499
500 pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
501 self.w.group(name, headers)?;
502 self.sync()
503 }
504
505 pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
507 self.w.batch(f)?;
508 self.sync()
509 }
510
511 fn sync(&mut self) -> io::Result<()> {
512 if self.sync {
513 self.w.get_mut().sync_all()?;
514 }
515 Ok(())
516 }
517}
518
519pub fn open_log(path: impl AsRef<Path>) -> io::Result<FileLog> {
522 open_log_with(path, true)
523}
524
525pub fn open_log_with(path: impl AsRef<Path>, sync: bool) -> io::Result<FileLog> {
527 let path = path.as_ref();
528 if path.exists() {
529 repair_log(path)?;
530 }
531 let file = OpenOptions::new().create(true).append(true).open(path)?;
532 Ok(FileLog {
533 w: StreamWriter::new(file),
534 sync,
535 })
536}
537
538pub fn repair_log(path: impl AsRef<Path>) -> io::Result<()> {
540 let path = path.as_ref();
541 let bytes = fs::read(path)?;
542 let r = StreamReader::new(&bytes);
543 if r.torn() {
544 let f = OpenOptions::new().write(true).open(path)?;
545 f.set_len(r.committed_end() as u64)?;
546 }
547 Ok(())
548}
549
550pub fn read_log(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
552 fs::read(path)
553}