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
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
//! Cutting a document into pieces: the byte range of a line range, and splitting the whole
//! document into part files of a given size or line count, always at line boundaries. Both
//! stream, so any file size works.

use crate::decompress::{Kind, Packer};
use std::fs::{self, File};
use std::io::{self, BufWriter, Write};
use std::ops::Range;
use std::path::{Path, PathBuf};

use crate::jobs::{CancelToken, Progress};
use crate::text::TextBuf;

const STEP: u64 = 16 << 20;

/// Exact start of 0-based `line`: from the line index when it already covers it, otherwise by
/// counting line breaks from the start. `None` when the line does not exist or on cancel.
pub fn exact_line_start(
    buf: &TextBuf,
    line: u64,
    cancel: &CancelToken,
    progress: Option<&Progress>,
) -> Option<u64> {
    if line == 0 {
        return Some(0);
    }
    if let Some((off, true)) = buf.line_start(line) {
        return Some(off);
    }
    let codec = buf.codec;
    let unit = codec.unit() as u64;
    let len = buf.len();
    let mut seen = 0u64;
    let mut pos = 0u64;
    while pos < len {
        if cancel.is_cancelled() {
            return None;
        }
        let end = (pos + STEP).min(len);
        let b = buf.read(pos..end)?;
        let n = codec.count_nl(&b, pos);
        if seen + n >= line {
            let i = codec.nth_nl(&b, pos, line - seen)?;
            return Some(pos + i as u64 + unit);
        }
        seen += n;
        if let Some(p) = progress {
            p.set_done(end);
        }
        pos = end;
    }
    None
}

/// Byte range of the 1-based, inclusive line range `from..=to` (including the last line's
/// break). `None` when `from` is past the end or on cancel.
pub fn line_range(
    buf: &TextBuf,
    from: u64,
    to: u64,
    cancel: &CancelToken,
    progress: Option<&Progress>,
) -> Option<Range<u64>> {
    if let Some(p) = progress {
        p.set_total(buf.len());
    }
    let start = exact_line_start(buf, from.max(1) - 1, cancel, progress)?;
    let end = exact_line_start(buf, to.max(from), cancel, progress);
    if cancel.is_cancelled() {
        return None;
    }
    Some(start.max(buf.codec.bom_len as u64)..end.unwrap_or(buf.len()))
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SplitBy {
    /// Parts of at least this many bytes (each ends at the first line break after the size).
    Bytes(u64),
    /// Parts of this many lines.
    Lines(u64),
}

/// How a CSV is split: between records only, and with its header row at the top of every
/// part when `repeat_header` (the header is then not counted as a row).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CsvSplit {
    pub dialect: crate::csv::Dialect,
    pub repeat_header: bool,
}

/// `app.log` → `app.part001.log` in `dir`.
pub fn part_path(dir: &Path, name: &str, n: usize) -> PathBuf {
    let p = Path::new(name);
    let stem = p
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| name.to_string());
    match p.extension() {
        Some(ext) => dir.join(format!("{stem}.part{n:03}.{}", ext.to_string_lossy())),
        None => dir.join(format!("{stem}.part{n:03}")),
    }
}

/// [`part_path`] with the compression's extension added (`app.part001.log.gz`).
pub fn packed_part_path(dir: &Path, name: &str, n: usize, pack: Option<Kind>) -> PathBuf {
    let p = part_path(dir, name, n);
    match pack {
        Some(k) => {
            let mut s = p.into_os_string();
            s.push(".");
            s.push(k.extension());
            PathBuf::from(s)
        }
        None => p,
    }
}

struct Parts<'a> {
    dir: &'a Path,
    name: &'a str,
    pack: Option<Kind>,
    bom: Vec<u8>,
    /// Written after the byte order mark at the top of every part but the first.
    header: Vec<u8>,
    cur: Option<Packer<BufWriter<File>>>,
    made: Vec<PathBuf>,
    bytes: u64,
    lines: u64,
}

