bigtext 0.16.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
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
//! Robustness tests for the parsers that read files from anywhere: random and broken input,
//! mixed from the pieces that matter to each parser, must neither panic nor give ranges outside
//! the input. Compressed files and archives, cut short or with bytes changed, must fail with an
//! error, not a panic or a hang. Seeded, so a failing case can be run again.

use std::io::Write;
use std::sync::{Arc, Mutex};

use crate::csv::{self, Dialect, ScanEnd};
use crate::csv_rows::{self, RecordIndex};
use crate::decompress::{self, Archive, Kind, Packer};
use crate::encoding::Codec;
use crate::file::{OpenMode, Source};
use crate::index;
use crate::jobs::{CancelToken, Progress};
use crate::text::rows::SEG;
use crate::text::TextBuf;

/// How many times more inputs to try: `BIGTEXT_FUZZ_ROUNDS=50 cargo test --lib robustness`
/// for a longer run (1 by default).
pub(crate) fn rounds(n: u64) -> u64 {
    let k = std::env::var("BIGTEXT_FUZZ_ROUNDS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(1);
    n * k.max(1)
}

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }
    fn below(&mut self, n: u64) -> u64 {
        self.next() % n.max(1)
    }
}

/// `len` bytes or a little more, picked from `pieces`, with now and then a random byte.
fn noise(r: &mut Rng, pieces: &[&[u8]], len: usize) -> Vec<u8> {
    let mut v = Vec::with_capacity(len + 64);
    while v.len() < len {
        if r.below(50) == 0 {
            v.push(r.next() as u8);
        } else {
            v.extend_from_slice(pieces[r.below(pieces.len() as u64) as usize]);
        }
    }
    v
}

/// Up to `max` bytes of [`noise`].
fn noise_upto(r: &mut Rng, pieces: &[&[u8]], max: u64) -> Vec<u8> {
    let n = r.below(max) as usize;
    noise(r, pieces, n)
}

fn buf_with(data: &[u8]) -> (tempfile::NamedTempFile, TextBuf) {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(data).unwrap();
    f.flush().unwrap();
    let src = Arc::new(Source::open(f.path(), OpenMode::Auto).unwrap());
    let codec = Codec::utf8();
    let idx = index::build_blocking(&src, codec);
    let mut t = TextBuf::new(src, idx, codec);
    t.blocking = true;
    (f, t)
}

const CSV_PIECES: &[&[u8]] = &[
    b"a",
    b"12",
    b",",
    b",",
    b";",
    b"\"",
    b"\"\"",
    b"\n",
    b"\r\n",
    b"\r",
    b"\t",
    b" ",
    "\u{171}".as_bytes(),
    "\u{65e5}".as_bytes(),
    b"\"x,y\"",
    b"\"q\nw\"",
];

#[test]
fn csv_records_and_rows_tile_any_bytes() {
    let cancel = CancelToken::new();
    for seed in 1..=rounds(40) {
        let mut r = Rng(seed * 0x9E37_79B9);
        let size = if seed % 5 == 0 {
            3 * SEG as usize
        } else {
            r.below(20_000) as usize
        };
        let data = noise(&mut r, CSV_PIECES, size);
        let (_f, buf) = buf_with(&data);
        let len = buf.len();
        let d = Dialect::new(b',');
        // Records follow one another and their fields stay inside them.
        let mut next = d.first(&buf);
        let end = csv::for_each_record(&buf, d, &cancel, None, |rec| {
            assert_eq!(rec.content.start, next, "seed {seed}");
            assert!(
                rec.content.end <= rec.next && rec.next <= len,
                "seed {seed}"
            );
            for f in rec.fields {
                assert!(rec.content.start <= f.start && f.end <= rec.content.end);
            }
            next = rec.next;
            true
        });
        assert_eq!(end, ScanEnd::Done);
        let _ = csv::detect_table(&buf.codec, &data, true, b',', 0);
        // The table's rows tile the document, stay bounded and are found from any offset.
        let out = Mutex::new(Arc::new(RecordIndex::empty(d)));
        csv_rows::index_records(&buf, d, &cancel, None, &out, &|| {});
        let idx = out.lock().unwrap().clone();
        let mut rows = vec![csv_rows::row_at(&buf, &idx, 0).unwrap()];
        while let Some(row) = csv_rows::next_row(&buf, &idx, rows.last().unwrap()).unwrap() {
            assert!(row.start > rows.last().unwrap().start, "seed {seed}");
            rows.push(row);
        }
        for w in rows.windows(2) {
            assert_eq!(w[0].seg.next, w[1].start, "seed {seed}");
            assert!(w[0].seg.next - w[0].start <= 2 * SEG + 16);
        }
        for _ in 0..50 {
            let p = r.below(len + 1);
            let row = csv_rows::row_at(&buf, &idx, p).unwrap();
            assert!(
                row.start <= p && (p < row.seg.next || row.seg.next == len),
                "seed {seed} at {p}"
            );
        }
    }
}

