bigtext 0.8.1

Free editor for huge text and log files (1-50+ GB): opens instantly, never freezes, 2.5 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
//! 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;
/// Maximum number of cached blocks (64 MB).
const CACHE_BLOCKS: usize = 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),
}

/// 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>,
}

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

    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 });
        }
        let force_chunked = mode == OpenMode::Chunked
            || std::env::var_os("BIGTEXT_FORCE_CHUNKED").is_some()
            || prefers_chunked(path);
        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 }),
                Err(_) => {
                    return Ok(Source { path: path_buf, len, backing: Backing::Chunked(Chunked::new(m.file, len)), modified })
                }
            }
        }
        Ok(Source { path: path_buf, len, backing: Backing::Chunked(Chunked::new(file, len)), modified })
    }

    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(_) => "chunked",
        }
    }

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

    /// 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) => read_exact_at(&c.inner.file, buf, offset),
        }
    }

    /// 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>>) {
        self.tick += 1;
        if self.map.len() >= CACHE_BLOCKS {
            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 {
    file: File,
    len: u64,
    cache: Mutex<BlockCache>,
    pending: Mutex<HashSet<u64>>,
    waker: Mutex<Option<Waker>>,
    failed: AtomicBool,
    reads: AtomicU64,
}

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

    fn load_block(&self, b: u64) -> io::Result<Arc<Vec<u8>>> {
        let r = self.block_range(b);
        let mut buf = vec![0u8; (r.end - r.start) as usize];
        read_exact_at(&self.file, &mut buf, r.start)?;
        self.reads.fetch_add(1, Ordering::Relaxed);
        let data = Arc::new(buf);
        self.cache.lock().unwrap().insert(b, data.clone());
        Ok(data)
    }
}

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

impl Chunked {
    fn new(file: File, len: u64) -> Chunked {
        let inner = Arc::new(ChunkedInner {
            file,
            len,
            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),
        });
        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];
            read_exact_at(&self.inner.file, &mut buf, r.start).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 / CHUNK_BLOCK;
        let last = (r.end - 1) / CHUNK_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>> {
        let n = (r.end - r.start) as usize;
        if n == 0 {
            return Some(Vec::new());
        }
        let first = r.start / CHUNK_BLOCK;
        let last = (r.end - 1) / CHUNK_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() {
        let mut batch = vec![b];
        while let Ok(more) = rx.try_recv() {
            batch.push(more);
        }
        batch.sort_unstable();
        for b in batch {
            let already = inner.cache.lock().unwrap().map.contains_key(&b);
            if !already && inner.load_block(b).is_err() {
                inner.failed.store(true, Ordering::Relaxed);
            }
            inner.pending.lock().unwrap().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) -> 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)
}

#[cfg(not(windows))]
fn prefers_chunked(_path: &Path) -> bool {
    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);
    }

    #[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!(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]);
    }

    #[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);
    }
}