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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
//! Sparse, incremental line index over the *original* file.
//!
//! `cp[k]` is the number of newline units in `[0, min(k*BLOCK, len))`. Only one `u64` per 64 KB is
//! stored (50 GB → 6.4 MB). Exact lookups scan at most one block. Positions beyond the indexed
//! frontier are estimated from the average line length seen so far.

use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, RwLock};
use std::time::{Duration, Instant};

use crate::encoding::Codec;
use crate::file::Source;
use crate::jobs::{self, CancelToken, Throttle, Waker};

pub const BLOCK: u64 = 64 * 1024;
/// Bytes read per indexer step.
const BATCH: u64 = 64 * BLOCK;

pub struct LineIndex {
    len: u64,
    cp: RwLock<Vec<u64>>,
    done: AtomicBool,
    failed: AtomicBool,
    started: Instant,
    finished_after: RwLock<Option<Duration>>,
}

impl LineIndex {
    pub fn new(len: u64) -> Arc<LineIndex> {
        Self::with_prefix(len, vec![0])
    }

    /// Starts from previously computed checkpoints (e.g. the unchanged prefix after a save).
    pub fn with_prefix(len: u64, mut cp: Vec<u64>) -> Arc<LineIndex> {
        if cp.is_empty() {
            cp.push(0);
        }
        let max_entries = len.div_ceil(BLOCK) as usize + 1;
        cp.truncate(max_entries.max(1));
        let done = (cp.len() as u64 - 1) * BLOCK >= len;
        Arc::new(LineIndex {
            len,
            cp: RwLock::new(cp),
            done: AtomicBool::new(done),
            failed: AtomicBool::new(false),
            started: Instant::now(),
            finished_after: RwLock::new(if done { Some(Duration::ZERO) } else { None }),
        })
    }