const SQL_PIECES: &[&[u8]] = &[
    b"CREATE TABLE ",
    b"`t`",
    b"\"public\".\"u\"",
    b" (id int, v text);\n",
    b"INSERT INTO ",
    b" VALUES (1,'a;b'),(2,'c\\'d');\n",
    b"'",
    b"\\'",
    b";",
    b"\n",
    b"-- note\n",
    b"/*",
    b"*/",
    b"/*!40101 SET NAMES utf8 */;\n",
    b"DELIMITER ;;\n",
    b"DELIMITER ;\n",
    b"$$",
    b"$f$",
    b"COPY public.u (id, v) FROM stdin;\n",
    b"1\tx\n",
    b"\\.\n",
    b"SET @saved_cs = 1;\n",
    b"\\restrict abc\n",
    b"ALTER TABLE ONLY u ADD CONSTRAINT f FOREIGN KEY (id) REFERENCES t(id);\n",
    b"CREATE VIEW w AS SELECT 1;\n",
    b"DROP TABLE IF EXISTS `t`;\n",
    b"BEGIN",
    b"END;;\n",
    b" ",
];

#[test]
fn sql_dump_scan_survives_any_dump() {
    let cancel = CancelToken::new();
    for seed in 1..=rounds(200) {
        let mut r = Rng(seed * 0x2545_F491);
        let data = noise_upto(&mut r, SQL_PIECES, 30_000);
        let (_f, buf) = buf_with(&data);
        let len = buf.len();
        let Ok(Some(dump)) = crate::sqldump::scan(&buf, &cancel, None, |_| {}) else {
            continue;
        };
        let inside = |r: &std::ops::Range<u64>| r.start <= r.end && r.end <= len;
        for t in &dump.tables {
            assert!(t.parts.iter().all(|p| inside(&p.range)), "seed {seed}");
        }
        assert!(dump
            .header
            .iter()
            .chain(&dump.prelude)
            .chain(&dump.other)
            .all(|p| inside(&p.range)));
        assert!(inside(&dump.footer), "seed {seed}");
        let all: Vec<usize> = (0..dump.tables.len()).collect();
        let mut out = Vec::new();
        crate::sqldump::write_tables(
            &buf,
            &dump,
            &all,
            crate::sqldump::Extract::WHOLE,
            &mut out,
            &cancel,
            None,
        )
        .unwrap();
    }
}

const LOG_PIECES: &[&[u8]] = &[
    b"10.0.0.1 - - ",
    b"[13/Nov/2026:10:00:00 +0000] ",
    b"\"GET /a?b=1 HTTP/1.1\" ",
    b"200 ",
    b"1234 ",
    b"\"-\" ",
    b"\"Mozilla/5.0\"",
    b"0.012",
    b"<34>",
    b"<165>1 ",
    b"Nov 13 10:00:00 ",
    b"host ",
    b"app[123]: ",
    b"2026-11-13T10:00:00.123Z ",
    b"#Fields: date time cs-uri-stem sc-status\n",
    b"https ",
    b"\n",
    b" ",
    b"\"",
    b"-",
];

#[test]
fn log_formats_survive_any_lines() {
    for seed in 1..=rounds(300) {
        let mut r = Rng(seed * 0x1234_5679);
        let text = noise_upto(&mut r, LOG_PIECES, 4000);
        let lines: Vec<&[u8]> = text.split(|&b| b == b'\n').collect();
        for line in &lines {
            let _ = crate::timestamp::parse_bytes(line);
            let _ = crate::patterns::template(line);
        }
        if let Some(f) = crate::logformat::Format::guess(&lines) {
            let mut s = crate::logformat::Splitter::new(&f);
            for line in &lines {
                let _ = s.split(line);
            }
        }
    }
}

