paircomp_core/within_line.rs
1use crate::file::open_regular_file;
2use crate::{Error, Fingerprint, LineInfo};
3use std::io::{self, Read};
4use std::path::Path;
5
6/// Inspects a 1-based line of a regular file.
7///
8/// Returns `Some` with its raw byte length, including any terminating LF, or
9/// `None` beyond EOF. CR is ordinary content; a trailing LF does not create an
10/// additional empty line. Invalid UTF-8 is accepted.
11///
12/// Reopens the path and requires [file stability](crate#file-stability).
13///
14/// # Errors
15///
16/// Returns [`Error::InvalidLineNumber`] for line zero, [`Error::Io`] if
17/// metadata lookup, opening, or reading fails, or [`Error::NotRegularFile`]
18/// for a non-regular input.
19///
20/// # Examples
21///
22/// See [`fingerprint_line_prefix`] for an example inspecting and hashing a line.
23pub fn inspect_line(path: &Path, line: u64) -> Result<Option<LineInfo>, Error> {
24 let byte_len = scan_line(open_regular_file(path)?, line, u64::MAX, |_| {})?;
25 Ok((byte_len > 0).then_some(LineInfo { byte_len }))
26}
27
28/// Hashes only the first `byte_count` raw bytes of a 1-based line.
29///
30/// Zero bytes or an absent line hashes the empty sequence. Requests beyond
31/// the line include its entire content, including LF if present, without
32/// entering the next line or adding an EOF marker. Invalid UTF-8 is accepted.
33/// The path must identify a readable regular file even when `byte_count` is
34/// zero.
35///
36/// Reopens the path and requires [file stability](crate#file-stability).
37///
38/// # Errors
39///
40/// Returns [`Error::InvalidLineNumber`] for line zero, [`Error::Io`] if
41/// metadata lookup, opening, or reading fails, or [`Error::NotRegularFile`]
42/// for a non-regular input.
43///
44/// # Examples
45///
46/// A line-local prefix excludes preceding lines and may end inside a UTF-8
47/// code point. Longer requests stop at the selected line's LF. Reference files
48/// make the expected bytes explicit and are hashed with [`crate::fingerprint_file`].
49///
50/// ```
51/// use paircomp_core::{
52/// fingerprint_file, fingerprint_line_prefix, fingerprint_through_line, inspect_line,
53/// };
54/// use std::fs;
55///
56/// let directory = std::env::temp_dir()
57/// .join(format!("paircomp-prefix-example-{}", std::process::id()));
58/// fs::create_dir(&directory)?;
59/// let path = directory.join("sample.txt");
60/// fs::write(&path, "header\ncafé\nnext\n")?;
61///
62/// assert_eq!(inspect_line(&path, 2)?.map(|line| line.byte_len), Some(6));
63/// let prefix = fingerprint_line_prefix(&path, 2, 4)?;
64/// let prefix_path = directory.join("prefix.bin");
65/// fs::write(&prefix_path, b"caf\xc3")?;
66/// assert_eq!(prefix, fingerprint_file(&prefix_path)?);
67///
68/// let whole_line = fingerprint_line_prefix(&path, 2, 100)?;
69/// let line_path = directory.join("line.txt");
70/// fs::write(&line_path, "café\n")?;
71/// assert_eq!(whole_line, fingerprint_file(&line_path)?);
72///
73/// // A file prefix also includes every preceding line.
74/// let file_prefix = fingerprint_through_line(&path, 2)?;
75/// let file_prefix_path = directory.join("file-prefix.txt");
76/// fs::write(&file_prefix_path, "header\ncafé\n")?;
77/// assert_eq!(file_prefix, fingerprint_file(&file_prefix_path)?);
78///
79/// // Zero bytes and an absent line both hash the empty sequence.
80/// assert_eq!(fingerprint_line_prefix(&path, 2, 0)?, fingerprint_line_prefix(&path, 4, 100)?);
81/// fs::remove_dir_all(&directory)?;
82/// # Ok::<(), Box<dyn std::error::Error>>(())
83/// ```
84pub fn fingerprint_line_prefix(
85 path: &Path,
86 line: u64,
87 byte_count: u64,
88) -> Result<Fingerprint, Error> {
89 let mut hasher = blake3::Hasher::new();
90 scan_line(open_regular_file(path)?, line, byte_count, |bytes| {
91 hasher.update(bytes);
92 })?;
93 Ok(Fingerprint(*hasher.finalize().as_bytes()))
94}
95
96/// Maps a 1-based byte position to a 1-based Unicode code-point position.
97///
98/// Every byte of a multibyte character maps to the same character. Immediately
99/// after an existing line, returns the next character position. CR and LF each
100/// count as a code point; these positions are not visual editor columns.
101///
102/// Validates the entire selected line, returning `None` if any part is invalid
103/// UTF-8, even after the requested byte. An absent line permits byte position
104/// 1 and returns `None`. Other lines' encodings do not affect the result.
105///
106/// Reopens the path and requires [file stability](crate#file-stability).
107///
108/// # Errors
109///
110/// Returns [`Error::InvalidLineNumber`] for line zero and
111/// [`Error::InvalidBytePosition`] for byte zero or a position more than one
112/// past the line. Coordinate validation also applies to invalid UTF-8 lines.
113/// Returns [`Error::Io`] if metadata lookup, opening, or reading fails,
114/// [`Error::NotRegularFile`] for a non-regular input, or [`Error::FileTooLarge`]
115/// if the next character position cannot fit in `u64`.
116///
117/// # Examples
118///
119/// Both bytes of `é` map to character 4. The terminating LF counts as a
120/// separate code point, and the position immediately after it is also valid.
121///
122/// ```
123/// use paircomp_core::utf8_character_position;
124/// use std::fs;
125///
126/// let directory = std::env::temp_dir()
127/// .join(format!("paircomp-utf8-example-{}", std::process::id()));
128/// fs::create_dir(&directory)?;
129/// let path = directory.join("sample.txt");
130/// fs::write(&path, b"caf\xc3\xa9\nvalid prefix\xff\n")?;
131///
132/// assert_eq!(utf8_character_position(&path, 1, 4)?, Some(4));
133/// assert_eq!(utf8_character_position(&path, 1, 5)?, Some(4));
134/// assert_eq!(utf8_character_position(&path, 1, 6)?, Some(5)); // LF
135/// assert_eq!(utf8_character_position(&path, 1, 7)?, Some(6)); // After LF
136///
137/// // Invalid UTF-8 later in line 2 suppresses even its first position.
138/// assert_eq!(utf8_character_position(&path, 2, 1)?, None);
139/// // A trailing LF does not create a third line.
140/// assert_eq!(utf8_character_position(&path, 3, 1)?, None);
141/// fs::remove_dir_all(&directory)?;
142/// # Ok::<(), Box<dyn std::error::Error>>(())
143/// ```
144pub fn utf8_character_position(path: &Path, line: u64, byte: u64) -> Result<Option<u64>, Error> {
145 if byte == 0 {
146 return Err(Error::InvalidBytePosition);
147 }
148 character_position(open_regular_file(path)?, line, byte)
149}
150
151/// Maps a byte position using a reader positioned at the start of the file.
152///
153/// The caller must reject byte zero before calling this helper.
154fn character_position(reader: impl Read, line: u64, byte: u64) -> Result<Option<u64>, Error> {
155 // Preserve an incomplete code point across chunks; UTF-8 needs at most four bytes.
156 let mut pending = [0_u8; 4];
157 let mut pending_len = 0;
158 let mut valid = true;
159 let mut seen = 0_u64;
160 let mut characters = 0_u64;
161 let mut position = None;
162 let byte_len = scan_line(reader, line, u64::MAX, |bytes| {
163 for &value in bytes {
164 if !valid {
165 // Keep scanning after invalid UTF-8 so the final byte bounds and
166 // any later I/O errors are still checked.
167 break;
168 }
169 seen += 1;
170 pending[pending_len] = value;
171 pending_len += 1;
172 match std::str::from_utf8(&pending[..pending_len]) {
173 Ok(_) => {
174 characters += 1;
175 if byte > seen - pending_len as u64 && byte <= seen {
176 position = Some(characters);
177 }
178 pending_len = 0;
179 }
180 Err(error) if error.error_len().is_none() && pending_len < 4 => {}
181 Err(_) => valid = false,
182 }
183 }
184 })?;
185 // Subtraction also handles a hypothetical u64::MAX-byte line without overflow.
186 if byte - 1 > byte_len {
187 return Err(Error::InvalidBytePosition);
188 }
189 if !valid || pending_len != 0 || byte_len == 0 {
190 return Ok(None);
191 }
192 if byte - 1 == byte_len {
193 return Ok(Some(characters.checked_add(1).ok_or(Error::FileTooLarge)?));
194 }
195 Ok(position)
196}
197
198/// Visits bounded chunks from a single line, without retaining its contents.
199///
200/// The reader must start at the beginning of the file. Visits at most
201/// `byte_limit` bytes, including the terminating LF if reached, and returns the
202/// number visited. An absent line or a zero limit visits nothing and returns
203/// zero. Line zero is invalid even when the limit is zero.
204fn scan_line(
205 mut reader: impl Read,
206 line: u64,
207 byte_limit: u64,
208 mut visit: impl FnMut(&[u8]),
209) -> Result<u64, Error> {
210 if line == 0 {
211 return Err(Error::InvalidLineNumber);
212 }
213 let mut lines_to_skip = line - 1;
214 let mut byte_len = 0_u64;
215 let mut buffer = [0_u8; 8192];
216 while byte_len < byte_limit {
217 let read = match reader.read(&mut buffer) {
218 Ok(0) => break,
219 Ok(read) => read,
220 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
221 Err(error) => return Err(error.into()),
222 };
223 let mut start = 0;
224 while lines_to_skip > 0 && start < read {
225 if buffer[start] == b'\n' {
226 lines_to_skip -= 1;
227 }
228 start += 1;
229 }
230 if start == read {
231 continue;
232 }
233 let bytes = &buffer[start..read];
234 let line_end = bytes.iter().position(|&value| value == b'\n');
235 let available = line_end.map_or(bytes.len(), |index| index + 1);
236 let included = (available as u64).min(byte_limit - byte_len) as usize;
237 byte_len = byte_len
238 .checked_add(included as u64)
239 .ok_or(Error::FileTooLarge)?;
240 visit(&bytes[..included]);
241 if line_end.is_some() {
242 break;
243 }
244 }
245 Ok(byte_len)
246}
247
248#[cfg(test)]
249mod tests;