impl Parts<'_> {
    fn write(&mut self, b: &[u8]) -> io::Result<()> {
        if b.is_empty() {
            return Ok(());
        }
        if self.cur.is_none() {
            let p = packed_part_path(self.dir, self.name, self.made.len() + 1, self.pack);
            let f = File::options().write(true).create_new(true).open(&p)?;
            self.made.push(p);
            let mut w = Packer::new(BufWriter::with_capacity(8 << 20, f), self.pack)?;
            w.write_all(&self.bom)?;
            if self.made.len() > 1 {
                w.write_all(&self.header)?;
            }
            self.cur = Some(w);
        }
        self.bytes += b.len() as u64;
        self.cur.as_mut().unwrap().write_all(b)
    }

    fn close(&mut self) -> io::Result<()> {
        self.bytes = 0;
        self.lines = 0;
        if let Some(w) = self.cur.take() {
            let mut w = w.finish()?;
            w.flush()?;
            w.get_ref().sync_all()?;
        }
        Ok(())
    }
}

/// Splits the document into part files in `dir` named after `name` (see [`part_path`]),
/// compressed with `pack` when given. A part never ends inside a line, and with `csv` never
/// inside a record (a quoted field may hold line breaks; `SplitBy::Lines` then counts
/// records); documents with a byte order mark get it at the start of every part. Returns the files written, or `None` when
/// cancelled (the parts are then removed, as they are on an error).
#[allow(clippy::too_many_arguments)]
pub fn split_to_files(
    buf: &TextBuf,
    by: SplitBy,
    dir: &Path,
    name: &str,
    pack: Option<Kind>,
    csv: Option<CsvSplit>,
    cancel: &CancelToken,
    progress: &Progress,
) -> io::Result<Option<Vec<PathBuf>>> {
    let codec = buf.codec;
    let mut csv_state = crate::csv::State::FieldStart;
    let unit = codec.unit() as u64;
    let bom = codec.bom_len as u64;
    let len = buf.len();
    progress.set_total(len);
    let mut parts = Parts {
        dir,
        name,
        pack,
        bom: buf.read(0..bom).map(|b| b.into_owned()).unwrap_or_default(),
        header: Vec::new(),
        cur: None,
        made: Vec::new(),
        bytes: 0,
        lines: 0,
    };
    // The header record, repeated in every part and not counted as a row.
    let mut header_end = 0;
    if let Some(c) = csv.filter(|c| c.repeat_header) {
        let first = c.dialect.first(buf);
        if let Some(b) = buf.read(first..(first + (64 << 10)).min(len)) {
            if let Some(r) = crate::csv::records_in(&codec, c.dialect, &b, false, 1).first() {
                header_end = first + r.2 as u64;
                parts.header = b[..r.2].to_vec();
            }
        }
    }
    let r = (|| -> io::Result<bool> {
        let mut pos = bom;
        while pos < len {
            if cancel.is_cancelled() {
                return Ok(false);
            }
            let end = (pos + STEP).min(len);
            let b = buf
                .read(pos..end)
                .ok_or_else(|| io::Error::other("Could not read the document"))?;
            let mut i = 0usize;
            while i < b.len() {
                let base = pos + i as u64;
                let rest = &b[i..];
                // Index into `rest` just past the line break that ends the current part, if any.
                let cut = match (csv, by) {
                    (Some(c), _) => record_cut(
                        &mut csv_state,
                        c.dialect,
                        codec,
                        rest,
                        base,
                        header_end,
                        by,
                        &mut parts,
                    ),
                    (None, SplitBy::Lines(n)) => {
                        let want = n.max(1) - parts.lines;
                        match codec.nth_nl(rest, base, want) {
                            Some(k) => Some(k + unit as usize),
                            None => {
                                parts.lines += codec.count_nl(rest, base);
                                None
                            }
                        }
                    }
                    (None, SplitBy::Bytes(n)) => {
                        let from = n
                            .saturating_sub(parts.bytes)
                            .saturating_sub(1)
                            .min(rest.len() as u64) as usize;
                        let from = from - (base as usize + from) % unit as usize;
                        codec
                            .find_nl(&rest[from..], base + from as u64)
                            .map(|k| from + k + unit as usize)
                    }
                };
                match cut {
                    Some(k) => {
                        parts.write(&rest[..k])?;
                        parts.close()?;
                        i += k;
                    }
                    None => {
                        parts.write(rest)?;
                        i = b.len();
                    }
                }
            }
            progress.set_done(end);
            pos = end;
        }
        parts.close()?;
        Ok(true)
    })();
    match r {
        Ok(true) => Ok(Some(std::mem::take(&mut parts.made))),
        other => {
            drop(parts.cur.take());
            for p in &parts.made {
                let _ = fs::remove_file(p);
            }
            other.map(|_| None)
        }
    }
}