const JSON_PIECES: &[&[u8]] = &[
    b"{",
    b"}",
    b"[",
    b"]",
    b":",
    b",",
    b"\"k\"",
    b"\"\\u00e9\"",
    b"\"\\",
    b"\"\\uD83D\"",
    b"1",
    b"-2.5e3",
    b"true",
    b"null",
    b" ",
    b"\n",
    b"\"open",
    b"0x",
    b"01",
];

#[test]
fn json_check_survives_any_bytes() {
    let cancel = CancelToken::new();
    for seed in 1..=rounds(200) {
        let mut r = Rng(seed * 0x0BAD_5EED);
        let data = noise_upto(&mut r, JSON_PIECES, 8000);
        let (_f, buf) = buf_with(&data);
        let _ = crate::json_check::check_document(&buf, &cancel, None);
    }
}

#[test]
fn queries_and_expressions_survive_any_text() {
    let q: &[&[u8]] = &[
        b".a", b".b.c", b" == ", b" != ", b" > ", b" <= ", b"\"x\"", b"1", b" and ", b" or ",
        b"not ", b"(", b")", b"[0]", b" ~ ", b"\"", b".", b" ",
    ];
    let e: &[&[u8]] = &[
        b"{a}", b"{b}", b"{", b"}", b"+", b"-", b"*", b"/", b"(", b")", b"substr(", b",", b"1",
        b"\"s\"", b"upper(", b" ", b"if(", b">", b"\"",
    ];
    let names = vec!["a".to_string(), "b".to_string()];
    for seed in 1..=rounds(2000) {
        let mut r = Rng(seed * 0x7F4A_7C15);
        let text = String::from_utf8_lossy(&noise_upto(&mut r, q, 60)).into_owned();
        let _ = crate::jsonq::FieldQuery::parse(&text);
        let text = String::from_utf8_lossy(&noise_upto(&mut r, e, 60)).into_owned();
        let _ = crate::csv_expr::Expr::compile(&text, &names);
        let _ = crate::timestamp::parse(&text);
    }
}

#[test]
fn redaction_survives_any_line() {
    let pieces: &[&[u8]] = &[
        b"token=",
        b"Bearer ",
        b"@",
        b"example.com",
        b"\"password\": \"",
        b"\"",
        b"?key=",
        b"&",
        b"10.0.0.",
        b"::",
        b"eyJ",
        b".",
        b" ",
        b"Cookie: ",
        "\u{171}".as_bytes(),
        b"\\",
        b"Authorization: ",
        b"a",
        b"1",
        b"ghs_",
        b"github_pat_",
        b"AKIA",
        b"xoxe.xoxb-1-",
        b"sk_live_",
        b"AIza",
        b"-",
        b"_",
    ];
    let opts = crate::redact::Options {
        ips: true,
        custom: vec![r"(\d+)".into()],
        ..Default::default()
    };
    let mut r = crate::redact::Redactor::new(&opts, [9; 16]).unwrap();
    for seed in 1..=rounds(500) {
        let mut rng = Rng(seed * 0x51ED_2701);
        let line = noise_upto(&mut rng, pieces, 400);
        let mut out = Vec::new();
        r.line(&line, &mut out);
    }
}

/// Runs one case on its own thread: a panic fails the test with the case named, and so does a
/// case still running after a minute (a decoder going round in a loop).
fn guarded(what: String, f: impl FnOnce() + Send + 'static) {
    use std::sync::mpsc::RecvTimeoutError;
    let (done, wait) = std::sync::mpsc::channel();
    let t = std::thread::spawn(move || {
        f();
        let _ = done.send(());
    });
    match wait.recv_timeout(std::time::Duration::from_secs(60)) {
        Ok(()) => t.join().unwrap(),
        Err(RecvTimeoutError::Disconnected) => panic!("{what}: panicked"),
        Err(RecvTimeoutError::Timeout) => panic!("{what}: still running after a minute"),
    }
}

/// A writer that takes this many bytes and then fails, like a full disk: a damaged length field
/// must not fill memory or the disk.
struct Capped(usize);

