bigtext 0.19.0

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
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
//! File access: windowed memory mapping when possible, buffered chunked reads otherwise.
//!
//! * The UI thread only calls [`Source::get`] with `blocking = false`. For mapped sources the
//!   bytes are borrowed from a small cache of mapped *views* (never the whole file: on Windows
//!   mapping a view commits page-table memory proportional to its size, ~100 MB for a 50 GB
//!   file, which would make memory O(file size)). For chunked sources it serves from a block
//!   cache and, on a miss, queues the blocks for a background loader and returns `None`.
//! * Workers stream large ranges with [`Source::read_into`] (positional reads into a reused
//!   buffer). On a cached file this is faster than first-touch page faults of a mapping and keeps
//!   the process's private memory flat.

use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io;
use std::ops::{Deref, Range};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

use crate::jobs::{self, Waker};

/// Block size of the chunked-read cache.
pub const CHUNK_BLOCK: u64 = 64 * 1024;
/// Block size for a remote file: every request costs a round trip, so fewer, larger ones.
pub const REMOTE_BLOCK: u64 = 256 * 1024;
/// Bytes the block cache keeps (64 MB).
const CACHE_BYTES: u64 = 64 * 1024 * 1024;
/// Reads larger than this bypass the block cache (workers streaming through the file).
const DIRECT_READ_MIN: u64 = 1024 * 1024;
/// Mapped views start every `VIEW_STRIDE` bytes and extend `VIEW_OVERLAP` beyond the next start,
/// so any read of up to `VIEW_OVERLAP` bytes fits inside a single view.
const VIEW_STRIDE: u64 = 256 * 1024 * 1024;
const VIEW_OVERLAP: u64 = 32 * 1024 * 1024;
const MAX_VIEWS: usize = 6;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OpenMode {
    /// Memory-mapped unless the path is on a network/removable drive or mapping fails.
    Auto,
    /// Always use chunked reads.
    Chunked,
}

/// Bytes read from a [`Source`]: borrowed, owned, or a slice of a cached mapped view.
pub struct Bytes<'a>(Repr<'a>);

enum Repr<'a> {
    Borrowed(&'a [u8]),
    Owned(Vec<u8>),
    View(Arc<memmap2::Mmap>, usize, usize),
}

impl<'a> Bytes<'a> {
    pub fn borrowed(b: &'a [u8]) -> Bytes<'a> {
        Bytes(Repr::Borrowed(b))
    }
    pub fn owned(v: Vec<u8>) -> Bytes<'a> {
        Bytes(Repr::Owned(v))
    }
    pub fn into_owned(self) -> Vec<u8> {
        match self.0 {
            Repr::Owned(v) => v,
            _ => self.to_vec(),
        }
    }
}

impl Deref for Bytes<'_> {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        match &self.0 {
            Repr::Borrowed(b) => b,
            Repr::Owned(v) => v,
            Repr::View(m, s, l) => &m[*s..*s + *l],
        }
    }
}

impl AsRef<[u8]> for Bytes<'_> {
    fn as_ref(&self) -> &[u8] {
        self
    }
}

impl std::fmt::Debug for Bytes<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Bytes({} bytes)", self.len())
    }
}

impl PartialEq for Bytes<'_> {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}

/// Lazily mapped, LRU-cached views of a file.
struct Mapped {
    file: File,
    len: u64,
    views: Mutex<Vec<(u64, Arc<memmap2::Mmap>, u64)>>,
    tick: AtomicU64,
}

impl Mapped {
    fn view(&self, k: u64) -> io::Result<Arc<memmap2::Mmap>> {
        let tick = self.tick.fetch_add(1, Ordering::Relaxed);
        let mut views = self.views.lock().unwrap();
        if let Some(v) = views.iter_mut().find(|v| v.0 == k) {
            v.2 = tick;
            return Ok(v.1.clone());
        }
        let start = k * VIEW_STRIDE;
        let len = (self.len - start).min(VIEW_STRIDE + VIEW_OVERLAP);
        // SAFETY: read-only mapping. Another process truncating the file while it is mapped is
        // not possible on Windows (ERROR_USER_MAPPED_FILE); on Unix it is a known limitation of
        // every mmap-based viewer.
        let map = Arc::new(unsafe {
            memmap2::MmapOptions::new()
                .offset(start)
                .len(len as usize)
                .map(&self.file)?
        });
        if views.len() >= MAX_VIEWS {
            if let Some(i) = views
                .iter()
                .enumerate()
                .min_by_key(|(_, v)| v.2)
                .map(|(i, _)| i)
            {
                views.swap_remove(i);
            }
        }
        views.push((k, map.clone(), tick));
        Ok(map)
    }

