tale_ndjson/readers/
chunked.rs1use 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#[derive(Debug)]
23pub struct FileChunk {
24 pub data: Vec<u8>,
26 pub start_offset: u64,
28 pub end_offset: u64,
30 pub starts_at_line_boundary: bool,
32 pub ends_at_line_boundary: bool,
34}
35
36impl FileChunk {
37 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 pub fn size(&self) -> usize {
53 self.data.len()
54 }
55
56 pub fn is_empty(&self) -> bool {
58 self.data.is_empty()
59 }
60
61 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 pub fn find_last_line_boundary(&self) -> Option<usize> {
69 self.data.iter().rposition(|&b| b == b'\n')
70 }
71
72 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#[derive(Debug)]
87pub struct ChunkedFileReader {
88 file: File,
90 file_size: u64,
92 current_position: u64,
94 pending_data: Vec<u8>,
96 strategy: StaticStrategy,
98}
99
100impl ChunkedFileReader {
101 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 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 pub fn static_optimal<P: AsRef<Path>>(path: P) -> Result<Self, TaleError> {
128 Self::new(path)
129 }
130
131 pub fn with_optimal_config<P: AsRef<Path>>(path: P) -> Result<Self, TaleError> {
133 Self::new(path)
134 }
135
136 pub fn file_size(&self) -> u64 {
138 self.file_size
139 }
140
141 pub fn position(&self) -> u64 {
143 self.current_position
144 }
145
146 pub fn is_at_end(&self) -> bool {
148 self.current_position >= self.file_size
149 }
150
151 pub fn read_chunk(&mut self) -> Result<Option<FileChunk>, TaleError> {
153 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 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 0
167 } else {
168 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 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 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 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 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 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 if lines_skipped + lines_in_chunk == count {
243 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 lines_skipped += lines_in_chunk;
257
258 if !chunk.ends_at_line_boundary && lines_skipped < count {
262 if let Some(last_nl) = last_newline_pos {
263 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 self.pending_data = chunk.data;
273 }
274 }
275 } else {
276 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}