Skip to main content

tale_ndjson/readers/
chunked.rs

1//! Memory-efficient chunked file processing.
2//!
3//! `ChunkedFileReader` processes large files in manageable chunks while
4//! maintaining:
5//! - **Bounded memory usage**: Memory footprint independent of file size
6//! - **Line boundary handling**: Proper JSON line parsing across chunks
7//!
8//! ## Architecture
9//! - StaticStrategy determines chunk size based on file size
10//! - ChunkConfig holds immutable settings (overlap_size, low_memory_mode)
11//! - FileChunk manages data boundaries and line parsing
12
13use std::fs::File;
14use std::io::{Read, Seek, SeekFrom};
15use std::path::Path;
16
17use super::FileProcessor;
18use crate::errors::TaleError;
19use crate::readers::strategies::StaticStrategy;
20
21/// A chunk of file data with metadata about its position
22#[derive(Debug)]
23pub struct FileChunk {
24    /// The chunk data
25    pub data: Vec<u8>,
26    /// Starting position in the file
27    pub start_offset: u64,
28    /// End position in the file (exclusive)
29    pub end_offset: u64,
30    /// Whether this chunk starts at a line boundary
31    pub starts_at_line_boundary: bool,
32    /// Whether this chunk ends at a line boundary
33    pub ends_at_line_boundary: bool,
34}
35
36impl FileChunk {
37    /// Create a new FileChunk
38    pub fn new(data: Vec<u8>, start_offset: u64, end_offset: u64) -> Self {
39        let starts_at_line_boundary = start_offset == 0 || data.first() != Some(&b'\n');
40        let ends_at_line_boundary = data.last() == Some(&b'\n');
41
42        Self {
43            data,
44            start_offset,
45            end_offset,
46            starts_at_line_boundary,
47            ends_at_line_boundary,
48        }
49    }
50
51    /// Get the size of this chunk
52    pub fn size(&self) -> usize {
53        self.data.len()
54    }
55
56    /// Check if this chunk is empty
57    pub fn is_empty(&self) -> bool {
58        self.data.is_empty()
59    }
60
61    /// Get lines from this chunk, handling partial lines
62    pub fn lines(&self) -> impl Iterator<Item = &str> {
63        let data_str = std::str::from_utf8(&self.data).unwrap_or("");
64        data_str.lines()
65    }
66
67    /// Find the last complete line boundary in this chunk
68    pub fn find_last_line_boundary(&self) -> Option<usize> {
69        self.data.iter().rposition(|&b| b == b'\n')
70    }
71
72    /// Split this chunk at the last complete line boundary
73    pub fn split_at_last_line(&mut self) -> Option<Vec<u8>> {
74        if let Some(boundary) = self.find_last_line_boundary() {
75            let remainder = self.data.split_off(boundary + 1);
76            self.end_offset = self.start_offset + self.data.len() as u64;
77            self.ends_at_line_boundary = true;
78            Some(remainder)
79        } else {
80            None
81        }
82    }
83}
84
85/// Reader that processes files in chunks with line boundary handling
86#[derive(Debug)]
87pub struct ChunkedFileReader {
88    /// An open file pointer we're reading from.
89    file: File,
90    /// The size of the file we're reading.
91    file_size: u64,
92    /// Our current position in the file we're reading.
93    current_position: u64,
94    /// Data from previous chunk that didn't end at line boundary
95    pending_data: Vec<u8>,
96    /// Chunk sizing strategy
97    strategy: StaticStrategy,
98}
99
100impl ChunkedFileReader {
101    /// Create a new ChunkedFileReader
102    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, TaleError> {
103        let file_size = std::fs::metadata(&path)?.len();
104        let strategy = StaticStrategy::optimal_for_file(file_size);
105        let file = File::open(&path)?;
106
107        Ok(Self {
108            file,
109            file_size,
110            current_position: 0,
111            pending_data: Vec::new(),
112            strategy,
113        })
114    }
115
116    /// Create with explicit strategy (for testing)
117    pub fn with_strategy<P: AsRef<Path>>(path: P, strategy: StaticStrategy) -> Result<Self, TaleError> {
118        let mut reader = Self::new(path)?;
119        reader.strategy = strategy;
120        Ok(reader)
121    }
122
123    /// Pick the optimal chunk size and stick with it.
124    ///
125    /// Equivalent to `Self::new`; kept as an explicit name for callers (mainly
126    /// benches) that want to make the static-sizing intent obvious.
127    pub fn static_optimal<P: AsRef<Path>>(path: P) -> Result<Self, TaleError> {
128        Self::new(path)
129    }
130
131    /// Create a ChunkedFileReader with optimal configuration for the file
132    pub fn with_optimal_config<P: AsRef<Path>>(path: P) -> Result<Self, TaleError> {
133        Self::new(path)
134    }
135
136    /// Get the file size
137    pub fn file_size(&self) -> u64 {
138        self.file_size
139    }
140
141    /// Get current position in file
142    pub fn position(&self) -> u64 {
143        self.current_position
144    }
145
146    /// Check if we've reached the end of file
147    pub fn is_at_end(&self) -> bool {
148        self.current_position >= self.file_size
149    }
150
151    /// Read the next chunk from the file
152    pub fn read_chunk(&mut self) -> Result<Option<FileChunk>, TaleError> {
153        // If we have pending data, we need to process it even if we're at EOF
154        if self.is_at_end() && self.pending_data.is_empty() {
155            return Ok(None);
156        }
157
158        let chunk_size = self.strategy.initial_chunk_size();
159
160        // Track how much pending data we have at the start
161        let pending_len = self.pending_data.len();
162
163        let mut buffer = vec![0u8; chunk_size];
164        let bytes_read = if self.is_at_end() {
165            // At EOF, just process any pending data
166            0
167        } else {
168            // Read new data from file
169            self.file.read(&mut buffer).map_err(TaleError::from)?
170        };
171
172        if bytes_read == 0 && self.pending_data.is_empty() {
173            return Ok(None);
174        }
175
176        buffer.truncate(bytes_read);
177
178        // Combine with any pending data from previous chunk
179        if !self.pending_data.is_empty() {
180            let mut combined = std::mem::take(&mut self.pending_data);
181            combined.extend_from_slice(&buffer);
182            buffer = combined;
183        }
184
185        let start_offset = self.current_position - pending_len as u64;
186        self.current_position += bytes_read as u64;
187
188        let mut chunk = FileChunk::new(buffer, start_offset, self.current_position);
189
190        // Handle line boundaries: if chunk doesn't end at a line boundary,
191        // save the partial line for the next chunk
192        if !chunk.ends_at_line_boundary
193            && !self.is_at_end()
194            && let Some(remainder) = chunk.split_at_last_line()
195        {
196            self.pending_data = remainder;
197        }
198
199        Ok(Some(chunk))
200    }
201
202    /// Seek to a specific position in the file
203    pub fn seek(&mut self, pos: SeekFrom) -> Result<u64, TaleError> {
204        let new_pos = self.file.seek(pos).map_err(TaleError::from)?;
205
206        self.current_position = new_pos;
207        // we've moved and no longer care what we read earlier
208        self.pending_data.clear();
209
210        Ok(new_pos)
211    }
212}
213
214impl FileProcessor for ChunkedFileReader {
215    fn process_lines<F>(&mut self, mut line_processor: F) -> Result<(), TaleError>
216    where
217        F: FnMut(&str) -> Result<(), TaleError>,
218    {
219        while let Some(chunk) = self.read_chunk()? {
220            for line in chunk.lines() {
221                line_processor(line)?;
222            }
223        }
224        Ok(())
225    }
226
227    fn skip_lines(&mut self, count: u64) -> Result<(), TaleError> {
228        let mut lines_skipped = 0u64;
229
230        while lines_skipped < count {
231            if let Some(chunk) = self.read_chunk()? {
232                // Count lines in this chunk and track position
233                let mut lines_in_chunk = 0u64;
234                let mut last_newline_pos = None;
235
236                for (i, &byte) in chunk.data.iter().enumerate() {
237                    if byte == b'\n' {
238                        lines_in_chunk += 1;
239                        last_newline_pos = Some(i);
240
241                        // Check if we've skipped enough lines
242                        if lines_skipped + lines_in_chunk == count {
243                            // We need to keep the rest of this chunk for
244                            // processing
245                            // Save the unprocessed portion as pending data
246                            let position_after_newline = i + 1;
247                            if position_after_newline < chunk.data.len() {
248                                self.pending_data = chunk.data[position_after_newline..].to_vec();
249                            }
250                            return Ok(());
251                        }
252                    }
253                }
254
255                // Entire chunk was consumed
256                lines_skipped += lines_in_chunk;
257
258                // If this chunk didn't end with a newline and we haven't
259                // skipped enough lines yet, we need to keep any
260                // partial line for the next iteration
261                if !chunk.ends_at_line_boundary && lines_skipped < count {
262                    if let Some(last_nl) = last_newline_pos {
263                        // Keep everything after the last newline as pending
264                        // data
265                        let after_last_newline = last_nl + 1;
266                        if after_last_newline < chunk.data.len() {
267                            self.pending_data = chunk.data[after_last_newline..].to_vec();
268                        }
269                    } else {
270                        // No newlines in this chunk, keep the entire chunk as
271                        // pending
272                        self.pending_data = chunk.data;
273                    }
274                }
275            } else {
276                // EOF reached before skipping all requested lines
277                break;
278            }
279        }
280
281        Ok(())
282    }
283
284    fn file_size(&self) -> u64 {
285        self.file_size
286    }
287
288    fn seek(&mut self, pos: SeekFrom) -> Result<u64, TaleError> {
289        self.seek(pos)
290    }
291
292    fn position(&self) -> u64 {
293        self.current_position
294    }
295}