Skip to main content

readcon_core/
iterators.rs

1//=============================================================================
2// The Public API - A clean iterator for users of our library
3//=============================================================================
4
5use crate::parser::{LineStream, parse_declared_sections};
6use crate::{error, types};
7use std::path::Path;
8
9/// memchr-backed line cursor for the full parse path (not only frame skip).
10///
11/// Profile note: `str::Lines` + `Peekable` showed up under
12/// `ConFrameIterator::next` on multi-atom multi-frame workloads. One cursor
13/// serves `next` / `peek` / `forward_fast` so skip and full parse share the
14/// same O(1) newline scan rather than two desynchronized views of the buffer.
15pub struct MemchrLines<'a> {
16    bytes: &'a [u8],
17    pos: usize,
18    peeked: Option<&'a str>,
19    /// When the buffer was not already a `&str`, header lines are checked
20    /// as they are tokenized. Coordinate rows stay on the byte parser.
21    check_utf8: bool,
22    utf8_bad: bool,
23    /// Absolute offsets of every `\n`. Set only for a frame-start scan.
24    /// `None` keeps the per-line `memchr` path used by a full parse.
25    newlines: Option<Vec<usize>>,
26    /// Index of the line that starts at `pos` when `newlines` is in use.
27    index_line: usize,
28    /// 1-based index of the last line produced by [`Self::read_one`], including
29    /// a line rejected as UTF-8. 0 before that.
30    line_no: u32,
31    /// Whether hitting end-of-file has already incremented `line_no` to the
32    /// first missing line (`total_lines + 1`).
33    eof_counted: bool,
34}
35
36impl<'a> MemchrLines<'a> {
37    pub fn new(text: &'a str) -> Self {
38        Self::from_parts(text.as_bytes(), false)
39    }
40
41    /// Cursor over bytes that are not yet known to be UTF-8.
42    ///
43    /// ASCII coordinate rows are accepted by the numeric scan. Text lines
44    /// are validated when they are materialized, so there is no separate
45    /// whole-buffer UTF-8 pass.
46    pub fn from_bytes(bytes: &'a [u8]) -> Self {
47        Self::from_parts(bytes, true)
48    }
49
50    fn from_parts(bytes: &'a [u8], check_utf8: bool) -> Self {
51        Self {
52            bytes,
53            pos: 0,
54            peeked: None,
55            check_utf8,
56            utf8_bad: false,
57            newlines: None,
58            index_line: 0,
59            line_no: 0,
60            eof_counted: false,
61        }
62    }
63
64    /// 1-based index of the last line read, including a line that is only peeked.
65    #[inline]
66    pub fn line_no(&self) -> u32 {
67        self.line_no
68    }
69
70    #[inline]
71    fn read_one(&mut self) -> Option<&'a str> {
72        if self.newlines.is_some() {
73            return self.read_one_indexed();
74        }
75        if self.utf8_bad {
76            return None;
77        }
78        if self.pos >= self.bytes.len() {
79            if !self.eof_counted {
80                self.eof_counted = true;
81                self.line_no = self.line_no.saturating_add(1);
82            }
83            return None;
84        }
85        let rest = &self.bytes[self.pos..];
86        let (line_bytes, advance) = match memchr::memchr(b'\n', rest) {
87            Some(i) => (&rest[..i], i + 1),
88            None => (rest, rest.len()),
89        };
90        let trimmed = if line_bytes.last() == Some(&b'\r') {
91            &line_bytes[..line_bytes.len() - 1]
92        } else {
93            line_bytes
94        };
95        if self.check_utf8 {
96            match std::str::from_utf8(trimmed) {
97                Ok(s) => {
98                    self.accept_line(advance);
99                    Some(s)
100                }
101                Err(_) => {
102                    // Stay on the rejected line. Moving past it makes a
103                    // whitespace tail look like a clean end of file.
104                    // The line number still names this line.
105                    self.line_no = self.line_no.saturating_add(1);
106                    self.utf8_bad = true;
107                    None
108                }
109            }
110        } else {
111            self.accept_line(advance);
112            // SAFETY: source was `&str`; line is a UTF-8 prefix cut on ASCII `\n`/`\r`.
113            Some(unsafe { std::str::from_utf8_unchecked(trimmed) })
114        }
115    }
116
117    #[inline]
118    fn accept_line(&mut self, advance: usize) {
119        self.pos += advance;
120        self.line_no = self.line_no.saturating_add(1);
121    }
122
123    #[inline]
124    pub fn next_line(&mut self) -> Option<&'a str> {
125        if let Some(p) = self.peeked.take() {
126            return Some(p);
127        }
128        self.read_one()
129    }
130
131    #[inline]
132    pub fn peek_line(&mut self) -> Option<&'a str> {
133        if self.peeked.is_none() {
134            self.peeked = self.read_one();
135        }
136        self.peeked
137    }
138
139    /// Bytes from the start of the next line, a peeked one included, to the
140    /// end of the buffer.
141    pub(crate) fn unread_len(&self) -> usize {
142        let start = match self.peeked {
143            Some(p) => p.as_ptr() as usize - self.bytes.as_ptr() as usize,
144            None => self.pos,
145        };
146        self.bytes.len() - start
147    }
148
149    /// Drop any peek buffer (required before bulk cursor advances).
150    fn clear_peek(&mut self) {
151        if let Some(p) = self.peeked.take() {
152            // Rewind pos to the start of the peeked line.
153            let start = p.as_ptr() as usize - self.bytes.as_ptr() as usize;
154            self.pos = start;
155            // A peek already counted this line. Rewinding must drop that
156            // count so the next read names it once, and must put the
157            // newline index back on the line `pos` now starts.
158            self.line_no = self.line_no.saturating_sub(1);
159            if let Some(nl) = self.newlines.as_deref() {
160                self.index_line = line_no_for_pos(nl, self.bytes.len(), start);
161            }
162        }
163    }
164
165    /// One line from the precomputed newline index.
166    ///
167    /// The cursor must sit on a line start (or at the end). The bytes of
168    /// the line are the same slice `memchr` would return, including a line
169    /// whose body crosses a chunk boundary: only the `\n` is indexed.
170    fn read_one_indexed(&mut self) -> Option<&'a str> {
171        if self.utf8_bad {
172            return None;
173        }
174        if self.pos >= self.bytes.len() {
175            if !self.eof_counted {
176                self.eof_counted = true;
177                self.line_no = self.line_no.saturating_add(1);
178            }
179            return None;
180        }
181        let len = self.bytes.len();
182        let line_no = {
183            let nl = self.newlines.as_deref().unwrap();
184            if self.pos == line_start_pos(nl, len, self.index_line) {
185                self.index_line
186            } else {
187                line_no_for_pos(nl, len, self.pos)
188            }
189        };
190        let span = indexed_span(self.newlines.as_deref().unwrap(), self.bytes, line_no)?;
191        let trimmed = &self.bytes[span.start..span.content_end];
192        if self.check_utf8 {
193            match std::str::from_utf8(trimmed) {
194                Ok(s) => {
195                    self.pos = span.next_pos;
196                    self.index_line = line_no + 1;
197                    self.line_no = self.index_line as u32;
198                    Some(s)
199                }
200                Err(_) => {
201                    self.utf8_bad = true;
202                    self.index_line = line_no;
203                    // The rejected line is 1-based `line_no + 1`. The index
204                    // stays on that line so a later read does not skip it.
205                    self.line_no = (line_no as u32).saturating_add(1);
206                    None
207                }
208            }
209        } else {
210            self.pos = span.next_pos;
211            self.index_line = line_no + 1;
212            self.line_no = self.index_line as u32;
213            // SAFETY: source was `&str`; the span is a UTF-8 line cut on ASCII `\n`/`\r`.
214            Some(unsafe { std::str::from_utf8_unchecked(trimmed) })
215        }
216    }
217
218    fn utf8_error(&self) -> Option<error::ParseError> {
219        self.utf8_bad.then(invalid_utf8)
220    }
221
222    /// Keep `err` unless this cursor already rejected a line as UTF-8.
223    fn prefer_utf8(&self, err: error::ParseError) -> error::ParseError {
224        if self.utf8_bad { invalid_utf8() } else { err }
225    }
226}
227
228fn invalid_utf8() -> error::ParseError {
229    error::ParseError::ValidationError("invalid UTF-8".into())
230}
231
232impl<'a> Iterator for MemchrLines<'a> {
233    type Item = &'a str;
234    fn next(&mut self) -> Option<&'a str> {
235        self.next_line()
236    }
237}
238
239impl<'a> LineStream<'a> for MemchrLines<'a> {
240    #[inline]
241    fn next_line(&mut self) -> Option<&'a str> {
242        MemchrLines::next_line(self)
243    }
244    #[inline]
245    fn peek_line(&mut self) -> Option<&'a str> {
246        MemchrLines::peek_line(self)
247    }
248    #[inline]
249    fn next_coord_row(
250        &mut self,
251        spec_version: u32,
252        default_id: u64,
253    ) -> Result<([f64; 3], [bool; 3], u64), crate::error::ParseError> {
254        if let Some(p) = self.peeked.take() {
255            return crate::parser::parse_coord_row_at(p.as_bytes(), 0, spec_version, default_id)
256                .map(|(row, _)| row);
257        }
258        // The failing row is this line even when the numeric scan returns Err
259        // before the cursor moves.
260        if !self.eof_counted {
261            self.line_no = self.line_no.saturating_add(1);
262            if self.pos >= self.bytes.len() {
263                self.eof_counted = true;
264            }
265        }
266        let (row, pos) =
267            crate::parser::parse_coord_row_at(self.bytes, self.pos, spec_version, default_id)?;
268        self.pos = pos;
269        Ok(row)
270    }
271    fn try_take_coord_block(
272        &mut self,
273        n: usize,
274        spec_version: u32,
275        start_id: u64,
276        symbol: &std::sync::Arc<str>,
277        workers: usize,
278    ) -> Option<crate::parser::CoordRows> {
279        if self.peeked.is_some() || self.utf8_bad {
280            return None;
281        }
282        #[cfg(feature = "parallel")]
283        {
284            let rest = &self.bytes[self.pos..];
285            let block = crate::parser::parallel_coord_rows(
286                rest,
287                n,
288                spec_version,
289                start_id,
290                workers,
291                Some(symbol),
292            )
293            .ok()?;
294            self.pos += block.consumed;
295            self.line_no = self.line_no.saturating_add(n as u32);
296            if self.newlines.is_some() {
297                self.index_line = self.index_line.saturating_add(n);
298            }
299            Some(block)
300        }
301        #[cfg(not(feature = "parallel"))]
302        {
303            let _ = (n, spec_version, start_id, symbol, workers);
304            None
305        }
306    }
307    #[inline]
308    fn next_vector_row(
309        &mut self,
310        spec_version: u32,
311    ) -> Result<([f64; 3], [bool; 3], u64), crate::error::ParseError> {
312        if let Some(p) = self.peeked.take() {
313            return crate::parser::parse_vector_row_at(p.as_bytes(), 0, spec_version)
314                .map(|(row, _)| row);
315        }
316        // The failing row is this line even when the numeric scan returns
317        // Err before the cursor moves. Count the first missing EOF line once.
318        if !self.eof_counted {
319            self.line_no = self.line_no.saturating_add(1);
320            if self.pos >= self.bytes.len() {
321                self.eof_counted = true;
322            }
323        }
324        let (row, pos) = crate::parser::parse_vector_row_at(self.bytes, self.pos, spec_version)?;
325        self.pos = pos;
326        Ok(row)
327    }
328    fn remainder_is_whitespace(&mut self) -> bool {
329        if self.utf8_bad {
330            return false;
331        }
332        if let Some(line) = self.peek_line()
333            && !line.trim().is_empty()
334        {
335            return false;
336        }
337        // `peek_line` may have rejected a line. That is a decode error,
338        // including when every byte after it is ASCII whitespace.
339        if self.utf8_bad {
340            return false;
341        }
342        self.bytes[self.pos..]
343            .iter()
344            .all(|b| b.is_ascii_whitespace())
345    }
346    fn blank_line_opens_section(&mut self) -> bool {
347        // `peek_line` has already moved `pos` to the line after the peek.
348        let Some(peeked) = self.peeked else {
349            return false;
350        };
351        if !peeked.trim().is_empty() {
352            return false;
353        }
354        match probe_section(&self.bytes[self.pos..]) {
355            SectionProbe::Opens => true,
356            SectionProbe::Closed => false,
357            // Leave the rejected bytes on the cursor. `prefer_utf8` then
358            // reports the decode error instead of a missing section.
359            SectionProbe::InvalidUtf8 => {
360                self.utf8_bad = true;
361                false
362            }
363        }
364    }
365
366    fn blank_opens_velocity_block(&mut self) -> bool {
367        match self.peek_line() {
368            Some(line) if line.trim().is_empty() => self.blank_line_opens_section(),
369            _ => true,
370        }
371    }
372}
373
374fn split_raw_line(bytes: &[u8]) -> Option<(&[u8], &[u8])> {
375    if bytes.is_empty() {
376        return None;
377    }
378    match memchr::memchr(b'\n', bytes) {
379        Some(i) => Some((&bytes[..i], &bytes[i + 1..])),
380        None => Some((bytes, &[])),
381    }
382}
383
384fn strip_cr(line: &[u8]) -> &[u8] {
385    if line.last() == Some(&b'\r') {
386        &line[..line.len() - 1]
387    } else {
388        line
389    }
390}
391
392enum SectionProbe {
393    Opens,
394    Closed,
395    InvalidUtf8,
396}
397
398/// A blank line opens a section when the next line is a symbol and the
399/// line after that is a component label (CON-file.5, CON-header.4).
400fn probe_section(after_blank: &[u8]) -> SectionProbe {
401    let Some((raw1, after1)) = split_raw_line(after_blank) else {
402        return SectionProbe::Closed;
403    };
404    let line1 = strip_cr(raw1);
405    if line1.iter().all(|b| matches!(b, b' ' | b'\t')) {
406        return SectionProbe::Closed;
407    }
408    let Ok(text1) = std::str::from_utf8(line1) else {
409        return SectionProbe::InvalidUtf8;
410    };
411    if text1.trim_start().starts_with('{') {
412        return SectionProbe::Closed;
413    }
414    let Some((raw2, _)) = split_raw_line(after1) else {
415        return SectionProbe::Closed;
416    };
417    let Ok(text2) = std::str::from_utf8(strip_cr(raw2)) else {
418        return SectionProbe::InvalidUtf8;
419    };
420    if crate::parser::line_has_component_label(text2) {
421        SectionProbe::Opens
422    } else {
423        SectionProbe::Closed
424    }
425}
426
427fn blank_opens_section(after_blank: &[u8]) -> bool {
428    matches!(probe_section(after_blank), SectionProbe::Opens)
429}
430
431/// How many declared sections follow the coordinates. `Legacy` is a missing
432/// `sections` key. An empty array is `Declared(0)`: no legacy velocity block.
433enum SectionPlan {
434    Legacy,
435    Declared(usize),
436}
437
438fn section_plan(line: &str) -> Result<SectionPlan, error::ParseError> {
439    let trimmed = line.trim_matches(|c: char| c == ' ' || c == '\t');
440    if !trimmed.starts_with('{') {
441        return Ok(SectionPlan::Legacy);
442    }
443    let value: serde_json::Value = crate::parser::parse_metadata_value(trimmed)?;
444    let Some(obj) = value.as_object() else {
445        return Err(error::ParseError::InvalidMetadataJson(
446            "expected a JSON object".into(),
447        ));
448    };
449    match obj.get("sections") {
450        None => Ok(SectionPlan::Legacy),
451        Some(serde_json::Value::Array(items)) => Ok(SectionPlan::Declared(items.len())),
452        Some(_) => Err(error::ParseError::InvalidMetadataJson(
453            "sections must be an array of strings".into(),
454        )),
455    }
456}
457
458/// True when [`ConFrameIterator`] yields nothing from byte `pos` of `bytes`
459/// on, because only whitespace is left (CON-frame.1). Frame scans stop
460/// here, so they find the frames that the iterator yields.
461pub(crate) fn no_frame_at(bytes: &[u8], pos: usize) -> bool {
462    match bytes.get(pos) {
463        None => true,
464        // A line that opens with a printable ASCII byte is not blank.
465        Some(b) if b.is_ascii_graphic() => false,
466        Some(_) => MemchrLines::from_bytes(&bytes[pos..]).remainder_is_whitespace(),
467    }
468}
469
470/// The blank test of the full parse: `line` is UTF-8 and [`str::trim`]
471/// leaves nothing of it. A line that opens with a printable ASCII byte is
472/// not blank, so that byte settles it without a decode.
473fn is_blank_line(line: &[u8]) -> bool {
474    match line.first() {
475        Some(b) if b.is_ascii_graphic() => false,
476        _ => std::str::from_utf8(line).is_ok_and(|s| s.trim().is_empty()),
477    }
478}
479
480/// An iterator that lazily parses simulation frames from a `.con` or `.convel`
481/// file's contents.
482///
483/// This struct wraps a memchr line cursor over the file buffer and, upon each
484/// iteration, attempts to parse a complete `ConFrame`. A blank line after the
485/// coordinates is a velocity section only when it begins a complete velocity
486/// block. Otherwise that line is line 1 of the next frame, and it may be empty.
487///
488/// The iterator yields items of type `Result<ConFrame, ParseError>`, allowing for
489/// robust error handling for each frame.
490pub struct ConFrameIterator<'a> {
491    pub(crate) lines: MemchrLines<'a>,
492    /// 0-based index of the frame the cursor is about to read.
493    /// Successful `next` and `forward_fast` advance it. A failure leaves
494    /// it on the frame that failed.
495    frame_index: u64,
496    /// Lines already consumed when this frame started. Line 2 of the frame
497    /// is `frame_origin + 2`, which is where metadata errors are reported.
498    frame_origin: u32,
499    /// Cross-frame id set when `ids_persistent` is in use (CON-id.11).
500    persistent_ids: Option<crate::types::PersistentIds>,
501}
502
503/// Newlines seen and the byte index just past the `n`-th `\n`.
504///
505/// When fewer than `n` newlines exist, the count is how many were seen
506/// and the index is `hay.len()`.
507///
508/// # Safety
509/// The CPU supports AVX2.
510#[cfg(target_arch = "x86_64")]
511#[target_feature(enable = "avx2,popcnt")]
512#[inline]
513unsafe fn skip_newlines_avx2(hay: &[u8], n: usize) -> (usize, usize) {
514    use std::arch::x86_64::{
515        __m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, _mm256_set1_epi8,
516        _popcnt32,
517    };
518    if n == 0 {
519        return (0, 0);
520    }
521    let mut need = n;
522    let mut offset = 0usize;
523    let ptr = hay.as_ptr();
524    let len = hay.len();
525    let nl = _mm256_set1_epi8(b'\n' as i8);
526    while offset + 32 <= len {
527        // SAFETY: `offset + 32 <= len`, so the 32-byte load stays inside `hay`.
528        let chunk = unsafe { _mm256_loadu_si256(ptr.add(offset) as *const __m256i) };
529        let eq = _mm256_cmpeq_epi8(chunk, nl);
530        let mask = _mm256_movemask_epi8(eq) as u32;
531        let count = _popcnt32(mask as i32) as usize;
532        if count >= need {
533            let mut bits = mask;
534            for _ in 1..need {
535                bits &= bits - 1;
536            }
537            let bit = bits.trailing_zeros() as usize;
538            return (n, offset + bit + 1);
539        }
540        need -= count;
541        offset += 32;
542    }
543    while offset < len {
544        if hay[offset] == b'\n' {
545            need -= 1;
546            if need == 0 {
547                return (n, offset + 1);
548            }
549        }
550        offset += 1;
551    }
552    (n - need, len)
553}
554
555impl<'a> ConFrameIterator<'a> {
556    /// Creates a new `ConFrameIterator` from a string slice of the entire file.
557    ///
558    /// # Arguments
559    ///
560    /// * `file_contents` - A string slice containing the text of one or more `.con` frames.
561    pub fn new(file_contents: &'a str) -> Self {
562        ConFrameIterator {
563            lines: MemchrLines::new(file_contents),
564            frame_index: 0,
565            frame_origin: 0,
566            persistent_ids: None,
567        }
568    }
569
570    /// Like [`Self::new`], but reading from byte `pos` of `file_contents`.
571    ///
572    /// `pos` must be 0 or follow a `\n`. The iterator keeps no state from
573    /// earlier frames, so skipping from `pos` sees what a scan sees there.
574    pub(crate) fn starting_at(file_contents: &'a str, pos: usize) -> Self {
575        debug_assert!(pos == 0 || file_contents.as_bytes()[pos - 1] == b'\n');
576        let mut it = Self::new(file_contents);
577        it.lines.pos = pos;
578        it
579    }
580
581    /// Like [`Self::new`] for a buffer that has not been UTF-8 validated.
582    ///
583    /// Text lines are checked as they are tokenized. Numeric rows reject a
584    /// non-ASCII byte during the fused parse, which is the UTF-8 check for
585    /// those lines.
586    pub fn from_bytes(bytes: &'a [u8]) -> Self {
587        ConFrameIterator {
588            lines: MemchrLines::from_bytes(bytes),
589            frame_index: 0,
590            frame_origin: 0,
591            persistent_ids: None,
592        }
593    }
594
595    /// 0-based index of the frame the cursor is on.
596    ///
597    /// This is the frame a following error belongs to. It is not the
598    /// number of frames still ahead.
599    pub(crate) fn frame_index(&self) -> u64 {
600        self.frame_index
601    }
602
603    /// File line of `error` on this cursor.
604    ///
605    /// An unknown section name and a missing `units.time` on a declared
606    /// velocities section are metadata, so they are line 2 of the frame
607    /// (CON-error.2). A header that runs out of lines names the missing
608    /// line. Every other error names the line the cursor is on.
609    pub fn error_line(&self, error: &error::ParseError) -> u32 {
610        use error::ParseError;
611        if matches!(error, ParseError::UnknownSection(_))
612            || matches!(error, ParseError::InvalidUnits(msg)
613                if msg.contains("units.time") && crate::parser::declared_velocities())
614        {
615            return self.frame_origin.saturating_add(2).max(1);
616        }
617        // A read that already counted the missing line at EOF keeps that
618        // number. A header that stopped on the last stored line names the
619        // next one.
620        if matches!(error, ParseError::IncompleteHeader)
621            && self.lines.peeked.is_none()
622            && self.lines.pos >= self.lines.bytes.len()
623            && !self.lines.eof_counted
624        {
625            return self.lines.line_no().saturating_add(1).max(1);
626        }
627        let line = self.lines.line_no();
628        if line == 0 { 1 } else { line }
629    }
630
631    fn note_skipped_frame(&mut self) -> Option<Result<(), error::ParseError>> {
632        self.frame_index = self.frame_index.saturating_add(1);
633        Some(Ok(()))
634    }
635
636    /// Bulk-skips `n` lines from the shared memchr cursor.
637    ///
638    /// A final line with no trailing newline still counts when it is the
639    /// last line this call needs and its bytes are present. The full
640    /// parser accepts that line. Further lines after it are missing.
641    ///
642    /// The header has already named the line count, so the skip counts
643    /// newlines instead of parsing the rows. On AVX2 that count is one
644    /// pass over the span.
645    #[inline(always)]
646    fn advance_lines(&mut self, n: usize) -> Result<(), error::ParseError> {
647        self.lines.clear_peek();
648        if self.lines.newlines.is_some() {
649            return self.advance_lines_indexed(n);
650        }
651        #[cfg(target_arch = "x86_64")]
652        {
653            if n > 1 && std::is_x86_feature_detected!("avx2") {
654                return self.advance_lines_avx2(n);
655            }
656        }
657        self.advance_lines_memchr(n)
658    }
659
660    fn advance_lines_memchr(&mut self, n: usize) -> Result<(), error::ParseError> {
661        for i in 0..n {
662            let rest = &self.lines.bytes[self.lines.pos..];
663            match memchr::memchr(b'\n', rest) {
664                Some(pos) => {
665                    self.lines.pos += pos + 1;
666                    self.lines.line_no = self.lines.line_no.saturating_add(1);
667                }
668                None => {
669                    if rest.is_empty() {
670                        if !self.lines.eof_counted {
671                            self.lines.eof_counted = true;
672                            self.lines.line_no = self.lines.line_no.saturating_add(1);
673                        }
674                        return Err(error::ParseError::IncompleteFrame);
675                    }
676                    self.lines.pos = self.lines.bytes.len();
677                    // Count the unterminated line so a later located error
678                    // names it. It satisfies this skip only when it is the
679                    // last line still required; the full parser accepts it.
680                    self.lines.line_no = self.lines.line_no.saturating_add(1);
681                    if i + 1 == n {
682                        return Ok(());
683                    }
684                    return Err(error::ParseError::IncompleteFrame);
685                }
686            }
687        }
688        Ok(())
689    }
690
691    /// [`Self::advance_lines_memchr`] counting newlines in AVX2 chunks.
692    ///
693    /// The landed position and the incomplete-frame condition match the
694    /// per-line search. `n > 1` is the caller's guard: a one-line skip
695    /// is already a single `memchr`.
696    #[cfg(target_arch = "x86_64")]
697    #[inline]
698    fn advance_lines_avx2(&mut self, n: usize) -> Result<(), error::ParseError> {
699        let rest = &self.lines.bytes[self.lines.pos..];
700        let (found, end) = unsafe { skip_newlines_avx2(rest, n) };
701        if found == n {
702            self.lines.pos += end;
703            // The per-line walk counts each skipped line. The vectorized
704            // jump has to keep the same 1-based file line.
705            self.lines.line_no = self
706                .lines
707                .line_no
708                .saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
709            return Ok(());
710        }
711        if rest.is_empty() {
712            if !self.lines.eof_counted {
713                self.lines.eof_counted = true;
714                self.lines.line_no = self.lines.line_no.saturating_add(1);
715            }
716            return Err(error::ParseError::IncompleteFrame);
717        }
718        let has_tail = rest.last().copied() != Some(b'\n');
719        self.lines.pos = self.lines.bytes.len();
720        let counted = found + usize::from(has_tail);
721        self.lines.line_no = self
722            .lines
723            .line_no
724            .saturating_add(u32::try_from(counted).unwrap_or(u32::MAX));
725        if counted >= n {
726            Ok(())
727        } else {
728            if !self.lines.eof_counted {
729                self.lines.eof_counted = true;
730                self.lines.line_no = self.lines.line_no.saturating_add(1);
731            }
732            Err(error::ParseError::IncompleteFrame)
733        }
734    }
735
736    /// [`Self::advance_lines`] for `n` lines expected to end at `end`.
737    ///
738    /// When `end` follows a `\n` and exactly `n` newlines lie before it,
739    /// the per-line search would stop at `end` too, so one vectorized
740    /// count replaces it. Any other case takes the per-line search.
741    fn advance_lines_to(&mut self, n: usize, end: Option<usize>) -> Result<(), error::ParseError> {
742        // The newline index jumps by line count. `end` does not change
743        // where that jump lands; it only shortcuts the per-line search.
744        if self.lines.newlines.is_some() {
745            return self.advance_lines(n);
746        }
747        self.lines.clear_peek();
748        let pos = self.lines.pos;
749        let bytes = self.lines.bytes;
750        if let Some(end) = end
751            && pos < end
752            && end <= bytes.len()
753            && bytes[end - 1] == b'\n'
754            && memchr::memchr_iter(b'\n', &bytes[pos..end]).count() == n
755        {
756            self.lines.pos = end;
757            // The per-line walk would count each of these lines. The
758            // vectorized jump has to keep the same 1-based line.
759            self.lines.line_no = self
760                .lines
761                .line_no
762                .saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
763            return Ok(());
764        }
765        self.advance_lines(n)
766    }
767
768    /// [`Self::advance_lines`] using the stitched newline index.
769    ///
770    /// A missing line and a final line with no `\n` land on the same byte
771    /// as the `memchr` loop. The index is not consulted for a full parse.
772    fn advance_lines_indexed(&mut self, n: usize) -> Result<(), error::ParseError> {
773        let len = self.lines.bytes.len();
774        let step = {
775            let nl = self.lines.newlines.as_deref().unwrap();
776            let nlines = line_count(nl, len);
777            let line_no = if self.lines.pos == line_start_pos(nl, len, self.lines.index_line) {
778                self.lines.index_line
779            } else {
780                line_no_for_pos(nl, len, self.lines.pos)
781            };
782            if n == 0 {
783                IndexStep::Stay(line_no)
784            } else if line_no >= nlines {
785                IndexStep::Missing(line_no)
786            } else {
787                match line_no.checked_add(n) {
788                    Some(target) if target <= nlines => {
789                        let pos = if target == nlines {
790                            len
791                        } else {
792                            line_start_pos(nl, len, target)
793                        };
794                        IndexStep::Landed(target, pos)
795                    }
796                    _ => IndexStep::Short(nlines, len),
797                }
798            }
799        };
800        match step {
801            IndexStep::Stay(line_no) => {
802                self.lines.index_line = line_no;
803                self.lines.line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
804                Ok(())
805            }
806            IndexStep::Missing(line_no) => {
807                self.lines.index_line = line_no;
808                self.lines.eof_counted = true;
809                self.lines.line_no = u32::try_from(line_no.saturating_add(1)).unwrap_or(u32::MAX);
810                Err(error::ParseError::IncompleteFrame)
811            }
812            IndexStep::Landed(line_no, pos) => {
813                self.lines.index_line = line_no;
814                self.lines.line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
815                self.lines.pos = pos;
816                Ok(())
817            }
818            IndexStep::Short(line_no, pos) => {
819                self.lines.index_line = line_no;
820                self.lines.eof_counted = true;
821                self.lines.line_no = u32::try_from(line_no.saturating_add(1)).unwrap_or(u32::MAX);
822                self.lines.pos = pos;
823                Err(error::ParseError::IncompleteFrame)
824            }
825        }
826    }
827
828    /// One line from the shared cursor (same as full-parse path).
829    fn read_line_str(&mut self) -> Option<&'a str> {
830        self.lines.clear_peek();
831        self.lines.next_line()
832    }
833
834    /// A blank line, then only whitespace, is not a section (CON-frame.5).
835    fn at_blank_separator(&self) -> Option<bool> {
836        let rest = &self.lines.bytes[self.lines.pos..];
837        if rest.is_empty() {
838            return None;
839        }
840        let (line, after) = split_raw_line(rest)?;
841        if !is_blank_line(line) {
842            return Some(false);
843        }
844        if after.iter().all(|b| b.is_ascii_whitespace()) {
845            return None;
846        }
847        Some(true)
848    }
849
850    fn section_line<'b>(&'b mut self, name: &str) -> Result<&'b str, error::ParseError> {
851        match self.read_line_str() {
852            Some(line) => Ok(line),
853            None => Err(self
854                .lines
855                .prefer_utf8(error::ParseError::IncompleteSection(name.to_string()))),
856        }
857    }
858
859    /// Consume one section block the full parser would consume.
860    ///
861    /// `exact` selects [`crate::parser::labels_equal`] against
862    /// `{name} of Component N`. Otherwise the label is a prefix, which is
863    /// what the reserved-section parsers check.
864    fn consume_section_block(
865        &mut self,
866        header: &types::FrameHeader,
867        name: &str,
868        prefix: &str,
869        exact: bool,
870        end: Option<usize>,
871    ) -> Result<(), error::ParseError> {
872        let missing = || error::ParseError::IncompleteSection(name.to_string());
873        let blank = self.section_line(name)?;
874        if !blank.trim().is_empty() {
875            return Err(missing());
876        }
877        for (type_idx, &rows) in header.natms_per_type.iter().enumerate() {
878            let _symbol = self.section_line(name)?;
879            let label = self.section_line(name)?;
880            let ok = if exact {
881                let expected = format!("{name} of Component {}", type_idx + 1);
882                crate::parser::labels_equal(label, &expected)
883            } else {
884                crate::parser::label_has_prefix(label, prefix)
885            };
886            if !ok {
887                return Err(missing());
888            }
889            self.advance_lines_to(rows, end).map_err(|_| missing())?;
890        }
891        Ok(())
892    }
893
894    /// Legacy velocity block: only a blank that begins a velocity label.
895    /// Anything else is the next frame, left for the following skip.
896    fn skip_legacy_velocity(
897        &mut self,
898        header: &types::FrameHeader,
899        end: Option<usize>,
900    ) -> Result<(), error::ParseError> {
901        if self.at_blank_separator().is_none() {
902            return Ok(());
903        }
904        let rest = &self.lines.bytes[self.lines.pos..];
905        let Some((_, after)) = split_raw_line(rest) else {
906            return Ok(());
907        };
908        if !blank_opens_section(after) {
909            return Ok(());
910        }
911        self.consume_section_block(header, "velocities", "Velocities of Component", false, end)
912    }
913
914    /// Skip the sections [`crate::parser::parse_declared_sections`] would read.
915    ///
916    /// A blank symbol line fails CON-section.4 for every declared section.
917    /// An undeclared block after `sections: []` is the next frame, not a
918    /// section this frame owns.
919    fn skip_declared_sections(
920        &mut self,
921        header: &types::FrameHeader,
922        end: Option<usize>,
923    ) -> Result<(), error::ParseError> {
924        if !header.sections_declared && header.sections.is_empty() {
925            return self.skip_legacy_velocity(header, end);
926        }
927        for name in &header.sections {
928            if let Some(prefix) = crate::parser::reserved_section_label_prefix(name) {
929                if self.at_blank_separator() != Some(true) {
930                    return Err(error::ParseError::IncompleteSection(name.clone()));
931                }
932                self.consume_section_block(header, name, prefix, true, end)?;
933                continue;
934            }
935            let newer = crate::parser::frame_minor(header) > u64::from(crate::CON_SPEC_MINOR);
936            if newer && crate::parser::section_row_arity(header, name).is_some() {
937                if self.at_blank_separator() != Some(true) {
938                    return Err(error::ParseError::IncompleteSection(name.clone()));
939                }
940                self.consume_section_block(header, name, "", true, end)?;
941                continue;
942            }
943            return Err(error::ParseError::UnknownSection(name.clone()));
944        }
945        Ok(())
946    }
947
948    /// memchr-backed equivalent of [`Self::forward`]. Skips the next
949    /// frame without fully parsing its atom data. Shares the same line
950    /// cursor as [`Iterator::next`], so skip and full parse interleave safely.
951    pub fn forward_fast(&mut self) -> Option<Result<(), error::ParseError>> {
952        self.forward_fast_to(None)
953    }
954
955    /// [`Self::forward_fast`] for a frame expected to end at byte `end`.
956    ///
957    /// The result and the new position are the same as without `end`.
958    /// Line blocks that end exactly at `end` are counted, not searched.
959    #[inline(always)]
960    pub(crate) fn forward_fast_to(
961        &mut self,
962        end: Option<usize>,
963    ) -> Option<Result<(), error::ParseError>> {
964        self.lines.clear_peek();
965        if self.lines.pos >= self.lines.bytes.len() {
966            return None;
967        }
968        // Line 1, then line 2. The section list on line 2 decides whether a
969        // following blank is a section or the next frame. Skipping six lines
970        // without reading that list was the thread split: the scan and the
971        // parser ended the frame at different bytes.
972        // CON-file.2: no frame may begin with U+FEFF. The full parse
973        // rejects it, and a skip of the same frame must too.
974        let line1 = match self.read_line_str() {
975            Some(line) => line,
976            None => return Some(Err(error::ParseError::IncompleteHeader)),
977        };
978        if line1.starts_with('\u{feff}') {
979            return Some(Err(error::ParseError::ValidationError(
980                "frame begins with a byte-order mark".into(),
981            )));
982        }
983        let line2 = match self.read_line_str() {
984            Some(line) => line.to_string(),
985            None => return Some(Err(error::ParseError::IncompleteHeader)),
986        };
987        let sections = match section_plan(&line2) {
988            Ok(plan) => plan,
989            Err(err) => return Some(Err(err)),
990        };
991        if let Err(e) = self.advance_lines(4) {
992            return Some(Err(e));
993        }
994        // Line 7: natm_types.
995        let natm_types: usize = match self.read_line_str() {
996            Some(line) => match crate::parser::parse_count_line(line, 1) {
997                Ok(v) => v[0],
998                Err(e) => return Some(Err(e)),
999            },
1000            None => return Some(Err(error::ParseError::IncompleteHeader)),
1001        };
1002        if natm_types == 0 {
1003            // Lines 8 and 9 are whitespace, or absent at EOF. Do not scan
1004            // for coordinates or a legacy velocity block (CON-count.1).
1005            return match crate::parser::read_zero_atom_tail(|| self.read_line_str()) {
1006                Ok(()) => self.note_skipped_frame(),
1007                Err(e) => Some(Err(e)),
1008            };
1009        }
1010        // Line 8: natms_per_type.
1011        let natms_per_type: Vec<usize> = match self.read_line_str() {
1012            Some(line) => match crate::parser::parse_count_line(line, natm_types) {
1013                Ok(v) => v,
1014                Err(e) => return Some(Err(e)),
1015            },
1016            None => return Some(Err(error::ParseError::IncompleteHeader)),
1017        };
1018        if natms_per_type.contains(&0) {
1019            return Some(Err(error::ParseError::InvalidCount(
1020                "each per-type count must be >= 1".into(),
1021            )));
1022        }
1023        // Line 9: masses_per_type, consumed.
1024        if let Err(e) = self.advance_lines(1) {
1025            return Some(Err(e));
1026        }
1027        // A block longer than `usize::MAX` lines never fits the buffer, so a
1028        // saturated length ends in `IncompleteFrame` as the exact one would.
1029        let total_atoms = natms_per_type
1030            .iter()
1031            .fold(0usize, |sum, &n| sum.saturating_add(n));
1032        let coord_block_lines = total_atoms.saturating_add(natm_types.saturating_mul(2));
1033        if let Err(e) = self.advance_lines_to(coord_block_lines, end) {
1034            return Some(Err(e));
1035        }
1036        // Sections the full parser will read. A declared list, including an
1037        // empty one, is not the legacy velocity probe (CON-frame.7).
1038        self.lines.clear_peek();
1039        match sections {
1040            SectionPlan::Legacy => {
1041                // One legacy block. A second blank is the next frame.
1042                // A short block is the parse error, not a successful skip.
1043                if let Err(err) = self.legacy_velocity_block(end, coord_block_lines) {
1044                    return Some(Err(err));
1045                }
1046            }
1047            SectionPlan::Declared(n) => {
1048                for _ in 0..n {
1049                    // A short window and a short section are the same skip
1050                    // error. Calling `next` here would turn a window that
1051                    // still needs bytes into a hard error. The span parser
1052                    // reports the verdict once the whole frame is in hand.
1053                    if let Err(err) = self.skip_declared_section(end, coord_block_lines) {
1054                        return Some(Err(err));
1055                    }
1056                }
1057            }
1058        }
1059        self.note_skipped_frame()
1060    }
1061
1062    /// Consume one legacy velocity block when the blank opens one.
1063    ///
1064    /// `Ok(false)` leaves the cursor where it was: the blank is line 1 of
1065    /// the next frame, or a whitespace tail. A block that opens and then
1066    /// runs out of rows is `IncompleteFrame`, the same error as a full parse.
1067    fn legacy_velocity_block(
1068        &mut self,
1069        end: Option<usize>,
1070        block_lines: usize,
1071    ) -> Result<bool, error::ParseError> {
1072        let rest = &self.lines.bytes[self.lines.pos..];
1073        if rest.is_empty() {
1074            return Ok(false);
1075        }
1076        let next_eol = memchr::memchr(b'\n', rest);
1077        let line = match next_eol {
1078            Some(pos) => &rest[..pos],
1079            None => rest,
1080        };
1081        if !is_blank_line(line) {
1082            return Ok(false);
1083        }
1084        let after = match next_eol {
1085            Some(pos) => &rest[pos + 1..],
1086            None => &[][..],
1087        };
1088        if after.iter().all(|b| b.is_ascii_whitespace()) {
1089            self.lines.pos = self.lines.bytes.len();
1090            return Ok(false);
1091        }
1092        if !blank_opens_section(after) {
1093            return Ok(false);
1094        }
1095        self.lines.pos += next_eol.map(|p| p + 1).unwrap_or(rest.len());
1096        self.lines.line_no = self.lines.line_no.saturating_add(1);
1097        self.advance_lines_to(block_lines, end)?;
1098        Ok(true)
1099    }
1100
1101    /// One declared section: the separator blank, then the same number of
1102    /// lines as a coordinate block. A blank symbol line still counts
1103    /// (CON-section.23). The full parse checks the label and the rows.
1104    fn skip_declared_section(
1105        &mut self,
1106        end: Option<usize>,
1107        block_lines: usize,
1108    ) -> Result<(), error::ParseError> {
1109        let rest = &self.lines.bytes[self.lines.pos..];
1110        if rest.is_empty() {
1111            return Err(error::ParseError::IncompleteSection("section".into()));
1112        }
1113        let next_eol = memchr::memchr(b'\n', rest);
1114        let line = match next_eol {
1115            Some(pos) => &rest[..pos],
1116            None => rest,
1117        };
1118        if !is_blank_line(line) {
1119            return Err(error::ParseError::IncompleteSection("section".into()));
1120        }
1121        let after = match next_eol {
1122            Some(pos) => &rest[pos + 1..],
1123            None => &[][..],
1124        };
1125        if after.iter().all(|b| b.is_ascii_whitespace()) {
1126            return Err(error::ParseError::IncompleteSection("section".into()));
1127        }
1128        self.lines.pos += next_eol.map(|p| p + 1).unwrap_or(rest.len());
1129        self.lines.line_no = self.lines.line_no.saturating_add(1);
1130        self.advance_lines_to(block_lines, end)
1131    }
1132
1133    /// Boundary scan for the parallel reader.
1134    ///
1135    /// [`Self::forward_fast`] skips six header lines and then any blank that
1136    /// looks like a section. This scan reads the sections list the parser
1137    /// reads, so an undeclared tail stays the next frame.
1138    fn scan_declared_frame(&mut self, end: Option<usize>) -> Option<Result<(), error::ParseError>> {
1139        self.lines.clear_peek();
1140        if self.lines.pos >= self.lines.bytes.len() {
1141            return None;
1142        }
1143        // A header the parser rejects, such as a non-finite box length, is
1144        // still a frame the line skip can walk past. Falling back keeps the
1145        // later frames in the boundary list.
1146        let saved = (
1147            self.lines.pos,
1148            self.lines.line_no,
1149            self.lines.index_line,
1150            self.lines.utf8_bad,
1151            self.lines.eof_counted,
1152        );
1153        // The header parse is the same one `next` uses, so a declared
1154        // `sections` list, including an empty one, is known before the
1155        // coordinate skip. Skipping those lines wholesale treated every
1156        // blank-plus-label tail as a section of this frame.
1157        let header = match crate::parser::parse_frame_header_inner(&mut self.lines) {
1158            Ok(header) => header,
1159            Err(_) => {
1160                self.lines.pos = saved.0;
1161                self.lines.line_no = saved.1;
1162                self.lines.index_line = saved.2;
1163                self.lines.utf8_bad = saved.3;
1164                self.lines.eof_counted = saved.4;
1165                self.lines.clear_peek();
1166                return self.forward_fast_to(end);
1167            }
1168        };
1169        if header.natm_types == 0 {
1170            return self.note_skipped_frame();
1171        }
1172        // A block longer than `usize::MAX` lines never fits the buffer, so a
1173        // saturated length ends in `IncompleteFrame` as the exact one would.
1174        let total_atoms = header
1175            .natms_per_type
1176            .iter()
1177            .fold(0usize, |sum, &n| sum.saturating_add(n));
1178        let coord_block_lines = total_atoms.saturating_add(header.natm_types.saturating_mul(2));
1179        if let Err(e) = self.advance_lines_to(coord_block_lines, end) {
1180            return Some(Err(e));
1181        }
1182        self.lines.clear_peek();
1183        if let Err(e) = self.skip_declared_sections(&header, end) {
1184            return Some(Err(e));
1185        }
1186        self.note_skipped_frame()
1187    }
1188
1189    /// Skips the next frame without fully parsing its atomic data.
1190    ///
1191    /// This is more efficient than `next()` if you only need to advance the
1192    /// iterator. It reads the frame's header to determine how many lines to skip,
1193    /// including any velocity section if present.
1194    ///
1195    /// # Returns
1196    ///
1197    /// * `Some(Ok(()))` on a successful skip.
1198    /// * `Some(Err(ParseError::...))` if there's an error parsing the header.
1199    /// * `None` if the iterator is already at the end.
1200    pub fn forward(&mut self) -> Option<Result<(), error::ParseError>> {
1201        // Prefer the shared memchr skip path (same cursor as full parse).
1202        self.forward_fast()
1203    }
1204
1205    /// Byte offset of the next frame start in the buffer passed to [`Self::new`].
1206    pub fn byte_pos(&self) -> usize {
1207        self.lines.pos
1208    }
1209
1210    /// Skip `n` frames without parsing atom data. Returns how many were skipped.
1211    /// Named `skip_frames` so it does not collide with [`Iterator::skip`].
1212    pub fn skip_frames(&mut self, n: usize) -> Result<usize, error::ParseError> {
1213        self.skip_frames_counted(n).map_err(|(_, err)| err)
1214    }
1215
1216    /// Like [`Self::skip_frames`]. The error's first field is how many frames
1217    /// were skipped before the failure, which is the 0-based index of the
1218    /// failing frame when the iterator started at frame 0.
1219    pub(crate) fn skip_frames_counted(
1220        &mut self,
1221        n: usize,
1222    ) -> Result<usize, (usize, error::ParseError)> {
1223        let mut skipped = 0usize;
1224        for _ in 0..n {
1225            match self.forward() {
1226                None => break,
1227                Some(Err(e)) => return Err((skipped, e)),
1228                Some(Ok(())) => skipped += 1,
1229            }
1230        }
1231        Ok(skipped)
1232    }
1233
1234    /// Next frame plus the exact substring of the buffer passed to [`Self::new`].
1235    ///
1236    /// **Corpus ingest contract:** successive successful spans from the same
1237    /// `file_contents` are contiguous (`end` of frame *i* equals `start` of frame
1238    /// *i+1*) and, for a buffer that is only multi-frame CON (no prefix garbage),
1239    /// concatenating all spans reproduces the trajectory text. Campaign stores
1240    /// (`readcon-db`) must persist these spans as authoritative blobs—do not
1241    /// re-serialize on the hot ingest path unless the caller supplied in-memory
1242    /// [`types::ConFrame`] values without source text.
1243    ///
1244    /// See also [`crate::index_proj::frame_byte_spans`] and
1245    /// [`crate::index_proj::spans_cover_buffer`].
1246    pub fn next_with_raw_span(
1247        &mut self,
1248        file_contents: &'a str,
1249    ) -> Option<Result<(types::ConFrame, &'a str), error::ParseError>> {
1250        let base = file_contents.as_ptr() as usize;
1251        let start = {
1252            let line = self.lines.peek_line()?;
1253            line.as_ptr() as usize - base
1254        };
1255        let frame = match self.next()? {
1256            Ok(f) => f,
1257            Err(e) => return Some(Err(e)),
1258        };
1259        let end = match self.lines.peek_line() {
1260            Some(line) => line.as_ptr() as usize - base,
1261            None => file_contents.len(),
1262        };
1263        debug_assert!(end >= start && end <= file_contents.len());
1264        Some(Ok((frame, &file_contents[start..end])))
1265    }
1266
1267    /// [`Iterator::next`] plus the byte offset where the frame ends.
1268    pub(crate) fn next_with_end(
1269        &mut self,
1270    ) -> Option<Result<(types::ConFrame, usize), error::ParseError>> {
1271        let frame = match self.next()? {
1272            Ok(f) => f,
1273            Err(e) => return Some(Err(e)),
1274        };
1275        let end = match self.lines.peek_line() {
1276            Some(line) => line.as_ptr() as usize - self.lines.bytes.as_ptr() as usize,
1277            None => self.lines.pos,
1278        };
1279        Some(Ok((frame, end)))
1280    }
1281}
1282
1283impl<'a> Iterator for ConFrameIterator<'a> {
1284    /// The type of item yielded by the iterator.
1285    ///
1286    /// Each item is a `Result` that contains a successfully parsed `ConFrame` or a
1287    /// `ParseError` if the frame's data is malformed.
1288    type Item = Result<types::ConFrame, error::ParseError>;
1289
1290    /// Advances the iterator and attempts to parse the next frame.
1291    ///
1292    /// This method will return `None` only when there are no more lines to consume.
1293    /// If there are lines but they do not form a complete frame, it will return
1294    /// `Some(Err(ParseError::...))`. Invalid UTF-8 is a validation error, not
1295    /// the end of the stream.
1296    fn next(&mut self) -> Option<Self::Item> {
1297        // A line rejected earlier in this cursor (for example while probing
1298        // for a velocity block) must not be reported as a clean EOF.
1299        if let Some(err) = self.lines.utf8_error() {
1300            return Some(Err(err));
1301        }
1302        // Trailing whitespace after the last complete frame is not a frame
1303        // (CON-frame.1, D2). An empty line that is followed by more text is
1304        // line 1 of the next frame (CON-frame.7).
1305        if self.lines.remainder_is_whitespace() {
1306            if let Some(err) = self.lines.utf8_error() {
1307                return Some(Err(err));
1308            }
1309            while self.lines.next_line().is_some() {}
1310            return None;
1311        }
1312        if let Some(err) = self.lines.utf8_error() {
1313            return Some(Err(err));
1314        }
1315        // Otherwise, attempt to parse the next frame from the available lines.
1316        // A peek of line 1 has already counted that line. The origin is the
1317        // line before the frame, so the metadata line is origin + 2.
1318        self.frame_origin = match self.lines.peeked {
1319            Some(_) => self.lines.line_no().saturating_sub(1),
1320            None => self.lines.line_no(),
1321        };
1322        let max_rows = Some(self.lines.unread_len() / crate::parser::MIN_COORD_ROW_BYTES);
1323        let mut frame = match crate::parser::parse_single_frame_ls(&mut self.lines, max_rows) {
1324            Ok(f) => f,
1325            Err(e) => return Some(Err(self.lines.prefer_utf8(e))),
1326        };
1327        // Optional sections mutate AoS; only re-sync section SoA when needed.
1328        // Plain .con assembly already filled positions/ids/masses (no O(N)
1329        // post-scan when no velocity/force sections were applied).
1330        let sections = match parse_declared_sections(&mut self.lines, &mut frame) {
1331            Ok(n) => n,
1332            // A section line that failed UTF-8 makes `next_line` return
1333            // `None`. That must not surface as `IncompleteSection`.
1334            Err(e) => return Some(Err(self.lines.prefer_utf8(e))),
1335        };
1336        if sections > 0 {
1337            // One flat fill per section that was actually parsed. The full
1338            // sync walks every absent section and writes each row through
1339            // ArcArray uniqueness checks.
1340            frame.sequential_plain = false;
1341            frame.install_declared_section_soa();
1342        }
1343        if let Err(error) = crate::types::observe_persistent_ids(&mut self.persistent_ids, &frame) {
1344            return Some(Err(self.lines.prefer_utf8(error)));
1345        }
1346        self.frame_index = self.frame_index.saturating_add(1);
1347        Some(Ok(frame))
1348    }
1349}
1350
1351#[cfg(test)]
1352mod aos_soa_agreement_tests {
1353    use super::*;
1354    use std::path::PathBuf;
1355
1356    #[test]
1357    fn iterator_vel_forces_soa_matches_aos() {
1358        let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1359            .join("resources/test/tiny_cuh2_vel_forces.con");
1360        let text = std::fs::read_to_string(&p).expect("fixture");
1361        let fr = ConFrameIterator::new(&text)
1362            .next()
1363            .expect("frame")
1364            .expect("parse");
1365        let n = fr.atom_data.len();
1366        assert!(n > 0);
1367        assert_eq!(fr.positions.nrows(), n);
1368        let has_vel = fr.atom_data.iter().any(|a| a.velocity().is_some());
1369        let has_frc = fr.atom_data.iter().any(|a| a.force().is_some());
1370        if has_vel {
1371            assert_eq!(
1372                fr.velocities.nrows(),
1373                n,
1374                "SoA velocities must match AoS after section parse"
1375            );
1376        }
1377        if has_frc {
1378            assert_eq!(fr.forces.nrows(), n, "SoA forces must match AoS");
1379        }
1380        for (i, a) in fr.atom_data.iter().enumerate() {
1381            let p = fr.positions.as_f64_row(i);
1382            assert_eq!(fr.xyz_at(i), p);
1383            if let Some(v) = a.velocity() {
1384                assert_eq!(v, fr.velocities.as_f64_row(i));
1385            }
1386            if let Some(f) = a.force() {
1387                assert_eq!(f, fr.forces.as_f64_row(i));
1388            }
1389        }
1390    }
1391
1392    /// After SoA-primary parse, section sync must not require rewriting positions
1393    /// (nrows already equals N); forces SoA still filled from AoS.
1394    #[test]
1395    fn sync_skips_pos_when_nrows_matches_keeps_force_soa() {
1396        let p =
1397            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2_forces.con");
1398        let text = std::fs::read_to_string(&p).expect("fixture");
1399        let fr = ConFrameIterator::new(&text)
1400            .next()
1401            .expect("frame")
1402            .expect("parse");
1403        let n = fr.atom_data.len();
1404        assert_eq!(fr.positions.nrows(), n);
1405        assert_eq!(fr.forces.nrows(), n);
1406        // Snapshot first position SoA row then re-sync; coords must stay bit-identical
1407        // (no needless rewrite would change nothing but we still require agreement).
1408        let p0 = fr.positions.as_f64_row(0);
1409        let mut fr2 = fr.clone();
1410        fr2.sync_arrays_from_atom_data();
1411        assert_eq!(fr2.positions.as_f64_row(0), p0);
1412        assert_eq!(fr2.forces.nrows(), n);
1413        assert_eq!(
1414            fr2.forces.as_f64_row(0),
1415            fr2.atom_data[0].force().expect("force")
1416        );
1417    }
1418
1419    /// Section SoA is filled from one flat buffer. Every value must match the
1420    /// per-atom tail, including past a small-vector boundary.
1421    #[test]
1422    fn declared_sections_soa_matches_every_atom() {
1423        let n = 400;
1424        let mut text = String::new();
1425        text.push_str("soa fill\n");
1426        text.push_str(
1427            "{\"con_spec_version\":2,\"sections\":[\"velocities\",\"forces\",\"energies\"]}\n",
1428        );
1429        text.push_str("10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0 0\n1\n");
1430        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
1431        for i in 0..n {
1432            let x = (i as f64) * 0.125 - 3.5;
1433            let y = (i as f64) * -0.05 + 1.0;
1434            let z = (i % 17) as f64 * 0.333;
1435            text.push_str(&format!("{x:.8} {y:.8} {z:.8} 0 {i}\n"));
1436        }
1437        text.push_str("\nCu\nVelocities of Component 1\n");
1438        for i in 0..n {
1439            let vx = (i as f64) * 1.0e-4 - 0.02;
1440            let vy = ((i * 3) % 11) as f64 * -1.0e-3;
1441            let vz = (i as f64).sin() * 0.01;
1442            text.push_str(&format!("{vx:.8} {vy:.8} {vz:.8} 0 {i}\n"));
1443        }
1444        text.push_str("\nCu\nForces of Component 1\n");
1445        for i in 0..n {
1446            let fx = (i as f64) * 0.01;
1447            let fy = -fx / 2.0;
1448            let fz = (i % 5) as f64;
1449            text.push_str(&format!("{fx:.8} {fy:.8} {fz:.8} 0 {i}\n"));
1450        }
1451        text.push_str("\nCu\nEnergies of Component 1\n");
1452        for i in 0..n {
1453            let e = (i as f64) * 0.02 - 4.0;
1454            text.push_str(&format!("{e:.8} 0 {i}\n"));
1455        }
1456        let frame = ConFrameIterator::new(&text)
1457            .next()
1458            .expect("frame")
1459            .expect("parse");
1460        assert_eq!(frame.atom_data.len(), n);
1461        assert_eq!(frame.velocities.nrows(), n);
1462        assert_eq!(frame.forces.nrows(), n);
1463        assert_eq!(frame.atom_energies.len(), n);
1464        assert_eq!(frame.positions.nrows(), n);
1465        assert!(frame.magmoms.nrows() == 0);
1466        for i in 0..n {
1467            let atom = &frame.atom_data[i];
1468            let pos = frame.positions.as_f64_row(i);
1469            assert_eq!(pos, frame.xyz_at(i));
1470            let vel = atom.velocity().unwrap();
1471            let soa_v = frame.velocities.as_f64_row(i);
1472            assert_eq!(soa_v[0].to_bits(), vel[0].to_bits());
1473            assert_eq!(soa_v[1].to_bits(), vel[1].to_bits());
1474            assert_eq!(soa_v[2].to_bits(), vel[2].to_bits());
1475            let frc = atom.force().unwrap();
1476            let soa_f = frame.forces.as_f64_row(i);
1477            assert_eq!(soa_f[0].to_bits(), frc[0].to_bits());
1478            assert_eq!(soa_f[1].to_bits(), frc[1].to_bits());
1479            assert_eq!(soa_f[2].to_bits(), frc[2].to_bits());
1480            assert_eq!(
1481                frame.atom_energies.get_f64(i).to_bits(),
1482                atom.energy().unwrap().to_bits()
1483            );
1484            assert_eq!(frame.atom_ids[i], atom.atom_id);
1485        }
1486    }
1487}
1488
1489/// Reads all frames from a file.
1490///
1491/// A plain file is parsed from a window on the calling thread, so the
1492/// file is not resident together with the finished frames. Compressed
1493/// input is read into one buffer. A worker pool runs only when
1494/// [`read_all_frames_with_threads`] is asked for two or more threads.
1495pub fn read_all_frames(path: &Path) -> Result<Vec<types::ConFrame>, Box<dyn std::error::Error>> {
1496    read_all_frames_with_threads(path, None)
1497}
1498
1499/// Collect every frame from `text`.
1500///
1501/// `None`, `Some(0)`, and `Some(1)` parse on the calling thread.
1502/// `Some(n)` with `n >= 2` uses a Rayon pool of that size when the
1503/// `parallel` feature is on. Builds without `parallel` always parse
1504/// sequentially.
1505///
1506/// ```
1507/// use readcon_core::iterators::frames_from_text;
1508/// let text = include_str!("../resources/test/tiny_multi_cuh2.con");
1509/// let one = frames_from_text(text, Some(1)).unwrap();
1510/// let pool = frames_from_text(text, Some(2)).unwrap();
1511/// assert_eq!(one.len(), pool.len());
1512/// assert!(one.len() >= 2);
1513/// ```
1514pub fn frames_from_text(
1515    text: &str,
1516    num_threads: Option<usize>,
1517) -> Result<Vec<types::ConFrame>, error::ParseError> {
1518    #[cfg(feature = "parallel")]
1519    {
1520        if let Some(n) = num_threads.filter(|n| *n >= 2) {
1521            // The phased path finishes the slots on the same pool. A
1522            // serial move of every frame was a growing tail once a worker
1523            // owned tens of thousands of frames.
1524            return Ok(frames_from_bytes_phased(text.as_bytes(), Some(n))?.frames);
1525        }
1526    }
1527    #[cfg(not(feature = "parallel"))]
1528    {
1529        let _ = num_threads;
1530    }
1531    ConFrameIterator::new(text).collect()
1532}
1533
1534/// Like [`read_all_frames`], with an explicit worker count.
1535///
1536/// `None`, `Some(0)`, and `Some(1)` parse on the calling thread.
1537/// `Some(n)` with `n >= 2` pins a Rayon pool when `parallel` is on.
1538///
1539/// A parse failure is the [`error::LocatedParseError`] from that parse.
1540/// Its line is the cursor that failed and its frame is the 0-based index.
1541/// The path is not opened again.
1542///
1543/// One thread reads a plain file in windows. Two or more threads map
1544/// the file. Compressed input is read into one buffer.
1545pub fn read_all_frames_with_threads(
1546    path: &Path,
1547    num_threads: Option<usize>,
1548) -> Result<Vec<types::ConFrame>, Box<dyn std::error::Error>> {
1549    if matches!(num_threads, Some(n) if n >= 2) {
1550        let bytes = crate::compression::read_bytes_owned(path)?;
1551        return Ok(frames_from_bytes_located(bytes.as_slice(), num_threads)?);
1552    }
1553    stream_frames(path).map_err(public_load_error)
1554}
1555
1556fn public_load_error(err: LoadError) -> Box<dyn std::error::Error> {
1557    match err {
1558        LoadError::Parse(located) => Box::new(located),
1559        other => Box::new(other),
1560    }
1561}
1562
1563/// Read plain text in windows and parse each complete frame before the next
1564/// window. The window is a few mebibytes, so the file is not resident with
1565/// the finished frames. Gzip and zstd are inflated into the same window.
1566fn stream_frames(path: &Path) -> Result<Vec<types::ConFrame>, LoadError> {
1567    use std::io::Read;
1568    let mut file = std::fs::File::open(path).map_err(LoadError::Io)?;
1569    let mut magic = [0u8; 4];
1570    let n = file.read(&mut magic).map_err(LoadError::Io)?;
1571    let compression = crate::compression::detect_compression(&magic[..n]);
1572    if matches!(compression, crate::compression::Compression::None) {
1573        let file_len = path.metadata().map(|m| m.len()).unwrap_or(0);
1574        // A modest plain file stays mapped, the same way the coordinate
1575        // read does. Copying it into a buffer first was a visible share of
1576        // a million-atom frame read. The windowed reader stays for a long
1577        // trajectory so the text is not resident beside every frame.
1578        // 128 MiB covers a million-atom frame with velocities and forces.
1579        // The 100k-frame, 32-atom trajectory is larger and stays on the window.
1580        if file_len > 0 && file_len <= 128 * 1024 * 1024 {
1581            drop(file);
1582            let source = crate::compression::read_bytes_owned(path).map_err(load_error_from_box)?;
1583            return frames_from_bytes_located(source.as_slice(), Some(1)).map_err(LoadError::Parse);
1584        }
1585        return stream_reader(&mut file, &magic[..n], file_len);
1586    }
1587    drop(file);
1588    // Indexed members inflate straight into one buffer. The plain bytes
1589    // are parsed in place, so a gzip file is not copied into a `String`.
1590    let bytes = crate::compression::read_file_bytes(path).map_err(load_error_from_box)?;
1591    let budget = crate::compression::decode_thread_budget();
1592    let threads = if budget >= 2 { Some(budget) } else { Some(1) };
1593    frames_from_bytes_located(&bytes, threads).map_err(LoadError::Parse)
1594}
1595
1596/// Decode `bytes`. At end of input, a hard parse error in the valid prefix
1597/// wins over a trailing non-UTF-8 byte, so that byte does not hide it.
1598fn utf8_text(bytes: &[u8], eof: bool) -> Result<&str, LoadError> {
1599    match std::str::from_utf8(bytes) {
1600        Ok(text) => Ok(text),
1601        Err(err) if eof => earlier_parse_or_utf8(bytes, err),
1602        Err(err) => Err(LoadError::Utf8(err)),
1603    }
1604}
1605
1606fn error_needs_more_input(error: &error::ParseError) -> bool {
1607    matches!(
1608        error,
1609        error::ParseError::IncompleteHeader
1610            | error::ParseError::IncompleteFrame
1611            | error::ParseError::IncompleteVelocitySection
1612            | error::ParseError::IncompleteForceSection
1613            | error::ParseError::IncompleteEnergySection
1614            | error::ParseError::IncompleteSection(_)
1615    )
1616}
1617
1618fn earlier_parse_or_utf8(bytes: &[u8], err: std::str::Utf8Error) -> Result<&str, LoadError> {
1619    let valid = err.valid_up_to();
1620    if valid > 0 {
1621        if let Ok(prefix) = std::str::from_utf8(&bytes[..valid]) {
1622            if let Err(located) = frames_from_text_located(prefix, Some(1)) {
1623                // A frame cut off by the bad byte is still the UTF-8 error.
1624                // A finished frame that already failed is the error to keep.
1625                if !error_needs_more_input(&located.error) {
1626                    return Err(LoadError::Parse(located));
1627                }
1628            }
1629        }
1630    }
1631    Err(LoadError::Utf8(err))
1632}
1633
1634fn stream_reader(
1635    reader: &mut dyn std::io::Read,
1636    prefix: &[u8],
1637    file_len: u64,
1638) -> Result<Vec<types::ConFrame>, LoadError> {
1639    let mut buf = Vec::with_capacity(8 << 20);
1640    buf.extend_from_slice(prefix);
1641    let mut frames = Vec::new();
1642    let mut sized = false;
1643    let mut line_base = 0u32;
1644    let mut eof = false;
1645    let mut read_more = |buf: &mut Vec<u8>, eof: &mut bool| -> Result<(), LoadError> {
1646        if *eof {
1647            return Ok(());
1648        }
1649        let start = buf.len();
1650        buf.resize(start + (8 << 20), 0);
1651        let got = reader.read(&mut buf[start..]).map_err(LoadError::Io)?;
1652        buf.truncate(start + got);
1653        if got == 0 {
1654            *eof = true;
1655        }
1656        Ok(())
1657    };
1658    if buf.len() < (8 << 20) {
1659        read_more(&mut buf, &mut eof)?;
1660    }
1661    loop {
1662        if buf.is_empty() {
1663            break;
1664        }
1665        let end = if eof {
1666            buf.len()
1667        } else {
1668            match buf.iter().rposition(|byte| *byte == b'\n') {
1669                Some(i) => i + 1,
1670                None => {
1671                    read_more(&mut buf, &mut eof)?;
1672                    continue;
1673                }
1674            }
1675        };
1676        let text = utf8_text(&buf[..end], eof)?;
1677        let (parsed, consumed) = take_complete_frames(text, eof, line_base, frames.len() as u64)?;
1678        if consumed == 0 && !eof {
1679            // The window holds the start of one frame and nothing else.
1680            // Parsing again after every 8 MiB rereads that prefix. Pull
1681            // the rest of a single oversized frame, then parse it once.
1682            if frames.is_empty() && file_len > 0 && file_len <= 512 * 1024 * 1024 {
1683                while !eof {
1684                    let before = buf.len();
1685                    read_more(&mut buf, &mut eof)?;
1686                    if buf.len() == before {
1687                        break;
1688                    }
1689                }
1690                continue;
1691            }
1692            let before = buf.len();
1693            read_more(&mut buf, &mut eof)?;
1694            if buf.len() == before && !eof {
1695                eof = true;
1696            }
1697            continue;
1698        }
1699        frames.extend(parsed);
1700        if !sized && consumed > 0 && !frames.is_empty() && file_len > 0 {
1701            let per = (consumed / frames.len()).max(1);
1702            let guess = (file_len as usize) / per + 8;
1703            if guess > frames.capacity() {
1704                frames.reserve_exact(guess - frames.len());
1705            }
1706            sized = true;
1707        }
1708        line_base += buf[..consumed]
1709            .iter()
1710            .filter(|byte| **byte == b'\n')
1711            .count() as u32;
1712        buf.drain(..consumed);
1713        if buf.is_empty() && eof {
1714            break;
1715        }
1716        if !eof && buf.len() < (8 << 20) {
1717            read_more(&mut buf, &mut eof)?;
1718        }
1719    }
1720    Ok(frames)
1721}
1722
1723fn take_complete_frames(
1724    text: &str,
1725    eof: bool,
1726    line_base: u32,
1727    frame_base: u64,
1728) -> Result<(Vec<types::ConFrame>, usize), LoadError> {
1729    let mut iter = ConFrameIterator::new(text);
1730    iter.lines.line_no = line_base;
1731    let mut frames = Vec::new();
1732    loop {
1733        // A finished frame may have peeked the next user line. That peek
1734        // moves `pos` past the line. Rewind before recording the resume point.
1735        iter.lines.clear_peek();
1736        let start = iter.lines.pos;
1737        if !eof && text[start..].trim().is_empty() {
1738            // A trailing blank line is the next frame's user line, not the
1739            // end of the file. Leave it for the next window.
1740            return Ok((frames, start));
1741        }
1742        match iter.next() {
1743            Some(Ok(frame)) => frames.push(frame),
1744            Some(Err(error)) => {
1745                // A complete line that is already illegal will not become
1746                // legal when the next window arrives. An unfinished frame
1747                // might: the window stopped at a newline before its rows.
1748                if eof || !error_needs_more_input(&error) {
1749                    return Err(LoadError::Parse(error::LocatedParseError::new(
1750                        error,
1751                        iter.lines.line_no(),
1752                        frame_base + frames.len() as u64,
1753                    )));
1754                }
1755                return Ok((frames, start));
1756            }
1757            None => {
1758                if eof {
1759                    return Ok((frames, text.len()));
1760                }
1761                return Ok((frames, start));
1762            }
1763        }
1764    }
1765}
1766
1767/// Positions of every frame, one row-major `f64` buffer.
1768#[derive(Debug)]
1769///
1770/// A parse failure is the [`error::LocatedParseError`] from the boundary
1771/// scan or the span parse that failed. The path is not opened again.
1772///
1773/// The boundary walk records each frame start. Each worker then parses
1774/// only its span and writes that frame's coordinates at
1775/// `frame * n_atoms * 3`. The returned buffer is the only retained
1776/// coordinate storage. A file whose frames do not share one atom count
1777/// is rejected, because the buffer is rectangular.
1778/// Rectangular coordinates for every frame of one file.
1779///
1780/// `values` is row-major `x, y, z`, index `frame * n_atoms * 3 + atom * 3`.
1781/// That `Vec` is the only coordinate allocation. Python `read_positions`
1782/// moves it into the NumPy array and does not copy the doubles again.
1783pub struct PositionBlock {
1784    pub n_frames: usize,
1785    pub n_atoms: usize,
1786    pub values: Vec<f64>,
1787}
1788
1789/// Read every frame's coordinates through the column walker.
1790///
1791/// `num_threads` of `None`, `Some(0)`, and `Some(1)` stay on the calling
1792/// thread. `Some(n)` with `n >= 2` uses that many workers when `parallel`
1793/// is enabled. The buffer is rectangular: frames that do not share one
1794/// atom count are an error. The returned [`PositionBlock`] owns the parse
1795/// buffer. Python `read_positions` moves `values` into NumPy.
1796///
1797/// # Examples
1798///
1799/// ```
1800/// # use std::path::Path;
1801/// let block = readcon_core::iterators::read_positions_with_threads(
1802///     Path::new("resources/test/tiny_cuh2.con"),
1803///     None,
1804/// )
1805/// .unwrap();
1806/// assert_eq!(
1807///     (block.n_frames, block.n_atoms, block.values.len()),
1808///     (1, 4, 12)
1809/// );
1810/// ```
1811pub fn read_positions_with_threads(
1812    path: &Path,
1813    num_threads: Option<usize>,
1814) -> Result<PositionBlock, Box<dyn std::error::Error>> {
1815    // Bytes, not a UTF-8 `String`. A bad numeric token is the same class the
1816    // frame reader reports; rejecting the whole file as invalid UTF-8 hid it.
1817    let bytes = crate::compression::read_file_bytes(path)?;
1818    Ok(fill_position_block(&bytes, num_threads)?)
1819}
1820
1821/// Masses and cell that belong with [`read_positions_with_threads`].
1822///
1823/// The column walker fills these when it certifies the file. Otherwise they
1824/// come from the frame parser, which is the same source as before.
1825pub struct CoordColumns {
1826    pub block: PositionBlock,
1827    pub masses: Vec<f64>,
1828    pub cells: Vec<f64>,
1829    /// Column 5, file order, length `n_frames * n_atoms` when identity was read.
1830    pub atom_ids: Vec<u64>,
1831    /// Decoded column-4 bitmask, same length as `atom_ids` when identity was read.
1832    pub fixed: Vec<u8>,
1833    /// One run-length element list when every frame matches, otherwise one per frame.
1834    ///
1835    /// Each run is `(symbol, count)` in file order. An empty list means identity
1836    /// was not collected.
1837    pub species: Vec<Vec<(String, usize)>>,
1838    pub has_section: bool,
1839    /// True when any atom is held on some axes and free on others.
1840    pub partial_fixed: bool,
1841}
1842
1843/// `true` when the column walker certified `bytes`.
1844///
1845/// With `identity`, the per-frame component runs must partition every
1846/// frame. A short components vector makes this return `false`, and the
1847/// reader then rebuilds the file with the frame parser.
1848#[doc(hidden)]
1849pub fn column_walk_certified(bytes: &[u8], num_threads: Option<usize>, identity: bool) -> bool {
1850    matches!(certified_columns(bytes, num_threads, identity), Ok(Some(_)))
1851}
1852
1853/// Positions, masses, and cells for a stock CON or convel file.
1854///
1855/// A certified file is one coordinate pass. Anything else uses the frame
1856/// reader. Python `read_coords` returns these columns.
1857pub fn read_coord_columns(
1858    path: &Path,
1859    num_threads: Option<usize>,
1860) -> Result<CoordColumns, Box<dyn std::error::Error>> {
1861    let bytes = crate::compression::read_file_bytes(path)?;
1862    if !persistent_ids_declared(&bytes) {
1863        match certified_columns(&bytes, num_threads, true) {
1864            Ok(Some(columns)) => return Ok(columns),
1865            Ok(None) => {}
1866            Err(err) => return Err(err.into()),
1867        }
1868    }
1869    let frames = frames_from_bytes_located(&bytes, num_threads)?;
1870    if let Some(first) = frames.first() {
1871        let n_atoms = first.positions.nrows();
1872        if let Some((index, _)) = frames
1873            .iter()
1874            .enumerate()
1875            .find(|(_, frame)| frame.positions.nrows() != n_atoms)
1876        {
1877            return Err(error::LocatedParseError::new(
1878                error::ParseError::InvalidCount(
1879                    "frame atom count does not match the first frame".into(),
1880                ),
1881                0,
1882                index as u64,
1883            )
1884            .into());
1885        }
1886    }
1887    Ok(columns_from_frames(&frames))
1888}
1889
1890/// True when a frame sets `ids_persistent` to true.
1891///
1892/// The column walk does not apply CON-id.11. Those files use the frame parser,
1893/// which does.
1894fn persistent_ids_declared(bytes: &[u8]) -> bool {
1895    let key = b"\"ids_persistent\"";
1896    let mut start = 0;
1897    while let Some(at) = bytes[start..]
1898        .windows(key.len())
1899        .position(|window| window == key)
1900    {
1901        let mut i = start + at + key.len();
1902        while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
1903            i += 1;
1904        }
1905        if bytes.get(i) == Some(&b':') {
1906            i += 1;
1907            while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
1908                i += 1;
1909            }
1910            if i < bytes.len() && bytes[i..].starts_with(b"true") {
1911                return true;
1912            }
1913        }
1914        start += at + key.len();
1915    }
1916    false
1917}
1918
1919fn certified_columns(
1920    bytes: &[u8],
1921    num_threads: Option<usize>,
1922    identity: bool,
1923) -> Result<Option<CoordColumns>, error::LocatedParseError> {
1924    let mut parsed = {
1925        let parsed = if parallel_column_threads(num_threads) {
1926            #[cfg(feature = "parallel")]
1927            {
1928                crate::columns::positions_parallel(bytes, num_threads.unwrap_or(1), identity)
1929            }
1930            #[cfg(not(feature = "parallel"))]
1931            {
1932                let _ = num_threads;
1933                if identity {
1934                    crate::columns::positions_with_identity(bytes)
1935                } else {
1936                    crate::columns::positions_from_con_bytes(bytes)
1937                }
1938            }
1939        } else if identity {
1940            crate::columns::positions_with_identity(bytes)
1941        } else {
1942            crate::columns::positions_from_con_bytes(bytes)
1943        };
1944        match parsed {
1945            Ok(parsed) if parsed.stock => parsed,
1946            _ => return Ok(None),
1947        }
1948    };
1949    if parsed.n_frames == 0 {
1950        return Ok(Some(CoordColumns {
1951            block: PositionBlock {
1952                n_frames: 0,
1953                n_atoms: 0,
1954                values: Vec::new(),
1955            },
1956            masses: Vec::new(),
1957            cells: Vec::new(),
1958            atom_ids: Vec::new(),
1959            fixed: Vec::new(),
1960            species: Vec::new(),
1961            has_section: false,
1962            partial_fixed: false,
1963        }));
1964    }
1965    let Some(n_atoms) = parsed.rectangular_atoms() else {
1966        let first = parsed.counts[0];
1967        let index = parsed
1968            .counts
1969            .iter()
1970            .position(|count| *count != first)
1971            .unwrap_or(0);
1972        let line = file_line_at_bytes(
1973            bytes,
1974            parsed.spans.get(index).map(|span| span.start).unwrap_or(0),
1975        );
1976        return Err(error::LocatedParseError::new(
1977            error::ParseError::InvalidCount(
1978                "frame atom count does not match the first frame".into(),
1979            ),
1980            line,
1981            index as u64,
1982        ));
1983    };
1984    let ColumnIdentity {
1985        atom_ids,
1986        fixed,
1987        species,
1988        partial_fixed,
1989    } = if identity {
1990        match frame_identity(&parsed, n_atoms) {
1991            Some(identity) => identity,
1992            None => return Ok(None),
1993        }
1994    } else {
1995        ColumnIdentity::default()
1996    };
1997    let has_section = parsed.has_section;
1998    let values = std::mem::take(&mut parsed.positions);
1999    Ok(Some(CoordColumns {
2000        block: PositionBlock {
2001            n_frames: parsed.n_frames,
2002            n_atoms,
2003            values,
2004        },
2005        masses: parsed.masses,
2006        cells: parsed.cells,
2007        atom_ids,
2008        fixed,
2009        species,
2010        has_section,
2011        partial_fixed,
2012    }))
2013}
2014
2015/// Column 5, the fixed mask, and the element runs for one coordinate read.
2016#[derive(Default)]
2017struct ColumnIdentity {
2018    atom_ids: Vec<u64>,
2019    fixed: Vec<u8>,
2020    species: Vec<Vec<(String, usize)>>,
2021    partial_fixed: bool,
2022}
2023
2024/// Column 5, the fixed mask, and element runs. `None` when the rich columns
2025/// do not partition the frames, so the caller uses the frame parser.
2026fn frame_identity(parsed: &crate::columns::ConPositions, n_atoms: usize) -> Option<ColumnIdentity> {
2027    let n = parsed.n_frames.saturating_mul(n_atoms);
2028    if parsed.ids.len() != n || parsed.flags.len() != n {
2029        return None;
2030    }
2031    let mut runs = Vec::with_capacity(parsed.n_frames);
2032    let mut components = parsed.components.iter();
2033    for &count in &parsed.counts {
2034        let mut left = count;
2035        let mut frame_runs = Vec::new();
2036        while left > 0 {
2037            let (symbol, width) = components.next()?;
2038            if *width == 0 || *width > left {
2039                return None;
2040            }
2041            frame_runs.push((symbol.to_string(), *width));
2042            left -= *width;
2043        }
2044        runs.push(frame_runs);
2045    }
2046    if components.next().is_some() {
2047        return None;
2048    }
2049    let partial_fixed = parsed.flags.iter().any(|flag| *flag != 0 && *flag != 7);
2050    let species = if runs.windows(2).all(|pair| pair[0] == pair[1]) {
2051        runs.into_iter().take(1).collect()
2052    } else {
2053        runs
2054    };
2055    Some(ColumnIdentity {
2056        atom_ids: parsed.ids.clone(),
2057        fixed: parsed.flags.clone(),
2058        species,
2059        partial_fixed,
2060    })
2061}
2062
2063fn parallel_column_threads(num_threads: Option<usize>) -> bool {
2064    // `None`, `Some(0)`, and `Some(1)` stay on the calling thread. A pool
2065    // runs only for an explicit count of two or more.
2066    #[cfg(feature = "parallel")]
2067    {
2068        matches!(num_threads, Some(n) if n >= 2)
2069    }
2070    #[cfg(not(feature = "parallel"))]
2071    {
2072        let _ = num_threads;
2073        false
2074    }
2075}
2076
2077fn columns_from_frames(frames: &[types::ConFrame]) -> CoordColumns {
2078    let n_frames = frames.len();
2079    let n_atoms = frames
2080        .first()
2081        .map(|frame| frame.positions.nrows())
2082        .unwrap_or(0);
2083    let mut values = Vec::with_capacity(n_frames * n_atoms * 3);
2084    let mut masses = Vec::with_capacity(n_frames * n_atoms);
2085    let mut cells = Vec::with_capacity(n_frames * 6);
2086    let mut atom_ids = Vec::with_capacity(n_frames * n_atoms);
2087    let mut fixed = Vec::with_capacity(n_frames * n_atoms);
2088    let mut runs = Vec::with_capacity(n_frames);
2089    let mut has_section = false;
2090    let mut partial_fixed = false;
2091    for frame in frames {
2092        cells.extend_from_slice(&frame.header.boxl);
2093        cells.extend_from_slice(&frame.header.angles);
2094        if let Some(src) = frame.positions.f64_slice() {
2095            values.extend_from_slice(src);
2096        } else {
2097            for row in 0..frame.positions.nrows() {
2098                values.extend_from_slice(&frame.positions.as_f64_row(row));
2099            }
2100        }
2101        for (type_index, &count) in frame.header.natms_per_type.iter().enumerate() {
2102            let mass = frame
2103                .header
2104                .masses_per_type
2105                .get(type_index)
2106                .copied()
2107                .unwrap_or(0.0);
2108            masses.extend(std::iter::repeat_n(mass, count));
2109        }
2110        has_section |= frame.has_velocities()
2111            || frame.has_forces()
2112            || frame.has_energies()
2113            || frame.has_charges()
2114            || frame.has_spins()
2115            || frame.has_magmoms()
2116            || frame.has_displacements()
2117            || frame.has_spreads();
2118        let mut frame_runs: Vec<(String, usize)> = Vec::new();
2119        for atom in &frame.atom_data {
2120            atom_ids.push(atom.atom_id);
2121            let mask = crate::types::encode_fixed_bitmask(atom.fixed());
2122            if mask != 0 && mask != 7 {
2123                partial_fixed = true;
2124            }
2125            fixed.push(mask);
2126            if let Some((symbol, count)) = frame_runs.last_mut()
2127                && symbol == atom.symbol.as_ref()
2128            {
2129                *count += 1;
2130                continue;
2131            }
2132            frame_runs.push((atom.symbol.to_string(), 1));
2133        }
2134        runs.push(frame_runs);
2135    }
2136    let species = if runs.windows(2).all(|pair| pair[0] == pair[1]) {
2137        runs.into_iter().take(1).collect()
2138    } else {
2139        runs
2140    };
2141    CoordColumns {
2142        block: PositionBlock {
2143            n_frames,
2144            n_atoms,
2145            values,
2146        },
2147        masses,
2148        cells,
2149        atom_ids,
2150        fixed,
2151        species,
2152        has_section,
2153        partial_fixed,
2154    }
2155}
2156
2157/// 1-based file line of the line that contains `byte`.
2158fn file_line_at_bytes(bytes: &[u8], byte: usize) -> u32 {
2159    let end = byte.min(bytes.len());
2160    1 + memchr::memchr_iter(b'\n', &bytes[..end]).count() as u32
2161}
2162
2163/// File line of a cursor that counted from the start of a share.
2164///
2165/// `local` is 1-based inside the share. A cursor that never moved still
2166/// names the share's first line.
2167fn share_cursor(local: u32, bytes: &[u8], share_start: usize) -> u32 {
2168    let base = file_line_at_bytes(bytes, share_start);
2169    if local == 0 {
2170        base
2171    } else {
2172        base.saturating_add(local.saturating_sub(1))
2173    }
2174}
2175
2176fn frame_starts(bytes: &[u8]) -> Result<Vec<usize>, error::LocatedParseError> {
2177    let mut scanner = ConFrameIterator::from_bytes(bytes);
2178    let mut boundaries = Vec::new();
2179    loop {
2180        scanner.lines.clear_peek();
2181        let start = scanner.lines.pos;
2182        if no_frame_at(bytes, start) {
2183            break;
2184        }
2185        boundaries.push(start);
2186        match scanner.forward_fast() {
2187            // A skip error is not the verdict. The start stays, and the
2188            // span parser reads the frame.
2189            Some(Ok(())) => {}
2190            Some(Err(_)) | None => break,
2191        }
2192    }
2193    Ok(boundaries)
2194}
2195
2196/// Parse one span. The error keeps this frame's file line.
2197fn parse_span_located(
2198    bytes: &[u8],
2199    start: usize,
2200    end: usize,
2201    frame_index: u64,
2202) -> Result<types::ConFrame, error::LocatedParseError> {
2203    let mut iter = ConFrameIterator::from_bytes(&bytes[start..end]);
2204    match iter.next() {
2205        Some(Ok(frame)) => Ok(frame),
2206        Some(Err(err)) => {
2207            let line = iter.error_line(&err);
2208            Err(error::LocatedParseError::new(
2209                err,
2210                share_cursor(line, bytes, start),
2211                frame_index,
2212            ))
2213        }
2214        None => Err(error::LocatedParseError::new(
2215            error::ParseError::IncompleteFrame,
2216            file_line_at_bytes(bytes, start),
2217            frame_index,
2218        )),
2219    }
2220}
2221
2222fn copy_positions(frame: &types::ConFrame, dest: &mut [f64]) -> Result<(), error::ParseError> {
2223    if frame.positions.nrows().saturating_mul(3) != dest.len() {
2224        return Err(error::ParseError::InvalidCount(
2225            "frame atom count does not match the first frame".into(),
2226        ));
2227    }
2228    if let Some(src) = frame.positions.f64_slice() {
2229        dest.copy_from_slice(src);
2230        return Ok(());
2231    }
2232    for (i, slot) in dest.as_chunks_mut::<3>().0.iter_mut().enumerate() {
2233        slot.copy_from_slice(&frame.positions.as_f64_row(i));
2234    }
2235    Ok(())
2236}
2237
2238fn fill_position_block(
2239    bytes: &[u8],
2240    num_threads: Option<usize>,
2241) -> Result<PositionBlock, error::LocatedParseError> {
2242    if persistent_ids_declared(bytes) {
2243        // The column walk never sees CON-id.11. The frame iterator does.
2244        let frames = frames_from_bytes_located(bytes, num_threads)?;
2245        return Ok(columns_from_frames(&frames).block);
2246    }
2247    match certified_columns(bytes, num_threads, false) {
2248        Ok(Some(columns)) => return Ok(columns.block),
2249        Ok(None) => {}
2250        Err(err) => return Err(err),
2251    }
2252    let boundaries = frame_starts(bytes)?;
2253    if boundaries.is_empty() {
2254        return Ok(PositionBlock {
2255            n_frames: 0,
2256            n_atoms: 0,
2257            values: Vec::new(),
2258        });
2259    }
2260    let end0 = boundaries.get(1).copied().unwrap_or(bytes.len());
2261    let first = parse_span_located(bytes, boundaries[0], end0, 0)?;
2262    let n_atoms = first.positions.nrows();
2263    let n_frames = boundaries.len();
2264    let stride = n_atoms.saturating_mul(3);
2265    let mut values = vec![0.0_f64; n_frames.saturating_mul(stride)];
2266    if stride == 0 {
2267        return Ok(PositionBlock {
2268            n_frames,
2269            n_atoms,
2270            values,
2271        });
2272    }
2273    fill_position_spans(bytes, &boundaries, n_atoms, num_threads, &mut values)?;
2274    Ok(PositionBlock {
2275        n_frames,
2276        n_atoms,
2277        values,
2278    })
2279}
2280
2281fn fill_position_spans(
2282    bytes: &[u8],
2283    boundaries: &[usize],
2284    n_atoms: usize,
2285    num_threads: Option<usize>,
2286    values: &mut [f64],
2287) -> Result<(), error::LocatedParseError> {
2288    let stride = n_atoms * 3;
2289    let write_one = |i: usize, dest: &mut [f64]| {
2290        let start = boundaries[i];
2291        let end = boundaries.get(i + 1).copied().unwrap_or(bytes.len());
2292        let frame = parse_span_located(bytes, start, end, i as u64)?;
2293        copy_positions(&frame, dest).map_err(|error| {
2294            error::LocatedParseError::new(error, file_line_at_bytes(bytes, start), i as u64)
2295        })
2296    };
2297    #[cfg(feature = "parallel")]
2298    {
2299        let parallel = !matches!(num_threads, Some(n) if n <= 1);
2300        if parallel {
2301            use rayon::prelude::*;
2302            // The serial walk reports the earliest failing span. A pool
2303            // that stops on the first finished failure can hand back a
2304            // later span of the same file. `find_map_first` keeps the
2305            // earliest slot and still stops spans to its right.
2306            let mut run = || match values
2307                .par_chunks_mut(stride)
2308                .enumerate()
2309                .find_map_first(|(i, dest)| write_one(i, dest).err())
2310            {
2311                Some(err) => Err(err),
2312                None => Ok(()),
2313            };
2314            return match num_threads {
2315                Some(n) if n >= 2 => {
2316                    let pool = rayon::ThreadPoolBuilder::new()
2317                        .num_threads(n)
2318                        .build()
2319                        .map_err(|err| {
2320                            error::LocatedParseError::new(
2321                                error::ParseError::ValidationError(err.to_string()),
2322                                0,
2323                                0,
2324                            )
2325                        })?;
2326                    pool.install(run)
2327                }
2328                _ => run(),
2329            };
2330        }
2331    }
2332    #[cfg(not(feature = "parallel"))]
2333    {
2334        let _ = num_threads;
2335    }
2336    for (i, dest) in values.chunks_mut(stride).enumerate() {
2337        write_one(i, dest)?;
2338    }
2339    Ok(())
2340}
2341
2342/// [`frames_from_text`] for bytes that may not be UTF-8 yet.
2343pub fn frames_from_bytes(
2344    bytes: &[u8],
2345    num_threads: Option<usize>,
2346) -> Result<Vec<types::ConFrame>, error::ParseError> {
2347    #[cfg(feature = "parallel")]
2348    {
2349        if let Some(n) = num_threads.filter(|n| *n >= 2) {
2350            let parts = parse_frames_parallel_bytes(bytes, Some(n));
2351            let mut frames = Vec::with_capacity(parts.len());
2352            for r in parts {
2353                frames.push(r?);
2354            }
2355            if crate::types::persistent_ids_requested(&frames) {
2356                return frames_from_bytes(bytes, Some(1));
2357            }
2358            return Ok(frames);
2359        }
2360    }
2361    #[cfg(not(feature = "parallel"))]
2362    {
2363        let _ = num_threads;
2364    }
2365    let mut frames = Vec::new();
2366    for r in ConFrameIterator::from_bytes(bytes) {
2367        frames.push(r?);
2368    }
2369    Ok(frames)
2370}
2371
2372/// [`frames_from_bytes`] that keeps the line and frame of the first error.
2373fn frames_from_bytes_located(
2374    bytes: &[u8],
2375    num_threads: Option<usize>,
2376) -> Result<Vec<types::ConFrame>, error::LocatedParseError> {
2377    #[cfg(feature = "parallel")]
2378    {
2379        if let Some(n) = num_threads.filter(|n| *n >= 2) {
2380            let timed = parse_bytes_timed(bytes, Some(n));
2381            let frames = collect_located_slots(timed.slots, &timed.fail_lines)?;
2382            if crate::types::persistent_ids_requested(&frames) {
2383                return frames_from_bytes_located(bytes, Some(1));
2384            }
2385            return Ok(frames);
2386        }
2387    }
2388    #[cfg(not(feature = "parallel"))]
2389    {
2390        let _ = num_threads;
2391    }
2392    collect_bytes_located(bytes)
2393}
2394
2395/// Serial byte parse. The cursor is the iterator's file line.
2396///
2397/// Species shells are built in this pass. Wrapping a finished column walk
2398/// in a second shell pass was slower on a million-atom frame, so
2399/// `read_positions` stays on the column walk and a full frame stays here.
2400fn collect_bytes_located(bytes: &[u8]) -> Result<Vec<types::ConFrame>, error::LocatedParseError> {
2401    let mut frames = Vec::new();
2402    let mut iter = ConFrameIterator::from_bytes(bytes);
2403    while let Some(item) = iter.next() {
2404        match item {
2405            Ok(frame) => frames.push(frame),
2406            Err(error) => {
2407                let line = iter.error_line(&error);
2408                return Err(error::LocatedParseError::new(
2409                    error,
2410                    line,
2411                    iter.frame_index(),
2412                ));
2413            }
2414        }
2415    }
2416    Ok(frames)
2417}
2418
2419/// First failed slot, with the file line its worker stored.
2420#[cfg(feature = "parallel")]
2421fn collect_located_slots(
2422    slots: Vec<Result<types::ConFrame, error::ParseError>>,
2423    fail_lines: &[(usize, u32)],
2424) -> Result<Vec<types::ConFrame>, error::LocatedParseError> {
2425    let mut frames = Vec::with_capacity(slots.len());
2426    for (index, part) in slots.into_iter().enumerate() {
2427        match part {
2428            Ok(frame) => frames.push(frame),
2429            Err(error) => {
2430                let line = fail_lines
2431                    .iter()
2432                    .find(|(slot, _)| *slot == index)
2433                    .map(|(_, line)| *line)
2434                    .unwrap_or(0);
2435                return Err(error::LocatedParseError::new(error, line, index as u64));
2436            }
2437        }
2438    }
2439    Ok(frames)
2440}
2441
2442#[cfg(feature = "parallel")]
2443fn span_end(boundaries: &[usize], index: usize, len: usize) -> usize {
2444    if index + 1 < boundaries.len() {
2445        boundaries[index + 1]
2446    } else {
2447        len
2448    }
2449}
2450
2451/// Pointer to slot storage shared by the workers that claim chunks.
2452///
2453/// Each claimed index is written by one thread, so the alias is the
2454/// partition. The pointer stays valid until those workers join.
2455#[cfg(feature = "parallel")]
2456#[derive(Copy, Clone)]
2457struct SlotWritePtr(*mut std::mem::MaybeUninit<Result<types::ConFrame, error::ParseError>>);
2458
2459#[cfg(feature = "parallel")]
2460impl SlotWritePtr {
2461    /// # Safety
2462    /// `index` is in range and this call is the only write of that slot.
2463    unsafe fn write_slot(self, index: usize, value: Result<types::ConFrame, error::ParseError>) {
2464        unsafe {
2465            (*self.0.add(index)).write(value);
2466        }
2467    }
2468}
2469
2470// SAFETY: `SlotWritePtr` is copied into the claim loop, and that loop
2471// writes each slot index from exactly one worker. The allocation
2472// outlives the join.
2473#[cfg(feature = "parallel")]
2474unsafe impl Send for SlotWritePtr {}
2475
2476// SAFETY: same partition as `Send`. Workers do not read a slot another
2477// worker is writing.
2478#[cfg(feature = "parallel")]
2479unsafe impl Sync for SlotWritePtr {}
2480
2481/// Minor faults of the calling thread.
2482///
2483/// `RUSAGE_THREAD` is Linux. Other hosts report 0; the counter is
2484/// diagnostic and the parse result does not depend on it.
2485#[cfg(feature = "parallel")]
2486fn thread_minflt() -> i64 {
2487    // Diagnostic. Miri has no `getrusage`; the parse does not use this count.
2488    #[cfg(all(target_os = "linux", not(miri)))]
2489    {
2490        unsafe {
2491            let mut usage = std::mem::zeroed::<libc::rusage>();
2492            libc::getrusage(libc::RUSAGE_THREAD, &mut usage);
2493            usage.ru_minflt
2494        }
2495    }
2496    #[cfg(not(all(target_os = "linux", not(miri))))]
2497    {
2498        0
2499    }
2500}
2501
2502/// Hardware LLC-miss counter for this process.
2503///
2504/// `-1` means the guest refused the event. This KVM guest returns
2505/// `EPERM` for `perf_event_open`, so the parse explanation uses the
2506/// per-worker minor faults instead.
2507#[cfg(feature = "parallel")]
2508fn sample_llc_misses() -> i64 {
2509    // `perf_event_open` is Linux. `-1` is the existing "counter refused" value.
2510    // Miri cannot make that syscall.
2511    #[cfg(not(all(target_os = "linux", not(miri))))]
2512    {
2513        return -1;
2514    }
2515    #[cfg(all(target_os = "linux", not(miri)))]
2516    {
2517        #[repr(C)]
2518        struct PerfEventAttr {
2519            typ: u32,
2520            size: u32,
2521            config: u64,
2522            rest: [u64; 14],
2523        }
2524        let attr = PerfEventAttr {
2525            typ: 3,
2526            size: std::mem::size_of::<PerfEventAttr>() as u32,
2527            // PERF_COUNT_HW_CACHE_LL, OP_READ, RESULT_MISS.
2528            config: 2 | (1 << 16),
2529            rest: [0; 14],
2530        };
2531        let fd = unsafe {
2532            libc::syscall(
2533                libc::SYS_perf_event_open,
2534                &attr as *const PerfEventAttr,
2535                0i32,
2536                -1i32,
2537                -1i32,
2538                0u64,
2539            )
2540        };
2541        if fd < 0 {
2542            return -1;
2543        }
2544        let fd = fd as libc::c_int;
2545        let mut value = 0u64;
2546        let n = unsafe { libc::read(fd, &mut value as *mut u64 as *mut libc::c_void, 8) };
2547        unsafe {
2548            libc::close(fd);
2549        }
2550        if n == 8 { value as i64 } else { -1 }
2551    }
2552}
2553
2554/// Pages that do not sit on node 0.
2555///
2556/// A guest with one memory node has no remote pages. The count is 0
2557/// in that case. A wider node list sums the pages `numa_maps` records
2558/// on every node other than 0.
2559#[cfg(feature = "parallel")]
2560fn numa_remote_pages() -> i64 {
2561    let online = std::fs::read_to_string("/sys/devices/system/node/online").unwrap_or_default();
2562    let online = online.trim();
2563    let nodes = if let Some((start, end)) = online.split_once('-') {
2564        let start: i64 = start.parse().unwrap_or(0);
2565        let end: i64 = end.parse().unwrap_or(0);
2566        end - start + 1
2567    } else {
2568        1
2569    };
2570    if nodes <= 1 {
2571        return 0;
2572    }
2573    let text = std::fs::read_to_string("/proc/self/numa_maps").unwrap_or_default();
2574    let mut remote = 0i64;
2575    for line in text.lines() {
2576        for token in line.split_whitespace() {
2577            if let Some(rest) = token.strip_prefix('N')
2578                && let Some((node, pages)) = rest.split_once('=')
2579                && node != "0"
2580            {
2581                remote += pages.parse::<i64>().unwrap_or(0);
2582            }
2583        }
2584    }
2585    remote
2586}
2587
2588/// True when `boundaries` is `0, span, 2*span, ...`.
2589#[cfg(feature = "parallel")]
2590fn equal_frame_stride(boundaries: &[usize]) -> bool {
2591    if boundaries.len() < 2 {
2592        return false;
2593    }
2594    let span = boundaries[1] - boundaries[0];
2595    if span == 0 || boundaries[0] != 0 {
2596        return false;
2597    }
2598    boundaries
2599        .iter()
2600        .enumerate()
2601        .all(|(index, start)| *start == index * span)
2602}
2603
2604/// One contiguous frame run per worker.
2605#[cfg(feature = "parallel")]
2606fn one_range_per_worker(n: usize, workers: usize) -> Vec<(usize, usize)> {
2607    let workers = workers.max(1).min(n.max(1));
2608    let mut ranges = Vec::with_capacity(workers);
2609    let mut start = 0usize;
2610    for worker in 0..workers {
2611        let end = if worker + 1 == workers {
2612            n
2613        } else {
2614            ((worker as u128 + 1) * (n as u128) / workers as u128) as usize
2615        };
2616        if end > start {
2617            ranges.push((start, end));
2618            start = end;
2619        }
2620    }
2621    ranges
2622}
2623
2624/// Contiguous frame ranges that cover `boundaries` and split the file
2625/// into similar byte lengths.
2626///
2627/// There are up to four ranges per worker, and never more ranges than
2628/// frames. Each range holds at least one frame. The cuts stay on frame
2629/// starts, so a worker parses a whole frame.
2630#[cfg(feature = "parallel")]
2631fn byte_balanced_ranges(boundaries: &[usize], len: usize, workers: usize) -> Vec<(usize, usize)> {
2632    let n = boundaries.len();
2633    if n == 0 {
2634        return Vec::new();
2635    }
2636    let workers = workers.max(1).min(n);
2637    let chunks = workers.saturating_mul(4).clamp(workers, n);
2638    let origin = boundaries[0];
2639    let total = len.saturating_sub(origin).max(1) as u128;
2640    let mut ranges = Vec::with_capacity(chunks);
2641    let mut start = 0usize;
2642    for chunk in 0..chunks {
2643        if start >= n {
2644            break;
2645        }
2646        let end = if chunk + 1 == chunks {
2647            n
2648        } else {
2649            let target = origin + ((total * (chunk as u128 + 1)) / chunks as u128) as usize;
2650            let mut idx = if start + 1 < n {
2651                boundaries[start + 1..].partition_point(|&b| b < target) + start + 1
2652            } else {
2653                n
2654            };
2655            let min_end = start + 1;
2656            let reserved = chunks - chunk - 1;
2657            let max_end = n.saturating_sub(reserved);
2658            if max_end >= min_end {
2659                idx = idx.clamp(min_end, max_end);
2660            } else {
2661                idx = min_end.min(n);
2662            }
2663            idx
2664        };
2665        if end > start {
2666            ranges.push((start, end));
2667            start = end;
2668        }
2669    }
2670    if start < n {
2671        match ranges.last_mut() {
2672            Some(last) => last.1 = n,
2673            None => ranges.push((start, n)),
2674        }
2675    }
2676    ranges
2677}
2678
2679/// Parse each frame into a slot allocated before any worker runs.
2680///
2681/// Workers claim chunk indexes from an atomic counter and write only
2682/// those slots. The returned vector is that slot storage, in boundary
2683/// order, which is the serial iterator order. `workers < 2` parses on
2684/// the calling thread.
2685#[cfg(feature = "parallel")]
2686fn parse_into_slots<F>(
2687    bytes: &[u8],
2688    len: usize,
2689    boundaries: &[usize],
2690    workers: usize,
2691    parse_span: F,
2692) -> Vec<Result<types::ConFrame, error::ParseError>>
2693where
2694    F: Fn(usize, usize) -> Result<types::ConFrame, error::ParseError> + Sync,
2695{
2696    parse_into_slots_timed(bytes, len, boundaries, workers, parse_span).slots
2697}
2698
2699/// Slot allocation and the worker parse, timed apart.
2700#[cfg(feature = "parallel")]
2701struct SlotParse {
2702    slots: Vec<Result<types::ConFrame, error::ParseError>>,
2703    alloc_s: f64,
2704    work_s: f64,
2705    sum_s: f64,
2706    max_s: f64,
2707    /// One entry per worker range, in worker order. This is CPU time.
2708    chunk_s: Vec<f64>,
2709    /// Minor faults on each worker during its range.
2710    worker_minflt: Vec<i64>,
2711    /// Frames in each worker's share.
2712    share_frames: Vec<u64>,
2713    /// File bytes in each worker's share.
2714    share_bytes: Vec<u64>,
2715    /// `(slot, file line)` for each parse that failed. The line is the
2716    /// cursor of that parse, not a later reread.
2717    fail_lines: Vec<(usize, u32)>,
2718}
2719
2720/// Slot allocation and the worker parse, timed apart.
2721///
2722/// `alloc_s` is the slot vector. `work_s` is the parse wall. `sum_s` is
2723/// the sum of per-chunk parse times and `max_s` is the slowest chunk.
2724/// `chunk_s` keeps every chunk. `workers < 2` still reserves the slot
2725/// vector before the calling thread fills it, and that one chunk's time
2726/// is the sum, the max, and the only entry.
2727#[cfg(feature = "parallel")]
2728fn parse_into_slots_timed<F>(
2729    bytes: &[u8],
2730    len: usize,
2731    boundaries: &[usize],
2732    workers: usize,
2733    parse_span: F,
2734) -> SlotParse
2735where
2736    F: Fn(usize, usize) -> Result<types::ConFrame, error::ParseError> + Sync,
2737{
2738    let n = boundaries.len();
2739    if n == 0 {
2740        return SlotParse {
2741            slots: Vec::new(),
2742            alloc_s: 0.0,
2743            work_s: 0.0,
2744            sum_s: 0.0,
2745            max_s: 0.0,
2746            chunk_s: Vec::new(),
2747            worker_minflt: Vec::new(),
2748            share_frames: Vec::new(),
2749            share_bytes: Vec::new(),
2750            fail_lines: Vec::new(),
2751        };
2752    }
2753    if workers < 2 {
2754        let t_alloc = std::time::Instant::now();
2755        let mut slots = Vec::with_capacity(n);
2756        let alloc_s = t_alloc.elapsed().as_secs_f64();
2757        let flt0 = thread_minflt();
2758        let t_work = std::time::Instant::now();
2759        for i in 0..n {
2760            slots.push(parse_span(boundaries[i], span_end(boundaries, i, len)));
2761        }
2762        let work_s = t_work.elapsed().as_secs_f64();
2763        let worker_minflt = vec![thread_minflt().saturating_sub(flt0)];
2764        return SlotParse {
2765            slots,
2766            alloc_s,
2767            work_s,
2768            sum_s: work_s,
2769            max_s: work_s,
2770            chunk_s: vec![work_s],
2771            worker_minflt,
2772            share_frames: vec![n as u64],
2773            share_bytes: vec![len as u64],
2774            fail_lines: Vec::new(),
2775        };
2776    }
2777    let t_alloc = std::time::Instant::now();
2778    let mut slots = take_slot_buf(n);
2779    let alloc_s = t_alloc.elapsed().as_secs_f64();
2780    // Equal frames are one range per worker. Each range prestashes its
2781    // coordinate shells and drops that stash at the end, so four ranges
2782    // on one worker allocate the same shells four times. Unequal frames
2783    // keep several byte-balanced ranges so a long frame can be stolen.
2784    let ranges = if equal_frame_stride(boundaries) {
2785        one_range_per_worker(n, workers)
2786    } else {
2787        byte_balanced_ranges(boundaries, len, workers)
2788    };
2789    let chunk_ns: Vec<std::sync::atomic::AtomicU64> = (0..ranges.len())
2790        .map(|_| std::sync::atomic::AtomicU64::new(0))
2791        .collect();
2792    let chunk_flt: Vec<std::sync::atomic::AtomicI64> = (0..ranges.len())
2793        .map(|_| std::sync::atomic::AtomicI64::new(0))
2794        .collect();
2795    let slots_ptr = SlotWritePtr(slots.as_mut_ptr());
2796    let fail_lines = std::sync::Mutex::new(Vec::<(usize, u32)>::new());
2797    let t_work = std::time::Instant::now();
2798    {
2799        let parse_range = |range_index: usize, start: usize, end: usize| {
2800            if start >= end {
2801                return;
2802            }
2803            let flt0 = thread_minflt();
2804            let t_chunk = std::time::Instant::now();
2805            let byte_start = boundaries[start];
2806            let byte_end = span_end(boundaries, end - 1, len);
2807            let wide = end - start == 1 && byte_end.saturating_sub(byte_start) >= (256 << 10);
2808            if wide {
2809                crate::parser::set_wide_workers(workers);
2810            }
2811            let mut iter = ConFrameIterator::from_bytes(&bytes[byte_start..byte_end]);
2812            OWNED_RANGES.with(|ranges| {
2813                let generation = PARSE_GEN.load(std::sync::atomic::Ordering::Relaxed);
2814                let mut owned = ranges.borrow_mut();
2815                if owned.first().map(|(seen, _, _)| *seen) != Some(generation) {
2816                    owned.clear();
2817                }
2818                owned.push((generation, start, end));
2819            });
2820            let mut known_atoms = 0usize;
2821            let mut failed = false;
2822            for i in start..end {
2823                let frame = match iter.next() {
2824                    Some(Ok(frame)) => {
2825                        if known_atoms == 0 {
2826                            known_atoms = frame.atom_data.len();
2827                            let left = end - i - 1;
2828                            if known_atoms > 0 && left > 0 {
2829                                crate::parser::prestash_coord_shells(left, known_atoms);
2830                            }
2831                        }
2832                        Ok(frame)
2833                    }
2834                    Some(Err(error)) => {
2835                        failed = true;
2836                        let line = share_cursor(iter.error_line(&error), bytes, byte_start);
2837                        fail_lines.lock().expect("fail lines").push((i, line));
2838                        Err(error)
2839                    }
2840                    None => {
2841                        failed = true;
2842                        let line = share_cursor(iter.lines.line_no(), bytes, byte_start);
2843                        fail_lines.lock().expect("fail lines").push((i, line));
2844                        Err(error::ParseError::IncompleteFrame)
2845                    }
2846                };
2847                // SAFETY: this range owns `start..end`, so `i` has one
2848                // writer. `slots` outlives the join.
2849                unsafe {
2850                    slots_ptr.write_slot(i, frame);
2851                }
2852            }
2853            // The scan can swallow a later frame into this share. `next`
2854            // stops at the first frame, so a non-whitespace tail is that
2855            // frame and has to fail the share. A slot that already failed
2856            // keeps that error: the cursor is mid-frame.
2857            if !failed && !iter.lines.remainder_is_whitespace() {
2858                let i = end - 1;
2859                let error = match iter.next() {
2860                    Some(Err(error)) => error,
2861                    Some(Ok(_)) | None => {
2862                        iter.lines.prefer_utf8(error::ParseError::IncompleteFrame)
2863                    }
2864                };
2865                let line = share_cursor(iter.error_line(&error), bytes, byte_start);
2866                fail_lines.lock().expect("fail lines").push((i, line));
2867                unsafe {
2868                    slots_ptr.write_slot(i, Err(error));
2869                }
2870            }
2871            crate::parser::clear_coord_shells();
2872            if wide {
2873                crate::parser::set_wide_workers(1);
2874            }
2875            chunk_ns[range_index].store(
2876                t_chunk.elapsed().as_nanos() as u64,
2877                std::sync::atomic::Ordering::Relaxed,
2878            );
2879            chunk_flt[range_index].store(
2880                thread_minflt().saturating_sub(flt0),
2881                std::sync::atomic::Ordering::Relaxed,
2882            );
2883        };
2884        let run_ranges = || {
2885            use rayon::prelude::*;
2886            ranges
2887                .par_iter()
2888                .enumerate()
2889                .for_each(|(range_index, &(start, end))| {
2890                    parse_range(range_index, start, end);
2891                });
2892        };
2893        if rayon::current_thread_index().is_some() {
2894            run_ranges();
2895        } else {
2896            match rayon::ThreadPoolBuilder::new().num_threads(workers).build() {
2897                Ok(pool) => pool.install(run_ranges),
2898                Err(_) => {
2899                    for (range_index, &(start, end)) in ranges.iter().enumerate() {
2900                        parse_range(range_index, start, end);
2901                    }
2902                }
2903            }
2904        }
2905    }
2906    let work_s = t_work.elapsed().as_secs_f64();
2907    let mut worker_sum_s = 0.0_f64;
2908    let mut worker_max_s = 0.0_f64;
2909    let mut chunk_s = Vec::new();
2910    let mut worker_minflt = Vec::new();
2911    let mut share_frames = Vec::new();
2912    let mut share_bytes = Vec::new();
2913    for (range_index, &(start, end)) in ranges.iter().enumerate() {
2914        if start >= end {
2915            continue;
2916        }
2917        let seconds =
2918            chunk_ns[range_index].load(std::sync::atomic::Ordering::Relaxed) as f64 / 1.0e9;
2919        chunk_s.push(seconds);
2920        worker_sum_s += seconds;
2921        worker_max_s = worker_max_s.max(seconds);
2922        worker_minflt.push(chunk_flt[range_index].load(std::sync::atomic::Ordering::Relaxed));
2923        share_frames.push((end - start) as u64);
2924        let nbytes = span_end(boundaries, end - 1, len).saturating_sub(boundaries[start]);
2925        share_bytes.push(nbytes as u64);
2926    }
2927    // Each index was written once. Reinterpreting the buffer avoids a
2928    // second serial walk of the frame shells after the workers join.
2929    let slots = unsafe {
2930        let mut raw = std::mem::ManuallyDrop::new(slots);
2931        Vec::from_raw_parts(
2932            raw.as_mut_ptr() as *mut Result<types::ConFrame, error::ParseError>,
2933            n,
2934            raw.capacity(),
2935        )
2936    };
2937    let fail_lines = fail_lines.into_inner().unwrap_or_default();
2938    SlotParse {
2939        slots,
2940        alloc_s,
2941        work_s,
2942        sum_s: worker_sum_s,
2943        max_s: worker_max_s,
2944        chunk_s,
2945        worker_minflt,
2946        share_frames,
2947        share_bytes,
2948        fail_lines,
2949    }
2950}
2951
2952#[cfg(feature = "parallel")]
2953fn parse_byte_span(
2954    bytes: &[u8],
2955    start: usize,
2956    end: usize,
2957) -> Result<types::ConFrame, error::ParseError> {
2958    let mut iter = ConFrameIterator::from_bytes(&bytes[start..end]);
2959    match iter.next() {
2960        Some(result) => result,
2961        None => Err(error::ParseError::IncompleteFrame),
2962    }
2963}
2964
2965#[cfg(feature = "parallel")]
2966fn parse_text_span(
2967    text: &str,
2968    start: usize,
2969    end: usize,
2970) -> Result<types::ConFrame, error::ParseError> {
2971    let mut iter = ConFrameIterator::new(&text[start..end]);
2972    match iter.next() {
2973        Some(result) => result,
2974        None => Err(error::ParseError::IncompleteFrame),
2975    }
2976}
2977
2978#[cfg(feature = "parallel")]
2979struct TimedParse {
2980    slots: Vec<Result<types::ConFrame, error::ParseError>>,
2981    /// Still alive so later phases of this read use the same workers.
2982    /// `None` when the call stayed on the calling thread.
2983    pool: Option<std::sync::Arc<rayon::ThreadPool>>,
2984    pool_s: f64,
2985    /// Zero here. The owner times the drop of its `pool` handle.
2986    pool_join_s: f64,
2987    scan_s: f64,
2988    scan_minflt: i64,
2989    slot_alloc_s: f64,
2990    worker_parse_s: f64,
2991    worker_sum_s: f64,
2992    worker_max_s: f64,
2993    chunk_s: Vec<f64>,
2994    worker_minflt: Vec<i64>,
2995    share_frames: Vec<u64>,
2996    share_bytes: Vec<u64>,
2997    /// `(slot, file line)` recorded by the worker that failed.
2998    fail_lines: Vec<(usize, u32)>,
2999    llc_misses: i64,
3000    numa_remote: i64,
3001    /// [`SCAN_SERIAL`], [`SCAN_INDEXED`], or [`SCAN_EQUAL_SPAN`].
3002    scan_kind: u8,
3003}
3004
3005/// Keep freed parse pages in the heap.
3006///
3007/// Eight workers otherwise return those pages to the kernel, and the
3008/// next file faults them again. One worker already keeps a smaller set.
3009/// The same policy on every width leaves the parse fault count flat.
3010#[cfg(feature = "parallel")]
3011fn keep_parse_pages() {
3012    // glibc `M_MMAP_MAX` and `M_TRIM_THRESHOLD`. macOS and Windows have
3013    // no `mallopt`; leaving the pages to the system allocator is enough
3014    // for the parse to be correct.
3015    #[cfg(all(target_os = "linux", not(miri)))]
3016    unsafe {
3017        libc::mallopt(-4, 0);
3018        libc::mallopt(-1, i32::MAX);
3019    }
3020}
3021
3022/// Slot storage kept between parses.
3023///
3024/// Eight workers write one `ConFrame` shell per frame into this buffer.
3025/// A fresh buffer is a new mapping, and those writes are the repeating
3026/// minor faults. The next parse reuses the same pages.
3027#[cfg(feature = "parallel")]
3028type SlotResult = std::mem::MaybeUninit<Result<types::ConFrame, error::ParseError>>;
3029
3030#[cfg(feature = "parallel")]
3031type SlotCache = std::sync::Mutex<Vec<SlotResult>>;
3032
3033#[cfg(feature = "parallel")]
3034fn take_slot_buf(n: usize) -> Vec<SlotResult> {
3035    let mut buf = slot_cache()
3036        .lock()
3037        .map(|mut slot| std::mem::take(&mut *slot))
3038        .unwrap_or_default();
3039    if buf.capacity() < n {
3040        buf = Vec::with_capacity(n);
3041    }
3042    unsafe { buf.set_len(n) };
3043    buf
3044}
3045
3046#[cfg(feature = "parallel")]
3047fn slot_cache() -> &'static SlotCache {
3048    static CACHE: crate::parser::PerProcess<SlotCache> = crate::parser::PerProcess::new();
3049    CACHE.get_or_init(|| std::sync::Mutex::new(Vec::new()))
3050}
3051
3052#[cfg(feature = "parallel")]
3053thread_local! {
3054    static OWNED_RANGES: std::cell::RefCell<Vec<(usize, usize, usize)>> =
3055        const { std::cell::RefCell::new(Vec::new()) };
3056}
3057
3058/// Bumped at the start of each parallel parse. Workers record it with
3059/// their frame ranges. Releasing frames only frees ranges from this
3060/// generation, so a parse does not have to wake every pool thread first.
3061#[cfg(feature = "parallel")]
3062static PARSE_GEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1);
3063
3064/// Drop `frames` on the threads that allocated them.
3065///
3066/// A parallel parse hands each worker a contiguous range. Freeing those
3067/// frames on the same workers keeps the pages in that worker's heap for
3068/// the next file. `workers < 2` drops on the calling thread.
3069pub fn release_parsed_frames(frames: Vec<types::ConFrame>, workers: usize) {
3070    #[cfg(feature = "parallel")]
3071    {
3072        if workers >= 2 {
3073            if let Some(pool) = shared_pool(workers) {
3074                let mut slots: Vec<Option<types::ConFrame>> =
3075                    frames.into_iter().map(Some).collect();
3076                let ptr = slots.as_mut_ptr() as usize;
3077                let len = slots.len();
3078                let generation = PARSE_GEN.load(std::sync::atomic::Ordering::Relaxed);
3079                pool.broadcast(|_| {
3080                    let ranges =
3081                        OWNED_RANGES.with(|ranges| std::mem::take(&mut *ranges.borrow_mut()));
3082                    for (seen, start, end) in ranges {
3083                        if seen != generation {
3084                            continue;
3085                        }
3086                        let end = end.min(len);
3087                        let start = start.min(end);
3088                        for index in start..end {
3089                            unsafe {
3090                                drop((*((ptr as *mut Option<types::ConFrame>).add(index))).take());
3091                            }
3092                        }
3093                    }
3094                });
3095                drop(slots);
3096                return;
3097            }
3098        }
3099    }
3100    let _ = workers;
3101    drop(frames);
3102}
3103
3104#[cfg(all(feature = "parallel", test, loom))]
3105use loom::sync::{Condvar as GateCondvar, Mutex as GateMutex};
3106#[cfg(all(feature = "parallel", not(all(test, loom))))]
3107use std::sync::{Condvar as GateCondvar, Mutex as GateMutex};
3108
3109/// Counts the workers of a new pool that have started.
3110///
3111/// Every worker calls [`StartGate::arrive`] once. The builder blocks in
3112/// [`StartGate::wait_for`] until all of them have. In the lib tests under
3113/// `--cfg loom` the lock and the condition variable are loom's, so the
3114/// handshake can be model-checked; see `start_gate_loom`.
3115#[cfg(feature = "parallel")]
3116struct StartGate {
3117    started: GateMutex<usize>,
3118    ready: GateCondvar,
3119}
3120
3121#[cfg(feature = "parallel")]
3122impl StartGate {
3123    fn new() -> Self {
3124        Self {
3125            started: GateMutex::new(0),
3126            ready: GateCondvar::new(),
3127        }
3128    }
3129
3130    fn arrive(&self) {
3131        // The count changes under the lock the waiter checks it under, so
3132        // the notify cannot fall between its check and its wait.
3133        *self.started.lock().unwrap_or_else(|err| err.into_inner()) += 1;
3134        self.ready.notify_one();
3135    }
3136
3137    fn wait_for(&self, workers: usize) {
3138        let mut started = self.started.lock().unwrap_or_else(|err| err.into_inner());
3139        while *started < workers {
3140            started = self
3141                .ready
3142                .wait(started)
3143                .unwrap_or_else(|err| err.into_inner());
3144        }
3145    }
3146}
3147
3148/// `RUSTFLAGS="--cfg loom" cargo test --release --features parallel --lib start_gate_loom`
3149///
3150/// Only these tests run under `--cfg loom`. The real pools would use the
3151/// loom gate outside a model.
3152#[cfg(all(test, loom, feature = "parallel"))]
3153mod start_gate_loom {
3154    use super::StartGate;
3155    use loom::sync::Arc;
3156
3157    /// In every interleaving the builder gets past the gate, and only
3158    /// after both workers have arrived. Loom fails a model that deadlocks.
3159    #[test]
3160    fn the_builder_returns_after_every_worker_arrives() {
3161        loom::model(|| {
3162            let gate = Arc::new(StartGate::new());
3163            let workers: Vec<_> = (0..2)
3164                .map(|_| {
3165                    let gate = Arc::clone(&gate);
3166                    loom::thread::spawn(move || gate.arrive())
3167                })
3168                .collect();
3169            gate.wait_for(2);
3170            assert_eq!(*gate.started.lock().unwrap(), 2);
3171            for worker in workers {
3172                worker.join().unwrap();
3173            }
3174        });
3175    }
3176}
3177
3178/// One pool per worker count, kept for the life of the process.
3179///
3180/// A fresh pool on every file made each worker fault its frames again.
3181/// Reusing the workers lets the allocator hand back the pages just freed.
3182///
3183/// The pools are never dropped, so their workers are never joined. They
3184/// park between jobs and end with the process. Rayon has no way to wait
3185/// for a pool's workers to exit; dropping a `ThreadPool` only tells them
3186/// to. A forked child builds its own pools; see
3187/// [`crate::parser::PerProcess`].
3188///
3189/// A new pool is returned once every worker has started. Until then the
3190/// only owner of a worker's thread handle is std's start box on the
3191/// global allocator, which LeakSanitizer does not scan, so a process
3192/// that exited first reported the handle as leaked.
3193#[cfg(feature = "parallel")]
3194#[allow(clippy::type_complexity)]
3195fn shared_pool(workers: usize) -> Option<std::sync::Arc<rayon::ThreadPool>> {
3196    use std::sync::{Arc, Mutex};
3197    static CACHE: crate::parser::PerProcess<Mutex<Vec<(usize, Arc<rayon::ThreadPool>)>>> =
3198        crate::parser::PerProcess::new();
3199    let mut guard = CACHE.get_or_init(|| Mutex::new(Vec::new())).lock().ok()?;
3200    if let Some((_, pool)) = guard.iter().find(|(count, _)| *count == workers) {
3201        return Some(Arc::clone(pool));
3202    }
3203    keep_parse_pages();
3204    let gate = Arc::new(StartGate::new());
3205    let signal = Arc::clone(&gate);
3206    let pool = Arc::new(
3207        rayon::ThreadPoolBuilder::new()
3208            .num_threads(workers)
3209            .start_handler(move |_| signal.arrive())
3210            .build()
3211            .ok()?,
3212    );
3213    gate.wait_for(pool.current_num_threads());
3214    guard.push((workers, Arc::clone(&pool)));
3215    Some(pool)
3216}
3217
3218/// Minor faults of this process.
3219///
3220/// `getrusage` is Unix. Windows reports 0.
3221#[cfg(feature = "parallel")]
3222pub fn process_minflt() -> i64 {
3223    // Diagnostic. Miri has no `getrusage`; the parse does not use this count.
3224    #[cfg(all(unix, not(miri)))]
3225    {
3226        unsafe {
3227            let mut usage = std::mem::zeroed::<libc::rusage>();
3228            libc::getrusage(libc::RUSAGE_SELF, &mut usage);
3229            usage.ru_minflt
3230        }
3231    }
3232    #[cfg(not(all(unix, not(miri))))]
3233    {
3234        0
3235    }
3236}
3237
3238/// Page size from `sysconf`, with the POSIX page as the fallback.
3239#[cfg(feature = "parallel")]
3240fn host_page_size() -> usize {
3241    #[cfg(all(unix, not(miri)))]
3242    {
3243        let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
3244        if raw > 0 { raw as usize } else { 4096 }
3245    }
3246    #[cfg(not(all(unix, not(miri))))]
3247    {
3248        4096
3249    }
3250}
3251
3252/// Fault one word on each page of `values`.
3253///
3254/// The page count is split by the worker count. The step is the host
3255/// page, so the slice a worker faults is its own. No extra chunk size.
3256#[cfg(feature = "parallel")]
3257fn first_touch_f64(values: &mut [f64], workers: usize) {
3258    use rayon::prelude::*;
3259    if values.is_empty() || workers < 2 {
3260        return;
3261    }
3262    let page = host_page_size().max(std::mem::size_of::<f64>());
3263    let step = (page / std::mem::size_of::<f64>()).max(1);
3264    let pages = values.len().div_ceil(step);
3265    let share = pages.div_ceil(workers);
3266    if rayon::current_thread_index().is_some() {
3267        // One chunk per page. The installed pool hands each page to one
3268        // worker, so that worker faults its own slice.
3269        values.par_chunks_mut(step).for_each(|chunk| {
3270            if let Some(slot) = chunk.first_mut() {
3271                *slot = 0.0;
3272            }
3273        });
3274        return;
3275    }
3276    std::thread::scope(|scope| {
3277        let mut rest = values;
3278        for worker in 0..workers {
3279            if rest.is_empty() {
3280                break;
3281            }
3282            let pages_here = share.min(rest.len().div_ceil(step));
3283            let take = (pages_here * step).min(rest.len());
3284            let (head, tail) = rest.split_at_mut(take);
3285            rest = tail;
3286            let _ = worker;
3287            scope.spawn(move || {
3288                let mut at = 0;
3289                while at < head.len() {
3290                    head[at] = 0.0;
3291                    at += step;
3292                }
3293            });
3294        }
3295    });
3296}
3297
3298/// Move every `Ok` frame on the read's pool.
3299///
3300/// A serial walk of the slot vector grows with the frame count. The
3301/// pool that parsed the frames does this move. One thread still walks
3302/// the slots when that pool is absent.
3303#[cfg(feature = "parallel")]
3304fn finish_results(
3305    pool: Option<&rayon::ThreadPool>,
3306    slots: Vec<Result<types::ConFrame, error::ParseError>>,
3307) -> Result<Vec<types::ConFrame>, error::ParseError> {
3308    if slots.len() < 2 || pool.is_none() {
3309        let mut frames = Vec::with_capacity(slots.len());
3310        for part in slots {
3311            frames.push(part?);
3312        }
3313        return Ok(frames);
3314    }
3315    let pool = pool.expect("pool");
3316    pool.install(|| {
3317        use rayon::prelude::*;
3318        if let Some(index) = slots.par_iter().position_first(|item| item.is_err()) {
3319            return Err(match slots.into_iter().nth(index) {
3320                Some(Err(err)) => err,
3321                _ => error::ParseError::IncompleteFrame,
3322            });
3323        }
3324        Ok(slots
3325            .into_par_iter()
3326            .map(|item| item.expect("ok"))
3327            .collect())
3328    })
3329}
3330
3331/// Header walk on the calling thread.
3332pub const SCAN_SERIAL: u8 = 0;
3333/// Newline index in chunks, then a header walk on the calling thread.
3334///
3335/// Frames that do not share one byte length take this path. The newline
3336/// bytes are split across the pool. The header walk is not, because a
3337/// later frame start is the end of the skip, and that end is not known
3338/// until the skip runs.
3339pub const SCAN_INDEXED: u8 = 1;
3340/// Equal-length frames. Each worker boundary is checked.
3341pub const SCAN_EQUAL_SPAN: u8 = 2;
3342
3343/// Frame starts when every frame occupies the same number of bytes.
3344///
3345/// The first frame sets the span. Each worker boundary is skipped on
3346/// its own slice. A span that does not tile the
3347/// buffer, or a skip that does not land on the next span, returns
3348/// `None` and the caller keeps the serial walk. The starts are
3349/// `0, span, 2*span, ...` and match [`collect_frame_starts`].
3350#[cfg(feature = "parallel")]
3351#[cfg_attr(not(test), allow(dead_code))]
3352fn equal_span_boundaries(bytes: &[u8], workers: usize) -> Option<Vec<usize>> {
3353    if workers < 2 || bytes.len() < 2 {
3354        return None;
3355    }
3356    let mut first = ConFrameIterator::from_bytes(bytes);
3357    match first.forward_fast() {
3358        Some(Ok(())) => {}
3359        _ => return None,
3360    }
3361    let span = first.lines.pos;
3362    if span < 2 {
3363        return None;
3364    }
3365    let n = bytes.len() / span;
3366    if n < 2 {
3367        return None;
3368    }
3369    // Bytes after the last full span are a tail, not another frame.
3370    // The serial walk ignores a whitespace tail.
3371    let tiled = n * span;
3372    if bytes[tiled..].iter().any(|b| !b.is_ascii_whitespace()) {
3373        return None;
3374    }
3375    // Equal byte ranges. A cut that falls inside a frame resyncs to the
3376    // next frame start, and only that header is checked. The checks stay
3377    // on this worker: a nested pool wake was larger than the checks.
3378    let byte_share = tiled.div_ceil(workers);
3379    for worker in 0..workers {
3380        let byte_cut = worker.saturating_mul(byte_share).min(tiled);
3381        if byte_cut >= tiled {
3382            continue;
3383        }
3384        let index = if worker == 0 {
3385            0
3386        } else {
3387            byte_cut.div_ceil(span).min(n - 1)
3388        };
3389        let start = index.saturating_mul(span);
3390        if start >= tiled {
3391            continue;
3392        }
3393        let end = (start + span).min(tiled);
3394        let mut iter = ConFrameIterator::from_bytes(&bytes[start..end]);
3395        match iter.forward_fast() {
3396            Some(Ok(())) if iter.lines.pos == end - start => {}
3397            _ => return None,
3398        }
3399    }
3400    Some(arithmetic_starts(span, n))
3401}
3402
3403/// Starts `0, span, 2*span, ...` from a buffer kept between files.
3404///
3405/// Building that buffer from a fresh allocation stalled for milliseconds
3406/// after a large free. The next file fills the same pages.
3407#[cfg(feature = "parallel")]
3408fn start_cache() -> &'static std::sync::Mutex<Vec<usize>> {
3409    static CACHE: crate::parser::PerProcess<std::sync::Mutex<Vec<usize>>> =
3410        crate::parser::PerProcess::new();
3411    CACHE.get_or_init(|| std::sync::Mutex::new(Vec::new()))
3412}
3413
3414#[cfg(feature = "parallel")]
3415#[cfg_attr(not(test), allow(dead_code))]
3416fn arithmetic_starts(span: usize, n: usize) -> Vec<usize> {
3417    let mut starts = start_cache()
3418        .lock()
3419        .map(|mut slot| std::mem::take(&mut *slot))
3420        .unwrap_or_default();
3421    if starts.len() != n {
3422        starts.resize(n, 0);
3423    }
3424    for (index, slot) in starts.iter_mut().enumerate() {
3425        *slot = index * span;
3426    }
3427    starts
3428}
3429
3430#[cfg(feature = "parallel")]
3431fn recycle_starts(starts: Vec<usize>) {
3432    if let Ok(mut slot) = start_cache().lock()
3433        && starts.capacity() >= slot.capacity()
3434    {
3435        *slot = starts;
3436    }
3437}
3438
3439#[cfg(feature = "parallel")]
3440fn parse_frames_parallel_bytes(
3441    bytes: &[u8],
3442    num_threads: Option<usize>,
3443) -> Vec<Result<types::ConFrame, error::ParseError>> {
3444    parse_bytes_timed(bytes, num_threads).slots
3445}
3446
3447/// Frame starts for a pool of `workers`.
3448///
3449/// Equal byte spans stay arithmetic. Anything else builds the newline
3450/// index on the pool and walks headers by line count, so the walk does
3451/// not reread atom rows. One worker keeps the serial byte walk.
3452#[cfg(feature = "parallel")]
3453fn parallel_boundaries(bytes: &[u8], workers: usize) -> (Vec<usize>, u8) {
3454    if workers >= 2 {
3455        if let Some(bounds) = equal_span_boundaries(bytes, workers) {
3456            return (bounds, SCAN_EQUAL_SPAN);
3457        }
3458        let newlines = newline_positions(bytes, workers);
3459        let mut scanner = ConFrameIterator::from_bytes(bytes);
3460        scanner.lines.index_line = 0;
3461        scanner.lines.newlines = Some(newlines);
3462        return (collect_frame_starts(scanner, true), SCAN_INDEXED);
3463    }
3464    (
3465        collect_frame_starts(ConFrameIterator::from_bytes(bytes), true),
3466        SCAN_SERIAL,
3467    )
3468}
3469
3470/// Scan, slot allocation, and worker parse of `bytes`.
3471///
3472/// `Some(n)` with `n >= 2` uses a pool of that size. Every other count
3473/// stays on the calling thread. `None` follows [`scan_thread_count`].
3474/// The pool lookup or build is `pool_s`. `pool_join_s` is zero, and the
3475/// caller that drops the pool handle times that drop. Neither one is
3476/// inside the scan or the parse.
3477#[cfg(feature = "parallel")]
3478fn parse_bytes_timed(bytes: &[u8], num_threads: Option<usize>) -> TimedParse {
3479    let parse_workers = match num_threads {
3480        Some(n) if n >= 2 => n,
3481        _ => 1,
3482    };
3483    let run = || {
3484        let fault0 = process_minflt();
3485        let t_scan = std::time::Instant::now();
3486        // Equal-length frames skip the serial header walk. Anything else
3487        // still walks headers on this thread. Workers then parse the
3488        // spans in file order.
3489        let (boundaries, scan_kind) = parallel_boundaries(bytes, parse_workers);
3490        let scan_s = t_scan.elapsed().as_secs_f64();
3491        let scan_minflt = process_minflt().saturating_sub(fault0);
3492        let parsed = parse_into_slots_timed(
3493            bytes,
3494            bytes.len(),
3495            &boundaries,
3496            parse_workers,
3497            |start, end| parse_byte_span(bytes, start, end),
3498        );
3499        recycle_starts(boundaries);
3500        (parsed, scan_s, scan_kind, scan_minflt)
3501    };
3502    let (pool_s, pool, packed) = match num_threads {
3503        None => (0.0, None, run()),
3504        Some(n) if n <= 1 => {
3505            let _ = n;
3506            keep_parse_pages();
3507            let fault0 = process_minflt();
3508            let t_scan = std::time::Instant::now();
3509            let boundaries = collect_frame_starts(ConFrameIterator::from_bytes(bytes), true);
3510            let scan_s = t_scan.elapsed().as_secs_f64();
3511            let scan_minflt = process_minflt().saturating_sub(fault0);
3512            let parsed =
3513                parse_into_slots_timed(bytes, bytes.len(), &boundaries, 1, |start, end| {
3514                    parse_byte_span(bytes, start, end)
3515                });
3516            (0.0, None, (parsed, scan_s, SCAN_SERIAL, scan_minflt))
3517        }
3518        Some(n) => {
3519            let t_pool = std::time::Instant::now();
3520            match shared_pool(n) {
3521                Some(pool) => {
3522                    let built = t_pool.elapsed().as_secs_f64();
3523                    PARSE_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3524                    let t_wake = std::time::Instant::now();
3525                    let (wake, body) = pool.install(|| {
3526                        let wake = t_wake.elapsed().as_secs_f64();
3527                        (wake, run())
3528                    });
3529                    // The same workers serve later files of this width.
3530                    // Their freed blocks stay warm for the next parse.
3531                    (built + wake, Some(pool), body)
3532                }
3533                None => (t_pool.elapsed().as_secs_f64(), None, run()),
3534            }
3535        }
3536    };
3537    let (parsed, scan_s, scan_kind, scan_minflt) = packed;
3538    TimedParse {
3539        slots: parsed.slots,
3540        pool,
3541        pool_s,
3542        pool_join_s: 0.0,
3543        scan_s,
3544        scan_minflt,
3545        slot_alloc_s: parsed.alloc_s,
3546        worker_parse_s: parsed.work_s,
3547        worker_sum_s: parsed.sum_s,
3548        worker_max_s: parsed.max_s,
3549        chunk_s: parsed.chunk_s,
3550        worker_minflt: parsed.worker_minflt,
3551        share_frames: parsed.share_frames,
3552        share_bytes: parsed.share_bytes,
3553        fail_lines: parsed.fail_lines,
3554        llc_misses: sample_llc_misses(),
3555        numa_remote: numa_remote_pages(),
3556        scan_kind,
3557    }
3558}
3559
3560/// Count frames by parsing them.
3561///
3562/// The count uses the same checks as a full read, so a file the reader
3563/// rejects is not reported as that many frames. A rejected frame is
3564/// [`LoadError::Parse`] with that frame's file line and 0-based index,
3565/// including when the failure is after the first frame.
3566pub fn count_frames(path: &Path) -> Result<usize, LoadError> {
3567    // The same parse as a full read. A header walk accepts files whose rows
3568    // the reader rejects, so the count and the read would disagree.
3569    let source = crate::compression::read_bytes_owned(path).map_err(load_error_from_box)?;
3570    let mut n = 0usize;
3571    let mut iter = ConFrameIterator::from_bytes(source.as_slice());
3572    loop {
3573        match iter.next() {
3574            Some(Ok(_)) => n += 1,
3575            Some(Err(e)) => {
3576                let line = iter.error_line(&e);
3577                return Err(LoadError::Parse(error::LocatedParseError::new(
3578                    e,
3579                    line,
3580                    iter.frame_index(),
3581                )));
3582            }
3583            None => break,
3584        }
3585    }
3586    Ok(n)
3587}
3588
3589/// Reads only the first frame from a file.
3590///
3591/// More efficient than `read_all_frames` for single-frame access because it
3592/// stops parsing after the first frame rather than collecting all of them.
3593///
3594/// ```
3595/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
3596/// use readcon_core::iterators::read_first_frame;
3597/// let frame = read_first_frame(std::path::Path::new("resources/test/tiny_cuh2.con"))?;
3598/// println!("{:?} {}", frame.header.boxl, frame.atom_data.len());
3599/// assert!(!frame.atom_data.is_empty());
3600/// # Ok(())
3601/// # }
3602/// ```
3603pub fn read_first_frame(path: &Path) -> Result<types::ConFrame, Box<dyn std::error::Error>> {
3604    let source = crate::compression::read_bytes_owned(path)?;
3605    let mut iter = ConFrameIterator::from_bytes(source.as_slice());
3606    match iter.next() {
3607        Some(Ok(frame)) => Ok(frame),
3608        Some(Err(e)) => {
3609            let line = iter.error_line(&e);
3610            Err(Box::new(error::LocatedParseError::new(e, line, 0)))
3611        }
3612        None => Err("No frames found in file".into()),
3613    }
3614}
3615
3616/// Skip `index` frames (no atom parse), then parse the next one.
3617///
3618/// `index == 0` is [`read_first_frame`]. Out of range is an error.
3619pub fn read_nth_frame(
3620    path: &Path,
3621    index: usize,
3622) -> Result<types::ConFrame, Box<dyn std::error::Error>> {
3623    let source = crate::compression::read_bytes_owned(path)?;
3624    let mut iter = ConFrameIterator::from_bytes(source.as_slice());
3625    let skipped = iter.skip_frames(index)?;
3626    if skipped < index {
3627        return Err(format!("frame {index} out of range (only {skipped} frames)").into());
3628    }
3629    match iter.next() {
3630        Some(Ok(frame)) => Ok(frame),
3631        Some(Err(e)) => {
3632            let line = iter.error_line(&e);
3633            Err(Box::new(error::LocatedParseError::new(
3634                e,
3635                line,
3636                index as u64,
3637            )))
3638        }
3639        None => Err(format!("frame {index} out of range").into()),
3640    }
3641}
3642
3643/// Same as [`read_nth_frame`] on an already-loaded buffer.
3644pub fn read_nth_frame_from_text(
3645    text: &str,
3646    index: usize,
3647) -> Result<types::ConFrame, Box<dyn std::error::Error>> {
3648    let mut iter = ConFrameIterator::new(text);
3649    let skipped = iter.skip_frames(index)?;
3650    if skipped < index {
3651        return Err(format!("frame {index} out of range (only {skipped} frames)").into());
3652    }
3653    match iter.next() {
3654        Some(Ok(frame)) => Ok(frame),
3655        Some(Err(e)) => Err(Box::new(e)),
3656        None => Err(format!("frame {index} out of range").into()),
3657    }
3658}
3659
3660/// Reads all frames using the checked `.rcidx` sidecar next to `path`.
3661///
3662/// Uncompressed input uses (and refreshes) `path.rcidx`; compressed
3663/// input is scanned in memory each time. UTF-8 is validated in
3664/// newline-aligned slices.
3665#[cfg(feature = "parallel")]
3666pub fn read_all_frames_indexed(
3667    path: &Path,
3668    num_threads: Option<usize>,
3669) -> Result<Vec<types::ConFrame>, Box<dyn std::error::Error>> {
3670    let contents = match crate::compression::read_file_contents(path) {
3671        Ok(contents) => contents,
3672        Err(err) => {
3673            // A whole-buffer UTF-8 rejection hides the line the parser
3674            // would name. The byte reader is the same verdict as a full read.
3675            let message = err.to_string();
3676            if message.contains("UTF-8") || message.contains("utf-8") {
3677                let source = crate::compression::read_bytes_owned(path)?;
3678                return Ok(frames_from_bytes_located(source.as_slice(), num_threads)?);
3679            }
3680            return Err(err);
3681        }
3682    };
3683    let read = || -> Result<Vec<types::ConFrame>, Box<dyn std::error::Error + Send + Sync>> {
3684        let text = contents.as_str_sliced()?;
3685        let idx = match contents {
3686            crate::compression::FileContents::Mapped(_) => {
3687                crate::frame_index::load_or_build(path, text, true)?
3688            }
3689            crate::compression::FileContents::Owned(_) => {
3690                let on_disk = std::fs::metadata(path)?.len();
3691                crate::frame_index::load_or_build(path, text, on_disk == text.len() as u64)?
3692            }
3693        };
3694        let offs: Vec<usize> = idx.offsets.iter().map(|&o| o as usize).collect();
3695        parse_frames_at_offsets(text, &offs, num_threads)
3696            .into_iter()
3697            .map(|r| r.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>))
3698            .collect()
3699    };
3700    // The UTF-8 check and the sidecar check use rayon. A threaded read runs
3701    // them on its own pool, because rayon's global pool has no workers in a
3702    // forked child.
3703    let frames = match num_threads {
3704        Some(n) if n >= 2 => match shared_pool(n) {
3705            Some(pool) => pool.install(read),
3706            None => read(),
3707        },
3708        _ => read(),
3709    };
3710    // The sidecar splits on text shape. A span that is not one frame, and a
3711    // file that links ids across frames, is read again with the same parser
3712    // as every other entry point.
3713    match frames {
3714        Ok(frames) if !crate::types::persistent_ids_requested(&frames) => Ok(frames),
3715        _ => {
3716            let source = crate::compression::read_bytes_owned(path)?;
3717            Ok(frames_from_bytes_located(source.as_slice(), num_threads)?)
3718        }
3719    }
3720}
3721
3722enum IndexStep {
3723    Stay(usize),
3724    Missing(usize),
3725    Landed(usize, usize),
3726    Short(usize, usize),
3727}
3728
3729struct IndexedSpan {
3730    start: usize,
3731    content_end: usize,
3732    next_pos: usize,
3733}
3734
3735/// Lines in `bytes`, counting a final line that has no `\n`.
3736fn line_count(nl: &[usize], len: usize) -> usize {
3737    if len == 0 {
3738        0
3739    } else if nl.last().copied() == Some(len - 1) {
3740        nl.len()
3741    } else {
3742        nl.len() + 1
3743    }
3744}
3745
3746fn line_start_pos(nl: &[usize], len: usize, line_no: usize) -> usize {
3747    if line_no == 0 {
3748        return 0;
3749    }
3750    if line_no >= line_count(nl, len) {
3751        return len;
3752    }
3753    nl[line_no - 1] + 1
3754}
3755
3756/// Line index of the line that contains `pos`, or the line count at `len`.
3757fn line_no_for_pos(nl: &[usize], len: usize, pos: usize) -> usize {
3758    if pos >= len {
3759        return line_count(nl, len);
3760    }
3761    nl.partition_point(|&p| p < pos)
3762}
3763
3764fn indexed_span(nl: &[usize], bytes: &[u8], line_no: usize) -> Option<IndexedSpan> {
3765    let len = bytes.len();
3766    if line_no >= line_count(nl, len) {
3767        return None;
3768    }
3769    let start = if line_no == 0 { 0 } else { nl[line_no - 1] + 1 };
3770    let (raw_end, next_pos) = if line_no < nl.len() {
3771        (nl[line_no], nl[line_no] + 1)
3772    } else {
3773        (len, len)
3774    };
3775    let mut content_end = raw_end;
3776    if content_end > start && bytes[content_end - 1] == b'\r' {
3777        content_end -= 1;
3778    }
3779    Some(IndexedSpan {
3780        start,
3781        content_end,
3782        next_pos,
3783    })
3784}
3785
3786/// `n` cuts covering `0..=len`. A cut may fall in the middle of a header line.
3787#[cfg(feature = "parallel")]
3788fn equal_cuts(len: usize, n: usize) -> Vec<usize> {
3789    let n = n.max(1);
3790    let mut cuts = Vec::with_capacity(n + 1);
3791    for i in 0..=n {
3792        let at = ((i as u128) * (len as u128) / (n as u128)) as usize;
3793        let at = at.min(len);
3794        if cuts.last().copied() != Some(at) {
3795            cuts.push(at);
3796        }
3797    }
3798    if cuts.last().copied() != Some(len) {
3799        cuts.push(len);
3800    }
3801    cuts
3802}
3803
3804/// Newline offsets in `bytes`.
3805///
3806/// `cuts` splits the buffer into `[cuts[i], cuts[i + 1])`. Each piece is
3807/// scanned on its own and the offsets are concatenated. A `\n` belongs to
3808/// the piece that contains that byte, so a header line whose body crosses
3809/// a cut still contributes one newline.
3810#[cfg(feature = "parallel")]
3811fn newline_positions_at_cuts(bytes: &[u8], cuts: &[usize]) -> Vec<usize> {
3812    let spans: Vec<(usize, usize)> = cuts
3813        .windows(2)
3814        .map(|w| (w[0].min(bytes.len()), w[1].min(bytes.len())))
3815        .filter(|(start, end)| start < end)
3816        .collect();
3817    if spans.len() <= 1 {
3818        let (start, end) = spans.first().copied().unwrap_or((0, 0));
3819        return memchr::memchr_iter(b'\n', &bytes[start..end])
3820            .map(|p| start + p)
3821            .collect();
3822    }
3823    // The current Rayon pool, or the global pool when the caller has not
3824    // installed one. Chunk count is the worker cap: two chunks do not
3825    // wake every core.
3826    use rayon::prelude::*;
3827    let parts: Vec<Vec<usize>> = spans
3828        .par_iter()
3829        .map(|&(start, end)| {
3830            memchr::memchr_iter(b'\n', &bytes[start..end])
3831                .map(|p| start + p)
3832                .collect()
3833        })
3834        .collect();
3835    let mut all = Vec::with_capacity(bytes.len() / 32);
3836    for part in parts {
3837        all.extend(part);
3838    }
3839    all
3840}
3841
3842#[cfg(feature = "parallel")]
3843fn newline_positions(bytes: &[u8], threads: usize) -> Vec<usize> {
3844    newline_positions_at_cuts(bytes, &equal_cuts(bytes.len(), threads))
3845}
3846
3847/// Worker count for a newline scan.
3848///
3849/// `Some(n)` with `n >= 2` uses that many workers at every file length.
3850/// A file shorter than two bytes has nothing to split, and [`equal_cuts`]
3851/// drops a cut that repeats the previous byte, so a short file does not
3852/// invent an empty chunk. `None`, `Some(0)`, and `Some(1)` stay on the
3853/// calling thread. An omitted count must not start the global pool:
3854/// that pool made a one-frame file slower. There is no byte-length
3855/// cutoff taken from one host.
3856#[cfg(feature = "parallel")]
3857fn scan_thread_count(num_threads: Option<usize>, len: usize) -> usize {
3858    let requested = match num_threads {
3859        Some(n) if n >= 2 => n,
3860        _ => return 1,
3861    };
3862    if len < 2 { 1 } else { requested }
3863}
3864
3865/// I/O, UTF-8, or a located parse failure while loading a path.
3866#[derive(Debug)]
3867pub enum LoadError {
3868    Io(std::io::Error),
3869    Utf8(std::str::Utf8Error),
3870    Parse(error::LocatedParseError),
3871    /// The path opened and decoded, and it held no frame.
3872    Empty,
3873}
3874
3875impl std::fmt::Display for LoadError {
3876    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3877        match self {
3878            LoadError::Io(e) => write!(f, "{e}"),
3879            LoadError::Utf8(e) => write!(f, "{e}"),
3880            LoadError::Parse(e) => write!(f, "{e}"),
3881            LoadError::Empty => write!(f, "no frames found in file"),
3882        }
3883    }
3884}
3885
3886impl std::error::Error for LoadError {}
3887
3888fn load_error_from_box(err: Box<dyn std::error::Error>) -> LoadError {
3889    if let Some(io) = err.downcast_ref::<std::io::Error>() {
3890        return LoadError::Io(std::io::Error::new(io.kind(), io.to_string()));
3891    }
3892    LoadError::Io(std::io::Error::other(err.to_string()))
3893}
3894
3895/// 1-based line number of the line that contains `byte`.
3896#[cfg(feature = "parallel")]
3897fn file_line_at(text: &str, byte: usize) -> u32 {
3898    let end = byte.min(text.len());
3899    1 + text.as_bytes()[..end]
3900        .iter()
3901        .filter(|&&b| b == b'\n')
3902        .count() as u32
3903}
3904
3905/// Collect every frame, keeping the line and frame index of the first error.
3906pub fn frames_from_text_located(
3907    text: &str,
3908    num_threads: Option<usize>,
3909) -> Result<Vec<types::ConFrame>, error::LocatedParseError> {
3910    #[cfg(feature = "parallel")]
3911    {
3912        // A caller that does not ask for a pool stays on this thread.
3913        // Starting the global pool for a long file made a one-frame read slower.
3914        let use_parallel = matches!(num_threads, Some(n) if n >= 2);
3915        if use_parallel {
3916            let pool = num_threads.filter(|&n| n >= 2);
3917            return collect_parallel_located(text, pool);
3918        }
3919    }
3920    #[cfg(not(feature = "parallel"))]
3921    {
3922        let _ = num_threads;
3923    }
3924    let mut frames = Vec::new();
3925    let mut iter = ConFrameIterator::new(text);
3926    let mut index = 0u64;
3927    while let Some(item) = iter.next() {
3928        match item {
3929            Ok(frame) => {
3930                frames.push(frame);
3931                index += 1;
3932            }
3933            Err(e) => {
3934                let line = iter.error_line(&e);
3935                return Err(error::LocatedParseError::new(e, line, index));
3936            }
3937        }
3938    }
3939    Ok(frames)
3940}
3941
3942/// Read every frame from `path`, with the line and frame index of the first error.
3943pub fn read_all_frames_located(
3944    path: &Path,
3945    num_threads: Option<usize>,
3946) -> Result<Vec<types::ConFrame>, LoadError> {
3947    if matches!(num_threads, Some(n) if n >= 2) {
3948        let source = crate::compression::read_bytes_owned(path).map_err(load_error_from_box)?;
3949        return frames_from_bytes_located(source.as_slice(), num_threads).map_err(LoadError::Parse);
3950    }
3951    stream_frames(path)
3952}
3953
3954/// Read the first frame from `path`, with a line number on failure.
3955pub fn read_first_frame_located(path: &Path) -> Result<types::ConFrame, LoadError> {
3956    let source = crate::compression::read_bytes_owned(path).map_err(load_error_from_box)?;
3957    let mut iter = ConFrameIterator::from_bytes(source.as_slice());
3958    match iter.next() {
3959        Some(Ok(frame)) => Ok(frame),
3960        Some(Err(e)) => {
3961            let line = iter.error_line(&e);
3962            Err(LoadError::Parse(error::LocatedParseError::new(e, line, 0)))
3963        }
3964        None => Err(LoadError::Empty),
3965    }
3966}
3967
3968/// Skip `index` frames, then parse one, with a line number on failure.
3969pub fn read_nth_frame_located(path: &Path, index: usize) -> Result<types::ConFrame, LoadError> {
3970    let source = crate::compression::read_bytes_owned(path).map_err(load_error_from_box)?;
3971    let mut iter = ConFrameIterator::from_bytes(source.as_slice());
3972    match iter.skip_frames_counted(index) {
3973        Ok(skipped) if skipped == index => {}
3974        Ok(skipped) => {
3975            return Err(LoadError::Parse(error::LocatedParseError::new(
3976                error::ParseError::IncompleteFrame,
3977                iter.lines.line_no(),
3978                skipped as u64,
3979            )));
3980        }
3981        Err((failed_at, e)) => {
3982            let line = iter.error_line(&e);
3983            return Err(LoadError::Parse(error::LocatedParseError::new(
3984                e,
3985                line,
3986                failed_at as u64,
3987            )));
3988        }
3989    }
3990    match iter.next() {
3991        Some(Ok(frame)) => Ok(frame),
3992        Some(Err(e)) => {
3993            let line = iter.error_line(&e);
3994            Err(LoadError::Parse(error::LocatedParseError::new(
3995                e,
3996                line,
3997                index as u64,
3998            )))
3999        }
4000        None => Err(LoadError::Parse(error::LocatedParseError::new(
4001            error::ParseError::IncompleteFrame,
4002            iter.lines.line_no(),
4003            index as u64,
4004        ))),
4005    }
4006}
4007
4008fn collect_frame_starts(scanner: ConFrameIterator<'_>, skip_whitespace_tail: bool) -> Vec<usize> {
4009    #[cfg(target_arch = "x86_64")]
4010    {
4011        if std::is_x86_feature_detected!("avx2") {
4012            // One AVX2 entry so the line skip stays in this function.
4013            // A separate call per block pays for an AVX/SSE transition.
4014            // SAFETY: the runtime check above is the AVX2 and POPCNT contract.
4015            return unsafe { collect_frame_starts_avx2(scanner, skip_whitespace_tail) };
4016        }
4017    }
4018    collect_frame_starts_inner(scanner, skip_whitespace_tail)
4019}
4020
4021#[cfg(target_arch = "x86_64")]
4022#[target_feature(enable = "avx2,popcnt")]
4023unsafe fn collect_frame_starts_avx2(
4024    scanner: ConFrameIterator<'_>,
4025    skip_whitespace_tail: bool,
4026) -> Vec<usize> {
4027    collect_frame_starts_inner(scanner, skip_whitespace_tail)
4028}
4029
4030#[inline(always)]
4031fn collect_frame_starts_inner(
4032    mut scanner: ConFrameIterator<'_>,
4033    skip_whitespace_tail: bool,
4034) -> Vec<usize> {
4035    // Callers used to skip only an ASCII tail. Every scan now stops where
4036    // the sequential reader stops, so the flag no longer changes the result.
4037    let _ = skip_whitespace_tail;
4038    let mut boundaries = Vec::new();
4039    loop {
4040        scanner.lines.clear_peek();
4041        let start = scanner.lines.pos;
4042        // A whitespace tail, including Unicode space, is not another frame
4043        // (CON-frame.1).
4044        if no_frame_at(scanner.lines.bytes, start) {
4045            break;
4046        }
4047        boundaries.push(start);
4048        match scanner.scan_declared_frame(None) {
4049            Some(Ok(())) => {}
4050            Some(Err(_)) | None => break,
4051        }
4052    }
4053    boundaries
4054}
4055
4056/// Serial header walk. This is the reference the chunked scan must match.
4057pub fn frame_start_offsets_serial(file_contents: &str) -> Vec<usize> {
4058    collect_frame_starts(ConFrameIterator::new(file_contents), false)
4059}
4060
4061#[cfg(feature = "parallel")]
4062fn scanner_with_newlines<'a>(text: &'a str, newlines: Vec<usize>) -> ConFrameIterator<'a> {
4063    let mut scanner = ConFrameIterator::new(text);
4064    scanner.lines.index_line = 0;
4065    scanner.lines.newlines = Some(newlines);
4066    scanner
4067}
4068
4069#[cfg(feature = "parallel")]
4070fn frame_start_offsets_indexed(text: &str, newlines: Vec<usize>) -> Vec<usize> {
4071    collect_frame_starts(scanner_with_newlines(text, newlines), false)
4072}
4073
4074/// Frame starts for `text` when the newline scan is split at `cuts`.
4075///
4076/// `cuts` is the chunk edges, including 0 and `text.len()`. A cut inside a
4077/// header line is the straddling case: the stitched offsets are still the
4078/// serial offsets.
4079#[cfg(all(feature = "parallel", test))]
4080fn frame_start_offsets_at_cuts(text: &str, cuts: &[usize]) -> Vec<usize> {
4081    let newlines = newline_positions_at_cuts(text.as_bytes(), cuts);
4082    frame_start_offsets_indexed(text, newlines)
4083}
4084
4085/// Frame start byte offsets via [`ConFrameIterator::forward_fast`] (no atom parse).
4086///
4087/// Stops at the first skip error (that start is still included).
4088///
4089/// With the `parallel` feature and more than one worker, the buffer is
4090/// split into chunks and the newline bytes are scanned together. The
4091/// length of the buffer does not choose the worker count. The chunks
4092/// are not aligned to lines. A header
4093/// that straddles a cut is one line, because each `\n` is recorded by the
4094/// chunk that holds that byte and the lists are stitched in order. The
4095/// returned offsets match the serial walk.
4096pub fn frame_start_offsets(file_contents: &str) -> Vec<usize> {
4097    frame_start_offsets_with_threads(file_contents, None)
4098}
4099
4100/// [`frame_start_offsets`] using `num_threads` chunks.
4101///
4102/// `None` uses the machine's parallelism. `Some(0)` and `Some(1)` stay on
4103/// the calling thread. The offsets do not depend on the thread count.
4104///
4105/// The timed work includes the cut setup, the per-chunk scans, the
4106/// stitch, and the frame walk that reads the stitched newline index.
4107pub fn frame_start_offsets_with_threads(
4108    file_contents: &str,
4109    num_threads: Option<usize>,
4110) -> Vec<usize> {
4111    #[cfg(feature = "parallel")]
4112    {
4113        let threads = scan_thread_count(num_threads, file_contents.len());
4114        if threads >= 2 {
4115            let newlines = newline_positions(file_contents.as_bytes(), threads);
4116            return frame_start_offsets_indexed(file_contents, newlines);
4117        }
4118    }
4119    #[cfg(not(feature = "parallel"))]
4120    {
4121        let _ = num_threads;
4122    }
4123    frame_start_offsets_serial(file_contents)
4124}
4125
4126/// Parses frames in parallel using rayon, splitting on frame boundaries.
4127///
4128/// Phase 1: frame starts from a serial [`ConFrameIterator::forward_fast`]
4129/// walk. The header names each block's line count, so the walk does not
4130/// parse atom rows. Phase 2 parses those spans on a Rayon pool and
4131/// stores the frames in file order. See [`parse_frames_parallel_with_threads`].
4132///
4133/// Requires the `parallel` feature.
4134#[cfg(feature = "parallel")]
4135pub fn parse_frames_parallel(
4136    file_contents: &str,
4137) -> Vec<Result<types::ConFrame, error::ParseError>> {
4138    parse_frames_parallel_with_threads(file_contents, None)
4139}
4140
4141/// Like [`parse_frames_parallel`], but `Some(n)` with `n >= 2` parses on
4142/// a Rayon pool of that size. `None`, `Some(0)`, and `Some(1)` stay on
4143/// the calling thread.
4144///
4145/// The boundary walk is serial. The parse ranges are byte-balanced and
4146/// the frames come back in file order, field for field with a serial
4147/// iterator.
4148///
4149/// Requires the `parallel` feature.
4150#[cfg(feature = "parallel")]
4151pub fn parse_frames_parallel_with_threads(
4152    file_contents: &str,
4153    num_threads: Option<usize>,
4154) -> Vec<Result<types::ConFrame, error::ParseError>> {
4155    let parse_workers = match num_threads {
4156        Some(n) if n >= 2 => n,
4157        _ => 1,
4158    };
4159    let run = || {
4160        // A whitespace tail is not a frame. The serial iterator stops
4161        // there. The offset scan used by callers still records that byte
4162        // when a skip error includes it.
4163        let (boundaries, _kind) = parallel_boundaries(file_contents.as_bytes(), parse_workers);
4164        parse_into_slots(
4165            file_contents.as_bytes(),
4166            file_contents.len(),
4167            &boundaries,
4168            parse_workers,
4169            |start, end| parse_text_span(file_contents, start, end),
4170        )
4171    };
4172    match num_threads {
4173        Some(n) if n >= 2 => match shared_pool(n) {
4174            Some(pool) => pool.install(run),
4175            None => run(),
4176        },
4177        _ => run(),
4178    }
4179}
4180
4181/// Phase 2 of [`parse_frames_parallel_with_threads`]: parse the frames
4182/// that start at `boundaries` (strictly increasing byte offsets into
4183/// `file_contents`; frame `i` ends where frame `i + 1` starts).
4184///
4185/// Offsets may come from [`frame_start_offsets`] or from a checked
4186/// [`crate::frame_index::FrameIndex`]. The output slots are allocated
4187/// first. Each worker then fills one contiguous index range. Results
4188/// stay in frame order.
4189///
4190/// The timer for this function starts after `boundaries` exist. It
4191/// includes slot allocation and the worker parse. It does not include
4192/// the newline scan or the stitch.
4193///
4194/// Requires the `parallel` feature.
4195#[cfg(feature = "parallel")]
4196pub fn parse_frames_at_offsets(
4197    file_contents: &str,
4198    boundaries: &[usize],
4199    num_threads: Option<usize>,
4200) -> Vec<Result<types::ConFrame, error::ParseError>> {
4201    let workers = match num_threads {
4202        Some(n) if n <= 1 => 1,
4203        Some(n) => n,
4204        None => rayon::current_num_threads().max(1),
4205    };
4206    let run = || {
4207        parse_into_slots(
4208            file_contents.as_bytes(),
4209            file_contents.len(),
4210            boundaries,
4211            workers,
4212            |start, end| parse_text_span(file_contents, start, end),
4213        )
4214    };
4215    match num_threads {
4216        Some(n) if n >= 2 => match shared_pool(n) {
4217            Some(pool) => pool.install(run),
4218            None => run(),
4219        },
4220        _ => run(),
4221    }
4222}
4223
4224/// Seconds for one phased read. The open time is the file read or the
4225/// map. Scan, slot allocation, and the worker parse are separate.
4226#[derive(Clone, Copy, Debug, Default)]
4227pub struct ReadPhaseTimes {
4228    pub open_mmap_s: f64,
4229    /// Finding the shared pool, and building it on the first read at this
4230    /// width. Zero when the call stays on one thread.
4231    pub pool_s: f64,
4232    /// Dropping this read's handle to the shared pool after the scan and
4233    /// the parse. The pool stays for the process and its workers are not
4234    /// joined, so this is the handle drop only. Zero when the call stays
4235    /// on one thread.
4236    pub pool_join_s: f64,
4237    pub scan_s: f64,
4238    pub slot_alloc_s: f64,
4239    pub worker_parse_s: f64,
4240    /// Moving each parsed `Result` into the frame vector.
4241    pub finish_s: f64,
4242    /// Sum of per-chunk parse times. This is CPU time, not wall time.
4243    pub worker_sum_s: f64,
4244    /// Slowest parse chunk. This is inside `worker_parse_s`.
4245    pub worker_max_s: f64,
4246    /// Drop of the mapped or owned file buffer after the parse.
4247    pub close_s: f64,
4248    /// Wake of the worker pool and the other gaps inside the read.
4249    pub schedule_s: f64,
4250    /// Minor faults during the scan.
4251    pub scan_minflt: i64,
4252    /// Sum of per-worker minor faults during the parse.
4253    pub parse_minflt: i64,
4254    /// LLC read misses, or `-1` when the guest refuses the counter.
4255    pub llc_misses: i64,
4256    /// Pages on a node other than node 0. Zero on a one-node guest.
4257    pub numa_remote: i64,
4258    /// Minor faults while the coordinate slab is filled.
4259    pub slab_minflt: i64,
4260    /// Minor faults during the touch checksum.
4261    pub touch_minflt: i64,
4262    /// True when the bytes came from a map rather than an owned buffer.
4263    pub mapped: bool,
4264}
4265
4266/// Frames from one phased read, plus the byte length of the buffer.
4267pub struct PhasedFrames {
4268    pub frames: Vec<types::ConFrame>,
4269    pub phases: ReadPhaseTimes,
4270    pub n_bytes: usize,
4271    /// Per-chunk parse seconds, in claim order.
4272    pub chunk_s: Vec<f64>,
4273    /// [`SCAN_SERIAL`], [`SCAN_INDEXED`], or [`SCAN_EQUAL_SPAN`] when
4274    /// `parallel` is on. Zero otherwise.
4275    pub scan_kind: u8,
4276    /// Minor faults on each parse worker.
4277    pub worker_minflt: Vec<i64>,
4278    /// Frames in each worker share.
4279    pub share_frames: Vec<u64>,
4280    /// File bytes in each worker share.
4281    pub share_bytes: Vec<u64>,
4282    /// Pool kept for the slab, the touch, and frame teardown.
4283    #[cfg(feature = "parallel")]
4284    pub pool: Option<std::sync::Arc<rayon::ThreadPool>>,
4285}
4286
4287/// Read `path` and time open, scan, slot allocation, and the worker parse.
4288///
4289/// Plain text at or above the map threshold is mapped. Smaller files and
4290/// compressed files are owned buffers. `Some(n)` with `n >= 2` parses on
4291/// that many workers. Every other count parses on the calling thread.
4292/// The frame list matches [`frames_from_bytes`].
4293///
4294#[cfg(feature = "parallel")]
4295type PipedFrames = (Vec<types::ConFrame>, f64, f64);
4296
4297/// A parse failure is the [`error::LocatedParseError`] from the parse
4298/// that failed. The path is not opened again.
4299/// Inflate each indexed member and parse its coordinate rows on that same
4300/// worker, with no barrier between the two. Old indexes without a row
4301/// table return `None` and the caller keeps the full-buffer parser.
4302#[cfg(feature = "parallel")]
4303fn piped_stock_frames(
4304    file: &[u8],
4305    threads: usize,
4306) -> Result<Option<PipedFrames>, Box<dyn std::error::Error>> {
4307    use std::sync::atomic::{AtomicBool, Ordering};
4308    let Some(index) = crate::compression::indexed_members(file) else {
4309        return Ok(None);
4310    };
4311    if threads < 2 {
4312        return Ok(None);
4313    }
4314    // A flipped length or row count must not overflow the sum or reserve
4315    // a buffer the compressed file cannot hold. The full parser reads it.
4316    let Some(plain_total) = crate::compression::trusted_plain_total(file.len(), &index.plain)
4317    else {
4318        return Ok(None);
4319    };
4320    let Some(n) = crate::compression::trusted_row_total(plain_total, &index.rows) else {
4321        return Ok(None);
4322    };
4323    if n == 0 {
4324        return Ok(None);
4325    }
4326    let t_alloc = std::time::Instant::now();
4327    let mut offset = Vec::with_capacity(index.plain.len());
4328    let mut cursor = 0usize;
4329    for len in &index.plain {
4330        offset.push(cursor);
4331        cursor += *len;
4332    }
4333    let mut ends = index.starts[1..].to_vec();
4334    ends.push(file.len());
4335    let header: std::sync::Mutex<Option<types::FrameHeader>> = std::sync::Mutex::new(None);
4336    let symbols: std::sync::Mutex<Vec<(std::sync::Arc<str>, usize)>> =
4337        std::sync::Mutex::new(Vec::new());
4338    let ready = AtomicBool::new(false);
4339    let failed = AtomicBool::new(false);
4340    let spec = std::sync::atomic::AtomicU32::new(0);
4341    let row_origin = std::sync::atomic::AtomicUsize::new(0);
4342    let mut xyz = Vec::<f64>::with_capacity(n.saturating_mul(3));
4343    let mut ids = Vec::<u64>::with_capacity(n);
4344    let mut flags = Vec::<[bool; 3]>::with_capacity(n);
4345    let mut atoms = crate::types::take_atom_spare(n);
4346    unsafe { atoms.set_len(n) };
4347    let error: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
4348    let alloc_s = t_alloc.elapsed().as_secs_f64();
4349    let nworkers = threads.min(index.plain.len()).max(1);
4350    let t_scope = std::time::Instant::now();
4351    let xyz_addr = xyz.as_mut_ptr() as usize;
4352    let ids_addr = ids.as_mut_ptr() as usize;
4353    let flags_addr = flags.as_mut_ptr() as usize;
4354    let atoms_addr = atoms.as_mut_ptr() as usize;
4355    crate::parser::on_pool(nworkers, || {
4356        rayon::scope(|scope| {
4357            for worker in 0..nworkers {
4358                let index = &index;
4359                let offset = &offset;
4360                let ends = &ends;
4361                let header = &header;
4362                let symbols = &symbols;
4363                let error = &error;
4364                let ready = &ready;
4365                let failed = &failed;
4366                let spec = &spec;
4367                let row_origin = &row_origin;
4368                scope.spawn(move |_| {
4369                    let xyz_ptr = xyz_addr as *mut f64;
4370                    let ids_ptr = ids_addr as *mut u64;
4371                    let flags_ptr = flags_addr as *mut [bool; 3];
4372                    let atoms_ptr = atoms_addr as *mut std::mem::MaybeUninit<types::AtomDatum>;
4373                    // One inflate buffer per pool thread, kept after the first file.
4374                    thread_local! {
4375                        static INFLATE_BUF: std::cell::RefCell<Vec<u8>> =
4376                            const { std::cell::RefCell::new(Vec::new()) };
4377                    }
4378                    crate::parser::pin_worker(worker);
4379                    let mut symbol: Option<std::sync::Arc<str>> = None;
4380                    let mut member = worker;
4381                    while member < index.plain.len() {
4382                        let src = &file[index.starts[member]..ends[member]];
4383                        let plain_len = index.plain[member];
4384                        let parsed = INFLATE_BUF.with(|cell| {
4385                            let mut buf = cell.borrow_mut();
4386                            buf.clear();
4387                            if buf.capacity() < plain_len {
4388                                let extra = plain_len - buf.len();
4389                                buf.reserve(extra);
4390                            }
4391                            unsafe { buf.set_len(plain_len) };
4392                            if let Err(err) = crate::compression::inflate_member(
4393                                index.gzip,
4394                                src,
4395                                &mut buf[..plain_len],
4396                            ) {
4397                                return Err(err.to_string());
4398                            }
4399                            if member == 0 {
4400                                match stock_header(&buf[..plain_len]) {
4401                                    Some((parsed, syms, origin)) => {
4402                                        spec.store(parsed.spec_version, Ordering::Release);
4403                                        row_origin.store(origin, Ordering::Release);
4404                                        *symbols.lock().unwrap() = syms;
4405                                        *header.lock().unwrap() = Some(parsed);
4406                                        ready.store(true, Ordering::Release);
4407                                    }
4408                                    None => {
4409                                        // More than one species, or a header this
4410                                        // fast path does not own. Stop the other
4411                                        // workers and let the full parser read
4412                                        // the concatenated members.
4413                                        failed.store(true, Ordering::Release);
4414                                        return Ok(());
4415                                    }
4416                                }
4417                            }
4418                            let (base, count) = index.rows[member];
4419                            if count == 0 {
4420                                return Ok(());
4421                            }
4422                            while !ready.load(Ordering::Acquire) {
4423                                if failed.load(Ordering::Acquire) {
4424                                    return Ok(());
4425                                }
4426                                std::thread::yield_now();
4427                            }
4428                            if symbol.is_none() {
4429                                symbol =
4430                                    symbols.lock().unwrap().first().map(|(sym, _)| sym.clone());
4431                            }
4432                            let Some(symbol) = symbol.as_ref() else {
4433                                return Err("indexed frame has no species".into());
4434                            };
4435                            let spec_v = spec.load(Ordering::Acquire);
4436                            let origin = row_origin.load(Ordering::Acquire);
4437                            let local = origin.saturating_sub(offset[member]);
4438                            let row = base as usize;
4439                            let nrows = count as usize;
4440                            if row.checked_add(nrows).map(|end| end <= n) != Some(true) {
4441                                return Err("indexed row is outside the frame".into());
4442                            }
4443                            if let Err(err) = crate::parser::parse_coord_run(
4444                                &buf[..plain_len],
4445                                local,
4446                                nrows,
4447                                spec_v,
4448                                row,
4449                                Some(symbol),
4450                                crate::parser::CoordRunOut {
4451                                    xyz: xyz_ptr,
4452                                    ids: ids_ptr,
4453                                    flags: flags_ptr,
4454                                    atoms: atoms_ptr,
4455                                },
4456                            ) {
4457                                return Err(err.to_string());
4458                            }
4459                            Ok(())
4460                        });
4461                        if let Err(err) = parsed {
4462                            *error.lock().unwrap() = Some(err);
4463                            failed.store(true, Ordering::Release);
4464                            return;
4465                        }
4466                        if failed.load(Ordering::Acquire) {
4467                            return;
4468                        }
4469                        member += nworkers;
4470                    }
4471                });
4472            }
4473        });
4474    });
4475    let scope_s = t_scope.elapsed().as_secs_f64();
4476    if let Some(err) = error.into_inner().unwrap_or(None) {
4477        release_uninit_atoms(atoms);
4478        return Err(err.into());
4479    }
4480    let Some(header) = header.into_inner().unwrap_or(None) else {
4481        release_uninit_atoms(atoms);
4482        return Ok(None);
4483    };
4484    // Every coordinate, id, and flag was written. The length stayed 0
4485    // until here, so an error does not drop an uninitialised bool.
4486    unsafe {
4487        xyz.set_len(n.saturating_mul(3));
4488        ids.set_len(n);
4489        flags.set_len(n);
4490    }
4491    let positions = crate::storage_dtype::FloatArray2::from_f64_row_major(n, 3, xyz);
4492    let atoms = owned_initialized_atoms(atoms, n);
4493    crate::types::mark_uniform_symbol_drop(&atoms);
4494    let frame = crate::types::con_frame_coords_only_with_ids(header, atoms, positions, ids);
4495    Ok(Some((vec![frame], alloc_s, scope_s)))
4496}
4497
4498/// The spare was `set_len`'d before the workers filled it. Dropping it
4499/// would run `AtomDatum`'s destructor on uninitialised slots. Setting the
4500/// length back to zero frees the allocation and drops nothing.
4501#[cfg(feature = "parallel")]
4502fn release_uninit_atoms(mut raw: Vec<std::mem::MaybeUninit<types::AtomDatum>>) {
4503    unsafe { raw.set_len(0) };
4504}
4505
4506/// `raw` is `n` initialized atoms in a buffer that may be larger than `n`.
4507///
4508/// The spare reused across frames keeps its real capacity. Passing `n` as
4509/// the capacity frees that allocation with the wrong layout.
4510#[cfg(feature = "parallel")]
4511fn owned_initialized_atoms(
4512    mut raw: Vec<std::mem::MaybeUninit<types::AtomDatum>>,
4513    n: usize,
4514) -> Vec<types::AtomDatum> {
4515    let cap = raw.capacity();
4516    debug_assert!(cap >= n);
4517    let ptr = raw.as_mut_ptr() as *mut types::AtomDatum;
4518    std::mem::forget(raw);
4519    unsafe { Vec::from_raw_parts(ptr, n, cap) }
4520}
4521
4522#[cfg(all(test, feature = "parallel"))]
4523mod spare_capacity {
4524    #[test]
4525    fn a_reused_spare_keeps_its_capacity() {
4526        let mut raw = crate::types::take_atom_spare(32);
4527        let cap = raw.capacity();
4528        assert!(cap >= 32);
4529        unsafe { raw.set_len(4) };
4530        for (index, slot) in raw.iter_mut().take(4).enumerate() {
4531            slot.write(crate::types::AtomDatum::coords(
4532                "Cu",
4533                0.0,
4534                0.0,
4535                0.0,
4536                [false, false, false],
4537                index as u64,
4538            ));
4539        }
4540        let atoms = super::owned_initialized_atoms(raw, 4);
4541        assert_eq!(atoms.capacity(), cap);
4542    }
4543}
4544
4545#[cfg(feature = "parallel")]
4546type StockHead = (types::FrameHeader, Vec<(std::sync::Arc<str>, usize)>, usize);
4547
4548#[cfg(feature = "parallel")]
4549fn stock_header(bytes: &[u8]) -> Option<StockHead> {
4550    // The member is several megabytes. The header is the first few dozen
4551    // lines; scanning the whole member as UTF-8 sat on the critical path.
4552    let header_region = {
4553        let mut seen = 0usize;
4554        let mut end = bytes.len();
4555        for (index, byte) in bytes.iter().enumerate() {
4556            if *byte == b'\n' {
4557                seen += 1;
4558                if seen == 64 {
4559                    end = index + 1;
4560                    break;
4561                }
4562            }
4563        }
4564        &bytes[..end]
4565    };
4566    let text = std::str::from_utf8(header_region).ok()?;
4567    let mut lines = text.lines();
4568    let header = crate::parser::parse_frame_header(&mut lines).ok()?;
4569    if header.natm_types != 1 || header.natms_per_type.len() != 1 {
4570        return None;
4571    }
4572    let mut symbols = Vec::with_capacity(header.natm_types);
4573    for &count in &header.natms_per_type {
4574        let symbol = lines.next()?.trim();
4575        let _label = lines.next()?;
4576        if symbol.is_empty() || count == 0 {
4577            return None;
4578        }
4579        symbols.push((std::sync::Arc::from(symbol), count));
4580    }
4581    let header_lines = 9 + header.natm_types * 2;
4582    let mut seen = 0usize;
4583    let mut origin = 0usize;
4584    for index in memchr::memchr_iter(b'\n', bytes) {
4585        seen += 1;
4586        if seen == header_lines {
4587            origin = index + 1;
4588            break;
4589        }
4590    }
4591    if seen != header_lines {
4592        return None;
4593    }
4594    Some((header, symbols, origin))
4595}
4596
4597fn read_compressed_phased(
4598    path: &Path,
4599    num_threads: Option<usize>,
4600) -> Result<PhasedFrames, Box<dyn std::error::Error>> {
4601    let t_open = std::time::Instant::now();
4602    let file = std::fs::read(path)?;
4603    let open_s = t_open.elapsed().as_secs_f64();
4604    let t_all = std::time::Instant::now();
4605    #[cfg(feature = "parallel")]
4606    let piped_threads = match num_threads {
4607        Some(n) if n >= 2 => n,
4608        _ => {
4609            let budget = crate::compression::decode_thread_budget();
4610            if budget >= 2 { budget } else { 1 }
4611        }
4612    };
4613    #[cfg(feature = "parallel")]
4614    if piped_threads >= 2 {
4615        if let Some((frames, alloc_s, scope_s)) = piped_stock_frames(&file, piped_threads)? {
4616            let elapsed = t_all.elapsed().as_secs_f64();
4617            let n_frames = frames.len() as u64;
4618            return Ok(PhasedFrames {
4619                frames,
4620                n_bytes: file.len(),
4621                chunk_s: vec![scope_s],
4622                scan_kind: SCAN_SERIAL,
4623                worker_minflt: Vec::new(),
4624                share_frames: vec![n_frames],
4625                share_bytes: Vec::new(),
4626                phases: ReadPhaseTimes {
4627                    open_mmap_s: open_s,
4628                    slot_alloc_s: alloc_s,
4629                    worker_parse_s: scope_s,
4630                    worker_sum_s: scope_s,
4631                    worker_max_s: scope_s,
4632                    finish_s: (elapsed - alloc_s - scope_s).max(0.0),
4633                    ..ReadPhaseTimes::default()
4634                },
4635                pool: None,
4636            });
4637        }
4638    }
4639    crate::compression::with_inflated_plain(&file, |plain| {
4640        let open_mmap_s = open_s + t_all.elapsed().as_secs_f64();
4641        let n_bytes = plain.len();
4642        let phased = frames_from_bytes_phased_located(plain, num_threads)
4643            .map_err(|err| Box::new(err) as Box<dyn std::error::Error>)?;
4644        let elapsed = t_all.elapsed().as_secs_f64();
4645        let parse = phased.worker_parse_s
4646            + phased.scan_s
4647            + phased.slot_alloc_s
4648            + phased.finish_s
4649            + phased.pool_s
4650            + phased.pool_join_s;
4651        let schedule_s = (elapsed - open_mmap_s - parse).max(0.0);
4652        let parse_minflt = phased.worker_minflt.iter().sum();
4653        Ok(PhasedFrames {
4654            frames: phased.frames,
4655            n_bytes,
4656            chunk_s: phased.chunk_s,
4657            scan_kind: phased.scan_kind,
4658            worker_minflt: phased.worker_minflt,
4659            share_frames: phased.share_frames,
4660            share_bytes: phased.share_bytes,
4661            phases: ReadPhaseTimes {
4662                open_mmap_s,
4663                pool_s: phased.pool_s,
4664                pool_join_s: phased.pool_join_s,
4665                scan_s: phased.scan_s,
4666                slot_alloc_s: phased.slot_alloc_s,
4667                worker_parse_s: phased.worker_parse_s,
4668                finish_s: phased.finish_s,
4669                worker_sum_s: phased.worker_sum_s,
4670                worker_max_s: phased.worker_max_s,
4671                schedule_s,
4672                scan_minflt: phased.scan_minflt,
4673                parse_minflt,
4674                llc_misses: phased.llc_misses,
4675                numa_remote: phased.numa_remote,
4676                ..ReadPhaseTimes::default()
4677            },
4678            #[cfg(feature = "parallel")]
4679            pool: phased.pool,
4680        })
4681    })
4682}
4683
4684fn path_is_compressed(path: &Path) -> bool {
4685    let mut file = match std::fs::File::open(path) {
4686        Ok(file) => file,
4687        Err(_) => return false,
4688    };
4689    let mut magic = [0u8; 4];
4690    let n = std::io::Read::read(&mut file, &mut magic).unwrap_or(0);
4691    !matches!(
4692        crate::compression::detect_compression(&magic[..n]),
4693        crate::compression::Compression::None
4694    )
4695}
4696
4697pub fn read_all_frames_phased(
4698    path: &Path,
4699    num_threads: Option<usize>,
4700) -> Result<PhasedFrames, Box<dyn std::error::Error>> {
4701    if path_is_compressed(path) {
4702        return read_compressed_phased(path, num_threads);
4703    }
4704    if !matches!(num_threads, Some(n) if n >= 2) {
4705        let t_all = std::time::Instant::now();
4706        let frames = stream_frames(path).map_err(public_load_error)?;
4707        let elapsed = t_all.elapsed().as_secs_f64();
4708        let n_frames = frames.len() as u64;
4709        return Ok(PhasedFrames {
4710            frames,
4711            n_bytes: 0,
4712            chunk_s: vec![elapsed],
4713            scan_kind: SCAN_SERIAL,
4714            worker_minflt: Vec::new(),
4715            share_frames: vec![n_frames],
4716            share_bytes: Vec::new(),
4717            phases: ReadPhaseTimes {
4718                worker_parse_s: elapsed,
4719                worker_sum_s: elapsed,
4720                worker_max_s: elapsed,
4721                ..ReadPhaseTimes::default()
4722            },
4723            #[cfg(feature = "parallel")]
4724            pool: None,
4725        });
4726    }
4727    let t_all = std::time::Instant::now();
4728    let t_open = std::time::Instant::now();
4729    // Bytes, not a UTF-8 string. A bad byte inside a numeric field is
4730    // InvalidNumberFormat (CON-num.10), which a whole-buffer decode would hide.
4731    let source = crate::compression::read_bytes_owned(path)?;
4732    let open_mmap_s = t_open.elapsed().as_secs_f64();
4733    let mapped = matches!(source, crate::compression::ByteSource::Map(_));
4734    let n_bytes = source.as_slice().len();
4735    let bytes = source.as_slice();
4736    let phased = frames_from_bytes_phased_located(bytes, num_threads)?;
4737    let workers = match num_threads {
4738        Some(n) if n >= 2 => n,
4739        _ => 1,
4740    };
4741    let t_close = std::time::Instant::now();
4742    if let crate::compression::ByteSource::Map(map) = &source {
4743        // The serial unmap of a fully resident file is the multi-worker
4744        // tail. Advise the pages away on the read's pool first.
4745        // One worker unmaps directly, so a serial read does not walk
4746        // the pages twice.
4747        if workers >= 2 {
4748            #[cfg(feature = "parallel")]
4749            {
4750                if let Some(pool) = phased.pool.as_ref() {
4751                    pool.install(|| {
4752                        crate::compression::advise_dontneed_parallel(map, workers);
4753                    });
4754                }
4755            }
4756            #[cfg(not(feature = "parallel"))]
4757            {
4758                let _ = (map, workers);
4759            }
4760        }
4761    }
4762    drop(source);
4763    let close_s = t_close.elapsed().as_secs_f64();
4764    let elapsed = t_all.elapsed().as_secs_f64();
4765    let named = open_mmap_s
4766        + phased.pool_s
4767        + phased.pool_join_s
4768        + phased.scan_s
4769        + phased.slot_alloc_s
4770        + phased.worker_parse_s
4771        + phased.finish_s
4772        + close_s;
4773    let schedule_s = (elapsed - named).max(0.0);
4774    let parse_minflt = phased.worker_minflt.iter().sum();
4775    Ok(PhasedFrames {
4776        frames: phased.frames,
4777        n_bytes,
4778        chunk_s: phased.chunk_s,
4779        scan_kind: phased.scan_kind,
4780        worker_minflt: phased.worker_minflt,
4781        share_frames: phased.share_frames,
4782        share_bytes: phased.share_bytes,
4783        phases: ReadPhaseTimes {
4784            open_mmap_s,
4785            pool_s: phased.pool_s,
4786            pool_join_s: phased.pool_join_s,
4787            scan_s: phased.scan_s,
4788            slot_alloc_s: phased.slot_alloc_s,
4789            worker_parse_s: phased.worker_parse_s,
4790            finish_s: phased.finish_s,
4791            worker_sum_s: phased.worker_sum_s,
4792            worker_max_s: phased.worker_max_s,
4793            close_s,
4794            schedule_s,
4795            scan_minflt: phased.scan_minflt,
4796            parse_minflt,
4797            llc_misses: phased.llc_misses,
4798            numa_remote: phased.numa_remote,
4799            mapped,
4800            ..ReadPhaseTimes::default()
4801        },
4802        #[cfg(feature = "parallel")]
4803        pool: phased.pool,
4804    })
4805}
4806
4807/// [`frames_from_bytes`] with scan, slot allocation, and worker-parse times.
4808///
4809/// `Some(n)` with `n >= 2` uses that pool. Every other count, including
4810/// `None`, stays on the calling thread. That is the `read_con` policy:
4811/// an omitted count does not start a pool.
4812pub struct PhasedByteTimes {
4813    pub frames: Vec<types::ConFrame>,
4814    pub pool_s: f64,
4815    pub pool_join_s: f64,
4816    pub scan_s: f64,
4817    pub slot_alloc_s: f64,
4818    pub worker_parse_s: f64,
4819    pub finish_s: f64,
4820    pub worker_sum_s: f64,
4821    pub worker_max_s: f64,
4822    /// Per-chunk parse seconds, in claim order.
4823    pub chunk_s: Vec<f64>,
4824    /// [`SCAN_SERIAL`], [`SCAN_INDEXED`], or [`SCAN_EQUAL_SPAN`] when
4825    /// `parallel` is on. Zero otherwise.
4826    pub scan_kind: u8,
4827    /// Minor faults during the scan.
4828    pub scan_minflt: i64,
4829    /// Minor faults on each parse worker, in worker order.
4830    pub worker_minflt: Vec<i64>,
4831    pub share_frames: Vec<u64>,
4832    pub share_bytes: Vec<u64>,
4833    /// LLC read misses, or `-1` when the guest refuses the counter.
4834    pub llc_misses: i64,
4835    /// Pages on a node other than node 0.
4836    pub numa_remote: i64,
4837    /// Pool kept for the slab, the touch, and frame teardown.
4838    #[cfg(feature = "parallel")]
4839    pub pool: Option<std::sync::Arc<rayon::ThreadPool>>,
4840}
4841
4842/// The first frame declares at least 4096 atoms and the file is too
4843/// small to hold a second copy of that frame.
4844///
4845/// The row parser then owns the threads. A frame split would walk the
4846/// same lines and leave every atom on one worker.
4847#[cfg(feature = "parallel")]
4848fn declared_wide_frame(bytes: &[u8]) -> bool {
4849    let mut pos = 0usize;
4850    let mut natypes = 0usize;
4851    for line_no in 0..8 {
4852        if pos >= bytes.len() {
4853            return false;
4854        }
4855        let end = memchr::memchr(b'\n', &bytes[pos..])
4856            .map(|rel| pos + rel)
4857            .unwrap_or(bytes.len());
4858        let line = &bytes[pos..end];
4859        if line_no == 6 {
4860            natypes = match first_header_usize(line) {
4861                Some(n) if (1..=64).contains(&n) => n,
4862                _ => return false,
4863            };
4864        } else if line_no == 7 {
4865            let mut sum = 0usize;
4866            let mut seen = 0usize;
4867            for field in line
4868                .split(|byte| byte.is_ascii_whitespace())
4869                .filter(|field| !field.is_empty())
4870            {
4871                let Some(n) = first_header_usize(field) else {
4872                    return false;
4873                };
4874                if n == 0 {
4875                    return false;
4876                }
4877                sum = sum.saturating_add(n);
4878                seen += 1;
4879            }
4880            if seen != natypes || sum < 4096 {
4881                return false;
4882            }
4883            return bytes.len() <= sum.saturating_mul(64).saturating_add(4096);
4884        }
4885        pos = end.saturating_add(1);
4886    }
4887    false
4888}
4889
4890#[cfg(feature = "parallel")]
4891fn first_header_usize(line: &[u8]) -> Option<usize> {
4892    let field = line
4893        .split(|byte| byte.is_ascii_whitespace())
4894        .find(|field| !field.is_empty())?;
4895    std::str::from_utf8(field).ok()?.parse().ok()
4896}
4897
4898#[cfg(feature = "parallel")]
4899fn wide_frame_phased(
4900    bytes: &[u8],
4901    workers: usize,
4902) -> Result<PhasedByteTimes, error::LocatedParseError> {
4903    struct Reset;
4904    impl Drop for Reset {
4905        fn drop(&mut self) {
4906            crate::parser::set_wide_workers(1);
4907        }
4908    }
4909    crate::parser::set_wide_workers(workers);
4910    let _reset = Reset;
4911    let flt0 = thread_minflt();
4912    let t_work = std::time::Instant::now();
4913    let frames = collect_bytes_located(bytes)?;
4914    let worker_parse_s = t_work.elapsed().as_secs_f64();
4915    let worker_flt = thread_minflt().saturating_sub(flt0);
4916    let n_frames = frames.len() as u64;
4917    Ok(PhasedByteTimes {
4918        frames,
4919        pool_s: 0.0,
4920        pool_join_s: 0.0,
4921        scan_s: 0.0,
4922        slot_alloc_s: 0.0,
4923        worker_parse_s,
4924        finish_s: 0.0,
4925        worker_sum_s: worker_parse_s,
4926        worker_max_s: worker_parse_s,
4927        chunk_s: vec![worker_parse_s],
4928        scan_kind: SCAN_SERIAL,
4929        scan_minflt: 0,
4930        worker_minflt: vec![worker_flt],
4931        share_frames: vec![n_frames],
4932        share_bytes: vec![bytes.len() as u64],
4933        llc_misses: sample_llc_misses(),
4934        numa_remote: numa_remote_pages(),
4935        pool: None,
4936    })
4937}
4938
4939pub fn frames_from_bytes_phased(
4940    bytes: &[u8],
4941    num_threads: Option<usize>,
4942) -> Result<PhasedByteTimes, error::ParseError> {
4943    frames_from_bytes_phased_located(bytes, num_threads).map_err(|err| err.error)
4944}
4945
4946fn frames_from_bytes_phased_located(
4947    bytes: &[u8],
4948    num_threads: Option<usize>,
4949) -> Result<PhasedByteTimes, error::LocatedParseError> {
4950    #[cfg(feature = "parallel")]
4951    {
4952        // One thread walks the file once. A scan plus a second parse made
4953        // a short file slower than the plain iterator.
4954        if !matches!(num_threads, Some(n) if n >= 2) {
4955            let flt0 = thread_minflt();
4956            let t_work = std::time::Instant::now();
4957            let frames = collect_bytes_located(bytes)?;
4958            let worker_parse_s = t_work.elapsed().as_secs_f64();
4959            let worker_flt = thread_minflt().saturating_sub(flt0);
4960            let n_frames = frames.len() as u64;
4961            return Ok(PhasedByteTimes {
4962                frames,
4963                pool_s: 0.0,
4964                pool_join_s: 0.0,
4965                scan_s: 0.0,
4966                slot_alloc_s: 0.0,
4967                worker_parse_s,
4968                finish_s: 0.0,
4969                worker_sum_s: worker_parse_s,
4970                worker_max_s: worker_parse_s,
4971                chunk_s: vec![worker_parse_s],
4972                scan_kind: SCAN_SERIAL,
4973                scan_minflt: 0,
4974                worker_minflt: vec![worker_flt],
4975                share_frames: vec![n_frames],
4976                share_bytes: vec![bytes.len() as u64],
4977                llc_misses: sample_llc_misses(),
4978                numa_remote: numa_remote_pages(),
4979                pool: None,
4980            });
4981        }
4982        // One wide frame has nothing for a frame split to divide. The
4983        // boundary walk would read every atom line and then the parse
4984        // would read them again, on a second pool. Parse it once, with
4985        // the row workers on the pinned pool.
4986        if let Some(workers) = num_threads.filter(|n| *n >= 2 && declared_wide_frame(bytes)) {
4987            return wide_frame_phased(bytes, workers);
4988        }
4989        let requested = Some(num_threads.expect("workers"));
4990        let timed = parse_bytes_timed(bytes, requested);
4991        let t_finish = std::time::Instant::now();
4992        let frames = if timed.slots.iter().any(|item| item.is_err()) {
4993            collect_located_slots(timed.slots, &timed.fail_lines)?
4994        } else {
4995            finish_results(timed.pool.as_deref(), timed.slots)
4996                .map_err(|error| error::LocatedParseError::new(error, 0, 0))?
4997        };
4998        // Cross-frame id checks run during the serial iterator. A parallel
4999        // span parse does not see the other frames, so a file that asked
5000        // for persistent ids is read again on one thread (CON-id.11).
5001        if crate::types::persistent_ids_requested(&frames) {
5002            return frames_from_bytes_phased_located(bytes, Some(1));
5003        }
5004        let finish_s = t_finish.elapsed().as_secs_f64();
5005        Ok(PhasedByteTimes {
5006            frames,
5007            pool_s: timed.pool_s,
5008            pool_join_s: timed.pool_join_s,
5009            scan_s: timed.scan_s,
5010            slot_alloc_s: timed.slot_alloc_s,
5011            worker_parse_s: timed.worker_parse_s,
5012            finish_s,
5013            worker_sum_s: timed.worker_sum_s,
5014            worker_max_s: timed.worker_max_s,
5015            chunk_s: timed.chunk_s,
5016            scan_kind: timed.scan_kind,
5017            scan_minflt: timed.scan_minflt,
5018            worker_minflt: timed.worker_minflt,
5019            share_frames: timed.share_frames,
5020            share_bytes: timed.share_bytes,
5021            llc_misses: timed.llc_misses,
5022            numa_remote: timed.numa_remote,
5023            pool: timed.pool,
5024        })
5025    }
5026    #[cfg(not(feature = "parallel"))]
5027    {
5028        let _ = num_threads;
5029        let t_work = std::time::Instant::now();
5030        let frames = collect_bytes_located(bytes)?;
5031        let worker_parse_s = t_work.elapsed().as_secs_f64();
5032        Ok(PhasedByteTimes {
5033            frames,
5034            pool_s: 0.0,
5035            pool_join_s: 0.0,
5036            scan_s: 0.0,
5037            slot_alloc_s: 0.0,
5038            worker_parse_s,
5039            finish_s: 0.0,
5040            worker_sum_s: worker_parse_s,
5041            worker_max_s: worker_parse_s,
5042            chunk_s: vec![worker_parse_s],
5043            scan_kind: 0,
5044            scan_minflt: 0,
5045            worker_minflt: Vec::new(),
5046            share_frames: Vec::new(),
5047            share_bytes: Vec::new(),
5048            llc_misses: -1,
5049            numa_remote: 0,
5050        })
5051    }
5052}
5053
5054/// Copy every frame's coordinates into one row-major buffer.
5055///
5056/// `None` means the frames do not share one atom count. `workers >= 2`
5057/// writes disjoint frame runs. The copy is bit-identical to reading
5058/// each frame's `f64` positions in order. A frame whose positions column
5059/// is projected to another type contributes the coordinates of its atoms.
5060pub fn pack_position_slab(frames: &[types::ConFrame], workers: usize) -> Option<Vec<f64>> {
5061    if frames.is_empty() {
5062        return None;
5063    }
5064    let n_atoms = frames[0].positions.nrows();
5065    if frames
5066        .iter()
5067        .any(|frame| frame.positions.nrows() != n_atoms)
5068    {
5069        return None;
5070    }
5071    let stride = n_atoms.saturating_mul(3);
5072    let total = frames.len().saturating_mul(stride);
5073    let mut values = Vec::<f64>::with_capacity(total);
5074    if total > 0 {
5075        // The parallel writers are the first touch of these pages.
5076        // A zeroed allocation would fault the whole slab on this thread.
5077        // SAFETY: every index is overwritten before the buffer is read.
5078        unsafe {
5079            values.set_len(total);
5080        }
5081    }
5082    if stride == 0 {
5083        return Some(values);
5084    }
5085    let write = |frame: &types::ConFrame, dest: &mut [f64]| {
5086        if let Some(src) = frame.positions.f64_slice() {
5087            dest.copy_from_slice(src);
5088        } else if frame.atom_data.len() == n_atoms {
5089            // A projected column holds the rounding of the values the atoms
5090            // keep, and the writer spells the atoms.
5091            for (index, slot) in dest.as_chunks_mut::<3>().0.iter_mut().enumerate() {
5092                *slot = frame.xyz_at(index);
5093            }
5094        } else {
5095            for (row, slot) in dest.as_chunks_mut::<3>().0.iter_mut().enumerate() {
5096                slot.copy_from_slice(&frame.positions.as_f64_row(row));
5097            }
5098        }
5099    };
5100    #[cfg(feature = "parallel")]
5101    {
5102        if workers >= 2 {
5103            let chunk_frames = frames.len().div_ceil(workers).max(1);
5104            let chunk_vals = chunk_frames.saturating_mul(stride);
5105            let copy_chunks = |dest_all: &mut [f64]| {
5106                use rayon::prelude::*;
5107                dest_all
5108                    .par_chunks_mut(chunk_vals)
5109                    .enumerate()
5110                    .for_each(|(chunk_index, dest)| {
5111                        let base = chunk_index * chunk_frames;
5112                        for (offset, slot) in dest.chunks_exact_mut(stride).enumerate() {
5113                            let index = base + offset;
5114                            if index < frames.len() {
5115                                write(&frames[index], slot);
5116                            }
5117                        }
5118                    });
5119            };
5120            // `par_chunks_mut` follows the installed pool. Outside one,
5121            // a private scope of `workers` threads keeps the global pool
5122            // out of this phase.
5123            if rayon::current_thread_index().is_some() {
5124                first_touch_f64(&mut values, workers);
5125                copy_chunks(&mut values);
5126            } else {
5127                first_touch_f64(&mut values, workers);
5128                std::thread::scope(|scope| {
5129                    let mut rest = &mut values[..];
5130                    let mut base = 0usize;
5131                    let mut handles = Vec::new();
5132                    while base < frames.len() {
5133                        let take_frames = chunk_frames.min(frames.len() - base);
5134                        let take_vals = take_frames * stride;
5135                        let (dest, tail) = rest.split_at_mut(take_vals);
5136                        rest = tail;
5137                        let frame_slice = &frames[base..base + take_frames];
5138                        handles.push(scope.spawn(move || {
5139                            for (frame, slot) in
5140                                frame_slice.iter().zip(dest.chunks_exact_mut(stride))
5141                            {
5142                                write(frame, slot);
5143                            }
5144                        }));
5145                        base += take_frames;
5146                    }
5147                    for handle in handles {
5148                        handle.join().expect("slab worker");
5149                    }
5150                });
5151            }
5152            return Some(values);
5153        }
5154    }
5155    #[cfg(not(feature = "parallel"))]
5156    {
5157        let _ = workers;
5158    }
5159    for (frame, dest) in frames.iter().zip(values.chunks_exact_mut(stride)) {
5160        write(frame, dest);
5161    }
5162    Some(values)
5163}
5164
5165fn mix_touch(hash: u64, value: u64) -> u64 {
5166    hash.wrapping_mul(0x9E3779B185EBCA87) ^ value
5167}
5168
5169fn one_frame_touch(frame: &types::ConFrame, coords: &[f64], index: u64) -> u64 {
5170    let mut hash = index;
5171    for value in frame.header.boxl {
5172        hash = mix_touch(hash, value.to_bits());
5173    }
5174    for atom in &frame.atom_data {
5175        hash = mix_touch(hash, atom.symbol.len() as u64);
5176        for byte in atom.symbol.as_bytes() {
5177            hash = mix_touch(hash, u64::from(*byte));
5178        }
5179    }
5180    for value in coords {
5181        hash = mix_touch(hash, value.to_bits());
5182    }
5183    hash
5184}
5185
5186/// XOR of positions, cell lengths, and atom-type symbols.
5187///
5188/// `positions` is frame-major `[frames, atoms, 3]`. `None` means the
5189/// slice does not match the frames. `workers >= 2` folds disjoint
5190/// frame runs on that many threads. Each frame's hash includes its
5191/// index, and the returned word is the XOR of those hashes.
5192pub fn touch_frame_checksum(
5193    frames: &[types::ConFrame],
5194    positions: &[f64],
5195    workers: usize,
5196) -> Option<u64> {
5197    if frames.is_empty() {
5198        return Some(0);
5199    }
5200    let n_atoms = frames[0].atom_data.len();
5201    let stride = n_atoms.saturating_mul(3);
5202    if stride == 0 || positions.len() != frames.len().saturating_mul(stride) {
5203        return None;
5204    }
5205    if frames.iter().any(|frame| frame.atom_data.len() != n_atoms) {
5206        return None;
5207    }
5208    let one = |index: usize| {
5209        let start = index * stride;
5210        one_frame_touch(
5211            &frames[index],
5212            &positions[start..start + stride],
5213            index as u64,
5214        )
5215    };
5216    Some(reduce_touch(frames.len(), workers, one))
5217}
5218
5219/// [`touch_frame_checksum`] for frames still sitting in optional slots.
5220///
5221/// `None` means a slot is empty or the position slice does not match.
5222pub fn touch_option_checksum(
5223    frames: &[Option<types::ConFrame>],
5224    positions: &[f64],
5225    workers: usize,
5226) -> Option<u64> {
5227    if frames.is_empty() {
5228        return Some(0);
5229    }
5230    if frames.iter().any(Option::is_none) {
5231        return None;
5232    }
5233    let n_atoms = frames[0].as_ref()?.atom_data.len();
5234    let stride = n_atoms.saturating_mul(3);
5235    if stride == 0 || positions.len() != frames.len().saturating_mul(stride) {
5236        return None;
5237    }
5238    if frames
5239        .iter()
5240        .any(|frame| frame.as_ref().map(|item| item.atom_data.len()) != Some(n_atoms))
5241    {
5242        return None;
5243    }
5244    let one = |index: usize| {
5245        let start = index * stride;
5246        one_frame_touch(
5247            frames[index].as_ref().expect("slot"),
5248            &positions[start..start + stride],
5249            index as u64,
5250        )
5251    };
5252    Some(reduce_touch(frames.len(), workers, one))
5253}
5254
5255fn reduce_touch(n: usize, workers: usize, one: impl Fn(usize) -> u64 + Sync) -> u64 {
5256    #[cfg(feature = "parallel")]
5257    if workers >= 2 {
5258        let fold_range = |first: usize, last: usize| {
5259            let mut acc = 0u64;
5260            for index in first..last {
5261                acc ^= one(index);
5262            }
5263            acc
5264        };
5265        let chunk = n.div_ceil(workers).max(1);
5266        // Reuse the installed read pool. A fresh pool per touch is the
5267        // build this phase used to pay on every call.
5268        if rayon::current_thread_index().is_some() {
5269            use rayon::prelude::*;
5270            return (0..workers)
5271                .into_par_iter()
5272                .map(|worker| {
5273                    let first = worker * chunk;
5274                    let last = (first + chunk).min(n);
5275                    fold_range(first, last)
5276                })
5277                .reduce(|| 0u64, |left, right| left ^ right);
5278        }
5279        let mut acc = 0u64;
5280        std::thread::scope(|scope| {
5281            let mut handles = Vec::with_capacity(workers);
5282            for worker in 0..workers {
5283                handles.push(scope.spawn(move || {
5284                    let first = worker * chunk;
5285                    let last = (first + chunk).min(n);
5286                    fold_range(first, last)
5287                }));
5288            }
5289            for handle in handles {
5290                acc ^= handle.join().unwrap_or(0);
5291            }
5292        });
5293        return acc;
5294    }
5295    #[cfg(not(feature = "parallel"))]
5296    {
5297        let _ = workers;
5298    }
5299    (0..n).map(one).fold(0, |acc, item| acc ^ item)
5300}
5301
5302/// Time a newline scan of `text`.
5303///
5304/// `chunked` with `threads >= 2` splits the buffer into that many
5305/// chunks, stitches the newline index, and walks frame starts. The
5306/// pool is built before the timer starts. The serial walk is
5307/// [`frame_start_offsets_serial`]. The returned offsets are the frame
5308/// starts. The caller chooses the worker count. File length does not.
5309pub fn measure_newline_scan(text: &str, threads: usize, chunked: bool) -> (Vec<usize>, f64) {
5310    #[cfg(feature = "parallel")]
5311    {
5312        if chunked && threads >= 2 {
5313            let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build();
5314            let t_scan = std::time::Instant::now();
5315            let offsets = match pool {
5316                Ok(pool) => pool.install(|| {
5317                    let newlines = newline_positions(text.as_bytes(), threads);
5318                    frame_start_offsets_indexed(text, newlines)
5319                }),
5320                Err(_) => {
5321                    let newlines = newline_positions(text.as_bytes(), threads);
5322                    frame_start_offsets_indexed(text, newlines)
5323                }
5324            };
5325            return (offsets, t_scan.elapsed().as_secs_f64());
5326        }
5327    }
5328    #[cfg(not(feature = "parallel"))]
5329    {
5330        let _ = (threads, chunked);
5331    }
5332    let t_scan = std::time::Instant::now();
5333    let offsets = frame_start_offsets_serial(text);
5334    (offsets, t_scan.elapsed().as_secs_f64())
5335}
5336
5337/// Parallel parse that keeps the file line of the first error.
5338/// Workers return the error. They do not write thread-local error state.
5339#[cfg(feature = "parallel")]
5340fn collect_parallel_located(
5341    file_contents: &str,
5342    num_threads: Option<usize>,
5343) -> Result<Vec<types::ConFrame>, error::LocatedParseError> {
5344    use rayon::prelude::*;
5345
5346    let boundaries = frame_start_offsets(file_contents);
5347    let parse_chunks = || -> Result<Vec<types::ConFrame>, error::LocatedParseError> {
5348        let num_frames = boundaries.len();
5349        let parts: Vec<Result<types::ConFrame, error::LocatedParseError>> = (0..num_frames)
5350            .into_par_iter()
5351            .map(|i| {
5352                let start = boundaries[i];
5353                let end = if i + 1 < num_frames {
5354                    boundaries[i + 1]
5355                } else {
5356                    file_contents.len()
5357                };
5358                let chunk = &file_contents[start..end];
5359                let mut iter = ConFrameIterator::new(chunk);
5360                match iter.next() {
5361                    Some(Ok(frame)) => Ok(frame),
5362                    Some(Err(e)) => {
5363                        let local = iter.lines.line_no();
5364                        let base = file_line_at(file_contents, start);
5365                        let cursor = if local == 0 { base } else { base + local - 1 };
5366                        Err(error::LocatedParseError::new(e, cursor, i as u64))
5367                    }
5368                    None => Err(error::LocatedParseError::new(
5369                        error::ParseError::IncompleteFrame,
5370                        file_line_at(file_contents, start),
5371                        i as u64,
5372                    )),
5373                }
5374            })
5375            .collect();
5376        let mut frames = Vec::with_capacity(parts.len());
5377        for part in parts {
5378            frames.push(part?);
5379        }
5380        Ok(frames)
5381    };
5382    match num_threads {
5383        None => parse_chunks(),
5384        Some(n) => match shared_pool(n.max(1)) {
5385            Some(pool) => pool.install(parse_chunks),
5386            None => parse_chunks(),
5387        },
5388    }
5389}
5390
5391#[cfg(all(test, feature = "parallel"))]
5392mod parallel_strong_scale_tests {
5393    use super::*;
5394    use std::path::PathBuf;
5395
5396    fn multi_frame_fixture() -> String {
5397        let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con");
5398        let one = std::fs::read_to_string(p).expect("fixture");
5399        // Enough frames for >1 worker to exercise the pool.
5400        one.repeat(8)
5401    }
5402
5403    fn sequential_frames(text: &str) -> Vec<types::ConFrame> {
5404        ConFrameIterator::new(text)
5405            .map(|r| r.expect("seq frame"))
5406            .collect()
5407    }
5408
5409    fn frames_payload_key(f: &types::ConFrame) -> (usize, Vec<(String, f64, f64, f64)>) {
5410        let atoms: Vec<_> = f
5411            .atom_data
5412            .iter()
5413            .enumerate()
5414            .map(|(i, a)| {
5415                let xyz = f.xyz_at(i);
5416                (a.symbol.to_string(), xyz[0], xyz[1], xyz[2])
5417            })
5418            .collect();
5419        (f.atom_data.len(), atoms)
5420    }
5421
5422    #[test]
5423    fn parallel_workers_match_sequential_payloads() {
5424        let text = multi_frame_fixture();
5425        let seq = sequential_frames(&text);
5426        assert!(seq.len() >= 8);
5427        let seq_keys: Vec<_> = seq.iter().map(frames_payload_key).collect();
5428
5429        for workers in [1usize, 2, 4] {
5430            let par = parse_frames_parallel_with_threads(&text, Some(workers));
5431            assert_eq!(par.len(), seq.len(), "workers={workers}");
5432            let par_keys: Vec<_> = par
5433                .into_iter()
5434                .map(|r| frames_payload_key(&r.expect("par frame")))
5435                .collect();
5436            assert_eq!(par_keys, seq_keys, "workers={workers} frame payloads");
5437        }
5438
5439        // Global pool path agrees too.
5440        let par_default = parse_frames_parallel(&text);
5441        let def_keys: Vec<_> = par_default
5442            .into_iter()
5443            .map(|r| frames_payload_key(&r.expect("par")))
5444            .collect();
5445        assert_eq!(def_keys, seq_keys);
5446    }
5447
5448    fn live_threads() -> usize {
5449        std::fs::read_to_string("/proc/self/status")
5450            .unwrap()
5451            .lines()
5452            .find(|line| line.starts_with("Threads:"))
5453            .unwrap()
5454            .split_whitespace()
5455            .nth(1)
5456            .unwrap()
5457            .parse()
5458            .unwrap()
5459    }
5460
5461    /// A file past the old map and pool gates stays on this thread.
5462    #[test]
5463    fn default_read_of_a_wide_file_stays_on_the_calling_thread() {
5464        const CHILD: &str = "READCON_DEFAULT_THREAD_CHILD";
5465        const NAME: &str = "iterators::parallel_strong_scale_tests::default_read_of_a_wide_file_stays_on_the_calling_thread";
5466        if std::env::var_os(CHILD).is_none() {
5467            let out = std::process::Command::new(std::env::current_exe().unwrap())
5468                .args([NAME, "--exact", "--test-threads=1"])
5469                .env(CHILD, "1")
5470                .output()
5471                .unwrap();
5472            let stdout = String::from_utf8_lossy(&out.stdout);
5473            assert!(
5474                out.status.success() && stdout.contains("test result: ok. 1 passed;"),
5475                "{stdout}{}",
5476                String::from_utf8_lossy(&out.stderr)
5477            );
5478            return;
5479        }
5480        let dir = tempfile::tempdir().unwrap();
5481        let path = dir.path().join("wide.con");
5482        let one = std::fs::read_to_string(
5483            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con"),
5484        )
5485        .unwrap();
5486        std::fs::write(&path, one.repeat(200)).unwrap();
5487        assert!(std::fs::metadata(&path).unwrap().len() > 64 * 1024);
5488        let before = live_threads();
5489        let frames = super::read_all_frames(&path).unwrap();
5490        let after = live_threads();
5491        assert_eq!(before, after, "default read started worker threads");
5492        assert!(frames.len() > 1);
5493        let text = std::fs::read_to_string(&path).unwrap();
5494        let sequential = super::frames_from_text(&text, None).unwrap();
5495        assert_eq!(sequential.len(), frames.len());
5496        assert_eq!(
5497            sequential[0].x_at(0),
5498            frames[0].x_at(0),
5499            "default read changed a coordinate"
5500        );
5501    }
5502}
5503
5504#[cfg(all(test, feature = "parallel"))]
5505mod parallel_header_scan_tests {
5506    use super::*;
5507    use std::path::PathBuf;
5508
5509    fn fixture(name: &str) -> String {
5510        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
5511            .join("resources/test")
5512            .join(name);
5513        std::fs::read_to_string(path).expect(name)
5514    }
5515
5516    /// A cut on the byte between `\r` and `\n`. The `\n` is in the next chunk.
5517    fn assert_crlf_gap_cut(text: &str) {
5518        let bytes = text.as_bytes();
5519        let mut found = 0usize;
5520        let mut i = 0usize;
5521        while i + 1 < bytes.len() && found < 6 {
5522            if bytes[i] == b'\r' && bytes[i + 1] == b'\n' {
5523                let cut = i + 1;
5524                assert_eq!(bytes[cut - 1], b'\r');
5525                assert_eq!(bytes[cut], b'\n');
5526                assert_cuts_match(text, &[0, cut, bytes.len()]);
5527                found += 1;
5528                i += 2;
5529                continue;
5530            }
5531            i += 1;
5532        }
5533        assert!(found > 0, "fixture has no CRLF pair");
5534    }
5535
5536    fn assert_cuts_match(text: &str, cuts: &[usize]) {
5537        let serial_nl: Vec<usize> = memchr::memchr_iter(b'\n', text.as_bytes()).collect();
5538        let stitched = newline_positions_at_cuts(text.as_bytes(), cuts);
5539        assert_eq!(stitched, serial_nl, "newline stitch at {cuts:?}");
5540        let serial = frame_start_offsets_serial(text);
5541        let parallel = frame_start_offsets_at_cuts(text, cuts);
5542        assert_eq!(parallel, serial, "frame offsets at {cuts:?}");
5543    }
5544
5545    fn header_straddle_cuts(text: &str) -> Vec<Vec<usize>> {
5546        let serial = frame_start_offsets_serial(text);
5547        let bytes = text.as_bytes();
5548        let mut out = Vec::new();
5549        // Equal splits, plus a cut forced into a header line of every frame.
5550        for n in [2usize, 3, 4, 8] {
5551            out.push(equal_cuts(bytes.len(), n));
5552        }
5553        for (index, &start) in serial.iter().enumerate() {
5554            let next = serial.get(index + 1).copied().unwrap_or(bytes.len());
5555            // The header ends at the coordinate label. The window is that
5556            // header, not a fixed count of bytes past the frame start.
5557            let window = super::header_window_end(bytes, start, next);
5558            let mut line = start;
5559            while line < window {
5560                let Some(rel) = memchr::memchr(b'\n', &bytes[line..window]) else {
5561                    break;
5562                };
5563                let end = line + rel;
5564                if end - line > 1 {
5565                    let mid = line + (end - line) / 2;
5566                    // mid is inside the line, so the header byte sits across two chunks.
5567                    assert!(mid > line && mid < end);
5568                    out.push(vec![0, mid, bytes.len()]);
5569                }
5570                line = end + 1;
5571            }
5572        }
5573        out
5574    }
5575
5576    fn assert_slab(text: &str) {
5577        assert!(!text.is_empty());
5578        for cuts in header_straddle_cuts(text) {
5579            assert_cuts_match(text, &cuts);
5580        }
5581        let bare = text.trim_end_matches(['\n', '\r']);
5582        if !bare.is_empty() {
5583            assert_cuts_match(bare, &equal_cuts(bare.len(), 4));
5584            let mid = bare.len() / 2;
5585            let line_start = bare[..mid].rfind('\n').map(|i| i + 1).unwrap_or(0);
5586            let line_end = bare[mid..]
5587                .find('\n')
5588                .map(|i| mid + i)
5589                .unwrap_or(bare.len());
5590            if line_end - line_start > 1 {
5591                let cut = line_start + (line_end - line_start) / 2;
5592                assert_cuts_match(bare, &[0, cut, bare.len()]);
5593            }
5594        }
5595        let tailed = format!("{text}\n   \n\t\n");
5596        assert_cuts_match(
5597            &tailed,
5598            &[0, 3, tailed.len() / 2, tailed.len() - 1, tailed.len()],
5599        );
5600        let crlf = text.replace('\n', "\r\n");
5601        assert_cuts_match(&crlf, &equal_cuts(crlf.len(), 5));
5602        assert_crlf_gap_cut(&crlf);
5603        let serial = frame_start_offsets_serial(text);
5604        if serial.len() >= 2 {
5605            let second = serial[1];
5606            let next = serial.get(2).copied().unwrap_or(text.len());
5607            let broken_at = second + (next - second) / 2;
5608            let broken = &text[..broken_at.max(1)];
5609            assert_cuts_match(broken, &[0, 1.max(broken.len() / 3), broken.len()]);
5610        }
5611    }
5612
5613    #[test]
5614    fn chunked_header_scan_matches_serial_offsets() {
5615        assert_eq!(frame_start_offsets_serial(""), frame_start_offsets(""));
5616        assert_cuts_match("\n", &[0, 1]);
5617        assert_cuts_match("   \n\n", &[0, 2, 5]);
5618        for name in [
5619            "tiny_cuh2.con",
5620            "tiny_cuh2.convel",
5621            "tiny_cuh2_forces.con",
5622            "tiny_cuh2_vel_forces.con",
5623            "cuh2.con",
5624        ] {
5625            let one = fixture(name);
5626            assert_slab(&one);
5627            assert_slab(&one.repeat(3));
5628        }
5629        // The bytes parser (the read_con path) uses the same stitch.
5630        // The single frame is the short file. The repeat is a wider file.
5631        // Both use the requested worker count. There is no length cutoff.
5632        let one = fixture("cuh2.con");
5633        for wide in [one.clone(), one.repeat(8)] {
5634            let serial = frame_start_offsets_serial(&wide);
5635            for workers in [2usize, 3, 4, 8] {
5636                let parallel = frame_start_offsets_with_threads(&wide, Some(workers));
5637                assert_eq!(parallel, serial, "workers={workers} bytes={}", wide.len());
5638                let parsed =
5639                    frames_from_bytes(wide.as_bytes(), Some(workers)).expect("bytes parse");
5640                assert_eq!(parsed.len(), serial.len());
5641                let seq = frames_from_text(&wide, Some(1)).expect("serial parse");
5642                assert_eq!(parsed.len(), seq.len());
5643                assert_eq!(parsed[0].x_at(0), seq[0].x_at(0));
5644                assert_eq!(
5645                    parsed
5646                        .last()
5647                        .unwrap()
5648                        .z_at(parsed.last().unwrap().atom_data.len() - 1),
5649                    seq.last()
5650                        .unwrap()
5651                        .z_at(seq.last().unwrap().atom_data.len() - 1)
5652                );
5653            }
5654        }
5655    }
5656}
5657
5658/// End of the header window used by straddle cuts.
5659///
5660/// The header runs up to the line that starts the coordinate block.
5661/// When that label is absent the window is the next frame start.
5662#[cfg(all(test, feature = "parallel"))]
5663fn header_window_end(bytes: &[u8], start: usize, limit: usize) -> usize {
5664    let limit = limit.min(bytes.len());
5665    let marker = b"Coordinates";
5666    let mut line = start;
5667    while line < limit {
5668        let rest = &bytes[line..limit];
5669        let rel = memchr::memchr(b'\n', rest).unwrap_or(rest.len());
5670        let content_end = line + rel;
5671        let content = &bytes[line..content_end];
5672        let trimmed = match content.iter().position(|byte| !byte.is_ascii_whitespace()) {
5673            Some(index) => &content[index..],
5674            None => b"",
5675        };
5676        if trimmed.starts_with(marker) {
5677            return line;
5678        }
5679        if content_end >= limit {
5680            break;
5681        }
5682        line = content_end + 1;
5683    }
5684    limit
5685}
5686
5687#[cfg(all(test, feature = "parallel"))]
5688mod parallel_frame_parse_tests {
5689    use super::*;
5690    use std::path::PathBuf;
5691
5692    const ZERO_ATOM: &str = "\
5693zero-atom frame
5694{\"con_spec_version\":3,\"con_spec_minor\":1,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}
569510.0 10.0 10.0
569690.0 90.0 90.0
5697
5698
56990
5700
5701
5702";
5703
5704    fn fixture(name: &str) -> String {
5705        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
5706            .join("resources/test")
5707            .join(name);
5708        std::fs::read_to_string(path).expect(name)
5709    }
5710
5711    fn serial_results(text: &str) -> Vec<Result<types::ConFrame, error::ParseError>> {
5712        ConFrameIterator::new(text).collect()
5713    }
5714
5715    fn written(frame: &types::ConFrame) -> Vec<u8> {
5716        let mut out = Vec::new();
5717        {
5718            let mut writer = crate::writer::ConFrameWriter::new(&mut out);
5719            writer.write_frame(frame).expect("write");
5720            writer.flush().expect("flush");
5721        }
5722        out
5723    }
5724
5725    fn assert_same_results(
5726        label: &str,
5727        serial: Vec<Result<types::ConFrame, error::ParseError>>,
5728        parallel: Vec<Result<types::ConFrame, error::ParseError>>,
5729    ) {
5730        assert_eq!(serial.len(), parallel.len(), "{label} count");
5731        for (i, (left, right)) in serial.into_iter().zip(parallel).enumerate() {
5732            match (left, right) {
5733                (Ok(a), Ok(b)) => {
5734                    assert_eq!(written(&a), written(&b), "{label} bytes frame {i}");
5735                    assert_eq!(a, b, "{label} fields frame {i}");
5736                }
5737                (Err(a), Err(b)) => {
5738                    assert_eq!(
5739                        format!("{a:?}"),
5740                        format!("{b:?}"),
5741                        "{label} error frame {i}"
5742                    );
5743                }
5744                (Ok(_), Err(err)) => panic!("{label} frame {i} serial ok parallel {err:?}"),
5745                (Err(err), Ok(_)) => panic!("{label} frame {i} serial {err:?} parallel ok"),
5746            }
5747        }
5748    }
5749
5750    fn assert_workers(label: &str, text: &str) {
5751        let serial_ok = serial_results(text).iter().all(|item| item.is_ok());
5752        for workers in [1usize, 2, 3, 4, 8] {
5753            let parallel = parse_frames_parallel_with_threads(text, Some(workers));
5754            assert_same_results(
5755                &format!("{label} workers {workers}"),
5756                serial_results(text),
5757                parallel,
5758            );
5759            let bounds = collect_frame_starts(ConFrameIterator::new(text), true);
5760            let at = parse_frames_at_offsets(text, &bounds, Some(workers));
5761            assert_same_results(
5762                &format!("{label} offsets workers {workers}"),
5763                serial_results(text),
5764                at,
5765            );
5766        }
5767        if serial_ok {
5768            for workers in [2usize, 3, 8] {
5769                let bytes = frames_from_bytes(text.as_bytes(), Some(workers)).expect(label);
5770                let seq = frames_from_text(text, Some(1)).expect(label);
5771                assert_eq!(bytes.len(), seq.len(), "{label} byte count");
5772                for (i, (a, b)) in bytes.iter().zip(seq.iter()).enumerate() {
5773                    assert_eq!(written(a), written(b), "{label} byte path frame {i}");
5774                    assert_eq!(a, b, "{label} byte path fields frame {i}");
5775                }
5776            }
5777        }
5778    }
5779
5780    fn crlf_gap_offsets(text: &str) -> Vec<usize> {
5781        let bytes = text.as_bytes();
5782        let mut cut = None;
5783        let mut i = 0usize;
5784        while i + 1 < bytes.len() {
5785            if bytes[i] == b'\r' && bytes[i + 1] == b'\n' {
5786                cut = Some(i + 1);
5787                break;
5788            }
5789            i += 1;
5790        }
5791        let cut = cut.expect("crlf");
5792        frame_start_offsets_at_cuts(text, &[0, cut, bytes.len()])
5793    }
5794
5795    #[test]
5796    fn parallel_slots_match_serial_frames() {
5797        assert_workers("empty", "");
5798        assert_workers("blank", "\n");
5799        assert_workers("space", "   \n\n");
5800        assert_workers("zero", ZERO_ATOM);
5801        assert_workers("zero-repeat", &ZERO_ATOM.repeat(5));
5802        for name in [
5803            "tiny_cuh2.con",
5804            "tiny_cuh2.convel",
5805            "tiny_cuh2_forces.con",
5806            "tiny_cuh2_vel_forces.con",
5807            "tiny_cuh2_charges_spins_magmoms.con",
5808            "tiny_cuh2_displacements.con",
5809            "tiny_cuh2_spreads.con",
5810            "cuh2.con",
5811        ] {
5812            let one = fixture(name);
5813            assert_workers(name, &one);
5814            assert_workers(&format!("{name} x5"), &one.repeat(5));
5815            let bare = one.trim_end_matches(['\n', '\r']);
5816            assert_workers(&format!("{name} bare"), bare);
5817            let tailed = format!("{one}\n   \n\t\n");
5818            assert_workers(&format!("{name} tail"), &tailed);
5819            let crlf = one.replace('\n', "\r\n");
5820            assert_workers(&format!("{name} crlf"), &crlf);
5821            let gap = crlf_gap_offsets(&crlf);
5822            assert_eq!(
5823                gap,
5824                frame_start_offsets_serial(&crlf),
5825                "{name} crlf gap offsets"
5826            );
5827            let parsed = parse_frames_at_offsets(&crlf, &gap, Some(4));
5828            assert_same_results(
5829                &format!("{name} crlf gap parse"),
5830                serial_results(&crlf),
5831                parsed,
5832            );
5833            let serial_offs = frame_start_offsets_serial(&one);
5834            let broken: &str = if serial_offs.len() >= 2 {
5835                let second = serial_offs[1];
5836                let next = serial_offs.get(2).copied().unwrap_or(one.len());
5837                &one[..second + (next - second) / 2]
5838            } else if one.len() > 8 {
5839                &one[..one.len() / 2]
5840            } else {
5841                ""
5842            };
5843            if !broken.is_empty() {
5844                let serial_err = frames_from_text(broken, Some(1))
5845                    .err()
5846                    .map(|e| format!("{e:?}"));
5847                assert!(serial_err.is_some(), "{name} chopped still parsed");
5848                for workers in [1usize, 2, 4, 8] {
5849                    let parallel_err = frames_from_text(broken, Some(workers))
5850                        .err()
5851                        .map(|e| format!("{e:?}"));
5852                    assert_eq!(parallel_err, serial_err, "{name} chopped workers {workers}");
5853                    let byte_err = frames_from_bytes(broken.as_bytes(), Some(workers))
5854                        .err()
5855                        .map(|e| format!("{e:?}"));
5856                    assert_eq!(
5857                        byte_err, serial_err,
5858                        "{name} chopped bytes workers {workers}"
5859                    );
5860                }
5861            }
5862        }
5863    }
5864}
5865
5866#[cfg(all(test, feature = "parallel"))]
5867mod phased_read_tests {
5868    use super::*;
5869    use std::path::PathBuf;
5870
5871    fn fixture(name: &str) -> String {
5872        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
5873            .join("resources/test")
5874            .join(name);
5875        std::fs::read_to_string(path).expect(name)
5876    }
5877
5878    #[test]
5879    fn phased_bytes_match_serial_frames() {
5880        let text = fixture("cuh2.con").repeat(4);
5881        let serial = frames_from_text(&text, Some(1)).expect("serial");
5882        for workers in [1usize, 2, 4, 8] {
5883            let phased = frames_from_bytes_phased(text.as_bytes(), Some(workers)).expect("phased");
5884            let parallel = phased.frames;
5885            assert_eq!(parallel.len(), serial.len(), "workers={workers}");
5886            assert!(
5887                phased.scan_s >= 0.0 && phased.slot_alloc_s >= 0.0 && phased.worker_parse_s >= 0.0
5888            );
5889            assert_eq!(parallel[0], serial[0], "workers={workers} first");
5890            assert_eq!(
5891                parallel.last().unwrap(),
5892                serial.last().unwrap(),
5893                "workers={workers} last"
5894            );
5895            let slab = pack_position_slab(&serial, workers).expect("slab");
5896            let stride = serial[0].positions.nrows() * 3;
5897            let src = serial[0].positions.f64_slice().expect("f64");
5898            assert_eq!(&slab[..stride], src);
5899            let (chunked, _) = measure_newline_scan(&text, workers.max(2), true);
5900            let (plain, _) = measure_newline_scan(&text, 1, false);
5901            if workers >= 2 {
5902                assert_eq!(chunked, plain);
5903            }
5904        }
5905    }
5906
5907    #[test]
5908    fn phased_file_matches_serial_and_maps_a_wide_file() {
5909        let _scratch = tempfile::tempdir().unwrap();
5910        let text = fixture("cuh2.con").repeat(5);
5911        let dir = _scratch.path();
5912        let path = dir.join("readcon-phased-wide.con");
5913        std::fs::write(&path, &text).expect("write");
5914        let phased = read_all_frames_phased(&path, Some(4)).expect("phased");
5915        let serial = frames_from_text(&text, Some(1)).expect("serial");
5916        assert_eq!(phased.frames, serial);
5917        assert!(phased.phases.mapped, "a file past 64 KiB is mapped");
5918        assert!(phased.phases.worker_parse_s >= 0.0);
5919        assert_eq!(phased.n_bytes, text.len());
5920        let _ = std::fs::remove_file(&path);
5921    }
5922
5923    #[test]
5924    fn equal_span_boundaries_match_the_serial_walk() {
5925        let text = fixture("cuh2.con").repeat(8);
5926        let bytes = text.as_bytes();
5927        let got = equal_span_boundaries(bytes, 4).expect("equal span");
5928        let expect = collect_frame_starts(ConFrameIterator::from_bytes(bytes), true);
5929        assert_eq!(got, expect);
5930        assert_eq!(got.len(), 8);
5931        let phased = frames_from_bytes_phased(bytes, Some(4)).expect("phased");
5932        assert_eq!(phased.scan_kind, SCAN_EQUAL_SPAN);
5933        let wide = fixture("cuh2.con").repeat(32);
5934        let ranges = frames_from_bytes_phased(wide.as_bytes(), Some(4)).expect("ranges");
5935        assert_eq!(ranges.frames.len(), 32);
5936        assert_eq!(
5937            ranges.chunk_s.len(),
5938            4,
5939            "equal frames are one range per worker, so the shell stash is one burst"
5940        );
5941        assert_eq!(
5942            ranges.frames,
5943            frames_from_text(&wide, Some(1)).expect("wide serial")
5944        );
5945        assert_eq!(
5946            phased.frames,
5947            frames_from_text(&text, Some(1)).expect("serial")
5948        );
5949        let tailed = format!("{text}\n\n  \n");
5950        let tail_phased = frames_from_bytes_phased(tailed.as_bytes(), Some(4)).expect("tail");
5951        assert_eq!(tail_phased.scan_kind, SCAN_EQUAL_SPAN);
5952        assert_eq!(
5953            tail_phased.frames,
5954            frames_from_text(&tailed, Some(1)).expect("tail serial")
5955        );
5956    }
5957
5958    #[test]
5959    fn a_wide_frame_matches_the_serial_parse() {
5960        let n = 5000usize;
5961        let mut text = String::new();
5962        text.push_str(
5963            "grid\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n1\n",
5964        );
5965        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
5966        for i in 0..n {
5967            text.push_str(&format!("{i}.125000 0.250000 0.500000 0 {i}\n"));
5968        }
5969        let serial = frames_from_text(&text, Some(1)).expect("serial");
5970        let parallel = frames_from_bytes_phased(text.as_bytes(), Some(4)).expect("parallel");
5971        assert_eq!(parallel.frames, serial);
5972    }
5973
5974    fn one_species_frame(n: usize) -> String {
5975        let mut text = String::new();
5976        text.push_str(
5977            "grid\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n1\n",
5978        );
5979        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
5980        for i in 0..n {
5981            text.push_str(&format!("{i}.125000 0.250000 0.500000 0 {i}\n"));
5982        }
5983        text
5984    }
5985
5986    fn two_species_frame(n_cu: usize, n_h: usize) -> String {
5987        let mut text = String::new();
5988        text.push_str(
5989            "grid\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n2\n",
5990        );
5991        text.push_str(&format!("{n_cu} {n_h}\n63.546 1.008\n"));
5992        text.push_str("Cu\nCoordinates of Component 1\n");
5993        for i in 0..n_cu {
5994            text.push_str(&format!("{i}.125000 0.250000 0.500000 0 {i}\n"));
5995        }
5996        text.push_str("H\nCoordinates of Component 2\n");
5997        for i in 0..n_h {
5998            text.push_str(&format!("1.500000 2.250000 {i}.125000 0 {}\n", n_cu + i));
5999        }
6000        text
6001    }
6002
6003    /// Drop the coordinate-row table from a gzip RC extra field.
6004    ///
6005    /// The plain lengths stay, which is the index written before the row
6006    /// spans existed. Member starts move back by the bytes removed.
6007    fn strip_gzip_row_table(bytes: &mut Vec<u8>) {
6008        assert_eq!(&bytes[0..2], b"\x1f\x8b");
6009        let xlen = u16::from_le_bytes([bytes[10], bytes[11]]) as usize;
6010        assert_eq!(&bytes[12..14], b"RC");
6011        let sub = u16::from_le_bytes([bytes[14], bytes[15]]) as usize;
6012        assert!(bytes[16..].starts_with(b"RCZ1"));
6013        let count = u16::from_le_bytes([bytes[20], bytes[21]]) as usize;
6014        let row_bytes = 8 * count;
6015        let payload_at = 16usize;
6016        assert_eq!(sub, xlen - 4);
6017        assert!(sub >= 6 + 16 * count + row_bytes);
6018        let row_at = payload_at + sub - row_bytes;
6019        bytes.drain(row_at..row_at + row_bytes);
6020        let new_sub = (sub - row_bytes) as u16;
6021        let new_xlen = (xlen - row_bytes) as u16;
6022        bytes[10..12].copy_from_slice(&new_xlen.to_le_bytes());
6023        bytes[14..16].copy_from_slice(&new_sub.to_le_bytes());
6024        for index in 1..count {
6025            let at = payload_at + 6 + 8 * index;
6026            let start = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap());
6027            let start = start - row_bytes as u64;
6028            bytes[at..at + 8].copy_from_slice(&start.to_le_bytes());
6029        }
6030    }
6031
6032    #[test]
6033    fn indexed_gzip_read_matches_the_serial_frame() {
6034        let text = one_species_frame(5000);
6035        let serial = frames_from_text(&text, Some(1)).expect("serial");
6036        let dir = tempfile::tempdir().unwrap();
6037        let path = dir.path().join("wide.con.gz");
6038        let members = crate::compression::write_gzip_members_n(&path, text.as_bytes(), 4).unwrap();
6039        assert!(members > 1);
6040        let piped = read_all_frames_phased(&path, Some(4)).expect("piped");
6041        assert_eq!(piped.frames, serial);
6042        let mixed = two_species_frame(3000, 2000);
6043        let mixed_serial = frames_from_text(&mixed, Some(1)).expect("mixed serial");
6044        let mixed_path = dir.path().join("mixed.con.gz");
6045        crate::compression::write_gzip_members_n(&mixed_path, mixed.as_bytes(), 4).unwrap();
6046        let mixed_read = read_all_frames_phased(&mixed_path, Some(4)).expect("mixed");
6047        assert_eq!(mixed_read.frames, mixed_serial);
6048        let mut old = std::fs::read(&path).unwrap();
6049        strip_gzip_row_table(&mut old);
6050        let old_path = dir.path().join("old.con.gz");
6051        std::fs::write(&old_path, &old).unwrap();
6052        let fallback = read_all_frames_phased(&old_path, Some(4)).expect("old index");
6053        assert_eq!(fallback.frames, serial);
6054    }
6055
6056    #[cfg(feature = "zstd")]
6057    #[test]
6058    fn indexed_zstd_read_matches_the_serial_frame() {
6059        let text = one_species_frame(5000);
6060        let serial = frames_from_text(&text, Some(1)).expect("serial");
6061        let dir = tempfile::tempdir().unwrap();
6062        let path = dir.path().join("wide.con.zst");
6063        let members = crate::compression::write_zstd_members_n(&path, text.as_bytes(), 4).unwrap();
6064        assert!(members > 1);
6065        let piped = read_all_frames_phased(&path, Some(4)).expect("piped");
6066        assert_eq!(piped.frames, serial);
6067    }
6068
6069    #[test]
6070    fn unequal_byte_spans_use_the_indexed_header_walk() {
6071        let one = fixture("cuh2.con");
6072        let mut longer = one.clone();
6073        longer.insert_str(0, "pad ");
6074        let text = format!("{one}{longer}{one}");
6075        let serial = frames_from_text(&text, Some(1)).expect("serial");
6076        let phased = frames_from_bytes_phased(text.as_bytes(), Some(4)).expect("phased");
6077        assert_eq!(phased.scan_kind, SCAN_INDEXED);
6078        assert_eq!(phased.frames, serial);
6079        assert!(equal_span_boundaries(text.as_bytes(), 4).is_none());
6080    }
6081
6082    #[test]
6083    fn a_whitespace_tail_uses_the_equal_span_walk() {
6084        let mut text = fixture("cuh2.con").repeat(3);
6085        text.push('\n');
6086        assert!(equal_span_boundaries(text.as_bytes(), 4).is_some());
6087        let serial = frames_from_text(&text, Some(1)).expect("serial");
6088        let parallel = frames_from_bytes_phased(text.as_bytes(), Some(4)).expect("phased");
6089        assert_eq!(parallel.scan_kind, SCAN_EQUAL_SPAN);
6090        assert_eq!(parallel.frames, serial);
6091    }
6092
6093    #[test]
6094    fn touch_checksum_matches_across_worker_counts() {
6095        let text = fixture("cuh2.con").repeat(4);
6096        let serial = frames_from_bytes_phased(text.as_bytes(), Some(1)).expect("serial");
6097        let parallel = frames_from_bytes_phased(text.as_bytes(), Some(4)).expect("parallel");
6098        let slab_s = pack_position_slab(&serial.frames, 1).expect("slab");
6099        let slab_p = pack_position_slab(&parallel.frames, 4).expect("slab");
6100        let left = touch_frame_checksum(&serial.frames, &slab_s, 1).expect("touch");
6101        let right = touch_frame_checksum(&parallel.frames, &slab_p, 4).expect("touch");
6102        assert_eq!(left, right);
6103        assert_ne!(left, 0);
6104    }
6105}
6106
6107#[cfg(test)]
6108mod later_frame_location_tests {
6109    use super::*;
6110    use std::fs;
6111
6112    fn one_atom(coord: &str) -> String {
6113        format!(
6114            "seed\n{{\"con_spec_version\":2}}\n10 10 10\n90 90 90\n0 0\n0 0 0\n1\n1\n1.0\nH\nCoordinates of Component 1\n{coord}\n"
6115        )
6116    }
6117
6118    fn bad_count_frame() -> String {
6119        "seed\n{\"con_spec_version\":2}\n10 10 10\n90 90 90\n0 0\n0 0 0\n1\n-1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n".into()
6120    }
6121
6122    fn two_frames() -> String {
6123        format!("{}{}", one_atom("0 0 0 0 0"), bad_count_frame())
6124    }
6125
6126    fn assert_later_count(
6127        err: &error::ParseError,
6128        line: u32,
6129        frame: u64,
6130        iter: &ConFrameIterator<'_>,
6131    ) {
6132        assert_eq!(err.class_name(), "InvalidCount", "{err}");
6133        assert_eq!(iter.lines.line_no(), line, "{err}");
6134        assert_eq!(iter.frame_index(), frame, "{err}");
6135    }
6136
6137    fn assert_first_pass(err: Box<dyn std::error::Error>) {
6138        let located = err
6139            .downcast_ref::<error::LocatedParseError>()
6140            .unwrap_or_else(|| panic!("first pass lost the location: {err}"));
6141        assert_eq!(located.error.class_name(), "InvalidCount", "{located:?}");
6142        assert_eq!(located.line, 20, "{located:?}");
6143        assert_eq!(located.frame_index, 1, "{located:?}");
6144    }
6145
6146    fn take_err<T>(result: Result<T, Box<dyn std::error::Error>>) -> Box<dyn std::error::Error> {
6147        match result {
6148            Err(err) => err,
6149            Ok(_) => panic!("expected a parse error"),
6150        }
6151    }
6152
6153    /// The batch readers report the later frame from the parse that failed.
6154    /// A second open of the path is not required.
6155    #[test]
6156    fn batch_readers_keep_the_later_frame_on_the_first_pass() {
6157        let _scratch = tempfile::tempdir().unwrap();
6158        let path = _scratch.path().join(format!(
6159            "readcon-later-frame-first-{}.con",
6160            std::process::id()
6161        ));
6162        fs::write(&path, two_frames()).unwrap();
6163        for threads in [None, Some(1), Some(2)] {
6164            assert_first_pass(take_err(read_all_frames_with_threads(&path, threads)));
6165            assert_first_pass(take_err(read_all_frames_phased(&path, threads)));
6166            assert_first_pass(take_err(read_positions_with_threads(&path, threads)));
6167        }
6168        let _ = fs::remove_file(&path);
6169    }
6170
6171    /// An error in the second frame keeps that frame's index and file line.
6172    #[test]
6173    fn next_forward_and_skip_locate_the_later_frame() {
6174        let text = two_frames();
6175
6176        let mut iter = ConFrameIterator::new(&text);
6177        assert!(iter.next().unwrap().is_ok());
6178        let err = iter.next().unwrap().unwrap_err();
6179        assert_later_count(&err, 20, 1, &iter);
6180
6181        let mut iter = ConFrameIterator::new(&text);
6182        assert!(iter.forward().unwrap().is_ok());
6183        let err = iter.forward().unwrap().unwrap_err();
6184        assert_later_count(&err, 20, 1, &iter);
6185
6186        let mut iter = ConFrameIterator::new(&text);
6187        let err = iter.skip_frames(3).unwrap_err();
6188        assert_later_count(&err, 20, 1, &iter);
6189    }
6190
6191    /// The blank line that opens a velocity block is a file line. A later
6192    /// frame's error must include it. 12 coordinate lines, the separator,
6193    /// and 3 velocity lines put the next frame's line 8 at file line 24.
6194    #[test]
6195    fn skip_after_a_velocity_frame_keeps_the_separator_line() {
6196        let text = format!(
6197            "{}\nH\nVelocities of Component 1\n0 0 0 0 0\n{}",
6198            one_atom("0 0 0 0 0"),
6199            bad_count_frame()
6200        );
6201        let mut iter = ConFrameIterator::new(&text);
6202        assert!(iter.forward().unwrap().is_ok());
6203        let err = iter.forward().unwrap().unwrap_err();
6204        assert_later_count(&err, 24, 1, &iter);
6205    }
6206
6207    #[test]
6208    fn count_frames_locates_the_later_frame() {
6209        let _scratch = tempfile::tempdir().unwrap();
6210        let path = _scratch.path().join(format!(
6211            "readcon-later-frame-count-{}.con",
6212            std::process::id()
6213        ));
6214        fs::write(&path, two_frames()).unwrap();
6215        let err = count_frames(&path).unwrap_err();
6216        let _ = fs::remove_file(&path);
6217        match err {
6218            LoadError::Parse(located) => {
6219                assert_eq!(located.error.class_name(), "InvalidCount");
6220                assert_eq!(located.line, 20, "{located}");
6221                assert_eq!(located.frame_index, 1, "{located}");
6222            }
6223            other => panic!("expected a located parse error, got {other}"),
6224        }
6225    }
6226
6227    /// Metadata on line 2 of the second frame is file line 14, not line 2.
6228    /// This is the serial contract the collective reader matches.
6229    #[test]
6230    fn metadata_in_a_later_frame_reports_that_frames_line() {
6231        let bad = "seed\n{not-json\n10 10 10\n90 90 90\n0 0\n0 0 0\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n";
6232        let text = format!("{}{}", one_atom("0 0 0 0 0"), bad);
6233        for threads in [Some(1usize), Some(2)] {
6234            let err = frames_from_text_located(&text, threads).unwrap_err();
6235            assert_eq!(
6236                err.error.class_name(),
6237                "InvalidMetadataJson",
6238                "{threads:?}: {err}"
6239            );
6240            assert_eq!(err.frame_index, 1, "{threads:?}");
6241            assert_eq!(err.line, 14, "{threads:?}: {err}");
6242        }
6243    }
6244
6245    /// Several spans after the first frame fail. Serial collection keeps
6246    /// the earliest slot. The parallel position reader must report that
6247    /// same line and frame index.
6248    ///
6249    /// The first frame is large. A later worker can fail before the
6250    /// calling thread reaches the earliest bad span, which is the case
6251    /// that used to return the later slot.
6252    #[test]
6253    fn parallel_positions_report_the_earliest_failing_slot() {
6254        let _scratch = tempfile::tempdir().unwrap();
6255        const SLOW_ATOMS: usize = 20_000;
6256        let slow = counted_frame(SLOW_ATOMS);
6257        let bad = counted_frame(1);
6258        let text = format!("{slow}{bad}{bad}{bad}");
6259        let earliest_line = 1 + slow.bytes().filter(|byte| *byte == b'\n').count() as u32;
6260        let path = _scratch
6261            .path()
6262            .join(format!("readcon-earliest-slot-{}.con", std::process::id()));
6263        fs::write(&path, &text).unwrap();
6264        assert_earliest_slot(
6265            take_err(read_positions_with_threads(&path, Some(1))),
6266            earliest_line,
6267        );
6268        assert_earliest_slot(
6269            take_err(read_positions_with_threads(&path, Some(2))),
6270            earliest_line,
6271        );
6272        let _ = fs::remove_file(&path);
6273    }
6274
6275    fn counted_frame(natoms: usize) -> String {
6276        let mut body = String::with_capacity(natoms * 10 + 96);
6277        body.push_str("seed\n{\"con_spec_version\":2}\n10 10 10\n90 90 90\n0 0\n0 0 0\n1\n");
6278        body.push_str(&natoms.to_string());
6279        body.push_str("\n1.0\nH\nCoordinates of Component 1\n");
6280        for _ in 0..natoms {
6281            body.push_str("0 0 0 0 0\n");
6282        }
6283        body
6284    }
6285
6286    fn assert_earliest_slot(err: Box<dyn std::error::Error>, line: u32) {
6287        let located = err
6288            .downcast_ref::<error::LocatedParseError>()
6289            .unwrap_or_else(|| panic!("position read lost the location: {err}"));
6290        assert_eq!(located.error.class_name(), "InvalidCount", "{located:?}");
6291        assert_eq!(located.frame_index, 1, "{located:?}");
6292        assert_eq!(located.line, line, "{located:?}");
6293    }
6294}
6295
6296#[cfg(test)]
6297mod frame_equality_tests {
6298    use super::ConFrameIterator;
6299
6300    fn sample_con(frames: usize, long: bool) -> String {
6301        let mut out = String::new();
6302        for f in 0..frames {
6303            let shift = (f as f64) * 1.0e-4;
6304            out.push_str("Generated by benchmark\n");
6305            out.push_str("{\"con_spec_version\":2}\n");
6306            out.push_str("15.3456 21.702 100.0\n");
6307            out.push_str("90.0 90.0 90.0\n");
6308            out.push_str("0 0\n");
6309            out.push_str(&format!("{f} 0 1\n"));
6310            out.push_str("2\n6 2\n63.546 1.00793\n");
6311            out.push_str("Cu\nCoordinates of Component 1\n");
6312            for i in 0..6 {
6313                let x = (i as f64) * 2.557 + 0.6394 + shift;
6314                let y = 0.9045 + shift * 0.5;
6315                let z = (f as f64) * 1.0e-6 + if i == 3 { -1.25 } else { 0.0 };
6316                if long {
6317                    out.push_str(&format!("   {x:.17}    {y:.17}    {z:.17} 0    {i}\n"));
6318                } else {
6319                    out.push_str(&format!("   {x:.6}    {y:.6}    {z:.6} 0    {i}\n"));
6320                }
6321            }
6322            out.push_str("H\nCoordinates of Component 2\n");
6323            out.push_str("   8.6823    9.947   11.733 0  6\n");
6324            out.push_str(&format!("  -7.9421    9.947   {shift:.6} 0  7\n"));
6325        }
6326        out
6327    }
6328
6329    fn sample_convel() -> String {
6330        let mut out = String::new();
6331        for f in 0..3 {
6332            let shift = (f as f64) * 1.0e-4;
6333            out.push_str("Generated by benchmark\n");
6334            out.push_str("{\"con_spec_version\":2}\n");
6335            out.push_str("15.3456 21.702 100.0\n");
6336            out.push_str("90.0 90.0 90.0\n");
6337            out.push_str("0 0\n");
6338            out.push_str(&format!("{f} 0 1\n"));
6339            out.push_str("2\n4 1\n63.546 1.00793\n");
6340            out.push_str("Cu\nCoordinates of Component 1\n");
6341            for i in 0..4 {
6342                let x = (i as f64) * 2.557 + shift;
6343                out.push_str(&format!("   {x:.17}    0.9045    1.0 0    {i}\n"));
6344            }
6345            out.push_str("H\nCoordinates of Component 2\n");
6346            out.push_str("   1.5    2.5    3.5 0  4\n");
6347            out.push_str("\nCu\nVelocities of Component 1\n");
6348            for i in 0..4 {
6349                let vx = (i as f64) * 1.0e-4 - shift;
6350                out.push_str(&format!("   {vx:.17}    -0.5    0.25 0    {i}\n"));
6351            }
6352            out.push_str("H\nVelocities of Component 2\n");
6353            out.push_str("   0.1    -0.2    0.3 0  4\n");
6354        }
6355        out
6356    }
6357
6358    fn reference_f64(token: &str) -> f64 {
6359        let (val, n) = fast_float2::parse_partial::<f64, _>(token).expect(token);
6360        assert_eq!(n, token.len(), "{token}");
6361        val
6362    }
6363
6364    fn assert_rows_match(text: &str, positions: bool) {
6365        let frames: Vec<_> = ConFrameIterator::new(text)
6366            .map(|frame| frame.expect("parse"))
6367            .collect();
6368        assert!(frames.len() >= 2);
6369        let mut frame_i = 0usize;
6370        let mut row = 0usize;
6371        let mut in_section = false;
6372        for line in text.lines() {
6373            let token = line.trim();
6374            if token.is_empty() {
6375                in_section = true;
6376                row = 0;
6377                continue;
6378            }
6379            if token.starts_with("Generated") {
6380                if row > 0 || in_section {
6381                    frame_i += 1;
6382                }
6383                row = 0;
6384                in_section = false;
6385                continue;
6386            }
6387            let cols: Vec<&str> = token.split_whitespace().collect();
6388            if cols.len() < 4 || reference_ok(cols[0]).is_none() {
6389                continue;
6390            }
6391            if cols[3].parse::<u64>().is_err() {
6392                continue;
6393            }
6394            let got = if in_section {
6395                frames[frame_i].atom_data[row].velocity().expect("velocity")
6396            } else if positions {
6397                let p = frames[frame_i].positions.as_f64_row(row);
6398                [p[0], p[1], p[2]]
6399            } else {
6400                continue;
6401            };
6402            for (k, token) in cols.iter().take(3).enumerate() {
6403                assert_eq!(
6404                    got[k].to_bits(),
6405                    reference_f64(token).to_bits(),
6406                    "frame {frame_i} row {row} col {k} token {token} section {in_section}"
6407                );
6408            }
6409            let aos = if in_section {
6410                frames[frame_i].atom_data[row].velocity().unwrap()
6411            } else {
6412                frames[frame_i].xyz_at(row)
6413            };
6414            for k in 0..3 {
6415                assert_eq!(aos[k].to_bits(), got[k].to_bits());
6416            }
6417            row += 1;
6418        }
6419    }
6420
6421    fn reference_ok(token: &str) -> Option<f64> {
6422        let (val, n) = fast_float2::parse_partial::<f64, _>(token).ok()?;
6423        (n == token.len()).then_some(val)
6424    }
6425
6426    #[test]
6427    fn frames_match_general_decimal_parser() {
6428        assert_rows_match(&sample_con(4, true), true);
6429        assert_rows_match(&sample_con(4, false), true);
6430        let text = sample_convel();
6431        let frames: Vec<_> = ConFrameIterator::new(&text)
6432            .map(|frame| frame.expect("convel"))
6433            .collect();
6434        assert_eq!(frames.len(), 3);
6435        assert!(
6436            frames
6437                .iter()
6438                .all(|frame| frame.atom_data[0].velocity().is_some())
6439        );
6440        assert_eq!(frames[0].positions.nrows(), 5);
6441        // Every stored coordinate and velocity bit matches the general parser.
6442        let mut frame_i = 0usize;
6443        let mut coord_row = 0usize;
6444        let mut vel_row = 0usize;
6445        let mut velocities = false;
6446        for line in text.lines() {
6447            let token = line.trim();
6448            if token.starts_with("Generated") && (coord_row > 0 || velocities) {
6449                frame_i += 1;
6450                coord_row = 0;
6451                vel_row = 0;
6452                velocities = false;
6453            }
6454            if token.starts_with("Velocities") {
6455                velocities = true;
6456                continue;
6457            }
6458            let cols: Vec<&str> = token.split_whitespace().collect();
6459            if cols.len() < 5 {
6460                continue;
6461            }
6462            if reference_ok(cols[0]).is_none() || cols[3].parse::<u64>().is_err() {
6463                continue;
6464            }
6465            let row = if velocities { vel_row } else { coord_row };
6466            let got = if velocities {
6467                frames[frame_i].atom_data[row].velocity().unwrap()
6468            } else {
6469                let p = frames[frame_i].positions.as_f64_row(row);
6470                [p[0], p[1], p[2]]
6471            };
6472            for (k, col) in cols.iter().take(3).enumerate() {
6473                assert_eq!(got[k].to_bits(), reference_f64(col).to_bits(), "{token}");
6474            }
6475            if velocities {
6476                let soa = frames[frame_i].velocities.as_f64_row(row);
6477                for k in 0..3 {
6478                    assert_eq!(soa[k].to_bits(), got[k].to_bits());
6479                }
6480                vel_row += 1;
6481            } else {
6482                coord_row += 1;
6483            }
6484        }
6485        assert_eq!(frame_i, 2);
6486        assert_eq!(vel_row, 5);
6487    }
6488}
6489
6490#[cfg(test)]
6491mod newline_skip_tests {
6492    use super::ConFrameIterator;
6493
6494    /// The per-line search [`ConFrameIterator::advance_lines`] used before
6495    /// the counted skip. Positions and errors are the oracle.
6496    fn naive(bytes: &[u8], n: usize) -> Result<usize, ()> {
6497        let mut pos = 0usize;
6498        for i in 0..n {
6499            let rest = &bytes[pos..];
6500            match memchr::memchr(b'\n', rest) {
6501                Some(at) => pos += at + 1,
6502                None => {
6503                    if rest.is_empty() {
6504                        return Err(());
6505                    }
6506                    pos = bytes.len();
6507                    if i + 1 == n {
6508                        return Ok(pos);
6509                    }
6510                    return Err(());
6511                }
6512            }
6513        }
6514        Ok(pos)
6515    }
6516
6517    #[test]
6518    fn counted_skip_matches_per_line_memchr() {
6519        let mut samples = vec![
6520            String::new(),
6521            "a".into(),
6522            "a\n".into(),
6523            "a\nb".into(),
6524            "\n".into(),
6525            "\n\n".into(),
6526            "abc\ndef\nghi".into(),
6527            "a\r\nb\r\n".into(),
6528            "x".repeat(100) + "\n" + &"y".repeat(40),
6529        ];
6530        let path =
6531            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/cuh2.con");
6532        let one = std::fs::read_to_string(&path).unwrap();
6533        samples.push(one.repeat(2));
6534        let bare = one.trim_end_matches(['\n', '\r']).to_string();
6535        samples.push(bare);
6536        for text in samples {
6537            let bytes = text.as_bytes();
6538            for n in [0usize, 1, 2, 3, 6, 7, 9, 40, 200, 450, 1000, 5000] {
6539                let expect = naive(bytes, n);
6540                let mut it = ConFrameIterator::from_bytes(bytes);
6541                let got = it.advance_lines(n).map(|_| it.byte_pos()).map_err(|_| ());
6542                assert_eq!(got, expect, "n={n} len={}", bytes.len());
6543            }
6544        }
6545    }
6546}
6547
6548#[cfg(test)]
6549mod cached_unit_table_read_paths {
6550    use super::*;
6551
6552    const FRAME: &str = "\
6553v3
6554{\"con_spec_version\":3,\"con_spec_minor\":1,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}
655510 10 10
655690 90 90
6557
6558
65591
65601
65611.0
6562H
6563Coordinates of Component 1
65640.5 0.25 0.125 0 7
6565";
6566
6567    fn coords(frame: &types::ConFrame) -> [f64; 3] {
6568        frame.positions.as_f64_row(0)
6569    }
6570
6571    /// The serial iterator, the byte reader behind the C API, and the phased
6572    /// reader behind `read_con` all validate units through the one table.
6573    #[test]
6574    fn read_paths_share_the_cached_unit_table() {
6575        let addr = crate::units::cached_unit_table_addr();
6576        let serial = ConFrameIterator::new(FRAME)
6577            .next()
6578            .expect("frame")
6579            .expect("parse");
6580        let from_bytes = frames_from_bytes(FRAME.as_bytes(), Some(1)).expect("bytes");
6581        let phased = frames_from_bytes_phased(FRAME.as_bytes(), Some(1)).expect("phased");
6582        assert_eq!(from_bytes.len(), 1);
6583        assert_eq!(phased.frames.len(), 1);
6584        assert_eq!(coords(&from_bytes[0]), coords(&serial));
6585        assert_eq!(coords(&phased.frames[0]), coords(&serial));
6586        assert_eq!(crate::units::cached_unit_table_addr(), addr);
6587        let bad = FRAME.replace("angstrom", "not-a-unit");
6588        assert!(ConFrameIterator::new(&bad).next().unwrap().is_err());
6589        assert!(frames_from_bytes(bad.as_bytes(), Some(1)).is_err());
6590        assert!(frames_from_bytes_phased(bad.as_bytes(), Some(1)).is_err());
6591        assert_eq!(crate::units::cached_unit_table_addr(), addr);
6592    }
6593}