    fn read(&self, r: Range<u64>) -> io::Result<Bytes<'static>> {
        let k = r.start / VIEW_STRIDE;
        let vstart = k * VIEW_STRIDE;
        if r.end <= vstart + VIEW_STRIDE + VIEW_OVERLAP {
            let v = self.view(k)?;
            Ok(Bytes(Repr::View(
                v,
                (r.start - vstart) as usize,
                (r.end - r.start) as usize,
            )))
        } else {
            let mut buf = vec![0u8; (r.end - r.start) as usize];
            read_exact_at(&self.file, &mut buf, r.start)?;
            Ok(Bytes::owned(buf))
        }
    }
}

enum Backing {
    Empty,
    Mapped(Mapped),
    Chunked(Chunked),
}

/// Positional reads of a file's bytes: a local file, or a remote one fetched in parts (HTTP
/// ranges, an SSH session).
pub trait RangeRead: Send + Sync {
    /// Fills `buf` with the bytes from `offset`.
    fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()>;
}

impl RangeRead for File {
    fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
        read_exact_at(self, buf, offset)
    }
}

/// An immutable view of a file's bytes as they were when it was opened.
pub struct Source {
    path: Option<PathBuf>,
    len: u64,
    backing: Backing,
    modified: Option<SystemTime>,
    /// On a rotating disk ([`slow_device`]); a network file system is read in chunks.
    slow_device: bool,
}

impl Source {
    /// An empty in-memory source (new, untitled documents).
    pub fn empty() -> Source {
        Source {
            path: None,
            len: 0,
            backing: Backing::Empty,
            modified: None,
            slow_device: false,
        }
    }

    pub fn open(path: &Path, mode: OpenMode) -> io::Result<Source> {
        let file = File::open(path)?;
        let meta = file.metadata()?;
        if meta.is_dir() {
            return Err(io::Error::other("path is a directory"));
        }
        let len = meta.len();
        let modified = meta.modified().ok();
        let path_buf = Some(path.to_path_buf());
        if len == 0 {
            return Ok(Source {
                path: path_buf,
                len,
                backing: Backing::Empty,
                modified,
                slow_device: false,
            });
        }
        let force_chunked = mode == OpenMode::Chunked
            || std::env::var_os("BIGTEXT_FORCE_CHUNKED").is_some()
            || prefers_chunked(path, &file);
        // Unix lets another process truncate a mapped file, and touching the lost pages then
        // kills the process with SIGBUS; positional reads just come up short. So there a local
        // file is read in blocks, filled at once like a mapping's page faults. Windows does not
        // let a mapped file be truncated, so it keeps the mapping. BIGTEXT_FORCE_PREAD picks the
        // block reads anywhere (to compare them with the mapping).
        let pread = cfg!(unix) || std::env::var_os("BIGTEXT_FORCE_PREAD").is_some();
        if !force_chunked && pread {
            let slow_device = slow_device(&file, &meta);
            return Ok(Source {
                path: path_buf,
                len,
                backing: Backing::Chunked(Chunked::new(
                    Box::new(file),
                    len,
                    CHUNK_BLOCK,
                    false,
                    true,
                )),
                modified,
                slow_device,
            });
        }
        if !force_chunked {
            let m = Mapped {
                file,
                len,
                views: Mutex::new(Vec::new()),
                tick: AtomicU64::new(0),
            };
            // Map the first view now so that a file which cannot be mapped falls back here.
            match m.view(0) {
                Ok(_) => {
                    return Ok(Source {
                        path: path_buf,
                        len,
                        backing: Backing::Mapped(m),
                        modified,
                        slow_device: false,
                    })
                }
                Err(_) => {
                    return Ok(Source {
                        path: path_buf,
                        len,
                        backing: Backing::Chunked(Chunked::new(
                            Box::new(m.file),
                            len,
                            CHUNK_BLOCK,
                            false,
                            false,
                        )),
                        modified,
                        slow_device: false,
                    })
                }
            }
        }
        Ok(Source {
            path: path_buf,
            len,
            backing: Backing::Chunked(Chunked::new(Box::new(file), len, CHUNK_BLOCK, false, false)),
            modified,
            slow_device: false,
        })
    }

    /// A remote file of `len` bytes, read in parts through `reader` as they are needed (what is
    /// on screen, what a search reaches); nothing is downloaded up front.
    pub fn remote(reader: Box<dyn RangeRead>, len: u64, modified: Option<SystemTime>) -> Source {
        let backing = if len == 0 {
            Backing::Empty
        } else {
            Backing::Chunked(Chunked::new(reader, len, REMOTE_BLOCK, true, false))
        };
        Source {
            path: None,
            len,
            backing,
            modified,
            slow_device: false,
        }
    }

    /// A remote file read in parts ([`Source::remote`]): whole-file scans such as the line
    /// index would download all of it, so they do not start on their own.
    pub fn is_remote(&self) -> bool {
        matches!(&self.backing, Backing::Chunked(c) if c.inner.remote)
    }

    /// Bytes read from the file so far (for a remote file: downloaded).
    pub fn bytes_read(&self) -> u64 {
        match &self.backing {
            Backing::Chunked(c) => c.inner.bytes_read.load(Ordering::Relaxed),
            _ => 0,
        }
    }

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

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

    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    pub fn modified(&self) -> Option<SystemTime> {
        self.modified
    }

