1use crate::*;
18use std::borrow::Cow;
19use std::fs::{self, File, OpenOptions};
20use std::io::{self, Write};
21use std::path::Path;
22
23pub struct StreamReader<'a> {
26 buf: &'a [u8],
27 committed_end: usize,
28 blocks: Vec<(usize, usize)>,
29 damaged: Vec<usize>,
30 torn: bool,
31}
32
33impl<'a> StreamReader<'a> {
34 pub fn new(buf: &'a [u8]) -> Self {
35 let mut r = StreamReader {
36 buf,
37 committed_end: 0,
38 blocks: Vec::new(),
39 damaged: Vec::new(),
40 torn: false,
41 };
42 r.scan();
43 r
44 }
45
46 pub fn buf(&self) -> &'a [u8] {
47 self.buf
48 }
49
50 pub fn committed_end(&self) -> usize {
52 self.committed_end
53 }
54
55 pub fn committed(&self) -> &'a [u8] {
57 &self.buf[..self.committed_end]
58 }
59
60 pub fn tail(&self) -> &'a [u8] {
62 &self.buf[self.committed_end..]
63 }
64
65 pub fn torn(&self) -> bool {
68 self.torn
69 }
70
71 pub fn block_count(&self) -> usize {
72 self.blocks.len()
73 }
74
75 pub fn block(&self, i: usize) -> &'a [u8] {
78 let (s, e) = self.blocks[i];
79 &self.buf[s..e]
80 }
81
82 pub fn block_ranges(&self) -> &[(usize, usize)] {
84 &self.blocks
85 }
86
87 pub fn blocks(&self) -> impl Iterator<Item = &'a [u8]> + '_ {
88 (0..self.blocks.len()).map(move |i| self.block(i))
89 }
90
91 pub fn damaged(&self) -> &[usize] {
93 &self.damaged
94 }
95
96 pub fn is_damaged(&self, i: usize) -> bool {
97 self.damaged.contains(&i)
98 }
99
100 pub fn undamaged(&self) -> Cow<'a, [u8]> {
104 if self.damaged.is_empty() {
105 return Cow::Borrowed(self.committed());
106 }
107 let mut out = Vec::new();
108 for (i, &(s, e)) in self.blocks.iter().enumerate() {
109 if !self.damaged.contains(&i) {
110 out.extend_from_slice(&self.buf[s..e]);
111 }
112 }
113 Cow::Owned(out)
114 }
115
116 pub fn records(&self) -> Result<Vec<Vec<Vec<u8>>>> {
119 let bytes = self.undamaged();
120 let doc = Document::new(&bytes)?;
121 let mut out = Vec::new();
122 for g in doc.groups() {
123 for r in g.records() {
124 out.push(r.values()?.into_iter().map(|v| v.into_owned()).collect());
125 }
126 }
127 Ok(out)
128 }
129
130 fn scan(&mut self) {
131 let buf = self.buf;
132 let len = buf.len();
133 let mut pos = 0;
134 let mut block_start = 0;
135 let mut in_text = false;
136 let mut depth = 0usize;
137 while pos < len {
138 let b = buf[pos];
139 if in_text {
140 if b == DLE {
141 pos += 2;
142 continue;
143 } else if b == ETX {
144 in_text = false;
145 } else if b == ETB {
146 self.commit(block_start, pos, true);
147 pos = self.payload_end(pos + 1);
148 block_start = pos;
149 in_text = false;
150 depth = 0;
151 continue;
152 } else if b == SYN || b == EOT || b == EM {
153 in_text = false;
155 depth = 0;
156 if b == SYN {
157 block_start = pos;
158 }
159 }
160 pos += 1;
161 } else {
162 if b == STX {
163 in_text = true;
164 } else if b == DLE {
165 depth += 1;
166 } else if b == CAN {
167 depth = depth.saturating_sub(1);
168 } else if b == ETB {
169 self.commit(block_start, pos, depth > 0);
170 pos = self.payload_end(pos + 1);
171 block_start = pos;
172 depth = 0;
173 continue;
174 } else if b == SYN && pos > 0 {
175 block_start = pos;
177 depth = 0;
178 }
179 pos += 1;
180 }
181 }
182 self.torn = self.torn_tail();
183 }
184
185 fn commit(&mut self, start: usize, stop: usize, damaged: bool) {
186 self.blocks.push((start, stop));
187 if damaged {
188 self.damaged.push(self.blocks.len() - 1);
189 }
190 }
191
192 fn payload_end(&mut self, pos: usize) -> usize {
195 let buf = self.buf;
196 let len = buf.len();
197 let mut p = scan::layout(buf, pos, len);
198 if p < len && buf[p] >= 0x20 {
199 p = scan::plain(buf, p, len);
200 while p > pos && buf[p - 1] == SP {
202 p -= 1;
203 }
204 } else {
205 p = pos; }
207 self.committed_end = p;
208 p
209 }
210
211 fn torn_tail(&self) -> bool {
213 let buf = self.buf;
214 let len = buf.len();
215 let mut pos = self.committed_end;
216 loop {
217 pos = scan::layout(buf, pos, len);
218 if pos >= len {
219 return false;
220 }
221 let b = buf[pos];
222 if b == EOT {
223 pos += 1;
224 } else if b == EM {
225 return false; } else if b == BEL {
227 let p2 = scan::layout(buf, pos + 1, len);
228 if p2 < len && buf[p2] < 0x20 && buf[p2] != STX {
229 return true; }
231 match scan::comment(buf, pos, len) {
232 Ok(p) => pos = p,
233 Err(_) => return true,
234 }
235 } else {
236 return true;
237 }
238 }
239 }
240}
241
242pub fn last_commit_end(buf: &[u8]) -> usize {
246 let mut i = buf.len();
247 while i > 0 {
248 i -= 1;
249 if buf[i] != ETB {
250 continue;
251 }
252 let dles = buf[..i].iter().rev().take_while(|&&b| b == DLE).count();
253 if dles % 2 == 0 {
254 return scan::plain(buf, i + 1, buf.len());
255 }
256 }
257 0
258}
259
260fn commit_bytes<F: FnOnce(&mut Builder)>(f: F) -> Vec<u8> {
262 let mut b = Builder::new();
263 f(&mut b);
264 b.etb();
265 b.into_bytes()
266}
267
268pub struct StreamWriter<W: Write> {
273 sink: W,
274}
275
276impl<W: Write> StreamWriter<W> {
277 pub fn new(sink: W) -> Self {
278 StreamWriter { sink }
279 }
280
281 pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
283 self.batch(|b| {
284 b.syn();
285 for (k, v) in heading {
286 b.heading(k, v);
287 }
288 })
289 }
290
291 pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
293 self.batch(|b| {
294 b.record(fields);
295 })
296 }
297
298 pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
300 self.batch(|b| {
301 b.map(pairs);
302 })
303 }
304
305 pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
307 self.batch(|b| {
308 b.header(names);
309 })
310 }
311
312 pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
314 self.batch(|b| {
315 b.group(name, headers);
316 })
317 }
318
319 pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
321 self.sink.write_all(&commit_bytes(f))?;
322 self.sink.flush()
323 }
324
325 pub fn get_ref(&self) -> &W {
326 &self.sink
327 }
328
329 pub fn get_mut(&mut self) -> &mut W {
330 &mut self.sink
331 }
332
333 pub fn into_inner(self) -> W {
335 self.sink
336 }
337}
338
339pub struct FileLog {
342 w: StreamWriter<File>,
343 sync: bool,
344}
345
346impl FileLog {
347 pub fn start(&mut self, heading: &[(&str, &str)]) -> io::Result<()> {
349 self.w.start(heading)?;
350 self.sync()
351 }
352
353 pub fn record<T: AsRef<[u8]>>(&mut self, fields: &[T]) -> io::Result<()> {
354 self.w.record(fields)?;
355 self.sync()
356 }
357
358 pub fn map<T: AsRef<[u8]>>(&mut self, pairs: &[(&str, T)]) -> io::Result<()> {
359 self.w.map(pairs)?;
360 self.sync()
361 }
362
363 pub fn header(&mut self, names: &[&str]) -> io::Result<()> {
364 self.w.header(names)?;
365 self.sync()
366 }
367
368 pub fn group(&mut self, name: &str, headers: Option<&[&str]>) -> io::Result<()> {
369 self.w.group(name, headers)?;
370 self.sync()
371 }
372
373 pub fn batch<F: FnOnce(&mut Builder)>(&mut self, f: F) -> io::Result<()> {
375 self.w.batch(f)?;
376 self.sync()
377 }
378
379 fn sync(&mut self) -> io::Result<()> {
380 if self.sync {
381 self.w.get_mut().sync_all()?;
382 }
383 Ok(())
384 }
385}
386
387pub fn open_log(path: impl AsRef<Path>) -> io::Result<FileLog> {
390 open_log_with(path, true)
391}
392
393pub fn open_log_with(path: impl AsRef<Path>, sync: bool) -> io::Result<FileLog> {
395 let path = path.as_ref();
396 if path.exists() {
397 repair_log(path)?;
398 }
399 let file = OpenOptions::new().create(true).append(true).open(path)?;
400 Ok(FileLog {
401 w: StreamWriter::new(file),
402 sync,
403 })
404}
405
406pub fn repair_log(path: impl AsRef<Path>) -> io::Result<()> {
408 let path = path.as_ref();
409 let bytes = fs::read(path)?;
410 let r = StreamReader::new(&bytes);
411 if r.torn() {
412 let f = OpenOptions::new().write(true).open(path)?;
413 f.set_len(r.committed_end() as u64)?;
414 }
415 Ok(())
416}
417
418pub fn read_log(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
420 fs::read(path)
421}