Skip to main content

large_text_core/
replacer.rs

1use anyhow::Result;
2use regex::bytes::Regex;
3use std::fs::{File, OpenOptions};
4use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
5use std::path::Path;
6use std::sync::{
7    atomic::{AtomicBool, Ordering},
8    mpsc::Sender,
9    Arc,
10};
11
12pub enum ReplaceMessage {
13    Progress(usize, usize), // bytes_processed, total_bytes
14    Done,
15    Error(String),
16}
17
18pub struct Replacer;
19
20impl Replacer {
21    pub fn replace_single(
22        file_path: &Path,
23        offset: usize,
24        old_len: usize,
25        new_text: &str,
26    ) -> Result<()> {
27        let new_bytes = new_text.as_bytes();
28
29        if new_bytes.len() == old_len {
30            // In-place optimization
31            let mut file = OpenOptions::new().write(true).open(file_path)?;
32            file.seek(SeekFrom::Start(offset as u64))?;
33            file.write_all(new_bytes)?;
34            return Ok(());
35        }
36
37        // Different length: rewrite file
38        let temp_path = file_path.with_extension("tmp");
39        {
40            let mut input_file = File::open(file_path)?;
41            let mut output_file = BufWriter::new(File::create(&temp_path)?);
42
43            // Copy before match
44            let mut buffer = vec![0u8; 8192];
45            let mut remaining = offset as u64;
46
47            while remaining > 0 {
48                let to_read = std::cmp::min(remaining, buffer.len() as u64) as usize;
49                let n = input_file.read(&mut buffer[0..to_read])?;
50                if n == 0 {
51                    break; // Unexpected EOF
52                }
53                output_file.write_all(&buffer[0..n])?;
54                remaining -= n as u64;
55            }
56
57            // Write replacement
58            output_file.write_all(new_bytes)?;
59
60            // Skip old match in input
61            input_file.seek(SeekFrom::Current(old_len as i64))?;
62
63            // Copy rest
64            std::io::copy(&mut input_file, &mut output_file)?;
65        }
66
67        // Replace original file
68        // On Windows, rename might fail if target exists.
69        if std::fs::rename(&temp_path, file_path).is_err() {
70            // Try to remove target and rename again.
71            if std::fs::remove_file(file_path).is_ok() {
72                std::fs::rename(&temp_path, file_path)?;
73            } else {
74                return Err(anyhow::anyhow!(
75                    "Failed to replace file. It might be open by another process."
76                ));
77            }
78        }
79
80        Ok(())
81    }
82
83    pub fn replace_all(
84        input_path: &Path,
85        output_path: &Path,
86        query: &str,
87        replace_with: &str,
88        use_regex: bool,
89        tx: Sender<ReplaceMessage>,
90        cancel_token: Arc<AtomicBool>,
91    ) {
92        match Self::replace_all_inner(
93            input_path,
94            output_path,
95            query,
96            replace_with,
97            use_regex,
98            &tx,
99            cancel_token,
100        ) {
101            Ok(_) => {
102                let _ = tx.send(ReplaceMessage::Done);
103            }
104            Err(e) => {
105                let _ = tx.send(ReplaceMessage::Error(e.to_string()));
106            }
107        }
108    }
109
110    fn replace_all_inner(
111        input_path: &Path,
112        output_path: &Path,
113        query: &str,
114        replace_with: &str,
115        use_regex: bool,
116        tx: &Sender<ReplaceMessage>,
117        cancel_token: Arc<AtomicBool>,
118    ) -> Result<()> {
119        let mut input_file = File::open(input_path)?;
120        let file_len = input_file.metadata()?.len() as usize;
121        let mut output_file = BufWriter::new(File::create(output_path)?);
122
123        let regex = if use_regex {
124            Regex::new(query)?
125        } else {
126            let pattern = format!("(?i){}", regex::escape(query));
127            Regex::new(&pattern)?
128        };
129
130        let replace_with_bytes = replace_with.as_bytes();
131
132        // Buffer size: 1MB
133        const BUFFER_SIZE: usize = 1024 * 1024;
134        // Overlap: enough to cover max match length.
135        const OVERLAP_SIZE: usize = 4096;
136
137        let mut buffer = vec![0u8; BUFFER_SIZE + OVERLAP_SIZE];
138        let mut eof = false;
139
140        // Initial fill
141        let n = input_file.read(&mut buffer[0..BUFFER_SIZE])?;
142        let mut buffer_len = n;
143        if n < BUFFER_SIZE {
144            eof = true;
145        }
146
147        let mut processed_offset = 0;
148
149        while buffer_len > 0 {
150            if cancel_token.load(Ordering::Relaxed) {
151                return Ok(());
152            }
153
154            // Ensure we end at a char boundary to avoid splitting UTF-8 chars
155            // even though we use bytes regex, we want to respect text boundaries if possible.
156            let mut valid_len = buffer_len;
157            while valid_len > 0 && !is_utf8_char_boundary(buffer[valid_len]) {
158                valid_len -= 1;
159            }
160            if valid_len == 0 && buffer_len > 0 {
161                valid_len = buffer_len;
162            }
163
164            let chunk_bytes = &buffer[..valid_len];
165
166            let safe_zone_end = if eof {
167                valid_len
168            } else {
169                valid_len.saturating_sub(OVERLAP_SIZE)
170            };
171
172            let mut last_match_end = 0;
173
174            for cap in regex.captures_iter(chunk_bytes) {
175                let mat = cap.get(0).unwrap();
176                if mat.start() >= safe_zone_end {
177                    break;
178                }
179
180                // Write text before match
181                output_file.write_all(&chunk_bytes[last_match_end..mat.start()])?;
182
183                // Expand replacement
184                let mut dst = Vec::new();
185                cap.expand(replace_with_bytes, &mut dst);
186                output_file.write_all(&dst)?;
187
188                last_match_end = mat.end();
189            }
190
191            // If last_match_end > safe_zone_end, it means we processed a match that crossed the boundary.
192            // In that case, we have already written the replacement, so we should NOT write the original text.
193            // And we should shift the buffer starting from last_match_end.
194
195            let shift_start = if last_match_end > safe_zone_end {
196                last_match_end
197            } else {
198                // Write remaining text in safe zone
199                output_file.write_all(&chunk_bytes[last_match_end..safe_zone_end])?;
200                safe_zone_end
201            };
202
203            // Shift remaining bytes to start
204            let remaining_bytes = &buffer[shift_start..buffer_len];
205            let remaining_len = remaining_bytes.len();
206
207            let remaining_vec = remaining_bytes.to_vec();
208            buffer[0..remaining_len].copy_from_slice(&remaining_vec);
209
210            // Fill the rest of the buffer
211            if !eof {
212                let bytes_to_read = BUFFER_SIZE - remaining_len;
213                let n =
214                    input_file.read(&mut buffer[remaining_len..remaining_len + bytes_to_read])?;
215                buffer_len = remaining_len + n;
216                if n == 0 {
217                    eof = true;
218                }
219            } else {
220                buffer_len = remaining_len; // We keep the remaining bytes if EOF (should be 0 if we processed everything)
221                if remaining_len == 0 {
222                    buffer_len = 0;
223                }
224            }
225
226            processed_offset += shift_start;
227            let _ = tx.send(ReplaceMessage::Progress(processed_offset, file_len));
228        }
229
230        output_file.flush()?;
231        Ok(())
232    }
233}
234
235fn is_utf8_char_boundary(b: u8) -> bool {
236    // In UTF-8, continuation bytes start with 10xxxxxx (0x80 to 0xBF)
237    // So a byte is a char boundary if it is NOT a continuation byte.
238    // i.e. it is < 0x80 or >= 0xC0.
239    (b as i8) >= -0x40
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use std::io::Write;
246    use std::sync::mpsc;
247    use tempfile::NamedTempFile;
248
249    #[test]
250    fn test_replace_all_simple() -> Result<()> {
251        let mut input = NamedTempFile::new()?;
252        write!(input, "Hello World, Hello Universe")?;
253        let input_path = input.path().to_path_buf();
254
255        let output = NamedTempFile::new()?;
256        let output_path = output.path().to_path_buf();
257
258        let (tx, rx) = mpsc::channel();
259        let cancel_token = Arc::new(AtomicBool::new(false));
260
261        Replacer::replace_all(
262            &input_path,
263            &output_path,
264            "Hello",
265            "Hi",
266            false,
267            tx,
268            cancel_token,
269        );
270
271        // Wait for done
272        loop {
273            match rx.recv() {
274                Ok(ReplaceMessage::Done) => break,
275                Ok(ReplaceMessage::Error(e)) => panic!("Error: {}", e),
276                Ok(ReplaceMessage::Progress(_, _)) => continue,
277                Err(_) => break,
278            }
279        }
280
281        let content = std::fs::read_to_string(&output_path)?;
282        assert_eq!(content, "Hi World, Hi Universe");
283        Ok(())
284    }
285
286    #[test]
287    fn test_replace_all_regex() -> Result<()> {
288        let mut input = NamedTempFile::new()?;
289        write!(input, "Item 1, Item 2, Item 3")?;
290        let input_path = input.path().to_path_buf();
291
292        let output = NamedTempFile::new()?;
293        let output_path = output.path().to_path_buf();
294
295        let (tx, rx) = mpsc::channel();
296        let cancel_token = Arc::new(AtomicBool::new(false));
297
298        Replacer::replace_all(
299            &input_path,
300            &output_path,
301            r"Item (\d)",
302            "Object $1",
303            true,
304            tx,
305            cancel_token,
306        );
307
308        loop {
309            match rx.recv() {
310                Ok(ReplaceMessage::Done) => break,
311                Ok(ReplaceMessage::Error(e)) => panic!("Error: {}", e),
312                Ok(ReplaceMessage::Progress(_, _)) => continue,
313                Err(_) => break,
314            }
315        }
316
317        let content = std::fs::read_to_string(&output_path)?;
318        assert_eq!(content, "Object 1, Object 2, Object 3");
319        Ok(())
320    }
321}