    pub fn kind_name(&self) -> &'static str {
        match self.backing {
            Backing::Empty => "empty",
            Backing::Mapped(_) => "mmap",
            Backing::Chunked(ref c) if c.inner.sync => "pread",
            Backing::Chunked(_) => "chunked",
        }
    }

    pub fn is_mmap(&self) -> bool {
        matches!(self.backing, Backing::Mapped(_))
    }

    /// A local file read in blocks filled on the calling thread (Unix instead of a mapping).
    pub fn is_pread(&self) -> bool {
        matches!(&self.backing, Backing::Chunked(c) if c.inner.sync)
    }

    /// True when several threads reading the file at once are likely to be faster than one: a
    /// local file (mapped or read in blocks) that is not on a rotating disk. Chunked sources
    /// (network file systems, removable drives on Windows, remote files) and slow devices are
    /// better read by one thread, front to back.
    pub fn parallel_reads(&self) -> bool {
        (self.is_mmap() || self.is_pread()) && !self.slow_device
    }

    /// Registers the function used to wake the UI when queued chunked reads complete.
    pub fn set_waker(&self, waker: Waker) {
        if let Backing::Chunked(c) = &self.backing {
            *c.inner.waker.lock().unwrap() = Some(waker);
        }
    }

    /// True if a chunked read failed (file vanished, network error, ...).
    pub fn has_io_error(&self) -> bool {
        match &self.backing {
            Backing::Chunked(c) => c.inner.failed.load(Ordering::Relaxed),
            _ => false,
        }
    }

    fn clamp(&self, r: Range<u64>) -> Range<u64> {
        let end = r.end.min(self.len);
        r.start.min(end)..end
    }

    /// Blocking read (worker threads).
    pub fn read(&self, r: Range<u64>) -> io::Result<Bytes<'_>> {
        let r = self.clamp(r);
        if r.is_empty() {
            return Ok(Bytes::borrowed(&[]));
        }
        match &self.backing {
            Backing::Empty => Ok(Bytes::borrowed(&[])),
            Backing::Mapped(m) => m.read(r),
            Backing::Chunked(c) => c.read_blocking(r).map(Bytes::owned),
        }
    }

    /// Non-blocking read for the UI thread. `None` means "not available yet" (queued) or failed.
    pub fn try_read(&self, r: Range<u64>) -> Option<Bytes<'_>> {
        let r = self.clamp(r);
        if r.is_empty() {
            return Some(Bytes::borrowed(&[]));
        }
        match &self.backing {
            Backing::Empty => Some(Bytes::borrowed(&[])),
            Backing::Mapped(m) => m.read(r).ok(),
            Backing::Chunked(c) => c.try_read(r).map(Bytes::owned),
        }
    }

    /// Positional bulk read into a caller buffer (workers streaming through the file).
    pub fn read_into(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
        if offset + buf.len() as u64 > self.len {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "read past end of source",
            ));
        }
        match &self.backing {
            Backing::Empty => Ok(()),
            Backing::Mapped(m) => read_exact_at(&m.file, buf, offset),
            Backing::Chunked(c) => c.inner.read_direct(offset, buf),
        }
    }

    /// Read with the given blocking behaviour; I/O errors map to `None`.
    pub fn get(&self, r: Range<u64>, blocking: bool) -> Option<Bytes<'_>> {
        if blocking {
            self.read(r).ok()
        } else {
            self.try_read(r)
        }
    }

    /// Number of currently mapped views (diagnostics).
    pub fn mapped_views(&self) -> usize {
        match &self.backing {
            Backing::Mapped(m) => m.views.lock().unwrap().len(),
            _ => 0,
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Chunked (buffered) reads with a block cache and a background loader thread.

struct BlockCache {
    map: HashMap<u64, (Arc<Vec<u8>>, u64)>,
    tick: u64,
}

impl BlockCache {
    fn get(&mut self, b: u64) -> Option<Arc<Vec<u8>>> {
        self.tick += 1;
        let tick = self.tick;
        self.map.get_mut(&b).map(|e| {
            e.1 = tick;
            e.0.clone()
        })
    }
    fn insert(&mut self, b: u64, data: Arc<Vec<u8>>, capacity: usize) {
        self.tick += 1;
        if self.map.len() >= capacity {
            if let Some((&oldest, _)) = self.map.iter().min_by_key(|(_, e)| e.1) {
                self.map.remove(&oldest);
            }
        }
        self.map.insert(b, (data, self.tick));
    }
}

struct ChunkedInner {
    reader: Box<dyn RangeRead>,
    len: u64,
    /// Block size of the cache ([`CHUNK_BLOCK`], [`REMOTE_BLOCK`]).
    block: u64,
    /// Blocks the cache keeps.
    capacity: usize,
    remote: bool,
    /// A block missing from the cache is read at once on the calling thread, as a page fault of
    /// a mapping would be, instead of being queued for the loader.
    sync: bool,
    cache: Mutex<BlockCache>,
    pending: Mutex<HashSet<u64>>,
    waker: Mutex<Option<Waker>>,
    failed: AtomicBool,
    reads: AtomicU64,
    bytes_read: AtomicU64,
}

impl ChunkedInner {
    fn block_range(&self, b: u64) -> Range<u64> {
        let s = b * self.block;
        s..(s + self.block).min(self.len)
    }

    /// Reads `buf` from `offset` past the cache (large reads of workers streaming the file).
    fn read_direct(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
        self.reader.read_at(offset, buf)?;
        self.bytes_read
            .fetch_add(buf.len() as u64, Ordering::Relaxed);
        Ok(())
    }

    fn load_block(&self, b: u64) -> io::Result<Arc<Vec<u8>>> {
        self.load_blocks(b, b).map(|mut v| v.remove(0))
    }

    /// Loads blocks `first..=last` with one read (one request for a remote file) and caches
    /// them.
    fn load_blocks(&self, first: u64, last: u64) -> io::Result<Vec<Arc<Vec<u8>>>> {
        let start = self.block_range(first).start;
        let end = self.block_range(last).end;
        let mut buf = vec![0u8; (end - start) as usize];
        self.read_direct(start, &mut buf)?;
        self.reads.fetch_add(1, Ordering::Relaxed);
        let mut cache = self.cache.lock().unwrap();
        let mut out = Vec::with_capacity((last - first + 1) as usize);
        for b in first..=last {
            let r = self.block_range(b);
            let data = Arc::new(buf[(r.start - start) as usize..(r.end - start) as usize].to_vec());
            cache.insert(b, data.clone(), self.capacity);
            out.push(data);
        }
        Ok(out)
    }
}

struct Chunked {
    inner: Arc<ChunkedInner>,
    tx: Sender<u64>,
}

impl Chunked {
    fn new(reader: Box<dyn RangeRead>, len: u64, block: u64, remote: bool, sync: bool) -> Chunked {
        let inner = Arc::new(ChunkedInner {
            reader,
            len,
            block,
            capacity: (CACHE_BYTES / block) as usize,
            remote,
            sync,
            cache: Mutex::new(BlockCache {
                map: HashMap::new(),
                tick: 0,
            }),
            pending: Mutex::new(HashSet::new()),
            waker: Mutex::new(None),
            failed: AtomicBool::new(false),
            reads: AtomicU64::new(0),
            bytes_read: AtomicU64::new(0),
        });
        let (tx, rx) = mpsc::channel::<u64>();
        let worker = inner.clone();
        jobs::spawn("chunk-loader", move || loader_loop(worker, rx));
        Chunked { inner, tx }
    }

    fn read_blocking(&self, r: Range<u64>) -> io::Result<Vec<u8>> {
        let n = (r.end - r.start) as usize;
        if r.end - r.start >= DIRECT_READ_MIN {
            let mut buf = vec![0u8; n];
            self.inner.read_direct(r.start, &mut buf).inspect_err(|_| {
                self.inner.failed.store(true, Ordering::Relaxed);
            })?;
            return Ok(buf);
        }
        let mut out = Vec::with_capacity(n);
        if n == 0 {
            return Ok(out);
        }
        let first = r.start / self.inner.block;
        let last = (r.end - 1) / self.inner.block;
        for b in first..=last {
            let cached = self.inner.cache.lock().unwrap().get(b);
            let data = match cached {
                Some(d) => d,
                None => self.inner.load_block(b).inspect_err(|_| {
                    self.inner.failed.store(true, Ordering::Relaxed);
                })?,
            };
            let br = self.inner.block_range(b);
            let s = r.start.max(br.start) - br.start;
            let e = r.end.min(br.end) - br.start;
            out.extend_from_slice(&data[s as usize..e as usize]);
        }
        Ok(out)
    }

    fn try_read(&self, r: Range<u64>) -> Option<Vec<u8>> {
        if self.inner.sync {
            return self.read_blocking(r).ok();
        }
        let n = (r.end - r.start) as usize;
        if n == 0 {
            return Some(Vec::new());
        }
        let first = r.start / self.inner.block;
        let last = (r.end - 1) / self.inner.block;
        let mut blocks = Vec::with_capacity((last - first + 1) as usize);
        let mut missing = Vec::new();
        {
            let mut cache = self.inner.cache.lock().unwrap();
            for b in first..=last {
                match cache.get(b) {
                    Some(d) => blocks.push(d),
                    None => missing.push(b),
                }
            }
        }
        if !missing.is_empty() {
            let mut pending = self.inner.pending.lock().unwrap();
            for b in missing {
                if pending.insert(b) {
                    let _ = self.tx.send(b);
                }
            }
            return None;
        }
        let mut out = Vec::with_capacity(n);
        for (i, data) in blocks.iter().enumerate() {
            let br = self.inner.block_range(first + i as u64);
            let s = r.start.max(br.start) - br.start;
            let e = r.end.min(br.end) - br.start;
            out.extend_from_slice(&data[s as usize..e as usize]);
        }
        Some(out)
    }
}

fn loader_loop(inner: Arc<ChunkedInner>, rx: Receiver<u64>) {
    // Exits when the owning `Source` is dropped (sender closed), releasing the file handle.
    while let Ok(b) = rx.recv() {
        // A reader sends all the blocks it misses while it holds `pending`. Wait for it to
        // finish, or the first block can be taken alone and its neighbours loaded with a
        // second request (the channel is unbounded, so the reader never waits for us).
        drop(inner.pending.lock().unwrap());
        let mut batch = vec![b];
        while let Ok(more) = rx.try_recv() {
            batch.push(more);
        }
        batch.sort_unstable();
        batch.dedup();
        let asked = batch.clone();
        {
            let cache = inner.cache.lock().unwrap();
            batch.retain(|b| !cache.map.contains_key(b));
        }
        // Runs of neighbouring blocks load with one read: one request instead of many for a
        // remote file (a screen that straddles blocks, a jump that needs two).
        let mut i = 0;
        while i < batch.len() {
            let mut j = i;
            while j + 1 < batch.len() && batch[j + 1] == batch[j] + 1 && j - i < 15 {
                j += 1;
            }
            if inner.load_blocks(batch[i], batch[j]).is_err() {
                inner.failed.store(true, Ordering::Relaxed);
            }
            i = j + 1;
        }
        {
            let mut pending = inner.pending.lock().unwrap();
            for b in &asked {
                pending.remove(b);
            }
        }
        if let Some(w) = inner.waker.lock().unwrap().as_ref() {
            w();
        }
    }
}

/// Positional read that fills `buf` completely.
pub fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileExt;
        file.read_exact_at(buf, offset)
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::FileExt;
        let mut done = 0usize;
        while done < buf.len() {
            let n = file.seek_read(&mut buf[done..], offset + done as u64)?;
            if n == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "file shrank while open",
                ));
            }
            done += n;
        }
        Ok(())
    }
}