impl Write for Capped {
    fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
        if b.len() > self.0 {
            return Err(std::io::Error::other("more than the test takes"));
        }
        self.0 -= b.len();
        Ok(b.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// `packed` with a few bytes changed, cut short, or both. Half the changes fall near the start
/// or the end, where the headers, sizes and checksums are.
fn damage(r: &mut Rng, packed: &[u8]) -> Vec<u8> {
    let mut v = packed.to_vec();
    let how = r.below(3);
    if how != 1 {
        for _ in 0..=r.below(4) {
            let n = v.len() as u64;
            if n == 0 {
                break;
            }
            let i = match r.below(4) {
                0 => r.below(n.min(64)),
                1 => n - 1 - r.below(n.min(32)),
                _ => r.below(n),
            } as usize;
            v[i] = if r.below(2) == 0 {
                v[i] ^ (1 << r.below(8))
            } else {
                r.next() as u8
            };
        }
    }
    if how != 0 {
        let cut = r.below(v.len() as u64) as usize;
        v.truncate(cut);
    }
    v
}

fn pack(data: &[u8], kind: Option<Kind>) -> Vec<u8> {
    let mut p = Packer::new(Vec::new(), kind).unwrap();
    p.write_all(data).unwrap();
    p.finish().unwrap()
}

#[test]
fn damaged_compressed_files_fail_cleanly() {
    let dir = tempfile::tempdir().unwrap();
    for seed in 1..=rounds(4) {
        let mut r = Rng(seed * 0x6A09_E667);
        let text = noise_upto(&mut r, LOG_PIECES, 20_000);
        for kind in Kind::ALL {
            let packed = pack(&text, Some(kind));
            for v in 0..8 {
                let path = dir
                    .path()
                    .join(format!("{seed}-{v}.log.{}", kind.extension()));
                std::fs::write(&path, damage(&mut r, &packed)).unwrap();
                guarded(format!("{} seed {seed} case {v}", kind.name()), move || {
                    let _ = decompress::detect(&path);
                    let _ = decompress::estimate_unpacked(&path, kind);
                    let _ = decompress::unpack_to(
                        &path,
                        kind,
                        &mut Capped(8 << 20),
                        &CancelToken::new(),
                        &Progress::default(),
                    );
                });
            }
        }
    }
}

fn zip_of(files: &[(&str, Vec<u8>)]) -> Vec<u8> {
    let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
    for (name, data) in files {
        z.start_file(*name, zip::write::SimpleFileOptions::default())
            .unwrap();
        z.write_all(data).unwrap();
    }
    z.finish().unwrap().into_inner()
}

fn tar_of(files: &[(&str, Vec<u8>)]) -> Vec<u8> {
    let mut b = tar::Builder::new(Vec::new());
    for (name, data) in files {
        let mut h = tar::Header::new_gnu();
        h.set_size(data.len() as u64);
        h.set_mode(0o644);
        h.set_mtime(1_700_000_000);
        h.set_cksum();
        b.append_data(&mut h, name, &data[..]).unwrap();
    }
    b.into_inner().unwrap()
}

#[test]
fn damaged_archives_fail_cleanly() {
    let dir = tempfile::tempdir().unwrap();
    for seed in 1..=rounds(3) {
        let mut r = Rng(seed * 0xBB67_AE85);
        let files = [
            ("logs/app.log", noise_upto(&mut r, LOG_PIECES, 6000)),
            ("logs/old/db.log", noise_upto(&mut r, LOG_PIECES, 6000)),
        ];
        let tar = tar_of(&files);
        let mut archives = vec![("bundle.zip".to_string(), Archive::Zip, zip_of(&files))];
        for kind in [None].into_iter().chain(Kind::ALL.map(Some)) {
            let name = match kind {
                None => "bundle.tar".to_string(),
                Some(k) => format!("bundle.tar.{}", k.extension()),
            };
            archives.push((name, Archive::Tar(kind), pack(&tar, kind)));
        }
        for (name, archive, bytes) in archives {
            for v in 0..6 {
                let path = dir.path().join(format!("{seed}-{v}-{name}"));
                std::fs::write(&path, damage(&mut r, &bytes)).unwrap();
                guarded(format!("{name} seed {seed} case {v}"), move || {
                    let cancel = CancelToken::new();
                    let progress = Progress::default();
                    let _ = decompress::detect_archive(&path);
                    let listed = decompress::list_members(&path, archive, &cancel, &progress);
                    let mut names: Vec<String> = match listed {
                        Ok(Some(m)) => m.into_iter().take(3).map(|m| m.name).collect(),
                        _ => Vec::new(),
                    };
                    names.push("logs/app.log".into());
                    for name in names {
                        let unpacked =
                            decompress::unpack_member(&path, archive, &name, &cancel, &progress);
                        if let Ok(Some(out)) = unpacked {
                            decompress::remove_temp(&out);
                            assert!(!out.exists(), "{} left behind", out.display());
                        }
                    }
                });
            }
        }
    }
}