Skip to main content

large_text_core/
file_reader.rs

1use anyhow::Result;
2use encoding_rs::{Encoding, UTF_16BE, UTF_16LE, UTF_8, WINDOWS_1252};
3use memmap2::Mmap;
4use std::fs::File;
5use std::path::PathBuf;
6
7pub struct FileReader {
8    mmap: Mmap,
9    path: PathBuf,
10    encoding: &'static Encoding,
11}
12
13impl FileReader {
14    pub fn new(path: PathBuf, encoding: &'static Encoding) -> Result<Self> {
15        let file = File::open(&path)?;
16        let metadata = file.metadata()?;
17        if metadata.len() == 0 {
18            anyhow::bail!("Cannot memory-map an empty file: {:?}", path);
19        }
20        let mmap = unsafe { Mmap::map(&file)? };
21
22        Ok(Self {
23            mmap,
24            path,
25            encoding,
26        })
27    }
28
29    pub fn get_chunk(&self, start: usize, end: usize) -> String {
30        let end = end.min(self.mmap.len());
31        if start >= end {
32            return String::new();
33        }
34
35        let bytes = &self.mmap[start..end];
36        let (cow, _encoding, _had_errors) = self.encoding.decode(bytes);
37        cow.into_owned()
38    }
39
40    pub fn get_bytes(&self, start: usize, end: usize) -> &[u8] {
41        let end = end.min(self.mmap.len());
42        if start >= end {
43            return &[];
44        }
45        &self.mmap[start..end]
46    }
47
48    pub fn len(&self) -> usize {
49        self.mmap.len()
50    }
51
52    pub fn is_empty(&self) -> bool {
53        self.mmap.is_empty()
54    }
55
56    pub fn path(&self) -> &PathBuf {
57        &self.path
58    }
59
60    pub fn encoding(&self) -> &'static Encoding {
61        self.encoding
62    }
63
64    pub fn all_data(&self) -> &[u8] {
65        &self.mmap[..]
66    }
67}
68
69pub fn detect_encoding(bytes: &[u8]) -> &'static Encoding {
70    // Check for BOM
71    if bytes.len() >= 3 && bytes[0..3] == [0xEF, 0xBB, 0xBF] {
72        return UTF_8;
73    }
74    if bytes.len() >= 2 {
75        if bytes[0..2] == [0xFF, 0xFE] {
76            return UTF_16LE;
77        }
78        if bytes[0..2] == [0xFE, 0xFF] {
79            return UTF_16BE;
80        }
81    }
82
83    // Try UTF-8 validation
84    if std::str::from_utf8(bytes).is_ok() {
85        return UTF_8;
86    }
87
88    // Default to WINDOWS_1252 (similar to ISO-8859-1)
89    WINDOWS_1252
90}
91
92pub fn available_encodings() -> Vec<(&'static str, &'static Encoding)> {
93    vec![
94        ("UTF-8", UTF_8),
95        ("UTF-16 LE", UTF_16LE),
96        ("UTF-16 BE", UTF_16BE),
97        ("Windows-1252", WINDOWS_1252),
98        ("ISO-8859-1", encoding_rs::WINDOWS_1252), // Similar enough
99    ]
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use std::io::Write;
106    use tempfile::NamedTempFile;
107
108    #[test]
109    fn test_detect_encoding() {
110        assert_eq!(detect_encoding(b"\xEF\xBB\xBFhello"), UTF_8);
111        assert_eq!(detect_encoding(b"\xFF\xFEhello"), UTF_16LE);
112        assert_eq!(detect_encoding(b"\xFE\xFFhello"), UTF_16BE);
113        assert_eq!(detect_encoding(b"hello world"), UTF_8);
114        // Invalid UTF-8 sequence
115        assert_eq!(detect_encoding(b"\xFF\xFF\xFF"), WINDOWS_1252);
116    }
117
118    #[test]
119    fn test_file_reader() -> Result<()> {
120        let mut file = NamedTempFile::new()?;
121        write!(file, "Hello World\nLine 2")?;
122        let path = file.path().to_path_buf();
123
124        let reader = FileReader::new(path.clone(), UTF_8)?;
125        assert_eq!(reader.len(), 18);
126        assert_eq!(reader.get_chunk(0, 5), "Hello");
127        assert_eq!(reader.get_chunk(6, 11), "World");
128        assert_eq!(reader.get_bytes(0, 5), b"Hello");
129
130        Ok(())
131    }
132
133    #[test]
134    fn test_empty_file() -> Result<()> {
135        let file = NamedTempFile::new()?;
136        let path = file.path().to_path_buf();
137        let result = FileReader::new(path, UTF_8);
138        assert!(result.is_err());
139        Ok(())
140    }
141}