/// Network, removable and optical drives are read in chunks instead of mapped, so that a slow
/// or disappearing device can never stall the UI thread inside a page fault.
#[cfg(windows)]
fn prefers_chunked(path: &Path, _file: &File) -> bool {
    let s = path.to_string_lossy();
    let s = s.strip_prefix(r"\\?\").unwrap_or(&s);
    if s.starts_with(r"\\") || s.starts_with(r"UNC\") {
        return true;
    }
    let b = s.as_bytes();
    if b.len() >= 2 && b[1] == b':' && b[0].is_ascii_alphabetic() {
        let root: Vec<u16> = format!("{}:\\", b[0] as char)
            .encode_utf16()
            .chain(Some(0))
            .collect();
        // SAFETY: `root` is a valid NUL-terminated UTF-16 string.
        let t = unsafe { GetDriveTypeW(root.as_ptr()) };
        // DRIVE_REMOVABLE = 2, DRIVE_REMOTE = 4, DRIVE_CDROM = 5
        return matches!(t, 2 | 4 | 5);
    }
    false
}

#[cfg(windows)]
#[link(name = "kernel32")]
extern "system" {
    fn GetDriveTypeW(root: *const u16) -> u32;
    fn GetFileInformationByHandle(file: *mut std::ffi::c_void, info: *mut FileInformation) -> i32;
}

/// BY_HANDLE_FILE_INFORMATION.
#[cfg(windows)]
#[repr(C)]
#[derive(Default)]
struct FileInformation {
    attributes: u32,
    times: [u32; 6],
    volume_serial: u32,
    size_high: u32,
    size_low: u32,
    links: u32,
    index_high: u32,
    index_low: u32,
}

/// Which file `path` names (volume and file number), to notice when a path comes to name
/// another file, as when a log is rotated. Unlike the creation time it is not fooled by NTFS
/// tunnelling. `None` when it cannot be read.
pub fn file_id(path: &Path) -> Option<(u64, u64)> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let m = std::fs::metadata(path).ok()?;
        Some((m.dev(), m.ino()))
    }
    #[cfg(windows)]
    {
        use std::os::windows::io::AsRawHandle;
        // Opened sharing read, write and delete, so the writer is never in the way.
        let f = File::open(path).ok()?;
        let mut info = FileInformation::default();
        // SAFETY: the handle is open for the call and `info` is a BY_HANDLE_FILE_INFORMATION.
        let ok = unsafe { GetFileInformationByHandle(f.as_raw_handle(), &mut info) };
        (ok != 0).then_some((
            info.volume_serial as u64,
            ((info.index_high as u64) << 32) | info.index_low as u64,
        ))
    }
}

