Skip to main content

agentmux_srv_core/backend/
editor_lines.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `fileindexlines`: where the lines of a text file start, for the Large text viewer. The file is read here, in
5//! blocks, once per `(path, modified time)`: what is kept is the byte offset of every `STEP`-th line, so the
6//! viewer asks for "lines 5,000,000 to 5,000,100" and gets the byte range to fetch, and a file bigger than memory
7//! never leaves srv. A line ends at `\n` (so `\r\n` and `\n` files both work); in UTF-16 it ends at the two-byte
8//! `\n`. A final line with no newline is a line; a newline at the very end starts none.
9//!
10//! docs/specs/SPEC_EDITOR_REVAMP_UNIFIED_VIEWERS_2026_10_15.md ยง4.4.6.
11
12use std::io::{Read, Seek, SeekFrom};
13use std::path::{Path, PathBuf};
14use std::sync::{Arc, Mutex, OnceLock};
15
16use crate::backend::base::expand_home_dir_safe;
17use crate::backend::rpc::engine::WshRpcEngine;
18use crate::backend::rpc_types::{FileIndexLinesReq, FileIndexLinesResult};
19
20/// One read.
21const BLOCK: usize = 1 << 20;
22/// The index keeps the offset of every this-many-th line.
23const STEP: u64 = 1024;
24/// The most lines one call may span, so an answer is a screenful, not a file.
25const MAX_COUNT: u64 = 100_000;
26/// The indexes kept (the most recently used).
27const CACHE_ENTRIES: usize = 6;
28/// How much of the start of a file says what encoding its text is in.
29const DETECT_BYTES: u64 = 256 * 1024;
30
31/// How a file's text marks the end of a line.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Unit {
34    /// One byte, `\n`: UTF-8, and the legacy single-byte encodings.
35    Byte,
36    /// Two bytes, `0A 00`.
37    Utf16Le,
38    /// Two bytes, `00 0A`.
39    Utf16Be,
40}
41
42impl Unit {
43    /// From a probe's `encoding`; anything else is an error naming it.
44    pub fn parse(encoding: &str) -> Result<Unit, String> {
45        match encoding {
46            "" | "utf-8" | "legacy" => Ok(Unit::Byte),
47            "utf-16le" => Ok(Unit::Utf16Le),
48            "utf-16be" => Ok(Unit::Utf16Be),
49            other => Err(format!("an encoding of utf-8, utf-16le or utf-16be, not {other:?}")),
50        }
51    }
52}
53
54/// Where the lines of one file start, as of one `(size, mtime)`.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct LineIndex {
57    pub size: u64,
58    pub mtime: i64,
59    pub total_lines: u64,
60    pub step: u64,
61    /// The start of line 0, `step`, `2 * step`, ...
62    pub checkpoints: Vec<u64>,
63    /// The text's encoding by its WHATWG name ("utf-8", "windows-1251", "utf-16le"...), found when the file was indexed.
64    pub encoding: String,
65}
66
67/// The offsets just after each line break in `block` (which starts at file offset `base`, an even number for UTF-16).
68fn breaks_in(block: &[u8], base: u64, unit: Unit, mut each: impl FnMut(u64)) {
69    match unit {
70        Unit::Byte => memchr::memchr_iter(b'\n', block).for_each(|i| each(base + i as u64 + 1)),
71        Unit::Utf16Le | Unit::Utf16Be => {
72            let (hi, lo) = if unit == Unit::Utf16Le { (1, 0) } else { (0, 1) };
73            for (i, pair) in block.chunks_exact(2).enumerate() {
74                if pair[lo] == b'\n' && pair[hi] == 0 {
75                    each(base + (i as u64) * 2 + 2);
76                }
77            }
78        }
79    }
80}
81
82/// A read size that is a whole number of code units.
83fn block_size(unit: Unit, block: usize) -> usize {
84    if unit == Unit::Byte {
85        block.max(1)
86    } else {
87        (block & !1).max(2)
88    }
89}
90
91/// Reads `file` (`size` bytes) front to back and notes where every `step`-th line starts.
92pub fn build_index<R: Read>(file: &mut R, size: u64, mtime: i64, unit: Unit, step: u64, block: usize) -> std::io::Result<LineIndex> {
93    let block = block_size(unit, block);
94    let mut buf = vec![0u8; block];
95    let mut checkpoints = Vec::new();
96    let mut lines = 0u64;
97    let mut note_line = |start: u64, lines: &mut u64| {
98        if *lines % step == 0 {
99            checkpoints.push(start);
100        }
101        *lines += 1;
102    };
103    if size > 0 {
104        note_line(0, &mut lines);
105    }
106    let mut at = 0u64;
107    while at < size {
108        let want = (size - at).min(block as u64) as usize;
109        file.read_exact(&mut buf[..want])?;
110        // A line starts after a break unless the file ends there.
111        breaks_in(&buf[..want], at, unit, |end| {
112            if end < size {
113                note_line(end, &mut lines);
114            }
115        });
116        at += want as u64;
117    }
118    Ok(LineIndex { size, mtime, total_lines: lines, step, checkpoints, encoding: String::new() })
119}
120
121/// The WHATWG name of the encoding of the text that `file` holds, from its start: UTF-16 as the unit says, else a
122/// UTF-8 BOM, else valid UTF-8 (a character cut at the end of the sample is not an error), else the detector's guess,
123/// as the Editor's own reader makes it. The probe says only "legacy" for a file that isn't UTF-8.
124pub fn detect_encoding<R: Read>(file: &mut R, unit: Unit) -> std::io::Result<String> {
125    match unit {
126        Unit::Utf16Le => return Ok("utf-16le".into()),
127        Unit::Utf16Be => return Ok("utf-16be".into()),
128        Unit::Byte => {}
129    }
130    let mut head = Vec::new();
131    file.take(DETECT_BYTES).read_to_end(&mut head)?;
132    let utf8 = head.starts_with(b"\xEF\xBB\xBF") || std::str::from_utf8(&head).map_or_else(|e| e.error_len().is_none(), |_| true);
133    if utf8 {
134        return Ok("utf-8".into());
135    }
136    let mut det = chardetng::EncodingDetector::new();
137    det.feed(&head, true);
138    Ok(det.guess(None, false).name().to_string())
139}
140
141/// The offset `n` lines after the line that starts at `from` (the size, when the file has fewer lines).
142fn skip_lines<F: Read + Seek>(file: &mut F, from: u64, n: u64, size: u64, unit: Unit, block: usize) -> std::io::Result<u64> {
143    if n == 0 {
144        return Ok(from.min(size));
145    }
146    let block = block_size(unit, block);
147    let mut buf = vec![0u8; block];
148    let (mut at, mut left) = (from, n);
149    file.seek(SeekFrom::Start(from))?;
150    while at < size {
151        let want = (size - at).min(block as u64) as usize;
152        file.read_exact(&mut buf[..want])?;
153        let mut found = None;
154        breaks_in(&buf[..want], at, unit, |end| {
155            if found.is_none() {
156                left -= 1;
157                if left == 0 {
158                    found = Some(end);
159                }
160            }
161        });
162        if let Some(end) = found {
163            return Ok(end.min(size));
164        }
165        at += want as u64;
166    }
167    Ok(size)
168}
169
170/// Where each of the `n` lines that begin at `from` starts (the first is `from`), and the offset just after the last
171/// of them (the size, when the file has fewer). One pass over the run, so a line of gigabytes is read once. When the
172/// run reaches the end of the file (`to_eof`) the last line is not read at all: its end is the size.
173fn starts_in<F: Read + Seek>(file: &mut F, from: u64, n: u64, size: u64, to_eof: bool, unit: Unit, block: usize) -> std::io::Result<(Vec<u64>, u64)> {
174    let mut starts = Vec::new();
175    if n == 0 || from >= size {
176        return Ok((starts, from.min(size)));
177    }
178    starts.push(from);
179    // The breaks to find: one after each line, except the last when it is known to end where the file does.
180    let need = if to_eof { n - 1 } else { n };
181    if need == 0 {
182        return Ok((starts, size));
183    }
184    let block = block_size(unit, block);
185    let mut buf = vec![0u8; block];
186    let (mut at, mut left) = (from, need);
187    file.seek(SeekFrom::Start(from))?;
188    while at < size {
189        let want = (size - at).min(block as u64) as usize;
190        file.read_exact(&mut buf[..want])?;
191        let mut found = None;
192        breaks_in(&buf[..want], at, unit, |end| {
193            if found.is_some() {
194                return;
195            }
196            // A break starts the next line, unless the file ends there or the run is complete.
197            if (starts.len() as u64) < n && end < size {
198                starts.push(end);
199            }
200            left -= 1;
201            if left == 0 {
202                found = Some(end);
203            }
204        });
205        if let Some(end) = found {
206            return Ok((starts, if to_eof { size } else { end.min(size) }));
207        }
208        at += want as u64;
209    }
210    Ok((starts, size))
211}
212
213/// Where line `line` (0-based) starts; the size for a line past the last.
214pub fn line_start<F: Read + Seek>(file: &mut F, idx: &LineIndex, line: u64, unit: Unit, block: usize) -> std::io::Result<u64> {
215    if line >= idx.total_lines {
216        return Ok(idx.size);
217    }
218    let Some(&checkpoint) = idx.checkpoints.get((line / idx.step) as usize) else { return Ok(idx.size) };
219    skip_lines(file, checkpoint, line % idx.step, idx.size, unit, block)
220}
221
222/// The line (0-based) that holds byte `offset`: the last one that starts at or before it. An offset past the end is in
223/// the last line. Reads from the nearest checkpoint to `offset`, counting breaks, so at most `STEP` lines.
224pub fn line_of<F: Read + Seek>(file: &mut F, idx: &LineIndex, offset: u64, unit: Unit, block: usize) -> std::io::Result<u64> {
225    let Some(last) = idx.size.checked_sub(1).filter(|_| idx.total_lines > 0) else { return Ok(0) };
226    let offset = offset.min(last);
227    let k = idx.checkpoints.partition_point(|c| *c <= offset).saturating_sub(1);
228    let Some(&from) = idx.checkpoints.get(k) else { return Ok(0) };
229    let block = block_size(unit, block);
230    let mut buf = vec![0u8; block];
231    let (mut at, mut line) = (from, k as u64 * idx.step);
232    file.seek(SeekFrom::Start(from))?;
233    // A break whose last byte is before `offset` starts a line at or before it.
234    while at < offset {
235        let want = (offset - at).min(block as u64) as usize;
236        file.read_exact(&mut buf[..want])?;
237        breaks_in(&buf[..want], at, unit, |_| line += 1);
238        at += want as u64;
239    }
240    Ok(line)
241}
242
243type CacheKey = (PathBuf, u8);
244
245fn cache() -> &'static Mutex<Vec<(CacheKey, Arc<LineIndex>)>> {
246    static CACHE: OnceLock<Mutex<Vec<(CacheKey, Arc<LineIndex>)>>> = OnceLock::new();
247    CACHE.get_or_init(|| Mutex::new(Vec::new()))
248}
249
250fn mtime_ms(meta: &std::fs::Metadata) -> i64 {
251    meta.modified()
252        .ok()
253        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
254        .map(|d| d.as_millis() as i64)
255        .unwrap_or(0)
256}
257
258/// The index of `path` as it is now: the one kept when the file has not changed, else a new one.
259fn index_of(path: &Path, unit: Unit) -> std::io::Result<Arc<LineIndex>> {
260    let meta = std::fs::metadata(path)?;
261    if meta.is_dir() {
262        return Err(std::io::Error::other("is a directory"));
263    }
264    let (size, mtime) = (meta.len(), mtime_ms(&meta));
265    let key: CacheKey = (path.to_path_buf(), unit as u8);
266    {
267        let mut kept = cache().lock().unwrap_or_else(|e| e.into_inner());
268        if let Some(i) = kept.iter().position(|(k, v)| *k == key && v.size == size && v.mtime == mtime) {
269            let hit = kept.remove(i);
270            let idx = hit.1.clone();
271            kept.insert(0, hit);
272            return Ok(idx);
273        }
274    }
275    let mut file = std::fs::File::open(path)?;
276    let encoding = detect_encoding(&mut file, unit)?;
277    file.seek(SeekFrom::Start(0))?;
278    let built = Arc::new(LineIndex { encoding, ..build_index(&mut file, size, mtime, unit, STEP, BLOCK)? });
279    let mut kept = cache().lock().unwrap_or_else(|e| e.into_inner());
280    kept.retain(|(k, _)| *k != key);
281    kept.insert(0, (key, built.clone()));
282    kept.truncate(CACHE_ENTRIES);
283    Ok(built)
284}
285
286/// The answer for `count` lines from line `from_line` of `path`.
287fn lines_of(path: &Path, unit: Unit, from_line: u64, count: u64, with_starts: bool) -> std::io::Result<FileIndexLinesResult> {
288    let idx = index_of(path, unit)?;
289    let mut file = std::fs::File::open(path)?;
290    let start = line_start(&mut file, &idx, from_line, unit, BLOCK)?;
291    let wanted = count.min(idx.total_lines.saturating_sub(from_line));
292    let to_eof = from_line.saturating_add(count) >= idx.total_lines;
293    let (starts, end) = if with_starts {
294        starts_in(&mut file, start, wanted, idx.size, to_eof, unit, BLOCK)?
295    } else if to_eof {
296        (Vec::new(), idx.size)
297    } else {
298        (Vec::new(), skip_lines(&mut file, start, wanted, idx.size, unit, BLOCK)?)
299    };
300    Ok(FileIndexLinesResult { total_lines: idx.total_lines, size: idx.size, mtime: idx.mtime, start, end, encoding: idx.encoding.clone(), starts, line_at: None })
301}
302
303/// The answer for `count` lines from the line that holds byte `offset` of `path`, with that line's number in `line_at`.
304fn lines_at(path: &Path, unit: Unit, offset: u64, count: u64, with_starts: bool) -> std::io::Result<FileIndexLinesResult> {
305    let idx = index_of(path, unit)?;
306    let line = line_of(&mut std::fs::File::open(path)?, &idx, offset, unit, BLOCK)?;
307    Ok(FileIndexLinesResult { line_at: Some(line), ..lines_of(path, unit, line, count, with_starts)? })
308}
309
310/// `fileindexlines`. This computer's files only, like `fileprobe`.
311pub fn register(engine: &std::sync::Arc<WshRpcEngine>) {
312    engine.register_typed("fileindexlines", move |cmd: FileIndexLinesReq, _ctx| async move {
313        let unit = Unit::parse(cmd.encoding.as_deref().unwrap_or("")).map_err(|e| format!("fileindexlines: {e}"))?;
314        if cmd.count > MAX_COUNT {
315            return Err(format!("fileindexlines: at most {MAX_COUNT} lines a call"));
316        }
317        let path = expand_home_dir_safe(&cmd.path);
318        let with_starts = cmd.line_starts.unwrap_or(false);
319        tokio::task::spawn_blocking(move || {
320            match cmd.at_offset {
321                Some(offset) => lines_at(&path, unit, offset, cmd.count, with_starts),
322                None => lines_of(&path, unit, cmd.from_line, cmd.count, with_starts),
323            }
324            .map_err(|e| format!("fileindexlines: {e}"))
325        })
326        .await
327        .map_err(|e| format!("fileindexlines: {e}"))?
328    });
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use std::io::Cursor;
335
336    /// The index of `data` with a step of 3 and blocks of 5 bytes, so checkpoints and block edges both get crossed.
337    fn small(data: &[u8], unit: Unit) -> LineIndex {
338        build_index(&mut Cursor::new(data.to_vec()), data.len() as u64, 7, unit, 3, 5).unwrap()
339    }
340
341    fn start_of(data: &[u8], idx: &LineIndex, line: u64, unit: Unit) -> u64 {
342        line_start(&mut Cursor::new(data.to_vec()), idx, line, unit, 5).unwrap()
343    }
344
345    /// Every line's start, by walking the text the slow way.
346    fn starts(data: &[u8]) -> Vec<u64> {
347        let mut out = Vec::new();
348        if !data.is_empty() {
349            out.push(0);
350        }
351        for (i, b) in data.iter().enumerate() {
352            if *b == b'\n' && i + 1 < data.len() {
353                out.push(i as u64 + 1);
354            }
355        }
356        out
357    }
358
359    #[test]
360    fn counts_lines_of_lf_crlf_and_mixed_text_with_or_without_a_final_break() {
361        for text in ["a\nbb\nccc\ndddd\n", "a\nbb\nccc\ndddd", "a\r\nbb\r\nccc\r\ndddd\r\n", "a\nbb\r\nccc\ndddd\r\n", "\n\n\n", "one"] {
362            let data = text.as_bytes();
363            let idx = small(data, Unit::Byte);
364            assert_eq!(idx.total_lines, starts(data).len() as u64, "{text:?}");
365            for (n, want) in starts(data).into_iter().enumerate() {
366                assert_eq!(start_of(data, &idx, n as u64, Unit::Byte), want, "{text:?} line {n}");
367            }
368            assert_eq!(start_of(data, &idx, idx.total_lines, Unit::Byte), data.len() as u64, "{text:?} past the end");
369            assert_eq!(start_of(data, &idx, idx.total_lines + 50, Unit::Byte), data.len() as u64);
370        }
371    }
372
373    fn line_at(data: &[u8], idx: &LineIndex, offset: u64, unit: Unit) -> u64 {
374        line_of(&mut Cursor::new(data.to_vec()), idx, offset, unit, 5).unwrap()
375    }
376
377    #[test]
378    fn every_byte_is_in_the_line_that_starts_at_or_before_it() {
379        for text in ["a\nbb\nccc\ndddd\n", "a\nbb\nccc\ndddd", "a\r\nbb\r\nccc\r\ndddd\r\n", "\n\n\n\n\n\n\n\n", "one"] {
380            let data = text.as_bytes();
381            let idx = small(data, Unit::Byte);
382            let want = starts(data);
383            for offset in 0..data.len() as u64 {
384                let expect = want.iter().rposition(|s| *s <= offset).unwrap() as u64;
385                assert_eq!(line_at(data, &idx, offset, Unit::Byte), expect, "{text:?} byte {offset}");
386            }
387            // Past the end is the last line.
388            assert_eq!(line_at(data, &idx, data.len() as u64 + 99, Unit::Byte), idx.total_lines - 1, "{text:?} past the end");
389        }
390        assert_eq!(line_at(b"", &small(b"", Unit::Byte), 5, Unit::Byte), 0);
391    }
392
393    #[test]
394    fn finds_the_line_of_a_byte_in_utf16_text() {
395        let text = "ab\ncd\r\nef\n\u{0a0a}x\ng";
396        for (unit, bytes) in [
397            (Unit::Utf16Le, text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect::<Vec<u8>>()),
398            (Unit::Utf16Be, text.encode_utf16().flat_map(|u| u.to_be_bytes()).collect::<Vec<u8>>()),
399        ] {
400            let idx = small(&bytes, unit);
401            // The first byte of each line is in it, and so is the byte before the next one.
402            let mut at = 0u64;
403            let units: Vec<u16> = text.encode_utf16().collect();
404            for (n, line) in units.split_inclusive(|u| *u == 10).enumerate() {
405                let len = line.len() as u64 * 2;
406                assert_eq!(line_at(&bytes, &idx, at, unit), n as u64, "{unit:?} start of line {n}");
407                assert_eq!(line_at(&bytes, &idx, at + len - 1, unit), n as u64, "{unit:?} end of line {n}");
408                at += len;
409            }
410        }
411    }
412
413    #[test]
414    fn answers_at_a_byte_with_the_run_from_its_line() {
415        let dir = tempfile::tempdir().unwrap();
416        let path = dir.path().join("a.txt");
417        std::fs::write(&path, "zero\none\ntwo\nthree\n").unwrap();
418        // Byte 9 is the 't' that starts "two".
419        let r = lines_at(&path, Unit::Byte, 9, 2, true).unwrap();
420        assert_eq!((r.line_at, r.start, r.end, r.starts), (Some(2), 9, 19, vec![9, 13]));
421        assert_eq!(lines_of(&path, Unit::Byte, 2, 1, false).unwrap().line_at, None);
422    }
423
424    #[test]
425    fn an_empty_file_has_no_lines_and_a_lone_break_has_one() {
426        let idx = small(b"", Unit::Byte);
427        assert_eq!((idx.total_lines, idx.checkpoints.len()), (0, 0));
428        assert_eq!(start_of(b"", &idx, 0, Unit::Byte), 0);
429        assert_eq!(small(b"\n", Unit::Byte).total_lines, 1);
430    }
431
432    #[test]
433    fn keeps_the_start_of_every_stepth_line() {
434        let data = b"0\n1\n2\n3\n4\n5\n6\n7\n";
435        let idx = small(data, Unit::Byte);
436        assert_eq!(idx.total_lines, 8);
437        assert_eq!(idx.checkpoints, vec![0, 6, 12]);
438    }
439
440    #[test]
441    fn indexes_utf16_by_its_two_byte_breaks() {
442        let text = "ab\ncd\r\nef\n\u{0a0a}x";
443        for (unit, bytes) in [
444            (Unit::Utf16Le, text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect::<Vec<u8>>()),
445            (Unit::Utf16Be, text.encode_utf16().flat_map(|u| u.to_be_bytes()).collect::<Vec<u8>>()),
446        ] {
447            let idx = small(&bytes, unit);
448            // The text has three breaks, so four lines; U+0A0A holds a 0A byte that is no break.
449            assert_eq!(idx.total_lines, 4, "{unit:?}");
450            let units: Vec<u64> = text.encode_utf16().scan(0u64, |at, u| { let here = *at; *at += 2; Some((here, u)) }).filter(|(_, u)| *u == 0x0a).map(|(at, _)| at + 2).collect();
451            assert_eq!(start_of(&bytes, &idx, 1, unit), units[0], "{unit:?}");
452            assert_eq!(start_of(&bytes, &idx, 3, unit), units[2], "{unit:?}");
453        }
454    }
455
456    #[test]
457    fn a_five_million_line_file_jumps_to_its_last_line() {
458        let data: Vec<u8> = b"x\n".repeat(5_000_000);
459        let idx = build_index(&mut Cursor::new(&data[..]), data.len() as u64, 0, Unit::Byte, STEP, BLOCK).unwrap();
460        assert_eq!(idx.total_lines, 5_000_000);
461        assert_eq!(idx.checkpoints.len(), 5_000_000usize.div_ceil(STEP as usize));
462        let at = |line| line_start(&mut Cursor::new(&data[..]), &idx, line, Unit::Byte, BLOCK).unwrap();
463        assert_eq!((at(0), at(1), at(4_999_999), at(2_500_000)), (0, 2, 9_999_998, 5_000_000));
464        assert_eq!(at(5_000_000), 10_000_000);
465    }
466
467    #[test]
468    fn the_answer_is_the_byte_range_of_the_lines_asked_for() {
469        let dir = std::env::temp_dir().join(format!("fileindexlines-{}", std::process::id()));
470        std::fs::create_dir_all(&dir).unwrap();
471        let path = dir.join("log.txt");
472        std::fs::write(&path, "a\nbb\nccc\ndddd\n").unwrap();
473        let r = lines_of(&path, Unit::Byte, 1, 2, false).unwrap();
474        assert_eq!((r.total_lines, r.size, r.start, r.end), (4, 14, 2, 9));
475        // Past the last line: the rest of the file, then nothing.
476        let r = lines_of(&path, Unit::Byte, 3, 10, false).unwrap();
477        assert_eq!((r.start, r.end), (9, 14));
478        let r = lines_of(&path, Unit::Byte, 9, 10, false).unwrap();
479        assert_eq!((r.start, r.end), (14, 14));
480        let r = lines_of(&path, Unit::Byte, 0, 0, false).unwrap();
481        assert_eq!((r.start, r.end), (0, 0));
482        // The file grew: the kept index is not reused.
483        std::fs::write(&path, "a\nbb\nccc\ndddd\neeeee\nf").unwrap();
484        let r = lines_of(&path, Unit::Byte, 0, 100, false).unwrap();
485        assert_eq!((r.total_lines, r.size), (6, 21));
486        assert!(lines_of(&dir, Unit::Byte, 0, 1, false).is_err(), "a folder is no file");
487        std::fs::remove_dir_all(&dir).unwrap();
488    }
489
490    #[test]
491    fn names_the_encoding_the_text_is_in() {
492        let name = |bytes: &[u8], unit| detect_encoding(&mut Cursor::new(bytes.to_vec()), unit).unwrap();
493        assert_eq!(name("plain ascii\n".as_bytes(), Unit::Byte), "utf-8");
494        assert_eq!(name("caf\u{e9} \u{4e2d}\n".as_bytes(), Unit::Byte), "utf-8");
495        assert_eq!(name(b"\xEF\xBB\xBFhello", Unit::Byte), "utf-8");
496        // A character cut at the end of the sample is still UTF-8.
497        assert_eq!(name(&"\u{4e2d}".as_bytes()[..2], Unit::Byte), "utf-8");
498        assert_eq!(name(b"", Unit::Utf16Le), "utf-16le");
499        assert_eq!(name(b"", Unit::Utf16Be), "utf-16be");
500        // Not UTF-8: what the detector says, not a fixed code page.
501        let (cyrillic, _, _) = encoding_rs::WINDOWS_1251.encode("\u{41f}\u{440}\u{438}\u{432}\u{435}\u{442}, \u{43c}\u{438}\u{440}! \u{41a}\u{430}\u{43a} \u{434}\u{435}\u{43b}\u{430}?");
502        assert_eq!(name(&cyrillic, Unit::Byte), "windows-1251");
503        let (jis, _, _) = encoding_rs::SHIFT_JIS.encode("\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{3001}\u{3053}\u{308c}\u{306f}\u{30c6}\u{30b9}\u{30c8}\u{3067}\u{3059}");
504        assert_eq!(name(&jis, Unit::Byte), "Shift_JIS");
505    }
506
507    #[test]
508    fn the_answer_names_the_encoding_of_the_file() {
509        let dir = std::env::temp_dir().join(format!("fileindexlines-enc-{}", std::process::id()));
510        std::fs::create_dir_all(&dir).unwrap();
511        let path = dir.join("ru.txt");
512        let (cyrillic, _, _) = encoding_rs::WINDOWS_1251.encode("\u{41f}\u{440}\u{438}\u{432}\u{435}\u{442}, \u{43c}\u{438}\u{440}! \u{41a}\u{430}\u{43a} \u{434}\u{435}\u{43b}\u{430}?\n");
513        std::fs::write(&path, &cyrillic).unwrap();
514        assert_eq!(lines_of(&path, Unit::Byte, 0, 1, false).unwrap().encoding, "windows-1251");
515        std::fs::write(&path, "just ascii\n").unwrap();
516        assert_eq!(lines_of(&path, Unit::Byte, 0, 1, false).unwrap().encoding, "utf-8");
517        std::fs::remove_dir_all(&dir).unwrap();
518    }
519
520    /// A file of a huge line (here 3 MB, bigger than a read block) between short ones.
521    #[test]
522    fn says_where_each_line_starts_with_the_one_pass_that_finds_the_end() {
523        let dir = std::env::temp_dir().join(format!("fileindexlines-starts-{}", std::process::id()));
524        std::fs::create_dir_all(&dir).unwrap();
525        let path = dir.join("huge.txt");
526        let mut data = b"first\n".to_vec();
527        data.extend(std::iter::repeat(b'x').take(3 << 20));
528        data.extend_from_slice(b"\nthird\r\nfourth");
529        std::fs::write(&path, &data).unwrap();
530        let want = starts(&data);
531        assert_eq!(want.len(), 4);
532
533        let r = lines_of(&path, Unit::Byte, 0, 4, true).unwrap();
534        assert_eq!(r.starts, want);
535        assert_eq!((r.start, r.end), (0, data.len() as u64));
536
537        // From the middle, and a run that stops short of the end of the file.
538        let r = lines_of(&path, Unit::Byte, 1, 2, true).unwrap();
539        assert_eq!(r.starts, want[1..3].to_vec());
540        assert_eq!((r.start, r.end), (want[1], want[3]));
541
542        // Past the end of the file: no lines.
543        let r = lines_of(&path, Unit::Byte, 9, 5, true).unwrap();
544        assert!(r.starts.is_empty());
545        assert_eq!((r.start, r.end), (data.len() as u64, data.len() as u64));
546
547        // Not asked for: not sent, and the range is the same.
548        let r = lines_of(&path, Unit::Byte, 0, 4, false).unwrap();
549        assert!(r.starts.is_empty());
550        assert_eq!(r.end, data.len() as u64);
551        std::fs::remove_dir_all(&dir).unwrap();
552    }
553
554    #[test]
555    fn starts_in_a_run_of_utf16_and_a_file_that_ends_in_a_break() {
556        let utf16 = |t: &str| t.encode_utf16().flat_map(|u| u.to_le_bytes()).collect::<Vec<u8>>();
557        let data = utf16("ab\ncd\nef\n");
558        let (got, end) = starts_in(&mut Cursor::new(data.clone()), 0, 3, data.len() as u64, true, Unit::Utf16Le, 4).unwrap();
559        assert_eq!((got, end), (vec![0, 6, 12], data.len() as u64));
560        let text = b"a\nb\n";
561        let (got, end) = starts_in(&mut Cursor::new(text.to_vec()), 0, 2, 4, true, Unit::Byte, 3).unwrap();
562        assert_eq!((got, end), (vec![0, 2], 4));
563        // More lines asked for than there are: what there is.
564        let (got, end) = starts_in(&mut Cursor::new(text.to_vec()), 0, 9, 4, true, Unit::Byte, 3).unwrap();
565        assert_eq!((got, end), (vec![0, 2], 4));
566    }
567
568    /// A run that reaches the end of the file doesn't read its last line: a file of one gigantic line is not scanned
569    /// again for its starts, and the last page of any file doesn't read through a gigantic last line.
570    #[test]
571    fn a_run_to_the_end_of_the_file_does_not_read_its_last_line() {
572        let mut data = b"a
573b
574".to_vec();
575        data.extend(std::iter::repeat(b'x').take(1000));
576        let size = data.len() as u64;
577        let mut file = Cursor::new(data.clone());
578        let (got, end) = starts_in(&mut file, 0, 3, size, true, Unit::Byte, 4).unwrap();
579        assert_eq!((got, end), (vec![0, 2, 4], size));
580        assert!(file.position() <= 8, "read to {}", file.position());
581        // One line only: nothing is read.
582        let mut file = Cursor::new(data.clone());
583        let (got, end) = starts_in(&mut file, 4, 1, size, true, Unit::Byte, 4).unwrap();
584        assert_eq!((got, end, file.position()), (vec![4], size, 0));
585        // Not to the end: the run's own end is found, and the answer is the same as before.
586        let (got, end) = starts_in(&mut Cursor::new(data), 0, 2, size, false, Unit::Byte, 4).unwrap();
587        assert_eq!((got, end), (vec![0, 2], 4));
588    }
589
590    #[test]
591    fn names_an_encoding_it_cannot_index() {
592        assert_eq!(Unit::parse("utf-8"), Ok(Unit::Byte));
593        assert_eq!(Unit::parse("utf-16be"), Ok(Unit::Utf16Be));
594        assert!(Unit::parse("shift-jis").unwrap_err().contains("shift-jis"));
595    }
596}