    pub fn len(&self) -> u64 {
        self.len
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    pub fn is_done(&self) -> bool {
        self.done.load(Ordering::Acquire)
    }

    pub fn failed(&self) -> bool {
        self.failed.load(Ordering::Relaxed)
    }

    pub fn finished_after(&self) -> Option<Duration> {
        *self.finished_after.read().unwrap()
    }

    /// Bytes from the start of the file that are fully indexed.
    pub fn indexed_bytes(&self) -> u64 {
        let n = self.cp.read().unwrap().len() as u64 - 1;
        (n * BLOCK).min(self.len)
    }

    pub fn progress(&self) -> f32 {
        if self.len == 0 {
            1.0
        } else {
            self.indexed_bytes() as f32 / self.len as f32
        }
    }

    /// Total number of lines (newlines + 1) once indexing has finished.
    pub fn total_lines(&self) -> Option<u64> {
        if self.is_done() {
            Some(self.cp.read().unwrap().last().copied().unwrap_or(0) + 1)
        } else {
            None
        }
    }

    /// Newlines in the indexed prefix.
    pub fn indexed_newlines(&self) -> u64 {
        self.cp.read().unwrap().last().copied().unwrap_or(0)
    }

    pub fn memory_bytes(&self) -> usize {
        self.cp.read().unwrap().capacity() * 8
    }

    /// Checkpoints whose blocks end at or before `limit` (to carry over after a save).
    pub fn prefix_checkpoints(&self, limit: u64) -> Vec<u64> {
        let cp = self.cp.read().unwrap();
        let n = ((limit / BLOCK) as usize + 1).min(cp.len());
        cp[..n].to_vec()
    }

    /// Average bytes per line in the indexed prefix.
    pub fn avg_line_len(&self) -> f64 {
        let (bytes, lines) = {
            let cp = self.cp.read().unwrap();
            (
                ((cp.len() as u64 - 1) * BLOCK).min(self.len),
                *cp.last().unwrap(),
            )
        };
        if bytes == 0 {
            80.0
        } else if lines == 0 {
            bytes.max(1) as f64
        } else {
            bytes as f64 / lines as f64
        }
    }

    /// Exact number of newlines in `[0, off)`, if `off` lies in the indexed region.
    pub fn nl_before(&self, src: &Source, codec: &Codec, blocking: bool, off: u64) -> Option<u64> {
        let off = off.min(self.len);
        let k = (off / BLOCK) as usize;
        let base = {
            let cp = self.cp.read().unwrap();
            *cp.get(k)?
        };
        let bstart = k as u64 * BLOCK;
        if off == bstart {
            return Some(base);
        }
        let bytes = src.get(bstart..off, blocking)?;
        Some(base + codec.count_nl(&bytes, bstart))
    }

    /// Estimated newlines in `[0, off)` (exact when indexed).
    pub fn nl_before_est(
        &self,
        src: &Source,
        codec: &Codec,
        blocking: bool,
        off: u64,
    ) -> (u64, bool) {
        if let Some(n) = self.nl_before(src, codec, blocking, off) {
            return (n, true);
        }
        let idx = self.indexed_bytes();
        let base = self.indexed_newlines();
        let extra = off.saturating_sub(idx) as f64 / self.avg_line_len();
        (base + extra as u64, false)
    }

    /// Exact start offset of 0-based `line`, if the index covers it. `None` also when the line
    /// does not exist (beyond the last line of a fully indexed file).
    pub fn line_start(
        &self,
        src: &Source,
        codec: &Codec,
        blocking: bool,
        line: u64,
    ) -> Option<u64> {
        if line == 0 {
            return Some(0);
        }
        let (k, need) = {
            let cp = self.cp.read().unwrap();
            let pp = cp.partition_point(|&c| c < line);
            if pp == cp.len() {
                return None;
            }
            (pp - 1, line - cp[pp - 1])
        };
        let bstart = k as u64 * BLOCK;
        let bend = (bstart + BLOCK).min(self.len);
        let bytes = src.get(bstart..bend, blocking)?;
        let p = codec.nth_nl(&bytes, bstart, need)?;
        Some(bstart + p as u64 + codec.unit() as u64)
    }

    /// Start offset of `line`: exact if indexed, otherwise an estimate (not necessarily a line
    /// start; callers snap it).
    pub fn line_start_est(
        &self,
        src: &Source,
        codec: &Codec,
        blocking: bool,
        line: u64,
    ) -> (u64, bool) {
        if let Some(off) = self.line_start(src, codec, blocking, line) {
            return (off, true);
        }
        if self.is_done() {
            return (self.len, false);
        }
        let idx = self.indexed_bytes();
        let base = self.indexed_newlines();
        let est = idx as f64 + line.saturating_sub(base) as f64 * self.avg_line_len();
        ((est as u64).min(self.len), false)
    }

    fn push(&self, entries: &[u64]) {
        self.cp.write().unwrap().extend_from_slice(entries);
    }
}

/// Builds the index in the background, from the start of the file (so the top is navigable at
/// once). Cancelled via `cancel`; wakes the UI periodically.
///
/// A large file on a local disk is counted by several threads (see [`Source::parallel_reads`]);
/// network and removable drives, rotating disks and remote files keep one sequential reader,
/// where parallel reads would only compete for the same slow device or server.
/// `BIGTEXT_INDEX_THREADS` sets the number of threads (1: one reader for every file).
pub fn spawn_indexer(
    src: Arc<Source>,
    codec: Codec,
    index: Arc<LineIndex>,
    cancel: CancelToken,
    waker: Waker,
) -> std::thread::JoinHandle<()> {
    jobs::spawn("indexer", move || {
        let remaining = index.len - index.indexed_bytes();
        let threads = indexer_threads(&src, remaining, max_index_threads());
        run_indexer(&src, codec, &index, &cancel, &waker, threads, BATCH);
    })
}

/// Most threads one indexer uses: newline counting runs at memory speed long before this.
const MAX_INDEX_THREADS: usize = 8;
/// Below this many batches left the file is counted by one thread.
const MIN_PARALLEL_BATCHES: u64 = 4;
/// A worker reads its batch in pieces this large, so that the bytes it counts are still in its
/// core's cache (several times faster than counting 4 MB read in one go, measured).
const PIECE: u64 = 4 * BLOCK;

/// Threads an indexer may use: `BIGTEXT_INDEX_THREADS` if set (1 to 64), otherwise the
/// available parallelism, at most [`MAX_INDEX_THREADS`].
fn max_index_threads() -> usize {
    static THREADS: OnceLock<usize> = OnceLock::new();
    *THREADS.get_or_init(|| {
        let available = std::thread::available_parallelism().map_or(1, |n| n.get());
        threads_setting(
            std::env::var("BIGTEXT_INDEX_THREADS").ok().as_deref(),
            available,
        )
    })
}

fn threads_setting(var: Option<&str>, available: usize) -> usize {
    var.and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or_else(|| available.min(MAX_INDEX_THREADS))
        .clamp(1, 64)
}

/// Threads for indexing the `remaining` bytes of `src`, at most `max`.
fn indexer_threads(src: &Source, remaining: u64, max: usize) -> usize {
    if !src.parallel_reads() {
        return 1;
    }
    let batches = remaining.div_ceil(BATCH);
    if batches < MIN_PARALLEL_BATCHES {
        return 1;
    }
    max.min(batches as usize)
}

/// Indexes from the end of the existing prefix to the end of the file with `threads` threads,
/// reading `batch` bytes (a multiple of [`BLOCK`]) per step.
fn run_indexer(
    src: &Source,
    codec: Codec,
    index: &LineIndex,
    cancel: &CancelToken,
    waker: &Waker,
    threads: usize,
    batch: u64,
) {
    debug_assert!(batch > 0 && batch.is_multiple_of(BLOCK));
    let finished = if threads > 1 {
        index_parallel(src, codec, index, cancel, waker, threads, batch)
    } else {
        index_serial(src, codec, index, cancel, waker, batch)
    };
    match finished {
        Ok(true) => {
            *index.finished_after.write().unwrap() = Some(index.started.elapsed());
            index.done.store(true, Ordering::Release);
            waker();
        }
        Ok(false) => {}
        Err(_) => {
            index.failed.store(true, Ordering::Relaxed);
            waker();
        }
    }
}

/// Appends the newline count of each block of `bytes` (whose first byte is at absolute offset
/// `base`, a multiple of [`BLOCK`]) to `out`.
fn count_blocks(codec: &Codec, bytes: &[u8], base: u64, out: &mut Vec<u64>) {
    for (i, block) in bytes.chunks(BLOCK as usize).enumerate() {
        out.push(codec.count_nl(block, base + i as u64 * BLOCK));
    }
}

/// Appends `counts` (per block) to the index as running totals.
fn publish(index: &LineIndex, counts: &mut [u64]) {
    let mut total = index.indexed_newlines();
    for c in counts.iter_mut() {
        total += *c;
        *c = total;
    }
    index.push(counts);
}

/// One thread reading the file front to back. `Ok(false)`: cancelled.
fn index_serial(
    src: &Source,
    codec: Codec,
    index: &LineIndex,
    cancel: &CancelToken,
    waker: &Waker,
    batch: u64,
) -> std::io::Result<bool> {
    let len = index.len;
    let mut pos = index.indexed_bytes();
    let mut throttle = Throttle::new(Duration::from_millis(100));
    let mut counts = Vec::with_capacity((batch / BLOCK) as usize);
    let mut buf = vec![0u8; batch.min(len - pos) as usize];
    while pos < len {
        if cancel.is_cancelled() {
            return Ok(false);
        }
        let end = (pos + batch).min(len);
        let bytes = &mut buf[..(end - pos) as usize];
        src.read_into(pos, bytes)?;
        counts.clear();
        count_blocks(&codec, bytes, pos, &mut counts);
        publish(index, &mut counts);
        pos = end;
        if throttle.ready() {
            waker();
        }
    }
    Ok(true)
}

/// State shared by the counting workers and the thread that publishes their results.
struct Pipeline {
    /// Next batch (0 = the first after the existing prefix) a worker may claim.
    next: u64,
    /// Batches published so far; workers stay within `window` batches of it.
    published: u64,
    /// Per-block newline counts of finished batches, at `batch % window`.
    slots: Vec<Option<Vec<u64>>>,
    /// First batch that could not be counted (its read failed or its worker panicked).
    failed_at: Option<u64>,
    /// Set when the publisher gives up (cancelled, or the next batch to publish failed):
    /// workers claim nothing more.
    stop: bool,
}

/// Locks the pipeline even if a panicking worker poisoned the lock: the state stays consistent
/// (every change is a single assignment), and the publisher must keep going to end the job.
fn lock(state: &Mutex<Pipeline>) -> MutexGuard<'_, Pipeline> {
    state.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Marks a claimed batch as failed if its worker unwinds before handing in the counts, so that
/// the publisher stops there instead of waiting for it.
struct Claim<'a> {
    state: &'a Mutex<Pipeline>,
    cv: &'a Condvar,
    batch: u64,
}