/// The file a log was most likely rotated to: a sibling whose name starts like this one's
/// (`app.log.1`, `app-20261028.log.gz` for `app.log`), changed in the two minutes before
/// `now`, the newest. A hint for the user, never opened by itself.
pub fn rotated_sibling(path: &Path, now: std::time::SystemTime) -> Option<PathBuf> {
    let dir = path.parent()?;
    let name = path.file_name()?.to_string_lossy().into_owned();
    let stem = path.file_stem()?.to_string_lossy().into_owned();
    let since = now - std::time::Duration::from_secs(120);
    std::fs::read_dir(dir)
        .ok()?
        .flatten()
        .filter(|e| {
            let n = e.file_name().to_string_lossy().into_owned();
            n != name && n.starts_with(&stem)
        })
        .filter_map(|e| {
            let m = e.metadata().ok().filter(|m| m.is_file())?;
            let t = m.modified().ok().filter(|t| *t >= since)?;
            Some((t, e.path()))
        })
        .max_by_key(|x| x.0)
        .map(|x| x.1)
}

/// A file on a network file system (NFS, SMB, sshfs and other FUSE mounts, WSL2's Windows
/// drives) is read in chunks by a loader thread, as on Windows, so a slow server cannot stall
/// the UI thread in a read; and by that one thread, as several would compete for one link.
#[cfg(not(windows))]
fn prefers_chunked(_path: &Path, file: &File) -> bool {
    network_fs(file)
}