/// Where in `rest` (at offset `base`) the current part ends for a CSV: just past the line break
/// of the record that makes it `n` records long, or the first record that ends past `n` bytes.
/// Counts the records it passes in `parts.lines`, except those ending by `header_end`; `st`
/// carries the quote state between calls.
#[allow(clippy::too_many_arguments)]
fn record_cut(
    st: &mut crate::csv::State,
    d: crate::csv::Dialect,
    codec: crate::encoding::Codec,
    rest: &[u8],
    base: u64,
    header_end: u64,
    by: SplitBy,
    parts: &mut Parts,
) -> Option<usize> {
    let unit = codec.unit();
    let nl = crate::csv::nl_value(&codec);
    let mut j = 0;
    while j + unit <= rest.len() {
        let c = crate::csv::unit_at(codec.enc, rest, j);
        j += unit;
        if st.step(c, d, nl) != crate::csv::Step::RecordEnd || base + (j as u64) <= header_end {
            continue;
        }
        parts.lines += 1;
        let done = match by {
            SplitBy::Lines(n) => parts.lines >= n.max(1),
            SplitBy::Bytes(n) => parts.bytes + j as u64 >= n,
        };
        if done {
            return Some(j);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encoding::{Codec, Encoding, NlByte};
    use crate::file::{OpenMode, Source};
    use crate::index;
    use std::sync::Arc;

    fn buf_with(data: &[u8], codec: Codec) -> (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 idx = index::build_blocking(&src, codec);
        let mut t = TextBuf::new(src, idx, codec);
        t.blocking = true;
        (f, t)
    }

    #[test]
    fn csv_parts_repeat_the_header() {
        let data = b"id,note\n1,\"a\nb\"\n2,c\n3,d\n";
        let (_f, t) = buf_with(data, Codec::utf8());
        let dir = tempfile::tempdir().unwrap();
        let files = split_to_files(
            &t,
            SplitBy::Lines(2),
            dir.path(),
            "t.csv",
            None,
            Some(CsvSplit {
                dialect: crate::csv::Dialect::new(b','),
                repeat_header: true,
            }),
            &CancelToken::new(),
            &Progress::default(),
        )
        .unwrap()
        .unwrap();
        let parts: Vec<String> = files
            .iter()
            .map(|f| String::from_utf8(fs::read(f).unwrap()).unwrap())
            .collect();
        assert_eq!(parts, ["id,note\n1,\"a\nb\"\n2,c\n", "id,note\n3,d\n"]);
    }

    #[test]
    fn csv_parts_end_between_records() {
        let data = b"id,note\n1,\"a\nb\"\n2,c\n3,\"d\ne\nf\"\n4,g\n";
        let (_f, t) = buf_with(data, Codec::utf8());
        let dir = tempfile::tempdir().unwrap();
        let files = split_to_files(
            &t,
            SplitBy::Lines(2),
            dir.path(),
            "t.csv",
            None,
            Some(CsvSplit {
                dialect: crate::csv::Dialect::new(b','),
                repeat_header: false,
            }),
            &CancelToken::new(),
            &Progress::default(),
        )
        .unwrap()
        .unwrap();
        let parts: Vec<String> = files
            .iter()
            .map(|f| String::from_utf8(fs::read(f).unwrap()).unwrap())
            .collect();
        assert_eq!(
            parts,
            ["id,note\n1,\"a\nb\"\n", "2,c\n3,\"d\ne\nf\"\n", "4,g\n"]
        );
        let dir = tempfile::tempdir().unwrap();
        let files = split_to_files(
            &t,
            SplitBy::Bytes(12),
            dir.path(),
            "t.csv",
            None,
            Some(CsvSplit {
                dialect: crate::csv::Dialect::new(b','),
                repeat_header: false,
            }),
            &CancelToken::new(),
            &Progress::default(),
        )
        .unwrap()
        .unwrap();
        let first = String::from_utf8(fs::read(&files[0]).unwrap()).unwrap();
        assert_eq!(first, "id,note\n1,\"a\nb\"\n");
    }

    #[test]
    fn line_ranges_with_and_without_the_index() {
        let (_f, mut t) = buf_with(b"l1\nl2\nl3\nl4", Codec::utf8());
        let c = CancelToken::new();
        assert_eq!(line_range(&t, 2, 3, &c, None), Some(3..9));
        assert_eq!(line_range(&t, 4, 9, &c, None), Some(9..11));
        assert_eq!(line_range(&t, 5, 6, &c, None), None);
        // An edit makes the counts inexact on a fresh buffer: the slow path must agree.
        t.replace(0..0, b"x\n");
        assert_eq!(line_range(&t, 3, 3, &c, None), Some(5..8));
    }

    fn split(data: &[u8], codec: Codec, by: SplitBy) -> Vec<Vec<u8>> {
        let (_f, t) = buf_with(data, codec);
        let dir = tempfile::tempdir().unwrap();
        let files = split_to_files(
            &t,
            by,
            dir.path(),
            "app.log",
            None,
            None,
            &CancelToken::new(),
            &Progress::default(),
        )
        .unwrap()
        .unwrap();
        files.iter().map(|p| fs::read(p).unwrap()).collect()
    }

    #[test]
    fn split_by_lines_and_size() {
        let data = b"a\nbb\nccc\ndddd\ne";
        assert_eq!(
            split(data, Codec::utf8(), SplitBy::Lines(2)),
            vec![b"a\nbb\n".to_vec(), b"ccc\ndddd\n".to_vec(), b"e".to_vec()]
        );
        assert_eq!(
            split(data, Codec::utf8(), SplitBy::Lines(5)),
            vec![data.to_vec()]
        );
        // At least 4 bytes per part, ending at the next line break.
        assert_eq!(
            split(data, Codec::utf8(), SplitBy::Bytes(4)),
            vec![
                b"a\nbb\n".to_vec(),
                b"ccc\n".to_vec(),
                b"dddd\n".to_vec(),
                b"e".to_vec()
            ]
        );
        assert_eq!(
            split(b"a\nb\n", Codec::utf8(), SplitBy::Lines(1)),
            vec![b"a\n".to_vec(), b"b\n".to_vec()]
        );
        assert_eq!(
            part_path(Path::new("d"), "app.log", 7),
            Path::new("d").join("app.part007.log")
        );
    }

    #[test]
    fn compressed_parts() {
        let data: Vec<u8> = (0..20_000)
            .flat_map(|i: u32| format!("line {i}\n").into_bytes())
            .collect();
        let (_f, t) = buf_with(&data, Codec::utf8());
        let dir = tempfile::tempdir().unwrap();
        let files = split_to_files(
            &t,
            SplitBy::Lines(7000),
            dir.path(),
            "app.log",
            Some(Kind::Zstd),
            None,
            &CancelToken::new(),
            &Progress::default(),
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            files
                .iter()
                .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
                .collect::<Vec<_>>(),
            [
                "app.part001.log.zst",
                "app.part002.log.zst",
                "app.part003.log.zst"
            ]
        );
        let mut all = Vec::new();
        for p in &files {
            crate::decompress::unpack_to(
                p,
                Kind::Zstd,
                &mut all,
                &CancelToken::new(),
                &Progress::default(),
            )
            .unwrap()
            .unwrap();
        }
        assert!(all == data);
    }

    #[test]
    fn split_utf16_keeps_the_bom_in_every_part() {
        let codec = Codec::new(Encoding::Utf16Le, NlByte::Lf, 2);
        let mut data = vec![0xFF, 0xFE];
        data.extend(codec.encode("one\ntwo\nthree\n"));
        let parts = split(&data, codec, SplitBy::Lines(2));
        let mut first = vec![0xFF, 0xFE];
        first.extend(codec.encode("one\ntwo\n"));
        let mut second = vec![0xFF, 0xFE];
        second.extend(codec.encode("three\n"));
        assert_eq!(parts, vec![first, second]);
    }

    #[test]
    fn existing_part_is_not_overwritten() {
        let (_f, t) = buf_with(b"a\nb\nc\n", Codec::utf8());
        let dir = tempfile::tempdir().unwrap();
        fs::write(part_path(dir.path(), "x.txt", 2), b"keep").unwrap();
        let r = split_to_files(
            &t,
            SplitBy::Lines(1),
            dir.path(),
            "x.txt",
            None,
            None,
            &CancelToken::new(),
            &Progress::default(),
        );
        assert!(r.is_err());
        assert!(
            !part_path(dir.path(), "x.txt", 1).exists(),
            "partial output removed"
        );
        assert_eq!(
            fs::read(part_path(dir.path(), "x.txt", 2)).unwrap(),
            b"keep"
        );
    }
}