impl Drop for Claim<'_> {
    fn drop(&mut self) {
        if std::thread::panicking() {
            let mut st = lock(self.state);
            if st.failed_at.is_none_or(|f| self.batch < f) {
                st.failed_at = Some(self.batch);
            }
            drop(st);
            self.cv.notify_all();
        }
    }
}

/// Workers claim successive batches, each reads its batch (in [`PIECE`]s) and counts the
/// newlines of every block; this thread adds the counts up and publishes them in file order, so
/// the indexed part is always a prefix of the file. At most `2 * threads` batches are claimed
/// ahead of the published prefix. `Ok(false)`: cancelled.
///
/// If not all workers can be started, the ones that did do the work; if none did, one thread
/// indexes the file. A read error or a panicking worker ends the job as failed, with the batches
/// before the one that could not be counted published.
fn index_parallel(
    src: &Source,
    codec: Codec,
    index: &LineIndex,
    cancel: &CancelToken,
    waker: &Waker,
    threads: usize,
    batch: u64,
) -> std::io::Result<bool> {
    let start = index.indexed_bytes();
    let len = index.len;
    let batches = (len - start).div_ceil(batch);
    let window = 2 * threads;
    let piece = PIECE.min(batch);
    let state = Mutex::new(Pipeline {
        next: 0,
        published: 0,
        slots: vec![None; window],
        failed_at: None,
        stop: false,
    });
    let cv = Condvar::new();
    let (state, cv) = (&state, &cv);

    let worker = || -> Option<std::io::Error> {
        let mut buf = vec![0u8; piece as usize];
        loop {
            let b = {
                let mut st = lock(state);
                loop {
                    if st.stop || st.failed_at.is_some() || st.next >= batches {
                        return None;
                    }
                    if cancel.is_cancelled() {
                        return None;
                    }
                    if st.next < st.published + window as u64 {
                        break;
                    }
                    st = cv.wait(st).unwrap_or_else(PoisonError::into_inner);
                }
                st.next += 1;
                st.next - 1
            };
            let _claim = Claim {
                state,
                cv,
                batch: b,
            };
            #[cfg(test)]
            tests::fault_in_batch(len, b);
            let pos = start + b * batch;
            let end = (pos + batch).min(len);
            let mut counts = Vec::with_capacity((batch / BLOCK) as usize);
            let mut result = Ok(());
            let mut p = pos;
            while p < end {
                let e = (p + piece).min(end);
                let bytes = &mut buf[..(e - p) as usize];
                result = src.read_into(p, bytes);
                if result.is_err() {
                    break;
                }
                count_blocks(&codec, bytes, p, &mut counts);
                p = e;
            }
            let mut st = lock(state);
            match result {
                Ok(()) => st.slots[(b % window as u64) as usize] = Some(counts),
                Err(e) => {
                    if st.failed_at.is_none_or(|f| b < f) {
                        st.failed_at = Some(b);
                        drop(st);
                        cv.notify_all();
                        return Some(e);
                    }
                }
            }
            drop(st);
            cv.notify_all();
        }
    };

    let outcome = std::thread::scope(|scope| {
        // Stops at the first worker that cannot be started (no threads or memory left).
        let handles: Vec<_> = (0..threads)
            .map_while(|i| spawn_worker(scope, i, len, worker).ok())
            .collect();
        if handles.is_empty() {
            return None;
        }
        let mut throttle = Throttle::new(Duration::from_millis(100));
        let finished = loop {
            let mut counts = {
                let mut st = lock(state);
                loop {
                    if st.published == batches {
                        break None;
                    }
                    if cancel.is_cancelled() || st.failed_at == Some(st.published) {
                        st.stop = true;
                        break None;
                    }
                    let slot = (st.published % window as u64) as usize;
                    if let Some(c) = st.slots[slot].take() {
                        break Some(c);
                    }
                    // Woken by every finished batch; the timeout notices a cancellation.
                    st = cv
                        .wait_timeout(st, Duration::from_millis(20))
                        .unwrap_or_else(PoisonError::into_inner)
                        .0;
                }
            };
            let Some(counts) = counts.as_mut() else {
                cv.notify_all();
                break lock(state).published == batches;
            };
            publish(index, counts);
            lock(state).published += 1;
            cv.notify_all();
            if throttle.ready() {
                waker();
            }
        };
        let mut error = None;
        for h in handles {
            match h.join() {
                Ok(Some(e)) => {
                    error.get_or_insert(e);
                }
                Ok(None) => {}
                Err(_) => {
                    error.get_or_insert(std::io::Error::other("index worker panicked"));
                }
            }
        }
        Some((finished, error))
    });
    match outcome {
        None => index_serial(src, codec, index, cancel, waker, batch),
        Some((true, _)) => Ok(true),
        Some((false, _)) if cancel.is_cancelled() => Ok(false),
        Some((false, error)) => {
            Err(error.unwrap_or_else(|| std::io::Error::other("index worker stopped")))
        }
    }
}