/// Whether the open `file` is on a network file system, by the file system's type. False when
/// that cannot be asked: the file is then read like a local one.
#[cfg(target_os = "linux")]
fn network_fs(file: &File) -> bool {
    use std::os::unix::io::AsRawFd;
    // SAFETY: `statfs` is plain data; fstatfs fills it for an open descriptor.
    let mut st: libc::statfs = unsafe { std::mem::zeroed() };
    let ok = unsafe { libc::fstatfs(file.as_raw_fd(), &mut st) } == 0;
    // f_type is a signed or an unsigned word depending on the platform; the magic numbers are
    // 32-bit.
    ok && network_fs_magic(st.f_type as u32)
}

#[cfg(target_os = "macos")]
fn network_fs(file: &File) -> bool {
    use std::os::unix::io::AsRawFd;
    // SAFETY: `statfs` is plain data; fstatfs fills it for an open descriptor.
    let mut st: libc::statfs = unsafe { std::mem::zeroed() };
    if unsafe { libc::fstatfs(file.as_raw_fd(), &mut st) } != 0 {
        return false;
    }
    let name: Vec<u8> = st
        .f_fstypename
        .iter()
        .take_while(|&&c| c != 0)
        .map(|&c| c as u8)
        .collect();
    network_fs_name(&name)
}

#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
fn network_fs(_file: &File) -> bool {
    false
}

/// A file on a rotating disk, where reads from several threads at once compete for one disk
/// head and are slower than one reader going front to back. Asked once, when a local file is
/// opened (Linux: the disk's `queue/rotational`). Network file systems never get here: they are
/// read in chunks ([`prefers_chunked`]).
#[cfg(target_os = "linux")]
fn slow_device(_file: &File, meta: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::MetadataExt;
    rotational_disk(meta.dev())
}

#[cfg(not(target_os = "linux"))]
fn slow_device(_file: &File, _meta: &std::fs::Metadata) -> bool {
    false
}

/// Linux `statfs.f_type` of network and FUSE file systems (`linux/magic.h`). FUSE covers sshfs,
/// rclone and similar mounts; a local disk mounted through FUSE (ntfs-3g) is read by one thread
/// too.
#[cfg(any(target_os = "linux", test))]
fn network_fs_magic(f_type: u32) -> bool {
    matches!(
        f_type,
        0x6969 // NFS
            | 0x517B // SMB
            | 0xFF53_4D42 // CIFS
            | 0xFE53_4D42 // SMB2
            | 0x6573_5546 // FUSE
            | 0x0102_1997 // 9P (WSL2 Windows drives, VM shared folders)
            | 0x00C3_6400 // Ceph
            | 0x5346_414F // AFS
            | 0x6B41_4653 // kAFS
            | 0x7375_7245 // Coda
            | 0x564C // NCP
            | 0x786F_4256 // VirtualBox shared folders
    )
}

/// macOS `statfs.f_fstypename` of network and FUSE file systems.
#[cfg(any(target_os = "macos", test))]
fn network_fs_name(name: &[u8]) -> bool {
    matches!(
        name,
        b"nfs" | b"smbfs" | b"afpfs" | b"webdav" | b"cifs" | b"ftp" | b"osxfuse" | b"macfuse"
    )
}

/// True if the block device `dev` (or the disk the partition `dev` is on) says it rotates.
/// Devices without a `/sys/dev/block` entry (btrfs subvolumes, tmpfs, overlays) count as not
/// rotating.
#[cfg(target_os = "linux")]
fn rotational_disk(dev: u64) -> bool {
    let base = format!("/sys/dev/block/{}:{}", libc::major(dev), libc::minor(dev));
    // A partition has no queue of its own: it uses its disk's, one level up.
    for queue in ["queue/rotational", "../queue/rotational"] {
        if let Ok(s) = std::fs::read_to_string(format!("{base}/{queue}")) {
            return s.trim() == "1";
        }
    }
    false
}

