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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use std::fs::{File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter, SeekFrom};
use std::path::PathBuf;
#[derive(Debug)]
pub struct Item {
pub id: u32,
pub data: Vec<u8>,
pub known_eof: bool,
}
#[derive(Debug)]
pub struct TruncatedItem {
pub id: u32,
pub data: Vec<u8>,
pub known_eof: bool,
}
#[derive(Debug)]
pub enum Decoded {
Item(Item),
TruncatedItem(TruncatedItem),
}
const READ_CHUNK_SIZE: u32 = 8192;
const WRITE_CHUNK_SIZE: u32 = 8192;
const FAIL_FILE_SIZE: u32 = 2_147_483_647;
const MARKER_ESCAPE: u8 = '\\' as u8;
const MARKER_SEPARATOR: u8 = '\n' as u8;
const MARKER_SEPARATOR_REMAP: u8 = '$' as u8;
const MARKER_FAIL: u8 = '-' as u8;
const MARKER_FAIL_REMAP: u8 = '.' as u8;
const MAX_FILE_SIZE1: u32 = FAIL_FILE_SIZE - (3 * MAX_ITEM_SIZE);
const MAX_FILE_SIZE: u32 = 8388608;
const MAX_ITEM_SIZE: u32 = 65_536;
#[derive(Debug)]
pub struct Section {
reader: SectionReader,
writer: SectionWriter,
}
impl Section {
pub fn is_eof(offset: u32) -> bool {
offset >= MAX_FILE_SIZE
}
pub fn new(path: &PathBuf) -> io::Result<Section> {
let writer = SectionWriter::new(path)?;
let reader = SectionReader::new(path);
Ok(Section { reader, writer })
}
pub fn append(&mut self, data: &[u8]) -> io::Result<()> {
self.writer.append(data)
}
pub fn is_empty(&self) -> bool {
self.writer.is_empty()
}
pub fn is_full(&self) -> bool {
self.writer.is_full()
}
pub fn last_id(&mut self) -> Option<u32> {
self.writer.last_id()
}
pub fn sync(&mut self) -> io::Result<()> {
self.writer.sync()
}
pub fn stream(&self, id: Option<u32>) -> io::Result<impl Iterator<Item = io::Result<Item>>> {
self.reader.stream(id)
}
pub fn stream_with_truncated(
&self,
id: Option<u32>,
) -> io::Result<impl Iterator<Item = io::Result<Decoded>>> {
self.reader.stream_with_truncated(id)
}
}
#[derive(Debug)]
pub(crate) struct SectionReader {
path_buf: PathBuf,
}
impl SectionReader {
pub(crate) fn new(path: &PathBuf) -> SectionReader {
let path_buf = PathBuf::from(path);
SectionReader { path_buf }
}
pub(crate) fn stream(
&self,
id: Option<u32>,
) -> io::Result<impl Iterator<Item = io::Result<Item>>> {
let iterator = self.stream_with_truncated(id)?.filter_map(|i| match i {
Ok(Decoded::Item(i)) => Some(Ok(i)),
Ok(Decoded::TruncatedItem(_)) => None,
Err(e) => Some(Err(e)),
});
Ok(iterator)
}
pub(crate) fn stream_with_truncated(
&self,
id: Option<u32>,
) -> io::Result<impl Iterator<Item = io::Result<Decoded>>> {
let mut file = self.open_file()?;
let mut always_fail = false;
let mut position = if let Some(requested_id) = id {
file.seek(SeekFrom::Start(requested_id as u64))?;
requested_id
} else {
0
};
let buf_reader = BufReader::with_capacity(READ_CHUNK_SIZE as usize, file);
let iterator = SplitWithCarry {
buf: buf_reader,
carry: None,
};
let iterator = iterator.map(move |p| {
if always_fail {
Err(io::Error::new(
io::ErrorKind::Other,
"a previous error has halted further execution",
))
} else {
match p {
Ok(item) => {
let id = item.len();
let result = if id > MAX_ITEM_SIZE as usize {
always_fail = true;
Err(io::Error::new(
io::ErrorKind::Other,
format!("item at position {} exceeds the maximum length", position),
))
} else {
position += 1 + id as u32;
let known_eof = position >= MAX_FILE_SIZE;
Self::parse_item(position, item, known_eof)
};
result
}
Err(e) => {
always_fail = true;
Err(e)
}
}
}
});
Ok(iterator)
}
fn open_file(&self) -> io::Result<File> {
OpenOptions::new().read(true).open(&self.path_buf)
}
fn parse_item(id: u32, mut data: Vec<u8>, known_eof: bool) -> io::Result<Decoded> {
let len = data.len();
let mut escaped = false;
let mut i = 0;
let mut t = 0;
while i < len {
let byte = data[i];
if escaped && byte == MARKER_FAIL_REMAP {
data[i - t] = MARKER_FAIL;
escaped = false;
} else if escaped && byte == MARKER_SEPARATOR_REMAP {
data[i - t] = MARKER_SEPARATOR;
escaped = false;
} else if escaped && byte == MARKER_ESCAPE {
data[i - t] = MARKER_ESCAPE;
escaped = false;
} else if escaped {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("cannot parse file, invalid byte {} after escape", byte),
));
} else if byte == MARKER_ESCAPE {
escaped = true;
t += 1;
} else {
data[i - t] = data[i];
}
i += 1;
}
let new_length = len - t;
if len > 1 && data[len - 1] == MARKER_FAIL {
Ok(Decoded::TruncatedItem(TruncatedItem {
id,
data,
known_eof,
}))
} else {
data.truncate(new_length);
Ok(Decoded::Item(Item {
id,
data,
known_eof,
}))
}
}
}
pub struct SplitWithCarry<B> {
buf: B,
carry: Option<Vec<u8>>,
}
impl<B: BufRead> Iterator for SplitWithCarry<B> {
type Item = io::Result<Vec<u8>>;
fn next(&mut self) -> Option<io::Result<Vec<u8>>> {
let mut buf = Vec::new();
if let Some(ref mut c) = self.carry {
buf.append(c);
}
self.carry = None;
match self.buf.read_until(MARKER_SEPARATOR, &mut buf) {
Ok(0) => {
if !buf.is_empty() {
self.carry = Some(buf);
}
None
}
Ok(_n) => {
if buf[buf.len() - 1] == MARKER_SEPARATOR {
buf.pop();
Some(Ok(buf))
} else {
self.carry = Some(buf);
None
}
}
Err(e) => Some(Err(e)),
}
}
}
#[derive(Debug)]
struct SectionWriter {
buffer: BufWriter<File>,
item_buffer: [u8; 2],
last_id: Option<u32>,
position: u32,
}
impl SectionWriter {
fn new(path: &PathBuf) -> io::Result<SectionWriter> {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.write(true)
.read(true)
.open(path)?;
let meta = file.metadata()?;
let length = meta.len();
if length > FAIL_FILE_SIZE as u64 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"file size exceeds maximum",
));
}
let position = if length > 0 {
let mut buf = vec![0u8; 3];
file.seek(SeekFrom::Start(length - 1))?;
file.read_exact(&mut buf[0..1])?;
let length = if buf[0] == MARKER_SEPARATOR as u8 {
length
} else {
let write_marker = if length > 2 {
file.seek(SeekFrom::Start(length - 3))?;
file.read_exact(&mut buf[0..3])?;
buf[0] != MARKER_FAIL as u8 || buf[1] != MARKER_FAIL as u8
} else {
true
};
if write_marker {
file.write_all(&[
MARKER_FAIL as u8,
MARKER_FAIL as u8,
MARKER_SEPARATOR as u8,
])?;
file.flush()?;
length + 3
} else {
file.write_all(&[MARKER_SEPARATOR as u8])?;
file.flush()?;
length + 1
}
};
length as u32
} else {
0
};
file.seek(SeekFrom::Start(position as u64))?;
let last_id = last_id(&mut file, position as u32)?;
let buffer = BufWriter::with_capacity(WRITE_CHUNK_SIZE as usize, file);
let item_buffer: [u8; 2] = [0; 2];
Ok(SectionWriter {
buffer,
item_buffer,
last_id,
position,
})
}
fn append(&mut self, data: &[u8]) -> io::Result<()> {
if data.len() > MAX_ITEM_SIZE as usize {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"item exceeds max item size",
));
}
if self.is_full() {
return Err(io::Error::new(io::ErrorKind::Other, "section is full"));
}
let next_id = self.position;
for byte in data {
match *byte {
MARKER_ESCAPE => {
self.item_buffer[0] = MARKER_ESCAPE;
self.item_buffer[1] = MARKER_ESCAPE;
self.buffer.write_all(&self.item_buffer[0..2])?;
self.position += 2;
}
MARKER_SEPARATOR => {
self.item_buffer[0] = MARKER_ESCAPE;
self.item_buffer[1] = MARKER_SEPARATOR_REMAP;
self.buffer.write_all(&self.item_buffer[0..2])?;
self.position += 2;
}
MARKER_FAIL => {
self.item_buffer[0] = MARKER_ESCAPE;
self.item_buffer[1] = MARKER_FAIL_REMAP;
self.buffer.write_all(&self.item_buffer[0..2])?;
self.position += 2;
}
other => {
self.item_buffer[0] = other;
self.buffer.write_all(&self.item_buffer[0..1])?;
self.position += 1;
}
};
}
self.buffer.write_all(&[MARKER_SEPARATOR as u8])?;
self.position += 1;
self.last_id = Some(next_id);
if self.is_full() {
self.sync()?;
}
Ok(())
}
fn is_empty(&self) -> bool {
self.last_id == None
}
fn is_full(&self) -> bool {
self.position >= MAX_FILE_SIZE
}
fn last_id(&mut self) -> Option<u32> {
self.last_id
}
fn sync(&mut self) -> io::Result<()> {
self.buffer.flush()
}
}
fn last_id(file: &mut File, length: u32) -> io::Result<Option<u32>> {
let mut buf = vec![0u8; READ_CHUNK_SIZE as usize];
let mut total = 0;
let mut items = 0;
while total < length {
let pos = length - total;
let starting_at = if pos < READ_CHUNK_SIZE {
0
} else {
pos - READ_CHUNK_SIZE
};
let bytes_to_read = pos - starting_at;
file.seek(SeekFrom::Start(starting_at as u64))?;
file.read_exact(&mut buf[0..bytes_to_read as usize])?;
total += bytes_to_read;
let mut i = 1;
while i < bytes_to_read {
let p = bytes_to_read - i;
if buf[p as usize] == MARKER_SEPARATOR && items > 0 {
return Ok(Some(pos - p));
} else if buf[p as usize] == MARKER_SEPARATOR {
items += 1;
}
i += 1;
}
}
if length == 0 {
Ok(None)
} else if items == 0 {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"file missing record separator",
))
} else {
Ok(Some(0))
}
}
#[cfg(test)]
mod tests {
}