/// Starts worker `i` of an indexer.
fn spawn_worker<'scope, F>(
    scope: &'scope std::thread::Scope<'scope, '_>,
    i: usize,
    len: u64,
    f: F,
) -> std::io::Result<std::thread::ScopedJoinHandle<'scope, Option<std::io::Error>>>
where
    F: FnOnce() -> Option<std::io::Error> + Send + 'scope,
{
    #[cfg(test)]
    tests::fault_in_spawn(len, i)?;
    #[cfg(not(test))]
    let _ = len;
    std::thread::Builder::new()
        .name(format!("indexer-{i}"))
        .spawn_scoped(scope, f)
}

/// Indexes synchronously (tests and benchmarks).
pub fn build_blocking(src: &Arc<Source>, codec: Codec) -> Arc<LineIndex> {
    let index = LineIndex::new(src.len());
    let h = spawn_indexer(
        src.clone(),
        codec,
        index.clone(),
        CancelToken::new(),
        jobs::noop_waker(),
    );
    let _ = h.join();
    index
}

/// Byte range helper used by tests.
pub fn block_range(k: u64, len: u64) -> Range<u64> {
    let s = k * BLOCK;
    s..(s + BLOCK).min(len)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encoding::{Encoding, NlByte};
    use crate::file::OpenMode;
    use std::io::Write;
    use std::sync::atomic::AtomicUsize;

    fn source_with(data: &[u8]) -> (tempfile::NamedTempFile, Arc<Source>) {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(data).unwrap();
        f.flush().unwrap();
        let s = Arc::new(Source::open(f.path(), OpenMode::Auto).unwrap());
        (f, s)
    }

    fn naive_line_starts(data: &[u8]) -> Vec<u64> {
        let mut v = vec![0];
        for (i, &b) in data.iter().enumerate() {
            if b == b'\n' {
                v.push(i as u64 + 1);
            }
        }
        v
    }

    #[test]
    fn index_matches_naive() {
        let mut data = Vec::new();
        let mut rng = 12345u64;
        while data.len() < 1_000_000 {
            rng ^= rng << 13;
            rng ^= rng >> 7;
            rng ^= rng << 17;
            let n = (rng % 300) as usize;
            data.extend(std::iter::repeat_n(b'x', n));
            data.push(b'\n');
        }
        data.extend_from_slice(b"tail without newline");
        let (_f, src) = source_with(&data);
        let codec = Codec::utf8();
        let idx = build_blocking(&src, codec);
        assert!(idx.is_done());
        let starts = naive_line_starts(&data);
        assert_eq!(idx.total_lines(), Some(starts.len() as u64));
        for (line, &s) in starts.iter().enumerate().step_by(97) {
            assert_eq!(
                idx.line_start(&src, &codec, true, line as u64),
                Some(s),
                "line {line}"
            );
            assert_eq!(idx.nl_before(&src, &codec, true, s), Some(line as u64));
        }
        assert_eq!(
            idx.line_start(&src, &codec, true, starts.len() as u64),
            None
        );
        assert!(idx.memory_bytes() < 1024);
    }

    #[test]
    fn index_utf16() {
        let text: String = (0..20_000).map(|i| format!("строка {i}\n")).collect();
        let mut data = vec![0xFF, 0xFE];
        data.extend(text.encode_utf16().flat_map(|u| u.to_le_bytes()));
        let (_f, src) = source_with(&data);
        let codec = Codec::new(Encoding::Utf16Le, NlByte::Lf, 2);
        let idx = build_blocking(&src, codec);
        assert_eq!(idx.total_lines(), Some(20_001));
        let off = idx.line_start(&src, &codec, true, 12_345).unwrap();
        let line_bytes = src.read(off..off + 40).unwrap();
        assert!(codec
            .decode_lossy(&line_bytes)
            .starts_with("строка 12345\n"));
    }

    #[test]
    fn empty_and_no_newline() {
        let (_f, src) = source_with(b"");
        let idx = build_blocking(&src, Codec::utf8());
        assert_eq!(idx.total_lines(), Some(1));
        let (_g, src) = source_with(b"single line");
        let idx = build_blocking(&src, Codec::utf8());
        assert_eq!(idx.total_lines(), Some(1));
        assert_eq!(idx.line_start(&src, &Codec::utf8(), true, 1), None);
    }

    #[test]
    fn estimates_before_indexing() {
        let data: Vec<u8> = b"0123456789\n".repeat(100_000);
        let (_f, src) = source_with(&data);
        let idx = LineIndex::with_prefix(src.len(), vec![0, BLOCK / 11]);
        let (est, exact) = idx.line_start_est(&src, &Codec::utf8(), true, 50_000);
        assert!(!exact);
        let real = 50_000u64 * 11;
        assert!(
            (est as i64 - real as i64).abs() < 1000,
            "estimate {est} vs {real}"
        );
    }

    /// Random bytes with newline units at random places (and some lone halves of UTF-16 ones).
    fn random_text(len: usize, codec: &Codec, seed: u64) -> Vec<u8> {
        let unit = codec.nl_unit();
        let mut rng = seed | 1;
        let mut next = move || {
            rng ^= rng << 13;
            rng ^= rng >> 7;
            rng ^= rng << 17;
            rng
        };
        let mut data = Vec::with_capacity(len + 2);
        while data.len() < len {
            let r = next();
            match r % 40 {
                0..=2 => data.extend_from_slice(unit),
                3 => data.push(unit[0]),
                _ => data.push((r >> 8) as u8),
            }
        }
        data.truncate(len);
        data
    }

    /// Checkpoints counted byte by byte, without [`Codec`].
    fn naive_checkpoints(data: &[u8], codec: &Codec) -> Vec<u64> {
        let unit = codec.nl_unit();
        let mut cp = vec![0u64];
        for block in data.chunks(BLOCK as usize) {
            // Blocks start at even offsets, so a UTF-16 unit is one at an even index here.
            let n = if unit.len() == 2 {
                block.chunks_exact(2).filter(|p| *p == unit).count()
            } else {
                block.iter().filter(|&&b| b == unit[0]).count()
            };
            cp.push(cp.last().unwrap() + n as u64);
        }
        cp
    }

    fn checkpoints(idx: &LineIndex) -> Vec<u64> {
        idx.cp.read().unwrap().clone()
    }

    fn run(src: &Source, codec: Codec, idx: &LineIndex, threads: usize, batch: u64) {
        run_indexer(
            src,
            codec,
            idx,
            &CancelToken::new(),
            &jobs::noop_waker(),
            threads,
            batch,
        );
    }

    #[test]
    fn parallel_index_matches_naive_count() {
        let codecs = [
            Codec::utf8(),
            Codec::new(Encoding::Utf8, NlByte::Cr, 0),
            Codec::new(Encoding::Utf16Le, NlByte::Lf, 2),
            Codec::new(Encoding::Utf16Be, NlByte::Lf, 2),
            Codec::new(Encoding::Utf16Le, NlByte::Cr, 2),
        ];
        let b = BLOCK as usize;
        let sizes = [
            1,
            3,
            b - 1,
            b,
            b + 1,
            3 * b + 7,
            7 * b,
            9 * b + 12_345,
            1_000_003,
        ];
        let runs = [
            (1, BATCH),
            (4, BATCH),
            (3, BLOCK),
            (4, 2 * BLOCK),
            (8, 3 * BLOCK),
            (5, 6 * BLOCK),
        ];
        for (ci, codec) in codecs.iter().enumerate() {
            for (si, &size) in sizes.iter().enumerate() {
                let data = random_text(size, codec, (ci * 100 + si) as u64 + 7);
                let want = naive_checkpoints(&data, codec);
                let (_f, src) = source_with(&data);
                for (threads, batch) in runs {
                    let idx = LineIndex::new(src.len());
                    run(&src, *codec, &idx, threads, batch);
                    let what = format!("{codec:?} size {size} threads {threads} batch {batch}");
                    assert!(idx.is_done() && !idx.failed(), "{what}");
                    assert_eq!(checkpoints(&idx), want, "{what}");
                    assert!(idx.finished_after().is_some(), "{what}");
                }
            }
        }
    }

    #[test]
    fn parallel_index_resumes_from_a_prefix() {
        let codec = Codec::new(Encoding::Utf16Be, NlByte::Lf, 2);
        let data = random_text(20 * BLOCK as usize + 333, &codec, 99);
        let want = naive_checkpoints(&data, &codec);
        let (_f, src) = source_with(&data);
        for keep in [1, 2, 5, 17, 21, want.len()] {
            let idx = LineIndex::with_prefix(src.len(), want[..keep].to_vec());
            run(&src, codec, &idx, 4, 2 * BLOCK);
            assert!(idx.is_done() && !idx.failed(), "keep {keep}");
            assert_eq!(checkpoints(&idx), want, "keep {keep}");
        }
        // Full-size batches on four threads, whatever drive the temp folder is on.
        let codec = Codec::utf8();
        let data = random_text(5 * BATCH as usize + 1, &codec, 5);
        let want = naive_checkpoints(&data, &codec);
        let (_f, src) = source_with(&data);
        let idx = LineIndex::with_prefix(src.len(), want[..70].to_vec());
        run(&src, codec, &idx, 4, BATCH);
        assert!(idx.is_done());
        assert_eq!(checkpoints(&idx), want);
        // The real entry point (one thread or several, as the source allows).
        let idx = build_blocking(&src, codec);
        assert_eq!(checkpoints(&idx), want);
        let idx = LineIndex::with_prefix(src.len(), want[..70].to_vec());
        spawn_indexer(
            src.clone(),
            codec,
            idx.clone(),
            CancelToken::new(),
            jobs::noop_waker(),
        )
        .join()
        .unwrap();
        assert!(idx.is_done());
        assert_eq!(checkpoints(&idx), want);
    }

    #[test]
    fn small_and_chunked_sources_use_one_thread() {
        let data = random_text(3 * BATCH as usize, &Codec::utf8(), 3);
        let (_f, src) = source_with(&data);
        assert_eq!(indexer_threads(&src, src.len(), 8), 1);
        let remote = Source::remote(Box::new(Slow::new(data, u64::MAX, None)), 9 * BATCH, None);
        assert_eq!(indexer_threads(&remote, remote.len(), 8), 1);
        // BIGTEXT_INDEX_THREADS=1 turns the parallel indexer off.
        let data = random_text(5 * BATCH as usize, &Codec::utf8(), 4);
        let (_g, src) = source_with(&data);
        assert_eq!(indexer_threads(&src, src.len(), 1), 1);
        let n = indexer_threads(&src, src.len(), 3);
        assert!(n == 3 || (n == 1 && !src.parallel_reads()));
    }

    #[test]
    fn thread_setting() {
        assert_eq!(threads_setting(None, 16), MAX_INDEX_THREADS);
        assert_eq!(threads_setting(None, 2), 2);
        assert_eq!(threads_setting(None, 0), 1);
        assert_eq!(threads_setting(Some("1"), 16), 1);
        assert_eq!(threads_setting(Some(" 3\n"), 16), 3);
        assert_eq!(threads_setting(Some("12"), 4), 12);
        assert_eq!(threads_setting(Some("0"), 16), 1);
        assert_eq!(threads_setting(Some("1000"), 16), 64);
        assert_eq!(threads_setting(Some("many"), 16), MAX_INDEX_THREADS);
    }

    /// Faults injected into the indexer of a file of a given length (one no other test uses).
    #[derive(Clone, Copy, PartialEq)]
    enum Fault {
        /// Starting worker `k` and every later one fails.
        SpawnFailsFrom(usize),
        /// The worker counting this batch panics.
        PanicIn(u64),
    }

    static FAULTS: Mutex<Vec<(u64, Fault)>> = Mutex::new(Vec::new());

    fn fault(len: u64, f: Fault) {
        FAULTS
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push((len, f));
    }

    fn faults(len: u64) -> Vec<Fault> {
        let all = FAULTS.lock().unwrap_or_else(PoisonError::into_inner);
        all.iter().filter(|f| f.0 == len).map(|f| f.1).collect()
    }

    pub(super) fn fault_in_spawn(len: u64, i: usize) -> std::io::Result<()> {
        let fails = faults(len)
            .iter()
            .any(|f| matches!(*f, Fault::SpawnFailsFrom(k) if i >= k));
        if fails {
            return Err(std::io::Error::other("injected spawn failure"));
        }
        Ok(())
    }

    pub(super) fn fault_in_batch(len: u64, batch: u64) {
        if faults(len).contains(&Fault::PanicIn(batch)) {
            panic!("injected panic in batch {batch}");
        }
    }

    /// Runs `f` on its own thread and fails the test if it does not finish within 20 s.
    fn within_timeout(f: impl FnOnce() + Send + 'static) {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            f();
            let _ = tx.send(());
        });
        rx.recv_timeout(Duration::from_secs(20))
            .expect("the indexer hung (or the test panicked)");
    }

    #[test]
    fn workers_that_cannot_be_started_are_done_without() {
        let codec = Codec::utf8();
        for k in [0, 1, 2] {
            let len = (30 + k) * BLOCK as usize + 17;
            fault(len as u64, Fault::SpawnFailsFrom(k));
            let data = random_text(len, &codec, 21 + k as u64);
            let want = naive_checkpoints(&data, &codec);
            within_timeout(move || {
                let (_f, src) = source_with(&data);
                let idx = LineIndex::new(src.len());
                run(&src, codec, &idx, 4, 2 * BLOCK);
                assert!(idx.is_done() && !idx.failed(), "spawn {k} fails");
                assert_eq!(checkpoints(&idx), want, "spawn {k} fails");
            });
        }
    }

    #[test]
    fn a_panicking_worker_fails_the_index_without_hanging() {
        let codec = Codec::utf8();
        for (threads, k) in [(2, 0), (4, 0), (4, 5), (8, 13)] {
            let len = (40 + 2 * threads + k as usize) * BLOCK as usize + 3;
            fault(len as u64, Fault::PanicIn(k));
            let data = random_text(len, &codec, 31 + k);
            let want = naive_checkpoints(&data, &codec);
            within_timeout(move || {
                let (_f, src) = source_with(&data);
                let idx = LineIndex::new(src.len());
                run(&src, codec, &idx, threads, 2 * BLOCK);
                let what = format!("threads {threads}, panic in batch {k}");
                assert!(idx.failed() && !idx.is_done(), "{what}");
                // Everything before the batch that could not be counted.
                assert_eq!(checkpoints(&idx), want[..=2 * k as usize], "{what}");
            });
        }
    }

    /// A remote file in memory that is slow to read, can cancel the indexer after some reads and
    /// fails from a given offset on.
    struct Slow {
        data: Vec<u8>,
        fail_from: u64,
        cancel_after: Option<(CancelToken, usize)>,
        reads: AtomicUsize,
    }

    impl Slow {
        fn new(data: Vec<u8>, fail_from: u64, cancel_after: Option<(CancelToken, usize)>) -> Slow {
            Slow {
                data,
                fail_from,
                cancel_after,
                reads: AtomicUsize::new(0),
            }
        }
    }

    impl crate::file::RangeRead for Slow {
        fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
            std::thread::sleep(Duration::from_millis(2));
            let n = self.reads.fetch_add(1, Ordering::Relaxed) + 1;
            if let Some((cancel, after)) = &self.cancel_after {
                if n >= *after {
                    cancel.cancel();
                }
            }
            if offset + buf.len() as u64 > self.fail_from {
                return Err(std::io::Error::other("gone"));
            }
            buf.copy_from_slice(&self.data[offset as usize..offset as usize + buf.len()]);
            Ok(())
        }
    }

    #[test]
    fn parallel_index_stops_when_cancelled() {
        let codec = Codec::utf8();
        let data = random_text(200 * BLOCK as usize, &codec, 11);
        let want = naive_checkpoints(&data, &codec);
        let len = data.len() as u64;
        for threads in [1, 4] {
            // Before the start: nothing is read.
            let cancel = CancelToken::new();
            cancel.cancel();
            let src = Source::remote(Box::new(Slow::new(data.clone(), u64::MAX, None)), len, None);
            let idx = LineIndex::new(src.len());
            run_indexer(
                &src,
                codec,
                &idx,
                &cancel,
                &jobs::noop_waker(),
                threads,
                BLOCK,
            );
            assert_eq!(checkpoints(&idx), vec![0]);
            assert!(!idx.is_done() && !idx.failed() && idx.finished_after().is_none());
            // Part way: stops soon after, with a correct prefix.
            let cancel = CancelToken::new();
            let slow = Slow::new(data.clone(), u64::MAX, Some((cancel.clone(), 10)));
            let src = Source::remote(Box::new(slow), len, None);
            let idx = LineIndex::new(src.len());
            let t = Instant::now();
            run_indexer(
                &src,
                codec,
                &idx,
                &cancel,
                &jobs::noop_waker(),
                threads,
                BLOCK,
            );
            assert!(t.elapsed() < Duration::from_secs(2));
            let got = checkpoints(&idx);
            assert!(!idx.is_done() && !idx.failed(), "threads {threads}");
            assert!(got.len() < 12 + threads, "threads {threads}: {}", got.len());
            assert_eq!(got, want[..got.len()], "threads {threads}");
        }
    }

    #[test]
    fn parallel_index_keeps_the_prefix_before_a_read_error() {
        let codec = Codec::utf8();
        let data = random_text(40 * BLOCK as usize + 5, &codec, 13);
        let want = naive_checkpoints(&data, &codec);
        let fail_from = 23 * BLOCK + 100;
        for threads in [1, 2, 4] {
            let slow = Slow::new(data.clone(), fail_from, None);
            let src = Source::remote(Box::new(slow), data.len() as u64, None);
            let idx = LineIndex::new(src.len());
            run(&src, codec, &idx, threads, 2 * BLOCK);
            assert!(idx.failed() && !idx.is_done(), "threads {threads}");
            // Batches of two blocks: everything before the batch holding `fail_from`.
            assert_eq!(checkpoints(&idx), want[..23], "threads {threads}");
        }
    }
}