/// Strips the `\\?\` verbatim prefix for display.
pub fn display_path(path: &Path) -> String {
    let s = path.to_string_lossy();
    if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
        format!(r"\\{rest}")
    } else if let Some(rest) = s.strip_prefix(r"\\?\") {
        rest.to_string()
    } else {
        s.into_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn file_ids_and_rotated_siblings() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("app.log");
        std::fs::write(&log, "one\n").unwrap();
        let first = file_id(&log).expect("an id");
        assert_eq!(file_id(&log), Some(first));
        // Rotation by rename: the path now names a new file.
        std::fs::rename(&log, dir.path().join("app.log.1")).unwrap();
        std::fs::write(&log, "two\n").unwrap();
        assert_ne!(file_id(&log), Some(first));
        assert_eq!(file_id(&dir.path().join("app.log.1")), Some(first));
        std::fs::write(dir.path().join("other.txt"), "x").unwrap();
        let old = dir.path().join("app-2020.log");
        std::fs::write(&old, "old").unwrap();
        File::options()
            .write(true)
            .open(&old)
            .unwrap()
            .set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(3600))
            .unwrap();
        assert_eq!(
            rotated_sibling(&log, std::time::SystemTime::now()),
            Some(dir.path().join("app.log.1"))
        );
        assert_eq!(file_id(&dir.path().join("missing.log")), None);
    }

    /// Another process truncating an open file: with a mapping, touching the lost pages would
    /// kill this test with SIGBUS; block reads come up short and report it.
    #[cfg(unix)]
    #[test]
    fn a_file_truncated_while_open_reads_short() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(&vec![b'x'; 4 << 20]).unwrap();
        f.flush().unwrap();
        let s = Source::open(f.path(), OpenMode::Auto).unwrap();
        assert!(s.is_pread());
        assert_eq!(s.try_read(0..16).unwrap().len(), 16);
        std::fs::OpenOptions::new()
            .write(true)
            .open(f.path())
            .unwrap()
            .set_len(1000)
            .unwrap();
        assert!(s.try_read(3 << 20..(3 << 20) + 100).is_none());
        assert!(s.read(2 << 20..(2 << 20) + 100).is_err());
        assert!(s.has_io_error());
        let mut buf = vec![0u8; 100];
        assert!(s.read_into(1 << 20, &mut buf).is_err());
    }

    #[test]
    fn mmap_and_chunked_agree() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        let data: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
        f.write_all(&data).unwrap();
        f.flush().unwrap();
        let a = Source::open(f.path(), OpenMode::Auto).unwrap();
        let b = Source::open(f.path(), OpenMode::Chunked).unwrap();
        assert_eq!(a.kind_name(), if cfg!(unix) { "pread" } else { "mmap" });
        assert_eq!(b.kind_name(), "chunked");
        for r in [0..10u64, 65_530..65_600, 100_000..250_000, 299_990..400_000] {
            let x = a.read(r.clone()).unwrap();
            let y = b.read(r.clone()).unwrap();
            assert_eq!(x, y);
        }
        // Non-blocking read eventually succeeds once the loader fills the cache.
        let mut got = None;
        for _ in 0..200 {
            if let Some(v) = b.try_read(70_000..140_000) {
                got = Some(v.into_owned());
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        assert_eq!(got.unwrap(), &data[70_000..140_000]);
    }

    /// A remote file in memory that counts the requests made to it.
    struct Counting(Vec<u8>, Arc<Mutex<Vec<Range<u64>>>>);

    impl RangeRead for Counting {
        fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
            self.1
                .lock()
                .unwrap()
                .push(offset..offset + buf.len() as u64);
            buf.copy_from_slice(&self.0[offset as usize..offset as usize + buf.len()]);
            Ok(())
        }
    }

    #[test]
    fn a_remote_file_is_read_only_where_asked() {
        let data: Vec<u8> = (0..5_000_000u32).map(|i| (i % 253) as u8).collect();
        let asked = Arc::new(Mutex::new(Vec::new()));
        let s = Source::remote(
            Box::new(Counting(data.clone(), asked.clone())),
            data.len() as u64,
            None,
        );
        assert!(s.is_remote() && s.kind_name() == "chunked" && s.path().is_none());
        // The UI asks without blocking: queued, then served from the cache.
        let mid = 2_600_000u64;
        let mut got = None;
        for _ in 0..400 {
            if let Some(v) = s.try_read(mid..mid + 4000) {
                got = Some(v.into_owned());
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        assert_eq!(got.unwrap(), &data[mid as usize..mid as usize + 4000]);
        // One block around the middle was fetched, nothing else.
        assert_eq!(asked.lock().unwrap().len(), 1);
        assert_eq!(s.bytes_read(), REMOTE_BLOCK);
        // A read across two blocks fetches both with one request.
        asked.lock().unwrap().clear();
        let edge = 3 * REMOTE_BLOCK - 100;
        assert_eq!(
            s.read(edge..edge + 200).unwrap().into_owned(),
            &data[edge as usize..edge as usize + 200]
        );
        assert_eq!(s.read(edge..edge + 200).unwrap().len(), 200);
        assert_eq!(
            asked.lock().unwrap().len(),
            2,
            "two blocks the first time, none the second"
        );
        // Workers' large reads go straight to the reader.
        let mut buf = vec![0u8; 2 << 20];
        s.read_into(1000, &mut buf).unwrap();
        assert_eq!(&buf[..], &data[1000..1000 + (2 << 20)]);
        assert!(s.bytes_read() < data.len() as u64);
        assert!(
            !Source::open(&std::env::current_exe().unwrap(), OpenMode::Chunked)
                .unwrap()
                .is_remote()
        );
    }

    #[test]
    fn neighbouring_blocks_load_with_one_request() {
        let data = vec![7u8; 3 << 20];
        let asked = Arc::new(Mutex::new(Vec::new()));
        let s = Source::remote(Box::new(Counting(data, asked.clone())), 3 << 20, None);
        // A screen that straddles four blocks.
        let r = REMOTE_BLOCK / 2..REMOTE_BLOCK * 3 + 10;
        for _ in 0..400 {
            if s.try_read(r.clone()).is_some() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        let asked = asked.lock().unwrap();
        assert_eq!(
            (asked.len(), asked.first().cloned()),
            (1, Some(0..REMOTE_BLOCK * 4))
        );
    }

    /// The loader takes its queue only once the reader that queued blocks has sent them all, so
    /// a screen's blocks load with one request however the two threads are scheduled (CI once
    /// saw block 0 taken alone and its neighbours fetched with a second request).
    #[test]
    fn loader_waits_for_a_reader_to_queue_all_its_blocks() {
        let data = vec![7u8; 3 << 20];
        let asked = Arc::new(Mutex::new(Vec::new()));
        let s = Source::remote(Box::new(Counting(data, asked.clone())), 3 << 20, None);
        let Backing::Chunked(c) = &s.backing else {
            panic!("a remote source is chunked");
        };
        {
            // What `try_read` does, with time for the loader to wake between two sends.
            let mut pending = c.inner.pending.lock().unwrap();
            for b in 0..4u64 {
                pending.insert(b);
                c.tx.send(b).unwrap();
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
        }
        let r = 0..REMOTE_BLOCK * 4;
        for _ in 0..400 {
            if s.try_read(r.clone()).is_some() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        let asked = asked.lock().unwrap();
        assert_eq!(
            (asked.len(), asked.first().cloned()),
            (1, Some(0..REMOTE_BLOCK * 4))
        );
    }

    #[test]
    fn empty_file() {
        let f = tempfile::NamedTempFile::new().unwrap();
        let s = Source::open(f.path(), OpenMode::Auto).unwrap();
        assert_eq!(s.len(), 0);
        assert_eq!(s.read(0..10).unwrap().len(), 0);
    }

    /// `BIGTEXT_NETWORK_FILE=/mnt/c/Windows/win.ini cargo test --lib network_mount -- --ignored`
    /// under WSL2 (its Windows drives are 9p), or a file on an NFS, SMB or sshfs mount, or on
    /// Windows a network drive.
    #[test]
    #[ignore]
    fn a_file_on_a_network_mount_is_read_in_chunks() {
        let p = std::env::var_os("BIGTEXT_NETWORK_FILE").expect("BIGTEXT_NETWORK_FILE");
        let s = Source::open(Path::new(&p), OpenMode::Auto).unwrap();
        assert_eq!(s.kind_name(), "chunked");
        assert!(!s.parallel_reads());
    }

    #[test]
    fn network_file_systems_are_recognised() {
        for nfs in [
            0x6969,
            0x517B,
            0xFF53_4D42,
            0xFE53_4D42,
            0x6573_5546,
            0x0102_1997,
        ] {
            assert!(network_fs_magic(nfs), "{nfs:#x}");
        }
        // ext4, btrfs, xfs, tmpfs, overlayfs
        for local in [0xEF53, 0x9123_683E, 0x5846_5342, 0x0102_1994, 0x794C_7630] {
            assert!(!network_fs_magic(local), "{local:#x}");
        }
        for name in ["nfs", "smbfs", "afpfs", "webdav", "macfuse", "osxfuse"] {
            assert!(network_fs_name(name.as_bytes()), "{name}");
        }
        for name in ["apfs", "hfs", "msdos", "exfat", ""] {
            assert!(!network_fs_name(name.as_bytes()), "{name}");
        }
        // Remote and chunked sources are read by one thread; the answer for a local file
        // depends on the drive the temp folder is on.
        let remote = Source::remote(
            Box::new(Counting(vec![0; 10], Default::default())),
            10,
            None,
        );
        assert!(!remote.parallel_reads());
        let f = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(f.path(), b"x\n").unwrap();
        assert!(!Source::open(f.path(), OpenMode::Chunked)
            .unwrap()
            .parallel_reads());
    }
}