Skip to main content

readcon_core/
parser.rs

1use crate::error::ParseError;
2use crate::helpers::symbol_to_atomic_number;
3use crate::types::{
4    AtomDatum, ConFrame, FrameHeader, PreboxHeader, SECTION_CHARGES, SECTION_DISPLACEMENTS,
5    SECTION_ENERGIES, SECTION_FORCES, SECTION_MAGMOMS, SECTION_SPINS, SECTION_SPREADS,
6    SECTION_VELOCITIES, meta,
7};
8use serde::de::Error as _;
9use serde_json::Value;
10use std::collections::HashSet;
11use std::iter::Peekable;
12use std::sync::Arc;
13use std::sync::atomic::{AtomicUsize, Ordering};
14
15/// Line source with peek for section detection (blank-line separators).
16///
17/// Implemented by the memchr cursor on the hot iterator path and by
18/// `Peekable<I>` for tests / ad-hoc callers.
19/// Rows of one coordinate block, in file order.
20///
21/// `atoms` is empty unless the caller asked for per-atom shells. The
22/// numeric columns are the bytes a serial `next_coord_row` loop would
23/// have stored.
24#[doc(hidden)]
25pub struct CoordRows {
26    pub xyz: Vec<f64>,
27    pub ids: Vec<u64>,
28    pub flags: Vec<[bool; 3]>,
29    pub atoms: Vec<crate::types::AtomDatum>,
30    pub consumed: usize,
31}
32
33/// Worker count for a coordinate block that is too wide to hand to one task.
34///
35/// One means the calling thread parses the block. The frame iterator sets
36/// this only for a single wide frame, then puts it back.
37pub(crate) fn wide_workers() -> usize {
38    WIDE_WORKERS.with(|slot| slot.get())
39}
40
41#[cfg(feature = "parallel")]
42pub(crate) fn set_wide_workers(n: usize) {
43    WIDE_WORKERS.with(|slot| slot.set(n.max(1)));
44}
45
46std::thread_local! {
47    static WIDE_WORKERS: std::cell::Cell<usize> = const { std::cell::Cell::new(1) };
48}
49
50/// Output columns for a parallel coordinate fill.
51#[derive(Clone, Copy)]
52#[cfg(feature = "parallel")]
53pub(crate) struct CoordPtrs {
54    pub xyz: *mut f64,
55    pub ids: *mut u64,
56    pub flags: *mut u8,
57}
58
59/// Output columns for one indexed member, including the atom records.
60#[derive(Clone, Copy)]
61#[cfg(feature = "parallel")]
62pub(crate) struct CoordRunOut {
63    pub xyz: *mut f64,
64    pub ids: *mut u64,
65    pub flags: *mut [bool; 3],
66    pub atoms: *mut std::mem::MaybeUninit<crate::types::AtomDatum>,
67}
68
69/// Fill `n` coordinate rows.
70///
71/// `breaks[i]` is the absolute index of that row's `\n`. Row 0 begins at
72/// `row0`. `xyz` receives `n * 3` values. `ids` and `flags` may be null
73/// when the caller does not want them. `flags` is the packed column-4 mask.
74#[cfg(feature = "parallel")]
75pub(crate) fn fill_rows_from_breaks(
76    bytes: &[u8],
77    breaks: &[usize],
78    row0: usize,
79    spec_version: u32,
80    start_id: u64,
81    workers: usize,
82    ptrs: CoordPtrs,
83) -> Result<(), ParseError> {
84    let CoordPtrs { xyz, ids, flags } = ptrs;
85    let n = breaks.len();
86    if n == 0 {
87        return Ok(());
88    }
89    let chunk = n.div_ceil(workers.max(1)).max(1);
90    let groups = n.div_ceil(chunk);
91    let xyz_ptr = xyz as usize;
92    let ids_ptr = ids as usize;
93    let flags_ptr = flags as usize;
94    let fill = || {
95        use rayon::prelude::*;
96        (0..groups).into_par_iter().try_for_each(|group| {
97            let first = group * chunk;
98            let last = (first + chunk).min(n);
99            for row_index in first..last {
100                let start = if row_index == 0 {
101                    row0
102                } else {
103                    breaks[row_index - 1] + 1
104                };
105                let end = breaks[row_index] + 1;
106                if end > bytes.len() || start > end {
107                    return Err(ParseError::IncompleteFrame);
108                }
109                let default_id = start_id + row_index as u64;
110                let ((row, fixed, atom_id), _next) =
111                    parse_coord_row_at(&bytes[start..end], 0, spec_version, default_id)?;
112                unsafe {
113                    std::ptr::copy_nonoverlapping(
114                        row.as_ptr(),
115                        (xyz_ptr as *mut f64).add(row_index * 3),
116                        3,
117                    );
118                    if ids_ptr != 0 {
119                        *((ids_ptr as *mut u64).add(row_index)) = atom_id;
120                    }
121                    if flags_ptr != 0 {
122                        let mask = u8::from(fixed[0])
123                            | (u8::from(fixed[1]) << 1)
124                            | (u8::from(fixed[2]) << 2);
125                        *((flags_ptr as *mut u8).add(row_index)) = mask;
126                    }
127                }
128            }
129            Ok(())
130        })
131    };
132    on_pool(workers, fill)
133}
134
135/// A value built once per process, and built again in a forked child.
136///
137/// A child of `fork` keeps the parent's memory but only the thread that
138/// called `fork`. A pool the parent built has no workers in the child, so
139/// a job queued on it never runs. A lock that another parent thread held
140/// at the fork also stays held. The child therefore never uses or drops
141/// the parent's value. It stays reachable from the child's own value.
142pub(crate) struct PerProcess<T: 'static> {
143    current: std::sync::atomic::AtomicPtr<ProcessSlot<T>>,
144}
145
146struct ProcessSlot<T: 'static> {
147    pid: u32,
148    value: T,
149    _parent: Option<&'static ProcessSlot<T>>,
150}
151
152impl<T: Send + Sync + 'static> PerProcess<T> {
153    pub(crate) const fn new() -> Self {
154        Self {
155            current: std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()),
156        }
157    }
158
159    /// The value of the calling process, built with `init` on first use.
160    pub(crate) fn get_or_init(&'static self, init: impl Fn() -> T) -> &'static T {
161        use std::sync::atomic::Ordering;
162        let pid = std::process::id();
163        loop {
164            // Acquire pairs with the publishing exchange, so a slot's
165            // fields are visible before its pointer is.
166            let current = self.current.load(Ordering::Acquire);
167            let parent = unsafe { current.as_ref() };
168            if let Some(slot) = parent
169                && slot.pid == pid
170            {
171                return &slot.value;
172            }
173            let fresh = Box::into_raw(Box::new(ProcessSlot {
174                pid,
175                value: init(),
176                _parent: parent,
177            }));
178            match self
179                .current
180                .compare_exchange(current, fresh, Ordering::AcqRel, Ordering::Relaxed)
181            {
182                Ok(_) => return unsafe { &(*fresh).value },
183                // Another thread published first. Failure does not publish
184                // `fresh`, and this iteration never dereferences the returned
185                // pointer. The next loop's Acquire load performs the required
186                // synchronization, so the failure ordering can be Relaxed.
187                Err(_) => drop(unsafe { Box::from_raw(fresh) }),
188            }
189        }
190    }
191}
192
193/// Run `body` on a pool of `workers` threads.
194///
195/// The pool for a given size is kept for the process. Building one per
196/// call was a serial pause on the wide-frame read and the row formatter.
197/// A forked child builds its own; see [`PerProcess`].
198#[cfg(feature = "parallel")]
199pub(crate) fn on_pool<T: Send>(workers: usize, body: impl FnOnce() -> T + Send) -> T {
200    if workers < 2 {
201        return body();
202    }
203    // The cached pool is leaked for the process. Miri rejects a thread
204    // that is still running when the test binary exits, so it builds a
205    // pool, runs `body`, and joins.
206    #[cfg(miri)]
207    {
208        return match rayon::ThreadPoolBuilder::new().num_threads(workers).build() {
209            Ok(pool) => pool.install(body),
210            Err(_) => body(),
211        };
212    }
213    #[cfg(not(miri))]
214    {
215        let pool = {
216            use std::sync::Mutex;
217            static POOLS: PerProcess<Mutex<Vec<(usize, &'static rayon::ThreadPool)>>> =
218                PerProcess::new();
219            let pools = POOLS.get_or_init(|| Mutex::new(Vec::new()));
220            let mut guard = pools.lock().unwrap_or_else(|err| err.into_inner());
221            if let Some((_, pool)) = guard.iter().find(|(size, _)| *size == workers) {
222                *pool
223            } else {
224                let next_core = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
225                let built = match rayon::ThreadPoolBuilder::new()
226                    .num_threads(workers)
227                    .spawn_handler(move |thread| {
228                        // One worker per physical core. Leaving the placement to
229                        // the kernel put two of these on one core and left
230                        // another idle, which is the whole 8-thread gap.
231                        let core = next_core.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
232                        std::thread::Builder::new().spawn(move || {
233                            pin_worker(core);
234                            thread.run();
235                        })?;
236                        Ok(())
237                    })
238                    .build()
239                {
240                    Ok(pool) => pool,
241                    Err(_) => return body(),
242                };
243                let pool: &'static rayon::ThreadPool = Box::leak(Box::new(built));
244                guard.push((workers, pool));
245                pool
246            }
247        };
248        pool.install(body)
249    }
250}
251
252pub(crate) fn pin_worker(core: usize) {
253    // `sched_setaffinity` is Linux. Pinning is a performance hint.
254    #[cfg(all(not(miri), target_os = "linux"))]
255    unsafe {
256        let mut set: libc::cpu_set_t = std::mem::zeroed();
257        libc::CPU_ZERO(&mut set);
258        libc::CPU_SET(core, &mut set);
259        libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set);
260    }
261    #[cfg(any(miri, not(target_os = "linux")))]
262    {
263        let _ = core;
264    }
265}
266
267/// Coordinate rows in `bytes`, which begins at the first row.
268///
269/// `n` rows are required. The returned `consumed` count is the number of
270/// bytes those rows occupy, including their newlines. `symbol` builds the
271/// per-atom shells; `None` leaves `atoms` empty. A structural miss returns
272/// `Err` and the caller keeps the serial loop.
273#[cfg(feature = "parallel")]
274pub(crate) fn parallel_coord_rows(
275    bytes: &[u8],
276    n: usize,
277    spec_version: u32,
278    start_id: u64,
279    workers: usize,
280    symbol: Option<&std::sync::Arc<str>>,
281) -> Result<CoordRows, ParseError> {
282    if n == 0 {
283        return Ok(CoordRows {
284            xyz: Vec::new(),
285            ids: Vec::new(),
286            flags: Vec::new(),
287            atoms: Vec::new(),
288            consumed: 0,
289        });
290    }
291    // Same chunking as the column reader: count newlines, then each worker
292    // walks its own run. An offset per line was a serial pass the plain
293    // read does not pay.
294    let (chunks, consumed) = plan_coord_chunks(bytes, 0, n, workers.max(1))?;
295    let mut xyz = Vec::<f64>::with_capacity(n.saturating_mul(3));
296    let mut ids = Vec::<u64>::with_capacity(n);
297    let mut flags = Vec::<[bool; 3]>::with_capacity(n);
298    let mut atoms_raw: Vec<std::mem::MaybeUninit<crate::types::AtomDatum>> = Vec::new();
299    if symbol.is_some() {
300        atoms_raw = Vec::with_capacity(n);
301        unsafe { atoms_raw.set_len(n) };
302    }
303    let xyz_ptr = xyz.as_mut_ptr() as usize;
304    let ids_ptr = ids.as_mut_ptr() as usize;
305    let flags_ptr = flags.as_mut_ptr() as usize;
306    let atoms_ptr = atoms_raw.as_mut_ptr() as usize;
307    let mut row0 = Vec::with_capacity(chunks.len());
308    let mut acc = 0usize;
309    for (_, nrows) in &chunks {
310        row0.push(acc);
311        acc += *nrows;
312    }
313    let fill_chunk = |index: usize| -> Result<(), ParseError> {
314        let (start, nrows) = chunks[index];
315        let mut row = row0[index];
316        let mut pos = start;
317        let mut shares = symbol.map(|symbol| symbol_shares(symbol, nrows));
318        for _ in 0..nrows {
319            let ((xyz, fixed, atom_id), next) =
320                parse_coord_row_at(bytes, pos, spec_version, start_id + row as u64)?;
321            unsafe {
322                std::ptr::copy_nonoverlapping(xyz.as_ptr(), (xyz_ptr as *mut f64).add(row * 3), 3);
323                *((ids_ptr as *mut u64).add(row)) = atom_id;
324                *((flags_ptr as *mut [bool; 3]).add(row)) = fixed;
325                if let Some(shares) = shares.as_mut() {
326                    let atom = crate::types::AtomDatum::coords(
327                        shares.take(),
328                        xyz[0],
329                        xyz[1],
330                        xyz[2],
331                        fixed,
332                        atom_id,
333                    );
334                    (*(atoms_ptr as *mut std::mem::MaybeUninit<crate::types::AtomDatum>).add(row))
335                        .write(atom);
336                }
337            }
338            pos = next;
339            row += 1;
340        }
341        Ok(())
342    };
343    let built = if workers < 2 || chunks.len() < 2 {
344        (0..chunks.len()).try_for_each(fill_chunk)
345    } else {
346        on_pool(workers, || {
347            use rayon::prelude::*;
348            (0..chunks.len()).into_par_iter().try_for_each(fill_chunk)
349        })
350    };
351    if let Err(err) = built {
352        std::mem::forget(atoms_raw);
353        return Err(err);
354    }
355    // SAFETY: every row was written before `built` returned Ok. The
356    // length stays 0 on the error path above.
357    unsafe {
358        xyz.set_len(n * 3);
359        ids.set_len(n);
360        flags.set_len(n);
361    }
362    let atoms = if symbol.is_some() {
363        let mut raw = std::mem::ManuallyDrop::new(atoms_raw);
364        unsafe {
365            Vec::from_raw_parts(
366                raw.as_mut_ptr() as *mut crate::types::AtomDatum,
367                n,
368                raw.capacity(),
369            )
370        }
371    } else {
372        Vec::new()
373    };
374    Ok(CoordRows {
375        xyz,
376        ids,
377        flags,
378        atoms,
379        consumed,
380    })
381}
382
383/// Walk `nrows` coordinate lines starting at byte `start`.
384///
385/// `row_base` is the first row's index in `xyz` / `ids` / `flags` / `atoms`.
386/// This is the per-member kernel of [`fill_rows_from_chunks`], so a worker
387/// can parse a slice as soon as that slice has been inflated.
388#[cfg(feature = "parallel")]
389pub(crate) fn parse_coord_run(
390    bytes: &[u8],
391    start: usize,
392    nrows: usize,
393    spec_version: u32,
394    row_base: usize,
395    symbol: Option<&std::sync::Arc<str>>,
396    ptrs: CoordRunOut,
397) -> Result<usize, ParseError> {
398    let CoordRunOut {
399        xyz,
400        ids,
401        flags,
402        atoms,
403    } = ptrs;
404    let mut pos = start;
405    let mut shares = symbol.map(|symbol| symbol_shares(symbol, nrows));
406    for step in 0..nrows {
407        let row = row_base + step;
408        let ((xyz_row, fixed, atom_id), next) =
409            parse_coord_row_at(bytes, pos, spec_version, row as u64)?;
410        unsafe {
411            let dest = xyz.add(row * 3);
412            std::ptr::copy_nonoverlapping(xyz_row.as_ptr(), dest, 3);
413            *ids.add(row) = atom_id;
414            *flags.add(row) = fixed;
415            if let Some(shares) = shares.as_mut() {
416                let atom = crate::types::AtomDatum::coords(
417                    shares.take(),
418                    xyz_row[0],
419                    xyz_row[1],
420                    xyz_row[2],
421                    fixed,
422                    atom_id,
423                );
424                (*atoms.add(row)).write(atom);
425            }
426        }
427        pos = next;
428    }
429    Ok(pos)
430}
431
432#[cfg(feature = "parallel")]
433#[allow(dead_code)]
434fn coord_line_ranges(
435    bytes: &[u8],
436    n: usize,
437    workers: usize,
438) -> Result<Vec<(usize, usize)>, ParseError> {
439    let newlines = newline_index(bytes, workers);
440    let mut ranges = Vec::with_capacity(n);
441    let mut start = 0usize;
442    for index in 0..n {
443        if start > bytes.len() {
444            return Err(ParseError::IncompleteFrame);
445        }
446        let end = if index < newlines.len() {
447            newlines[index] + 1
448        } else if index == newlines.len() && start < bytes.len() {
449            bytes.len()
450        } else {
451            return Err(ParseError::IncompleteFrame);
452        };
453        if end < start {
454            return Err(ParseError::IncompleteFrame);
455        }
456        ranges.push((start, end));
457        start = end;
458    }
459    Ok(ranges)
460}
461
462/// Newline positions in `bytes`.
463///
464/// Chunks are cut on byte boundaries, then each interior cut that lands
465/// inside a line is moved to the next newline so a row is not split.
466/// Workers count those newlines, a prefix sum places each run, and the
467/// same workers write the offsets. The offset array is not zeroed, so
468/// the writer is the first touch. `workers < 2` scans on the calling thread.
469#[cfg(feature = "parallel")]
470pub(crate) fn newline_index(bytes: &[u8], workers: usize) -> Vec<usize> {
471    newline_index_at(bytes, 0, workers)
472}
473
474/// [`newline_index`] with `base` added to every stored offset.
475#[cfg(feature = "parallel")]
476pub(crate) fn newline_index_at(bytes: &[u8], base: usize, workers: usize) -> Vec<usize> {
477    if bytes.is_empty() || workers < 2 || bytes.len() < (1 << 20) {
478        return memchr::memchr_iter(b'\n', bytes)
479            .map(|index| base + index)
480            .collect();
481    }
482    let cuts = newline_cuts(bytes, workers);
483    newline_index_exact(&cuts, bytes, base)
484}
485
486/// One cache line, so adjacent chunk counters do not share a line.
487#[cfg(feature = "parallel")]
488#[derive(Clone)]
489#[repr(C, align(64))]
490struct ChunkTally {
491    n: usize,
492}
493
494#[cfg(feature = "parallel")]
495pub(crate) fn newline_cuts(bytes: &[u8], workers: usize) -> Vec<usize> {
496    let workers = workers.min(bytes.len()).max(1);
497    let mut cuts = Vec::with_capacity(workers + 1);
498    cuts.push(0usize);
499    for index in 1..workers {
500        let mut at = index * bytes.len() / workers;
501        // A cut in the middle of a row belongs to the chunk that holds
502        // the newline. Move it to the first byte after that newline.
503        if at > 0 && at < bytes.len() && bytes[at - 1] != b'\n' {
504            if let Some(rel) = memchr::memchr(b'\n', &bytes[at..]) {
505                at += rel + 1;
506            } else {
507                at = bytes.len();
508            }
509        }
510        if cuts.last().copied() != Some(at) {
511            cuts.push(at);
512        }
513    }
514    if cuts.last().copied() != Some(bytes.len()) {
515        cuts.push(bytes.len());
516    }
517    cuts
518}
519
520/// Count newlines in each `cuts` window. One store per chunk, so the
521/// counters do not bounce a cache line during the scan.
522#[cfg(feature = "parallel")]
523fn count_newline_chunks(bytes: &[u8], cuts: &[usize]) -> Vec<usize> {
524    let nchunks = cuts.len().saturating_sub(1);
525    let mut tallies = vec![ChunkTally { n: 0 }; nchunks];
526    if nchunks == 0 {
527        return Vec::new();
528    }
529    let ptr = tallies.as_mut_ptr() as usize;
530    let count = || {
531        use rayon::prelude::*;
532        (0..nchunks).into_par_iter().for_each(|index| {
533            let n = memchr::memchr_iter(b'\n', &bytes[cuts[index]..cuts[index + 1]]).count();
534            unsafe {
535                (*(ptr as *mut ChunkTally).add(index)).n = n;
536            }
537        });
538    };
539    if nchunks < 2 {
540        count();
541    } else {
542        on_pool(nchunks, count);
543    }
544    tallies.into_iter().map(|tally| tally.n).collect()
545}
546
547/// Byte start and row count for each worker that parses `n_rows`
548/// coordinate lines beginning at `start`.
549///
550/// The newline *count* places the rows. Workers then parse their own
551/// slice in order, so the read does not materialise an offset per line.
552/// The returned end is the first byte after the `n_rows`-th newline.
553#[cfg(feature = "parallel")]
554pub(crate) fn plan_coord_chunks(
555    bytes: &[u8],
556    start: usize,
557    n_rows: usize,
558    workers: usize,
559) -> Result<(Vec<(usize, usize)>, usize), ParseError> {
560    if n_rows == 0 {
561        return Ok((Vec::new(), start));
562    }
563    if start >= bytes.len() {
564        return Err(ParseError::IncompleteFrame);
565    }
566    let mut window = n_rows.saturating_mul(96).max(1);
567    loop {
568        let end = start.saturating_add(window).min(bytes.len());
569        let region = &bytes[start..end];
570        let cuts = newline_cuts(region, workers);
571        let counts = count_newline_chunks(region, &cuts);
572        let total: usize = counts.iter().sum();
573        if total >= n_rows || end == bytes.len() {
574            if total < n_rows {
575                return Err(ParseError::IncompleteFrame);
576            }
577            return chunks_from_counts(bytes, start, &cuts, &counts, n_rows);
578        }
579        window = window.saturating_mul(2);
580    }
581}
582
583#[cfg(feature = "parallel")]
584fn chunks_from_counts(
585    bytes: &[u8],
586    start: usize,
587    cuts: &[usize],
588    counts: &[usize],
589    n_rows: usize,
590) -> Result<(Vec<(usize, usize)>, usize), ParseError> {
591    let mut need = n_rows;
592    let mut chunks = Vec::new();
593    let mut end_abs = start;
594    for index in 0..counts.len() {
595        if need == 0 {
596            break;
597        }
598        let have = counts[index];
599        if have == 0 {
600            continue;
601        }
602        let from = start + cuts[index];
603        let to = start + cuts[index + 1];
604        let take = have.min(need);
605        let chunk_end = if take == have && to > from && bytes[to - 1] == b'\n' {
606            to
607        } else {
608            let mut seen = 0usize;
609            let mut found = None;
610            for rel in memchr::memchr_iter(b'\n', &bytes[from..to]) {
611                seen += 1;
612                if seen == take {
613                    found = Some(from + rel + 1);
614                    break;
615                }
616            }
617            found.ok_or(ParseError::IncompleteFrame)?
618        };
619        chunks.push((from, take));
620        end_abs = chunk_end;
621        need -= take;
622    }
623    if need != 0 {
624        return Err(ParseError::IncompleteFrame);
625    }
626    Ok((chunks, end_abs))
627}
628
629/// Parse coordinate rows described by [`plan_coord_chunks`].
630///
631/// Each chunk is a contiguous run of lines. The worker walks that run
632/// and writes `nrows` coordinates at the prefix-summed row.
633#[cfg(feature = "parallel")]
634pub(crate) fn fill_rows_from_chunks(
635    bytes: &[u8],
636    chunks: &[(usize, usize)],
637    spec_version: u32,
638    start_id: u64,
639    workers: usize,
640    ptrs: CoordPtrs,
641) -> Result<(), ParseError> {
642    let CoordPtrs { xyz, ids, flags } = ptrs;
643    if chunks.is_empty() {
644        return Ok(());
645    }
646    let mut row0 = Vec::with_capacity(chunks.len());
647    let mut acc = 0usize;
648    for (_, nrows) in chunks {
649        row0.push(acc);
650        acc += *nrows;
651    }
652    let xyz_ptr = xyz as usize;
653    let ids_ptr = ids as usize;
654    let flags_ptr = flags as usize;
655    let fill = || {
656        use rayon::prelude::*;
657        chunks
658            .par_iter()
659            .zip(row0.par_iter().copied())
660            .try_for_each(|(&(start, nrows), mut row)| {
661                let mut pos = start;
662                for _ in 0..nrows {
663                    let ((xyz, fixed, atom_id), next) =
664                        parse_coord_row_at(bytes, pos, spec_version, start_id + row as u64)?;
665                    unsafe {
666                        std::ptr::copy_nonoverlapping(
667                            xyz.as_ptr(),
668                            (xyz_ptr as *mut f64).add(row * 3),
669                            3,
670                        );
671                        if ids_ptr != 0 {
672                            *((ids_ptr as *mut u64).add(row)) = atom_id;
673                        }
674                        if flags_ptr != 0 {
675                            let mask = u8::from(fixed[0])
676                                | (u8::from(fixed[1]) << 1)
677                                | (u8::from(fixed[2]) << 2);
678                            *((flags_ptr as *mut u8).add(row)) = mask;
679                        }
680                    }
681                    pos = next;
682                    row += 1;
683                }
684                Ok(())
685            })
686    };
687    if workers < 2 {
688        let mut row_at = 0usize;
689        for &(start, nrows) in chunks {
690            let mut pos = start;
691            for _ in 0..nrows {
692                let ((row_xyz, fixed, atom_id), next) =
693                    parse_coord_row_at(bytes, pos, spec_version, start_id + row_at as u64)?;
694                unsafe {
695                    std::ptr::copy_nonoverlapping(row_xyz.as_ptr(), xyz.add(row_at * 3), 3);
696                    if ids_ptr != 0 {
697                        *((ids_ptr as *mut u64).add(row_at)) = atom_id;
698                    }
699                    if flags_ptr != 0 {
700                        let mask = u8::from(fixed[0])
701                            | (u8::from(fixed[1]) << 1)
702                            | (u8::from(fixed[2]) << 2);
703                        *((flags_ptr as *mut u8).add(row_at)) = mask;
704                    }
705                }
706                pos = next;
707                row_at += 1;
708            }
709        }
710        Ok(())
711    } else if chunks.len() < 2 {
712        fill()
713    } else {
714        on_pool(workers, fill)
715    }
716}
717
718/// Exact index: count, prefix sum, then store into an unzeroed buffer.
719#[cfg(feature = "parallel")]
720fn newline_index_exact(cuts: &[usize], bytes: &[u8], base: usize) -> Vec<usize> {
721    let nchunks = cuts.len() - 1;
722    let counts = count_newline_chunks(bytes, cuts);
723    let mut slots = vec![0usize; nchunks];
724    let mut total = 0usize;
725    for index in 0..nchunks {
726        slots[index] = total;
727        total += counts[index];
728    }
729    let mut out = Vec::<usize>::with_capacity(total);
730    let ptr = out.as_mut_ptr() as usize;
731    let store = || {
732        use rayon::prelude::*;
733        (0..nchunks).into_par_iter().for_each(|index| {
734            let from = cuts[index];
735            let mut at = slots[index];
736            for rel in memchr::memchr_iter(b'\n', &bytes[from..cuts[index + 1]]) {
737                unsafe {
738                    *((ptr as *mut usize).add(at)) = base + from + rel;
739                }
740                at += 1;
741            }
742        });
743    };
744    if nchunks < 2 {
745        store();
746    } else {
747        on_pool(nchunks.max(1), store);
748    }
749    // SAFETY: the store wrote every index in `0..total`.
750    unsafe { out.set_len(total) };
751    out
752}
753
754pub trait LineStream<'a> {
755    fn next_line(&mut self) -> Option<&'a str>;
756    fn peek_line(&mut self) -> Option<&'a str>;
757    /// Take `n` coordinate rows starting at the cursor, or `None` to keep
758    /// the one-row loop. The cursor moves only when this returns `Some`.
759    fn try_take_coord_block(
760        &mut self,
761        _n: usize,
762        _spec_version: u32,
763        _start_id: u64,
764        _symbol: &std::sync::Arc<str>,
765        _workers: usize,
766    ) -> Option<CoordRows> {
767        None
768    }
769    /// True when every remaining line, including the current peek, is
770    /// empty or whitespace. Default is false so a one-line peek cannot
771    /// hide a following section.
772    fn remainder_is_whitespace(&mut self) -> bool {
773        false
774    }
775    /// Called while a blank line is peeked. True when that blank begins a
776    /// section: the next line is a symbol and the line after it is a
777    /// component label. A blank that does not is line 1 of the next frame.
778    fn blank_line_opens_section(&mut self) -> bool {
779        false
780    }
781
782    /// With a blank line peeked, true when [`Self::blank_line_opens_section`]
783    /// is true. A stream that cannot look ahead keeps the legacy rule and
784    /// returns true.
785    fn blank_opens_velocity_block(&mut self) -> bool {
786        true
787    }
788
789    /// One coordinate row, fused with the line scan when the stream can do it.
790    ///
791    /// The default pulls a `&str` line. [`crate::iterators::MemchrLines`]
792    /// parses the row directly from the byte cursor so tokenize and numeric
793    /// parse are one pass.
794    fn next_coord_row(
795        &mut self,
796        spec_version: u32,
797        default_id: u64,
798    ) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
799        let line = self.next_line().ok_or(ParseError::IncompleteFrame)?;
800        parse_coord_row(line, spec_version, default_id)
801    }
802
803    /// One vector-section row (xyz, flag, required id), fused with the line
804    /// scan when the stream can do it. End of input is [`ParseError::IncompleteFrame`];
805    /// callers that are inside a named section map that to `IncompleteSection`.
806    fn next_vector_row(
807        &mut self,
808        spec_version: u32,
809    ) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
810        let line = self.next_line().ok_or(ParseError::IncompleteFrame)?;
811        parse_vector_section_row(line, spec_version)
812    }
813}
814
815fn take_vector_row<'a>(
816    lines: &mut impl LineStream<'a>,
817    spec_version: u32,
818    section: &str,
819) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
820    match lines.next_vector_row(spec_version) {
821        Ok(row) => Ok(row),
822        Err(ParseError::IncompleteFrame) => Err(ParseError::IncompleteSection(section.to_string())),
823        Err(err) => Err(err),
824    }
825}
826
827impl<'a, I> LineStream<'a> for Peekable<I>
828where
829    I: Iterator<Item = &'a str> + Clone,
830{
831    #[inline]
832    fn next_line(&mut self) -> Option<&'a str> {
833        Iterator::next(self)
834    }
835    #[inline]
836    fn peek_line(&mut self) -> Option<&'a str> {
837        Peekable::peek(self).copied()
838    }
839    fn blank_line_opens_section(&mut self) -> bool {
840        let mut probe = self.clone();
841        let Some(blank) = probe.next_line() else {
842            return false;
843        };
844        if !blank.trim().is_empty() {
845            return false;
846        }
847        section_follows(&mut probe)
848    }
849
850    fn blank_opens_velocity_block(&mut self) -> bool {
851        match self.peek_line() {
852            Some(line) if line.trim().is_empty() => self.blank_line_opens_section(),
853            _ => true,
854        }
855    }
856}
857
858/// True when `line` has the words `of` and `Component` in that order.
859pub(crate) fn line_has_component_label(line: &str) -> bool {
860    let mut words = line.split_ascii_whitespace();
861    while let Some(word) = words.next() {
862        if word.eq_ignore_ascii_case("of")
863            && words
864                .next()
865                .is_some_and(|next| next.eq_ignore_ascii_case("component"))
866        {
867            return true;
868        }
869    }
870    false
871}
872
873fn section_follows<'a>(lines: &mut impl LineStream<'a>) -> bool {
874    let Some(symbol) = lines.next_line() else {
875        return false;
876    };
877    if symbol.trim().is_empty() || symbol.trim_start().starts_with('{') {
878        return false;
879    }
880    let Some(label) = lines.next_line() else {
881        return false;
882    };
883    line_has_component_label(label)
884}
885
886/// Length of the stack buffer of [`parse_line_of_range_f64_stack`]: the most
887/// columns an atom line has, which are x, y, z, the flag and the optional id
888/// (spec "Coordinates").
889pub const NUMERIC_STACK_WIDTH: usize = COORD_ROW_MIN_COLUMNS + 1;
890
891/// Hot-path: parse up to [`NUMERIC_STACK_WIDTH`] whitespace-separated f64s
892/// into a stack buffer.
893/// Returns count of tokens actually present (before padding).
894/// Pads `out[found..max]` from `defaults` when `found < max` and `found >= min`.
895///
896/// Single-pass over the line bytes: skip ASCII whitespace, then
897/// [`fast_float2::parse_partial`] (Eisel–Lemire / SIMD-class decimal kernel)
898/// with a token-boundary check. No `SplitWhitespace`, no per-token `&str`,
899/// no heap `Vec`. Prefer this over allocating [`parse_line_of_n_f64`] on atom lines.
900#[inline]
901pub fn parse_line_of_range_f64_stack(
902    line: &str,
903    min: usize,
904    max: usize,
905    defaults: &[f64],
906    out: &mut [f64; NUMERIC_STACK_WIDTH],
907) -> Result<usize, ParseError> {
908    debug_assert!(max <= NUMERIC_STACK_WIDTH && min <= max && defaults.len() >= max);
909    let bytes = line.as_bytes();
910    let n = bytes.len();
911    let mut i = 0usize;
912    let mut found = 0usize;
913    while found < max {
914        while i < n && is_field_ws(bytes[i]) {
915            i += 1;
916        }
917        if i >= n {
918            break;
919        }
920        let end = bytes[i..]
921            .iter()
922            .position(|b| is_field_ws(*b))
923            .map(|k| i + k)
924            .unwrap_or(n);
925        let token = std::str::from_utf8(&bytes[i..end]).unwrap_or("");
926        if is_nonfinite_spelling(token) {
927            return Err(ParseError::NonFiniteValue(token.to_string()));
928        }
929        let (val, consumed) = fast_float2::parse_partial::<f64, _>(&bytes[i..])
930            .map_err(|_| ParseError::InvalidNumberFormat(format!("invalid float: {token}")))?;
931        let next = i + consumed;
932        // Reject partial tokens like "1.2abc" (must end at space/tab or EOS).
933        if next != end {
934            return Err(ParseError::InvalidNumberFormat(format!(
935                "invalid float: {token}"
936            )));
937        }
938        if !val.is_finite() {
939            return Err(ParseError::NonFiniteValue(token.to_string()));
940        }
941        out[found] = val;
942        found += 1;
943        i = next;
944    }
945    while i < n && is_field_ws(bytes[i]) {
946        i += 1;
947    }
948    // Reject trailing extra tokens (same contract as the old split loop).
949    if i < n {
950        return Err(ParseError::InvalidVectorLength {
951            expected: max,
952            found: found + 1,
953        });
954    }
955    if found < min || found > max {
956        return Err(ParseError::InvalidVectorLength {
957            expected: max,
958            found,
959        });
960    }
961    while found < max {
962        out[found] = defaults[found];
963        found += 1;
964    }
965    Ok(found)
966}
967
968/// Parses a line of whitespace-separated f64 values using fast-float2.
969///
970/// This is the hot-path parser for coordinate and velocity lines. It uses
971/// `fast_float2::parse` instead of `str::parse::<f64>()` for better throughput
972/// on the numeric-heavy atom data lines. Fixed-width atom lines use
973/// [`parse_line_of_range_f64_stack`] to avoid a heap `Vec` per line.
974///
975/// # Arguments
976///
977/// * `line` - A string slice representing a single line of data.
978/// * `n` - The exact number of f64 values expected on the line.
979pub fn parse_line_of_n_f64(line: &str, n: usize) -> Result<Vec<f64>, ParseError> {
980    if n <= NUMERIC_STACK_WIDTH {
981        let defaults = [0.0f64; NUMERIC_STACK_WIDTH];
982        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
983        parse_line_of_range_f64_stack(line, n, n, &defaults, &mut buf)?;
984        return Ok(buf[..n].to_vec());
985    }
986    let mut values = Vec::with_capacity(n.min(max_tokens_on_line(line)));
987    for token in split_field_ws(line) {
988        values.push(parse_finite_float_token(token)?);
989    }
990    if values.len() == n {
991        Ok(values)
992    } else {
993        Err(ParseError::InvalidVectorLength {
994            expected: n,
995            found: values.len(),
996        })
997    }
998}
999
1000/// Parses the three numbers of a cell line (box lengths, or box angles).
1001///
1002/// The values are those of [`parse_line_of_n_f64`]. A NaN, an infinity, or a
1003/// number too large for binary64 is [`ParseError::NonFiniteValue`] naming the
1004/// field `name[i]` and the token, where plain [`parse_line_of_n_f64`] names
1005/// only the token. The check costs nothing on a finite line: it runs on the
1006/// failing path only, and the frame is named by whoever knows its index.
1007pub(crate) fn parse_cell_line(line: &str, name: &str) -> Result<Vec<f64>, ParseError> {
1008    parse_line_of_n_f64(line, 3).map_err(|error| match error {
1009        ParseError::NonFiniteValue(token) => match split_field_ws(line).position(|t| t == token) {
1010            Some(index) => ParseError::non_finite_cell(&format!("{name}[{index}]"), token),
1011            None => ParseError::NonFiniteValue(token),
1012        },
1013        other => other,
1014    })
1015}
1016
1017/// Parses a line of whitespace-separated f64 values, accepting between `min`
1018/// and `max` values (inclusive). Returns a vector of exactly `max` elements,
1019/// padding with values from `defaults` when fewer than `max` are present.
1020///
1021/// Used for atom lines where column 5 (atom_index) is optional.
1022/// Prefer [`parse_line_of_range_f64_stack`] on the atom hot path
1023/// (`max <= NUMERIC_STACK_WIDTH`).
1024pub fn parse_line_of_range_f64(
1025    line: &str,
1026    min: usize,
1027    max: usize,
1028    defaults: &[f64],
1029) -> Result<Vec<f64>, ParseError> {
1030    if max <= NUMERIC_STACK_WIDTH {
1031        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
1032        parse_line_of_range_f64_stack(line, min, max, defaults, &mut buf)?;
1033        return Ok(buf[..max].to_vec());
1034    }
1035    let mut values = Vec::with_capacity(max);
1036    for token in split_field_ws(line) {
1037        values.push(parse_finite_float_token(token)?);
1038    }
1039    if values.len() < min || values.len() > max {
1040        return Err(ParseError::InvalidVectorLength {
1041            expected: max,
1042            found: values.len(),
1043        });
1044    }
1045    while values.len() < max {
1046        let idx = values.len();
1047        values.push(defaults[idx]);
1048    }
1049    Ok(values)
1050}
1051
1052/// CON-num.1 spellings. A leading sign is optional. Case is ignored.
1053/// Digit and dot tokens return before any letter compare so the atom
1054/// hot path does not allocate.
1055fn is_nonfinite_spelling(token: &str) -> bool {
1056    let rest = token
1057        .strip_prefix('+')
1058        .or_else(|| token.strip_prefix('-'))
1059        .unwrap_or(token);
1060    match rest.as_bytes().first() {
1061        Some(b) if b.is_ascii_digit() || *b == b'.' => return false,
1062        None => return false,
1063        _ => {}
1064    }
1065    rest.eq_ignore_ascii_case("nan")
1066        || rest.eq_ignore_ascii_case("inf")
1067        || rest.eq_ignore_ascii_case("infinity")
1068}
1069
1070fn parse_finite_float_token(token: &str) -> Result<f64, ParseError> {
1071    if is_nonfinite_spelling(token) {
1072        return Err(ParseError::NonFiniteValue(token.to_string()));
1073    }
1074    let (val, consumed) = fast_float2::parse_partial::<f64, _>(token.as_bytes())
1075        .map_err(|_| ParseError::InvalidNumberFormat(format!("invalid float: {token}")))?;
1076    if consumed != token.len() {
1077        return Err(ParseError::InvalidNumberFormat(format!(
1078            "invalid float: {token}"
1079        )));
1080    }
1081    if !val.is_finite() {
1082        return Err(ParseError::NonFiniteValue(token.to_string()));
1083    }
1084    Ok(val)
1085}
1086
1087fn skip_ascii_ws(bytes: &[u8], mut i: usize) -> usize {
1088    while i < bytes.len() && is_field_ws(bytes[i]) {
1089        i += 1;
1090    }
1091    i
1092}
1093
1094fn take_token(line: &str, i: usize) -> Option<(&str, usize)> {
1095    let bytes = line.as_bytes();
1096    if i >= bytes.len() {
1097        return None;
1098    }
1099    let mut j = i;
1100    while j < bytes.len() && !is_field_ws(bytes[j]) && !at_row_end(bytes, j) {
1101        j += 1;
1102    }
1103    Some((&line[i..j], j))
1104}
1105
1106/// Column 4. A sign, a decimal point, or a value outside the spec's set
1107/// is `InvalidFixedFlag` in every mode (CON-mask.1, CON-mask.5, D8).
1108fn parse_fixed_flag(token: &str, spec_version: u32) -> Result<[bool; 3], ParseError> {
1109    let bad = || {
1110        ParseError::InvalidFixedFlag(format!(
1111            "column 4 flag {token:?} is not a legal integer for spec {spec_version}"
1112        ))
1113    };
1114    if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
1115        return Err(bad());
1116    }
1117    let val: u64 = token.parse::<u64>().map_err(|_| bad())?;
1118    if spec_version < 2 {
1119        return match val {
1120            0 => Ok([false, false, false]),
1121            1 => Ok([true, true, true]),
1122            _ => Err(bad()),
1123        };
1124    }
1125    if val > 7 {
1126        return Err(bad());
1127    }
1128    let v = val as u8;
1129    Ok([v & 1 != 0, v & 2 != 0, v & 4 != 0])
1130}
1131
1132/// Column 5. Digits only, parsed as `u64`, never through `f64` (CON-id.1, D9).
1133/// A sign or a decimal point is `InvalidNumberFormat` at the token level.
1134fn parse_atom_id_token(token: &str) -> Result<u64, ParseError> {
1135    if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
1136        return Err(ParseError::InvalidNumberFormat(format!(
1137            "invalid integer: {token}"
1138        )));
1139    }
1140    token.parse::<u64>().map_err(|_| {
1141        ParseError::InvalidNumberFormat(format!("integer out of range 0..=2^64-1: {token}"))
1142    })
1143}
1144
1145/// Coordinate row: three finite floats, an integer flag, and an optional id.
1146/// Four columns take `default_id`, the 0-based position in the frame
1147/// (CON-id.9). Any other width is `InvalidVectorLength` (CON-num.9).
1148fn parse_coord_row(
1149    line: &str,
1150    spec_version: u32,
1151    default_id: u64,
1152) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
1153    parse_vector_row(line, spec_version, Some(default_id))
1154}
1155
1156/// Vector section row. The flag and id columns are required (exact width 5).
1157fn parse_vector_section_row(
1158    line: &str,
1159    spec_version: u32,
1160) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
1161    parse_vector_row(line, spec_version, None)
1162}
1163
1164fn parse_vector_row(
1165    line: &str,
1166    spec_version: u32,
1167    default_id: Option<u64>,
1168) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
1169    let (row, end) = parse_coord_fields(line.as_bytes(), 0, spec_version, default_id)?;
1170    if end != line.len() {
1171        let found = 5 + count_tokens_on_line(line.as_bytes(), end);
1172        return Err(ParseError::InvalidVectorLength { expected: 5, found });
1173    }
1174    Ok(row)
1175}
1176
1177/// Field separator inside a row. CON-token.3 allows spaces and tabs only.
1178/// A carriage return ends a line (CON-file.3); it is not a separator.
1179#[inline(always)]
1180fn is_field_ws(b: u8) -> bool {
1181    matches!(b, b' ' | b'\t')
1182}
1183
1184fn split_field_ws(line: &str) -> impl Iterator<Item = &str> {
1185    line.split([' ', '\t']).filter(|token| !token.is_empty())
1186}
1187
1188/// True at the end of a row: end of input, LF, or a CR that ends the line.
1189#[inline(always)]
1190fn at_row_end(bytes: &[u8], i: usize) -> bool {
1191    if i >= bytes.len() || bytes[i] == b'\n' {
1192        return true;
1193    }
1194    bytes[i] == b'\r' && (i + 1 >= bytes.len() || bytes[i + 1] == b'\n')
1195}
1196
1197/// A space, a tab, or the end of the row. A form feed or a CR between
1198/// fields is not one of these, so that byte stays in the token.
1199#[inline(always)]
1200fn ends_field(bytes: &[u8], i: usize) -> bool {
1201    i >= bytes.len() || is_field_ws(bytes[i]) || at_row_end(bytes, i)
1202}
1203
1204/// Index just past the row ending at `i`, when [`at_row_end`] is true.
1205#[inline(always)]
1206fn consume_row_end(bytes: &[u8], i: usize) -> usize {
1207    if i >= bytes.len() {
1208        return i;
1209    }
1210    if bytes[i] == b'\r' {
1211        let next = i + 1;
1212        if next < bytes.len() && bytes[next] == b'\n' {
1213            return next + 1;
1214        }
1215        return next;
1216    }
1217    if bytes[i] == b'\n' {
1218        return i + 1;
1219    }
1220    i
1221}
1222
1223#[inline(always)]
1224fn skip_field_ws(bytes: &[u8], mut i: usize) -> usize {
1225    while i < bytes.len() && is_field_ws(bytes[i]) {
1226        i += 1;
1227    }
1228    i
1229}
1230
1231fn token_on_line(bytes: &[u8], i: usize) -> String {
1232    let mut j = i;
1233    while j < bytes.len() && !is_field_ws(bytes[j]) && !at_row_end(bytes, j) {
1234        j += 1;
1235    }
1236    String::from_utf8_lossy(&bytes[i..j]).into_owned()
1237}
1238
1239fn count_tokens_on_line(bytes: &[u8], mut i: usize) -> usize {
1240    let mut n = 0usize;
1241    loop {
1242        i = skip_field_ws(bytes, i);
1243        if at_row_end(bytes, i) {
1244            break;
1245        }
1246        n += 1;
1247        while i < bytes.len() && !is_field_ws(bytes[i]) && !at_row_end(bytes, i) {
1248            i += 1;
1249        }
1250    }
1251    n
1252}
1253
1254/// Invalid UTF-8 in a numeric row, otherwise a normal number-format error.
1255fn utf8_or_number(bytes: &[u8], line_start: usize, i: usize) -> ParseError {
1256    let end = bytes[line_start..]
1257        .iter()
1258        .position(|b| *b == b'\n')
1259        .map(|p| line_start + p)
1260        .unwrap_or(bytes.len());
1261    if std::str::from_utf8(&bytes[line_start..end]).is_err() {
1262        return ParseError::ValidationError("invalid UTF-8".into());
1263    }
1264    ParseError::InvalidNumberFormat(format!("invalid float: {}", token_on_line(bytes, i)))
1265}
1266
1267#[inline(always)]
1268fn parse_f64_at(bytes: &[u8], i: usize, line_start: usize) -> Result<(f64, usize), ParseError> {
1269    if at_row_end(bytes, i) {
1270        return Err(ParseError::InvalidVectorLength {
1271            expected: 5,
1272            found: 0,
1273        });
1274    }
1275    if bytes[i] >= 0x80 {
1276        return Err(utf8_or_number(bytes, line_start, i));
1277    }
1278    if looks_like_nonfinite(bytes, i) {
1279        let token = token_on_line(bytes, i);
1280        if is_nonfinite_spelling(&token) {
1281            return Err(ParseError::NonFiniteValue(token));
1282        }
1283    }
1284    let (val, consumed) = fast_float2::parse_partial::<f64, _>(&bytes[i..]).map_err(|_| {
1285        ParseError::InvalidNumberFormat(format!("invalid float: {}", token_on_line(bytes, i)))
1286    })?;
1287    let next = i + consumed;
1288    let boundary = ends_field(bytes, next);
1289    if !boundary {
1290        return Err(ParseError::InvalidNumberFormat(format!(
1291            "invalid float: {}",
1292            token_on_line(bytes, i)
1293        )));
1294    }
1295    if !val.is_finite() {
1296        return Err(ParseError::NonFiniteValue(token_on_line(bytes, i)));
1297    }
1298    Ok((val, next))
1299}
1300
1301#[inline(always)]
1302fn parse_flag_at(
1303    bytes: &[u8],
1304    i: usize,
1305    spec_version: u32,
1306) -> Result<([bool; 3], usize), ParseError> {
1307    if at_row_end(bytes, i) {
1308        return Err(ParseError::InvalidVectorLength {
1309            expected: 5,
1310            found: 3,
1311        });
1312    }
1313    let bad = || {
1314        ParseError::InvalidFixedFlag(format!(
1315            "column 4 flag {:?} is not a legal integer for spec {spec_version}",
1316            token_on_line(bytes, i)
1317        ))
1318    };
1319    if !bytes[i].is_ascii_digit() {
1320        return Err(bad());
1321    }
1322    let mut j = i;
1323    let mut val: u64 = 0;
1324    while j < bytes.len() && bytes[j].is_ascii_digit() {
1325        let d = u64::from(bytes[j] - b'0');
1326        val = val
1327            .checked_mul(10)
1328            .and_then(|v| v.checked_add(d))
1329            .ok_or_else(bad)?;
1330        j += 1;
1331    }
1332    if !ends_field(bytes, j) {
1333        return Err(bad());
1334    }
1335    let fixed = if spec_version < 2 {
1336        match val {
1337            0 => [false, false, false],
1338            1 => [true, true, true],
1339            _ => return Err(bad()),
1340        }
1341    } else if val <= 7 {
1342        let v = val as u8;
1343        [v & 1 != 0, v & 2 != 0, v & 4 != 0]
1344    } else {
1345        return Err(bad());
1346    };
1347    Ok((fixed, j))
1348}
1349
1350#[inline(always)]
1351fn parse_id_at(bytes: &[u8], i: usize) -> Result<(u64, usize), ParseError> {
1352    if at_row_end(bytes, i) || !bytes[i].is_ascii_digit() {
1353        return Err(ParseError::InvalidNumberFormat(format!(
1354            "invalid integer: {}",
1355            token_on_line(bytes, i)
1356        )));
1357    }
1358    let mut j = i;
1359    let mut val: u64 = 0;
1360    while j < bytes.len() && bytes[j].is_ascii_digit() {
1361        let d = u64::from(bytes[j] - b'0');
1362        val = val
1363            .checked_mul(10)
1364            .and_then(|v| v.checked_add(d))
1365            .ok_or_else(|| {
1366                ParseError::InvalidNumberFormat(format!(
1367                    "integer out of range 0..=2^64-1: {}",
1368                    token_on_line(bytes, i)
1369                ))
1370            })?;
1371        j += 1;
1372    }
1373    if !ends_field(bytes, j) {
1374        return Err(ParseError::InvalidNumberFormat(format!(
1375            "invalid integer: {}",
1376            token_on_line(bytes, i)
1377        )));
1378    }
1379    Ok((val, j))
1380}
1381
1382/// One parsed coordinate row: xyz, fixed flags, and the atom id.
1383type ParsedCoord = ([f64; 3], [bool; 3], u64);
1384
1385/// One coordinate or vector row starting at `i`.
1386///
1387/// Stops at newline or end of `bytes` and returns the index just past the
1388/// row (after the newline, when one was present). Floats, the flag, and the
1389/// id are parsed in that single scan. The success path does not build error
1390/// strings; those stay on the cold fallback.
1391#[inline(always)]
1392fn parse_coord_fields(
1393    bytes: &[u8],
1394    i: usize,
1395    spec_version: u32,
1396    default_id: Option<u64>,
1397) -> Result<(ParsedCoord, usize), ParseError> {
1398    if let Some(parsed) = parse_coord_fields_fast(bytes, i, spec_version, default_id) {
1399        return Ok(parsed);
1400    }
1401    parse_coord_fields_detailed(bytes, i, spec_version, default_id)
1402}
1403
1404/// Common coordinate row: three finite decimals, a small flag, an optional id.
1405#[inline(always)]
1406fn parse_coord_fields_fast(
1407    bytes: &[u8],
1408    i: usize,
1409    spec_version: u32,
1410    default_id: Option<u64>,
1411) -> Option<(ParsedCoord, usize)> {
1412    let mut i = skip_field_ws(bytes, i);
1413    let mut xyz = [0.0f64; 3];
1414    for dest in &mut xyz {
1415        if at_row_end(bytes, i) || bytes[i] >= 0x80 {
1416            return None;
1417        }
1418        let (val, next) = crate::fast_dec::parse_f64_hot(bytes, i)?;
1419        if !ends_field(bytes, next) {
1420            return None;
1421        }
1422        *dest = val;
1423        i = skip_field_ws(bytes, next);
1424    }
1425    let (fixed, next) = parse_flag_fast(bytes, i, spec_version)?;
1426    i = skip_field_ws(bytes, next);
1427    let (atom_id, next) = if at_row_end(bytes, i) {
1428        (default_id?, i)
1429    } else {
1430        parse_u64_fast(bytes, i)?
1431    };
1432    i = skip_field_ws(bytes, next);
1433    if !at_row_end(bytes, i) {
1434        return None;
1435    }
1436    i = consume_row_end(bytes, i);
1437    Some(((xyz, fixed, atom_id), i))
1438}
1439
1440#[inline(always)]
1441fn parse_u64_fast(bytes: &[u8], i: usize) -> Option<(u64, usize)> {
1442    if i >= bytes.len() || !bytes[i].is_ascii_digit() {
1443        return None;
1444    }
1445    let mut j = i;
1446    let mut val: u64 = 0;
1447    let mut digits = 0u32;
1448    while j < bytes.len() && bytes[j].is_ascii_digit() {
1449        digits += 1;
1450        // 19 digits can overflow u64; the detailed parser reports that.
1451        if digits > 18 {
1452            return None;
1453        }
1454        val = val * 10 + u64::from(bytes[j] - b'0');
1455        j += 1;
1456    }
1457    if !ends_field(bytes, j) {
1458        return None;
1459    }
1460    Some((val, j))
1461}
1462
1463#[inline(always)]
1464fn parse_flag_fast(bytes: &[u8], i: usize, spec_version: u32) -> Option<([bool; 3], usize)> {
1465    let (val, j) = parse_u64_fast(bytes, i)?;
1466    let fixed = if spec_version < 2 {
1467        match val {
1468            0 => [false, false, false],
1469            1 => [true, true, true],
1470            _ => return None,
1471        }
1472    } else if val <= 7 {
1473        let v = val as u8;
1474        [v & 1 != 0, v & 2 != 0, v & 4 != 0]
1475    } else {
1476        return None;
1477    };
1478    Some((fixed, j))
1479}
1480
1481#[cold]
1482#[inline(never)]
1483fn parse_coord_fields_detailed(
1484    bytes: &[u8],
1485    i: usize,
1486    spec_version: u32,
1487    default_id: Option<u64>,
1488) -> Result<(ParsedCoord, usize), ParseError> {
1489    let line_start = i;
1490    let mut i = skip_field_ws(bytes, i);
1491    if at_row_end(bytes, i) {
1492        return Err(ParseError::InvalidVectorLength {
1493            expected: 5,
1494            found: 0,
1495        });
1496    }
1497    let mut xyz = [0.0f64; 3];
1498    for (slot, dest) in xyz.iter_mut().enumerate() {
1499        if at_row_end(bytes, i) {
1500            return Err(ParseError::InvalidVectorLength {
1501                expected: 5,
1502                found: slot,
1503            });
1504        }
1505        if bytes[i] >= 0x80 {
1506            return Err(utf8_or_number(bytes, line_start, i));
1507        }
1508        let (val, next) = parse_f64_at(bytes, i, line_start)?;
1509        *dest = val;
1510        i = skip_field_ws(bytes, next);
1511    }
1512    let (fixed, next) = parse_flag_at(bytes, i, spec_version)?;
1513    i = skip_field_ws(bytes, next);
1514    let (atom_id, next) = if at_row_end(bytes, i) {
1515        (
1516            default_id.ok_or(ParseError::InvalidVectorLength {
1517                expected: 5,
1518                found: 4,
1519            })?,
1520            i,
1521        )
1522    } else {
1523        parse_id_at(bytes, i)?
1524    };
1525    i = skip_field_ws(bytes, next);
1526    if !at_row_end(bytes, i) {
1527        let found = 5 + count_tokens_on_line(bytes, i);
1528        return Err(ParseError::InvalidVectorLength { expected: 5, found });
1529    }
1530    i = consume_row_end(bytes, i);
1531    Ok(((xyz, fixed, atom_id), i))
1532}
1533
1534/// Coordinate row at byte offset `i` in a multi-line buffer.
1535///
1536/// The returned index is the start of the next line. ASCII rows are valid
1537/// UTF-8 without a separate scan; a non-ASCII byte is checked only then.
1538pub(crate) fn parse_coord_row_at(
1539    bytes: &[u8],
1540    i: usize,
1541    spec_version: u32,
1542    default_id: u64,
1543) -> Result<(ParsedCoord, usize), ParseError> {
1544    if i >= bytes.len() {
1545        return Err(ParseError::IncompleteFrame);
1546    }
1547    parse_coord_fields(bytes, i, spec_version, Some(default_id))
1548}
1549
1550/// Vector-section row at `i`. The id column is required.
1551pub(crate) fn parse_vector_row_at(
1552    bytes: &[u8],
1553    i: usize,
1554    spec_version: u32,
1555) -> Result<(ParsedCoord, usize), ParseError> {
1556    if i >= bytes.len() {
1557        return Err(ParseError::IncompleteFrame);
1558    }
1559    parse_coord_fields(bytes, i, spec_version, None)
1560}
1561
1562/// Scalar section row: one finite float, a flag, and an id. Exact width 3.
1563fn parse_scalar_section_row(
1564    line: &str,
1565    spec_version: u32,
1566) -> Result<(f64, [bool; 3], u64), ParseError> {
1567    let bytes = line.as_bytes();
1568    let i = skip_ascii_ws(bytes, 0);
1569    let (value, i) = parse_finite_at(line, i)?;
1570    let i = skip_ascii_ws(bytes, i);
1571    let (flag_tok, i) = take_token(line, i).ok_or(ParseError::InvalidVectorLength {
1572        expected: 3,
1573        found: 1,
1574    })?;
1575    let fixed = parse_fixed_flag(flag_tok, spec_version)?;
1576    let i = skip_ascii_ws(bytes, i);
1577    let (id_tok, i) = take_token(line, i).ok_or(ParseError::InvalidVectorLength {
1578        expected: 3,
1579        found: 2,
1580    })?;
1581    let atom_id = parse_atom_id_token(id_tok)?;
1582    let i = skip_ascii_ws(bytes, i);
1583    if i < bytes.len() {
1584        let found = 3 + split_field_ws(&line[i..]).count();
1585        return Err(ParseError::InvalidVectorLength { expected: 3, found });
1586    }
1587    Ok((value, fixed, atom_id))
1588}
1589
1590fn parse_finite_at(line: &str, i: usize) -> Result<(f64, usize), ParseError> {
1591    let bytes = line.as_bytes();
1592    if i >= bytes.len() {
1593        return Err(ParseError::InvalidVectorLength {
1594            expected: 3,
1595            found: 0,
1596        });
1597    }
1598    // "infinity" parses as the prefix "inf" in fast_float2. Name that
1599    // spelling before the numeric kernel so the leftover is not a format error.
1600    if looks_like_nonfinite(bytes, i) {
1601        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
1602        if is_nonfinite_spelling(token) {
1603            return Err(ParseError::NonFiniteValue(token.to_string()));
1604        }
1605    }
1606    let (val, consumed) = fast_float2::parse_partial::<f64, _>(&bytes[i..]).map_err(|_| {
1607        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
1608        ParseError::InvalidNumberFormat(format!("invalid float: {token}"))
1609    })?;
1610    let next = i + consumed;
1611    let boundary = ends_field(bytes, next);
1612    if !boundary {
1613        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
1614        return Err(ParseError::InvalidNumberFormat(format!(
1615            "invalid float: {token}"
1616        )));
1617    }
1618    if !val.is_finite() {
1619        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
1620        return Err(ParseError::NonFiniteValue(token.to_string()));
1621    }
1622    Ok((val, next))
1623}
1624
1625/// True when the token may be a non-finite spelling. Digit and dot
1626/// tokens, the common atom-line case, are false after one byte.
1627fn looks_like_nonfinite(bytes: &[u8], i: usize) -> bool {
1628    let mut j = i;
1629    if bytes[j] == b'+' || bytes[j] == b'-' {
1630        j += 1;
1631        if j >= bytes.len() {
1632            return false;
1633        }
1634    }
1635    let b = bytes[j];
1636    !b.is_ascii_digit() && b != b'.'
1637}
1638
1639/// Case-insensitive, after collapsing each run of spaces (CON-file.5, D17).
1640pub(crate) fn labels_equal(found: &str, expected: &str) -> bool {
1641    let mut found_words = found.split_ascii_whitespace();
1642    let mut expected_words = expected.split_ascii_whitespace();
1643    loop {
1644        match (found_words.next(), expected_words.next()) {
1645            (Some(a), Some(b)) => {
1646                if !a.eq_ignore_ascii_case(b) {
1647                    return false;
1648                }
1649            }
1650            (None, None) => return true,
1651            _ => return false,
1652        }
1653    }
1654}
1655
1656/// Label prefix of a reserved section, in the form the section parser checks.
1657pub(crate) fn reserved_section_label_prefix(name: &str) -> Option<&'static str> {
1658    match name {
1659        crate::types::SECTION_VELOCITIES => Some("Velocities of Component"),
1660        crate::types::SECTION_FORCES => Some("Forces of Component"),
1661        crate::types::SECTION_ENERGIES => Some("Energies of Component"),
1662        crate::types::SECTION_CHARGES => Some("Charges of Component"),
1663        crate::types::SECTION_SPINS => Some("Spins of Component"),
1664        crate::types::SECTION_MAGMOMS => Some("Magmoms of Component"),
1665        crate::types::SECTION_DISPLACEMENTS => Some("Displacements of Component"),
1666        crate::types::SECTION_SPREADS => Some("Spreads of Component"),
1667        _ => None,
1668    }
1669}
1670
1671/// True when `line`, after the same folding, starts with every word of `prefix`.
1672pub(crate) fn label_has_prefix(line: &str, prefix: &str) -> bool {
1673    let mut found_words = line.split_ascii_whitespace();
1674    for word in prefix.split_ascii_whitespace() {
1675        match found_words.next() {
1676            Some(got) if got.eq_ignore_ascii_case(word) => {}
1677            _ => return false,
1678        }
1679    }
1680    true
1681}
1682
1683fn token_count(line: &str) -> usize {
1684    line.split_ascii_whitespace().count()
1685}
1686
1687/// Most whitespace-separated tokens `line` can hold.
1688///
1689/// `k` tokens take at least one byte each and one separator between each
1690/// pair, `2k - 1` bytes in all.
1691fn max_tokens_on_line(line: &str) -> usize {
1692    line.len().div_ceil(2)
1693}
1694
1695/// Matches the JSON integer grammar `0|[1-9][0-9]*` (rejects `-0`, `+`,
1696/// leading zeros, fractions, and exponents).
1697pub(crate) fn is_nonneg_decimal_int(token: &str) -> bool {
1698    match token.as_bytes() {
1699        [b'0'] => true,
1700        [b'1'..=b'9', rest @ ..] => rest.iter().all(|b| b.is_ascii_digit()),
1701        _ => false,
1702    }
1703}
1704
1705/// Shared text for a repeated top-level `con_spec_minor` (CON-line2.14).
1706pub(crate) const DUPLICATE_CON_SPEC_MINOR: &str = "duplicate con_spec_minor key";
1707
1708/// True only for oversized `0|[1-9][0-9]*` tokens that do not fit in `u64`
1709/// yet `serde_json` accepts as a finite JSON number. That includes integers
1710/// above `f64::MAX` that round to it, through `floor(f64::MAX) + 2^970 - 1`.
1711/// Tokens that `serde_json` itself rejects (`number out of range`) are left
1712/// untouched so the original error and column surface unchanged.
1713pub(crate) fn is_substitutable_huge_minor(token: &str) -> bool {
1714    is_nonneg_decimal_int(token)
1715        && token.parse::<u64>().is_err()
1716        && serde_json::from_str::<serde_json::Number>(token).is_ok()
1717}
1718
1719/// `con_spec_version`, `con_spec_minor`, and `con_spec_patch`, by exact name.
1720///
1721/// CON-line2.22 rejects an integer literal above `u64` on these keys.
1722/// A `*_version` suffix is not this set. Any other key is left alone.
1723pub(crate) fn is_reserved_integer_version_field(key: &str) -> bool {
1724    matches!(
1725        key,
1726        meta::CON_SPEC_VERSION | meta::CON_SPEC_MINOR | meta::CON_SPEC_PATCH
1727    )
1728}
1729
1730/// `true` when `token` is the integer grammar `0|[1-9][0-9]*` and does
1731/// not fit in `u64`. A negative, a fraction, and an exponent are not.
1732pub(crate) fn decimal_integer_above_u64(token: &str) -> bool {
1733    is_nonneg_decimal_int(token) && token.parse::<u64>().is_err()
1734}
1735
1736/// CON-line2.22. One check for the reader, the builder, and Python.
1737pub(crate) fn reserved_version_integer_above_u64(key: &str, token: &str) -> bool {
1738    is_reserved_integer_version_field(key) && decimal_integer_above_u64(token)
1739}
1740
1741/// First top-level reserved version field whose integer literal does not
1742/// fit in `u64` (CON-line2.22).
1743///
1744/// The key is `con_spec_version`, `con_spec_minor`, or `con_spec_patch`.
1745/// A nested key is not that field. The token is the JSON integer grammar
1746/// `0|[1-9][0-9]*`. A fraction, an exponent, a negative, and every
1747/// unreserved key stay with the checks those tokens already had.
1748pub(crate) fn oversized_integer_version_field(json: &str) -> Option<String> {
1749    let bytes = json.as_bytes();
1750    let mut start = 0usize;
1751    skip_json_ws(bytes, &mut start);
1752    if bytes.get(start) != Some(&b'{') {
1753        return None;
1754    }
1755    let mut found = None;
1756    scan_json_object_fields(json, start, skip_json_ws, |key, _key_end, span| {
1757        if found.is_some() {
1758            return;
1759        }
1760        let token = json[span].trim();
1761        if reserved_version_integer_above_u64(key, token) {
1762            found = Some(key.to_string());
1763        }
1764    });
1765    found
1766}
1767
1768/// Top-level `con_spec_patch` whose token is not a non-negative decimal
1769/// integer.
1770///
1771/// [`oversized_integer_version_field`] owns `0|[1-9][0-9]*` and rejects a
1772/// value that does not fit in `u64`. A leading minus never enters that
1773/// scan. CON-line2.15 still requires the patch to be an integer >= 0, and
1774/// the reader and the builder already reject it. RPC uses this so the
1775/// three paths agree. `schema_version: -1` is not this field.
1776pub(crate) fn patch_token_outside_u64_grammar(json: &str) -> bool {
1777    let bytes = json.as_bytes();
1778    let mut start = 0usize;
1779    skip_json_ws(bytes, &mut start);
1780    if bytes.get(start) != Some(&b'{') {
1781        return false;
1782    }
1783    let mut outside = false;
1784    scan_json_object_fields(json, start, skip_json_ws, |key, _key_end, span| {
1785        if outside || key != meta::CON_SPEC_PATCH {
1786            return;
1787        }
1788        let token = json[span].trim();
1789        if !is_nonneg_decimal_int(token) {
1790            outside = true;
1791        }
1792    });
1793    outside
1794}
1795
1796pub(crate) fn integer_version_u64_sentence(field: &str) -> String {
1797    format!("{field} must be a JSON integer >= 0 that fits in an unsigned 64-bit integer")
1798}
1799
1800pub(crate) fn integer_version_field_limit(field: &str) -> ParseError {
1801    metadata_json_error(integer_version_u64_sentence(field))
1802}
1803
1804/// Decimal forms of `floor(f64::MAX) + 1`, `floor(f64::MAX) + 2^970 - 1`,
1805/// and `floor(f64::MAX) + 2^970`.
1806///
1807/// `floor(f64::MAX)` is `(2^53 - 1) * 2^971`. Integers through one less than
1808/// the half-ULP step `2^970` round to `f64::MAX`. The next integer does not.
1809#[cfg(test)]
1810pub(crate) fn f64_max_minor_edge_digits() -> (String, String, String) {
1811    let fmax = mul_pow2_decimal((1u128 << 53) - 1, 971);
1812    let half_step = mul_pow2_decimal((1u128 << 54) - 1, 970);
1813    let plus_one = add_small_decimal(&fmax, 1);
1814    let last_finite = sub_one_decimal(&half_step);
1815    (plus_one, last_finite, half_step)
1816}
1817
1818#[cfg(test)]
1819fn mul_pow2_decimal(mut mantissa: u128, shift: u32) -> String {
1820    let mut digits = Vec::new();
1821    if mantissa == 0 {
1822        digits.push(0);
1823    }
1824    while mantissa > 0 {
1825        digits.push((mantissa % 10) as u8);
1826        mantissa /= 10;
1827    }
1828    for _ in 0..shift {
1829        let mut carry = 0u16;
1830        for digit in &mut digits {
1831            let value = u16::from(*digit) * 2 + carry;
1832            *digit = (value % 10) as u8;
1833            carry = value / 10;
1834        }
1835        if carry > 0 {
1836            digits.push(carry as u8);
1837        }
1838    }
1839    digits
1840        .iter()
1841        .rev()
1842        .map(|digit| char::from(b'0' + digit))
1843        .collect()
1844}
1845
1846#[cfg(test)]
1847fn add_small_decimal(digits: &str, mut add: u64) -> String {
1848    let mut out = Vec::new();
1849    for byte in digits.bytes().rev() {
1850        let value = u64::from(byte - b'0') + add;
1851        out.push(char::from(b'0' + (value % 10) as u8));
1852        add = value / 10;
1853    }
1854    while add > 0 {
1855        out.push(char::from(b'0' + (add % 10) as u8));
1856        add /= 10;
1857    }
1858    out.iter().rev().collect()
1859}
1860
1861#[cfg(test)]
1862fn sub_one_decimal(digits: &str) -> String {
1863    let mut bytes = digits.as_bytes().to_vec();
1864    let mut index = bytes.len() - 1;
1865    loop {
1866        if bytes[index] > b'0' {
1867            bytes[index] -= 1;
1868            break;
1869        }
1870        bytes[index] = b'9';
1871        index -= 1;
1872    }
1873    let start = usize::from(bytes[0] == b'0');
1874    String::from_utf8(bytes[start..].to_vec()).unwrap()
1875}
1876
1877fn skip_json_ws(bytes: &[u8], i: &mut usize) {
1878    while *i < bytes.len() && matches!(bytes[*i], b' ' | b'\t' | b'\r' | b'\n') {
1879        *i += 1;
1880    }
1881}
1882
1883/// ASCII whitespace between line-2 JSON tokens, including form feed: the
1884/// set `simple_metadata_version` skips. Row fields use [`is_field_ws`].
1885fn skip_ascii_ws_mut(bytes: &[u8], i: &mut usize) {
1886    while *i < bytes.len() && bytes[*i].is_ascii_whitespace() {
1887        *i += 1;
1888    }
1889}
1890
1891fn scan_json_string_end(bytes: &[u8], start: usize) -> Option<usize> {
1892    if bytes.get(start) != Some(&b'"') {
1893        return None;
1894    }
1895    let mut i = start + 1;
1896    let mut escaped = false;
1897    while i < bytes.len() {
1898        let b = bytes[i];
1899        if escaped {
1900            escaped = false;
1901        } else if b == b'\\' {
1902            escaped = true;
1903        } else if b == b'"' {
1904            return Some(i + 1);
1905        }
1906        i += 1;
1907    }
1908    None
1909}
1910
1911fn scan_json_value_end(bytes: &[u8], start: usize) -> Option<usize> {
1912    let first = *bytes.get(start)?;
1913    if first == b'"' {
1914        return scan_json_string_end(bytes, start);
1915    }
1916    if first == b'{' || first == b'[' {
1917        let mut depth = 0usize;
1918        let mut i = start;
1919        while i < bytes.len() {
1920            match bytes[i] {
1921                b'"' => {
1922                    i = scan_json_string_end(bytes, i)?;
1923                    continue;
1924                }
1925                b'{' | b'[' => depth += 1,
1926                b'}' | b']' => {
1927                    depth = depth.saturating_sub(1);
1928                    if depth == 0 {
1929                        return Some(i + 1);
1930                    }
1931                }
1932                _ => {}
1933            }
1934            i += 1;
1935        }
1936        return None;
1937    }
1938    let mut i = start;
1939    while i < bytes.len() && !matches!(bytes[i], b' ' | b'\t' | b'\r' | b'\n' | b',' | b'}' | b']')
1940    {
1941        i += 1;
1942    }
1943    (i > start).then_some(i)
1944}
1945
1946fn decode_json_key(raw_quoted: &str) -> Option<std::borrow::Cow<'_, str>> {
1947    if !raw_quoted.contains('\\') {
1948        Some(std::borrow::Cow::Borrowed(
1949            &raw_quoted[1..raw_quoted.len() - 1],
1950        ))
1951    } else {
1952        serde_json::from_str::<String>(raw_quoted)
1953            .ok()
1954            .map(std::borrow::Cow::Owned)
1955    }
1956}
1957
1958fn scan_json_object_fields(
1959    json: &str,
1960    start: usize,
1961    skip_ws: fn(&[u8], &mut usize),
1962    mut on_field: impl FnMut(&str, usize, std::ops::Range<usize>),
1963) {
1964    let bytes = json.as_bytes();
1965    if bytes.get(start) != Some(&b'{') {
1966        return;
1967    }
1968    let mut i = start + 1;
1969    loop {
1970        skip_ws(bytes, &mut i);
1971        if i >= bytes.len() || bytes[i] == b'}' {
1972            break;
1973        }
1974        if bytes[i] == b',' {
1975            i += 1;
1976            skip_ws(bytes, &mut i);
1977        }
1978        if bytes.get(i) != Some(&b'"') {
1979            break;
1980        }
1981        let Some(k_end) = scan_json_string_end(bytes, i) else {
1982            break;
1983        };
1984        let raw_key = &json[i..k_end];
1985        i = k_end;
1986        skip_ws(bytes, &mut i);
1987        if bytes.get(i) != Some(&b':') {
1988            break;
1989        }
1990        i += 1;
1991        skip_ws(bytes, &mut i);
1992        let v_start = i;
1993        let Some(v_end) = scan_json_value_end(bytes, v_start) else {
1994            break;
1995        };
1996        i = v_end;
1997        if let Some(key) = decode_json_key(raw_key) {
1998            on_field(key.as_ref(), k_end, v_start..v_end);
1999        }
2000    }
2001}
2002
2003/// Scan top-level `con_spec_minor` raw value spans from a JSON object string.
2004pub(crate) fn top_level_minor_spans(json: &str) -> Vec<std::ops::Range<usize>> {
2005    let mut out = Vec::new();
2006    let bytes = json.as_bytes();
2007    let mut start = 0usize;
2008    skip_json_ws(bytes, &mut start);
2009    if bytes.get(start) != Some(&b'{') {
2010        return out;
2011    }
2012    scan_json_object_fields(json, start, skip_json_ws, |key, _key_end, span| {
2013        if key == meta::CON_SPEC_MINOR {
2014            out.push(span);
2015        }
2016    });
2017    out
2018}
2019
2020/// Byte index just after the first top-level `con_spec_minor` key.
2021///
2022/// CON-line2.10 says a missing minor is 0. A nested object, an array
2023/// element, or a dotted name is not that field. Tokens may be separated
2024/// by ASCII whitespace, the set the fast path skips, including form feed.
2025pub(crate) fn top_level_first_minor_key_end(json: &str) -> Option<usize> {
2026    let bytes = json.as_bytes();
2027    let mut start = 0usize;
2028    skip_ascii_ws_mut(bytes, &mut start);
2029    if bytes.get(start) != Some(&b'{') {
2030        return None;
2031    }
2032    let mut found = None;
2033    scan_json_object_fields(json, start, skip_ascii_ws_mut, |key, key_end, _span| {
2034        if found.is_none() && key == meta::CON_SPEC_MINOR {
2035            found = Some(key_end);
2036        }
2037    });
2038    found
2039}
2040
2041/// Returns the last raw value token for top-level `target` in `json`.
2042pub(crate) fn top_level_last_raw_token<'a>(json: &'a str, target: &str) -> Option<&'a str> {
2043    let bytes = json.as_bytes();
2044    let mut start = 0usize;
2045    skip_json_ws(bytes, &mut start);
2046    if bytes.get(start) != Some(&b'{') {
2047        return None;
2048    }
2049    let mut last: Option<std::ops::Range<usize>> = None;
2050    scan_json_object_fields(json, start, skip_json_ws, |key, _key_end, span| {
2051        if key == target {
2052            last = Some(span);
2053        }
2054    });
2055    last.map(|span| &json[span])
2056}
2057
2058/// Replace any serde-accepted `con_spec_minor` integer token exceeding `u64::MAX`
2059/// with a valid JSON number (`0.00...0`) of the exact same byte length so
2060/// `serde_json` preserves every original column and offset across the line.
2061/// Returns the exact digits only when the last (effective) `con_spec_minor`
2062/// token is substituted.
2063pub(crate) fn sanitize_huge_con_spec_minor<'a>(
2064    json: &'a str,
2065    minor_spans: &[std::ops::Range<usize>],
2066) -> (std::borrow::Cow<'a, str>, Option<String>) {
2067    let huge_minor = minor_spans.last().and_then(|span| {
2068        let tok = &json[span.clone()];
2069        is_substitutable_huge_minor(tok).then(|| tok.to_owned())
2070    });
2071    let mut huge_spans: Vec<std::ops::Range<usize>> = minor_spans
2072        .iter()
2073        .filter(|span| is_substitutable_huge_minor(&json[(*span).clone()]))
2074        .cloned()
2075        .collect();
2076    if huge_spans.is_empty() {
2077        return (std::borrow::Cow::Borrowed(json), None);
2078    }
2079    huge_spans.sort_by_key(|s| (s.start, s.end));
2080    huge_spans.dedup();
2081    let mut out = String::with_capacity(json.len());
2082    let mut cursor = 0usize;
2083    for span in huge_spans {
2084        if span.start < cursor {
2085            continue;
2086        }
2087        out.push_str(&json[cursor..span.start]);
2088        let width = span.end - span.start;
2089        out.push_str("0.");
2090        for _ in 2..width {
2091            out.push('0');
2092        }
2093        cursor = span.end;
2094    }
2095    out.push_str(&json[cursor..]);
2096    (std::borrow::Cow::Owned(out), huge_minor)
2097}
2098
2099pub(crate) fn parse_metadata_json_object_with_raw(
2100    metadata_json: &str,
2101) -> Result<(serde_json::Map<String, Value>, Option<String>), serde_json::Error> {
2102    let spans = top_level_minor_spans(metadata_json);
2103    if spans.len() > 1 {
2104        return Err(serde_json::Error::custom(DUPLICATE_CON_SPEC_MINOR));
2105    }
2106    let (sanitized, minor_raw) = sanitize_huge_con_spec_minor(metadata_json, &spans);
2107    let mut object: serde_json::Map<String, Value> = serde_json::from_str(sanitized.as_ref())?;
2108    if let Some(field) = oversized_integer_version_field(metadata_json) {
2109        return Err(serde_json::Error::custom(format!(
2110            "{field} must be a JSON integer >= 0 that fits in an unsigned 64-bit integer"
2111        )));
2112    }
2113    if minor_raw.is_some() {
2114        object.insert(
2115            meta::CON_SPEC_MINOR.into(),
2116            Value::from(crate::types::SATURATED_SPEC_MINOR),
2117        );
2118    }
2119    Ok((object, minor_raw))
2120}
2121
2122pub(crate) fn parse_metadata_object_with_raw(
2123    metadata_json: &str,
2124) -> Result<(serde_json::Map<String, Value>, Option<String>), ParseError> {
2125    let (object, minor_raw) = parse_metadata_json_object_with_raw(metadata_json)?;
2126    validate_builder_metadata_schema(&object)?;
2127    Ok((object, minor_raw))
2128}
2129
2130/// Validates metadata handed to a frame builder.
2131///
2132/// Builders drop `sections` and the writer derives it from the atoms,
2133/// emitting it whenever `validate` is true. A missing `sections` array is
2134/// therefore not an error here, so metadata read from a strict file can be
2135/// handed back unchanged. Every other check matches
2136/// [`validate_metadata_schema`].
2137pub fn validate_builder_metadata_schema(
2138    json_obj: &serde_json::Map<String, Value>,
2139) -> Result<(), ParseError> {
2140    if json_obj.contains_key(meta::SECTIONS)
2141        || json_obj.get(meta::VALIDATE) != Some(&Value::Bool(true))
2142    {
2143        return validate_metadata_schema(json_obj);
2144    }
2145    let mut with_sections = json_obj.clone();
2146    with_sections.insert(meta::SECTIONS.into(), Value::Array(Vec::new()));
2147    validate_metadata_schema(&with_sections)
2148}
2149
2150/// Map and exact huge-minor digits for an RPC `metadataJson` string.
2151///
2152/// `con_spec_minor` must be a JSON integer >= 0 (CON-line2.13), as on
2153/// read, so a frame received over RPC cannot be written with a minor no
2154/// reader accepts.
2155#[cfg_attr(not(feature = "rpc"), allow(dead_code))]
2156pub(crate) fn parse_metadata_map_with_minor_raw(
2157    metadata_json: &str,
2158) -> Result<(std::collections::BTreeMap<String, Value>, Option<String>), serde_json::Error> {
2159    let spans = top_level_minor_spans(metadata_json);
2160    if spans.len() > 1 {
2161        return Err(serde_json::Error::custom(DUPLICATE_CON_SPEC_MINOR));
2162    }
2163    let (sanitized, minor_raw) = sanitize_huge_con_spec_minor(metadata_json, &spans);
2164    let mut map: std::collections::BTreeMap<String, Value> =
2165        serde_json::from_str(sanitized.as_ref())?;
2166    if let Some(field) = oversized_integer_version_field(metadata_json) {
2167        return Err(serde_json::Error::custom(format!(
2168            "{field} must be a JSON integer >= 0 that fits in an unsigned 64-bit integer"
2169        )));
2170    }
2171    if patch_token_outside_u64_grammar(metadata_json) {
2172        return Err(serde_json::Error::custom(
2173            "con_spec_patch must be a JSON integer >= 0 that fits in an unsigned 64-bit integer",
2174        ));
2175    }
2176    if minor_raw.is_some() {
2177        map.insert(
2178            meta::CON_SPEC_MINOR.into(),
2179            Value::from(crate::types::SATURATED_SPEC_MINOR),
2180        );
2181    }
2182    if map
2183        .get(meta::CON_SPEC_MINOR)
2184        .is_some_and(|value| json_u64(value).is_none())
2185    {
2186        return Err(serde_json::Error::custom(
2187            "con_spec_minor must be a JSON integer >= 0 that fits in an unsigned 64-bit integer",
2188        ));
2189    }
2190    for (key, value) in &map {
2191        if key == meta::CON_SPEC_VERSION {
2192            match json_major_version(value) {
2193                None => {
2194                    return Err(serde_json::Error::custom(
2195                        "con_spec_version must be a JSON integer, the major version",
2196                    ));
2197                }
2198                Some(ver) => {
2199                    if let Some(reported) = rejected_spec_major(ver) {
2200                        return Err(serde_json::Error::custom(
2201                            ParseError::UnsupportedVersion(reported).to_string(),
2202                        ));
2203                    }
2204                }
2205            }
2206        }
2207    }
2208    Ok((map, minor_raw))
2209}
2210
2211fn json_u64(value: &Value) -> Option<u64> {
2212    value.as_u64()
2213}
2214
2215/// A major the reader rejects, as the value `UnsupportedVersion` carries.
2216///
2217/// A value above `u32::MAX` is reported as `u32::MAX`. `0`, `1`, and any
2218/// major this library does not read are reported as themselves.
2219/// `4294967295.0` is `u32::MAX` and is not a known major, so the bound
2220/// stays `<=`. A strict `<` would call that float "not a major integer".
2221fn rejected_spec_major(ver: u64) -> Option<u32> {
2222    if ver > u64::from(u32::MAX) {
2223        return Some(u32::MAX);
2224    }
2225    let narrow = ver as u32;
2226    if narrow == 0 || narrow == 1 || narrow > crate::CON_SPEC_VERSION {
2227        Some(narrow)
2228    } else {
2229        None
2230    }
2231}
2232
2233/// CON-line2.4: the major is a JSON number, not a string. `3.0` and `3e0`
2234/// are that number. A non-integer such as `3.5` is not a major.
2235fn json_major_version(value: &Value) -> Option<u64> {
2236    if let Some(n) = value.as_u64() {
2237        return Some(n);
2238    }
2239    let n = value.as_f64()?;
2240    // A major fits in u32. A float above that, including 2^64, is not one.
2241    if n.is_finite() && n >= 0.0 && n <= u32::MAX as f64 && n.fract() == 0.0 {
2242        Some(n as u64)
2243    } else {
2244        None
2245    }
2246}
2247
2248fn validate_section_arity_value(value: &Value) -> Result<(), ParseError> {
2249    let obj = value.as_object().ok_or_else(|| {
2250        metadata_json_error("section_arity must be an object mapping section names to integers")
2251    })?;
2252    for (name, entry) in obj {
2253        let n = json_u64(entry).ok_or_else(|| {
2254            metadata_json_error(format!("section_arity.{name} must be an integer >= 1"))
2255        })?;
2256        if n < 1 {
2257            return Err(ParseError::InvalidCount(format!(
2258                "section_arity.{name} must be >= 1"
2259            )));
2260        }
2261        // Reserved names have a fixed value-field count (CON-section.13).
2262        if let Some(expect) = crate::types::reserved_section_value_arity(name)
2263            && n != expect
2264        {
2265            return Err(ParseError::InvalidVectorLength {
2266                expected: usize::try_from(expect).unwrap_or(usize::MAX),
2267                found: usize::try_from(n).unwrap_or(usize::MAX),
2268            });
2269        }
2270    }
2271    Ok(())
2272}
2273
2274/// Integer counts. A sign, a decimal point, or any other non-digit token
2275/// is `InvalidCount` (CON-error.3). Zero is a legal token here. The caller
2276/// rejects a per-type count of 0 when the type count is 1 or more (D4).
2277pub(crate) fn parse_count_line(line: &str, n: usize) -> Result<Vec<usize>, ParseError> {
2278    let mut values = Vec::with_capacity(n.min(max_tokens_on_line(line)));
2279    for token in split_field_ws(line) {
2280        if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
2281            return Err(ParseError::InvalidCount(format!(
2282                "count field is not an unsigned integer: {token}"
2283            )));
2284        }
2285        let val: u64 = token.parse::<u64>().map_err(|_| {
2286            ParseError::InvalidCount(format!("count field is out of range: {token}"))
2287        })?;
2288        let val = usize::try_from(val).map_err(|_| {
2289            ParseError::InvalidCount(format!("count field is out of range: {token}"))
2290        })?;
2291        values.push(val);
2292    }
2293    if values.len() == n {
2294        Ok(values)
2295    } else {
2296        Err(ParseError::InvalidVectorLength {
2297            expected: n,
2298            found: values.len(),
2299        })
2300    }
2301}
2302
2303/// True when `line` has no tokens. Spaces and tabs count as empty.
2304pub(crate) fn line_is_whitespace(line: &str) -> bool {
2305    line.split_ascii_whitespace().next().is_none()
2306}
2307
2308/// Lines 8 and 9 of a type count of 0.
2309///
2310/// A token on either line is `InvalidCount`. At end of file, a missing
2311/// line is empty (CON-count.4), and that frame is not `IncompleteHeader`
2312/// (CON-frame.3). Mid-file, both lines are required.
2313pub(crate) fn read_zero_atom_tail<'a>(
2314    mut next_line: impl FnMut() -> Option<&'a str>,
2315) -> Result<(), ParseError> {
2316    let bad = || {
2317        ParseError::InvalidCount("a zero-atom frame requires whitespace-only lines 8 and 9".into())
2318    };
2319    match next_line() {
2320        None => Ok(()),
2321        Some(line) if line_is_whitespace(line) => match next_line() {
2322            None => Ok(()),
2323            Some(line) if line_is_whitespace(line) => Ok(()),
2324            Some(_) => Err(bad()),
2325        },
2326        Some(_) => Err(bad()),
2327    }
2328}
2329
2330fn metadata_json_error(message: impl Into<String>) -> ParseError {
2331    ParseError::InvalidMetadataJson(message.into())
2332}
2333
2334fn validate_metadata_number(key: &str, value: &Value) -> Result<(), ParseError> {
2335    if value.as_f64().is_some() {
2336        Ok(())
2337    } else {
2338        Err(metadata_json_error(format!(
2339            "{key} must be a finite number"
2340        )))
2341    }
2342}
2343
2344fn validate_metadata_integer(key: &str, value: &Value) -> Result<(), ParseError> {
2345    if value.as_u64().is_some() {
2346        Ok(())
2347    } else {
2348        Err(metadata_json_error(format!(
2349            "{key} must be a non-negative integer"
2350        )))
2351    }
2352}
2353
2354/// Check the types of reserved metadata keys that apply in every mode (CON-line2.13).
2355///
2356/// `bonds` stays gated by `validate = true` (CON-bonds.2, CON-bonds.3), and
2357/// `units` / `sections` / `con_spec_version` / `con_spec_minor` / `section_arity` /
2358/// `validate` are validated by the caller or `validate_metadata_schema`.
2359fn validate_reserved_key_types(
2360    json_obj: &serde_json::Map<String, Value>,
2361) -> Result<(), ParseError> {
2362    for (key, value) in json_obj {
2363        match key.as_str() {
2364            meta::ENERGY
2365            | meta::TIME
2366            | meta::TIMESTEP
2367            | meta::CONVERGENCE_FMAX
2368            | meta::CONVERGENCE_ENERGY
2369            | meta::FMAX => {
2370                validate_metadata_number(key, value)?;
2371                if value.as_f64().is_some_and(|n| !n.is_finite()) {
2372                    return Err(metadata_json_error(format!(
2373                        "{key} must be a finite number"
2374                    )));
2375                }
2376            }
2377            meta::FRAME_INDEX | meta::NEB_BEAD | meta::NEB_BAND => {
2378                validate_metadata_integer(key, value)?;
2379            }
2380            meta::GENERATOR if !value.is_string() => {
2381                return Err(metadata_json_error("generator must be a string"));
2382            }
2383            meta::POTENTIAL if !value.is_object() => {
2384                return Err(metadata_json_error("potential must be an object"));
2385            }
2386            meta::POTENTIAL => {
2387                if let Some(potential_type) = value.get("type")
2388                    && !potential_type.is_string()
2389                {
2390                    return Err(metadata_json_error("potential.type must be a string"));
2391                }
2392            }
2393            meta::PBC => validate_pbc_metadata(value)?,
2394            meta::LATTICE_VECTORS => validate_lattice_vectors_metadata(value)?,
2395            meta::CONVERGED if !value.is_boolean() => {
2396                return Err(metadata_json_error("converged must be a boolean"));
2397            }
2398            _ => {}
2399        }
2400    }
2401    Ok(())
2402}
2403
2404/// Validates a parsed metadata JSON object against the spec v2 schema.
2405///
2406/// Type-checks the `validate` and `sections` keys, then runs per-key
2407/// schema checks for the recommended metadata keys. Used by the
2408/// builder/Python `set_metadata_json` paths to fail fast on malformed
2409/// input, and by the parser when the file requested strict validation
2410/// via `"validate": true`.
2411pub fn validate_metadata_schema(
2412    json_obj: &serde_json::Map<String, Value>,
2413) -> Result<(), ParseError> {
2414    let strict_requested = match json_obj.get(meta::VALIDATE) {
2415        Some(Value::Bool(b)) => *b,
2416        Some(_) => return Err(metadata_json_error("validate must be a boolean")),
2417        None => false,
2418    };
2419
2420    match json_obj.get(meta::SECTIONS) {
2421        Some(Value::Array(values)) => {
2422            if values.iter().any(|entry| !entry.is_string()) {
2423                return Err(metadata_json_error("sections must be an array of strings"));
2424            }
2425        }
2426        Some(_) => return Err(metadata_json_error("sections must be an array of strings")),
2427        None if strict_requested => {
2428            return Err(metadata_json_error(
2429                "validate=true requires a sections array, even when empty",
2430            ));
2431        }
2432        None => {}
2433    }
2434
2435    for (key, value) in json_obj {
2436        match key.as_str() {
2437            meta::CON_SPEC_VERSION => match json_major_version(value) {
2438                None => {
2439                    return Err(metadata_json_error(
2440                        "con_spec_version must be a JSON integer, the major version",
2441                    ));
2442                }
2443                Some(ver) => {
2444                    if let Some(reported) = rejected_spec_major(ver) {
2445                        return Err(ParseError::UnsupportedVersion(reported));
2446                    }
2447                }
2448            },
2449            meta::SECTIONS | meta::VALIDATE => {}
2450            meta::CON_SPEC_MINOR | meta::CON_SPEC_PATCH => {
2451                if json_u64(value).is_none() {
2452                    return Err(integer_version_field_limit(key));
2453                }
2454            }
2455            meta::IDS_PERSISTENT if !value.is_boolean() => {
2456                return Err(metadata_json_error("ids_persistent must be a boolean"));
2457            }
2458            meta::IDS_PERSISTENT => {}
2459            meta::SECTION_ARITY => validate_section_arity_value(value)?,
2460            meta::ENERGY
2461            | meta::TIME
2462            | meta::TIMESTEP
2463            | meta::CONVERGENCE_FMAX
2464            | meta::CONVERGENCE_ENERGY
2465            | meta::FMAX => validate_metadata_number(key, value)?,
2466            meta::FRAME_INDEX | meta::NEB_BEAD | meta::NEB_BAND => {
2467                validate_metadata_integer(key, value)?
2468            }
2469            meta::GENERATOR if !value.is_string() => {
2470                return Err(metadata_json_error("generator must be a string"));
2471            }
2472            meta::GENERATOR => {}
2473            meta::UNITS | meta::POTENTIAL if !value.is_object() => {
2474                return Err(metadata_json_error(format!("{key} must be an object")));
2475            }
2476            meta::POTENTIAL => {
2477                if let Some(potential_type) = value.get("type")
2478                    && !potential_type.is_string()
2479                {
2480                    return Err(metadata_json_error("potential.type must be a string"));
2481                }
2482            }
2483            meta::UNITS => {
2484                // Full v3 checks (required keys) run when con_spec_version >= 3.
2485            }
2486            meta::PBC => validate_pbc_metadata(value)?,
2487            meta::BONDS => validate_bonds_metadata(value)?,
2488            meta::LATTICE_VECTORS => validate_lattice_vectors_metadata(value)?,
2489            meta::CONVERGED if !value.is_boolean() => {
2490                return Err(metadata_json_error("converged must be a boolean"));
2491            }
2492            meta::CONVERGED => {}
2493            _ => {}
2494        }
2495    }
2496
2497    Ok(())
2498}
2499
2500fn validate_pbc_metadata(value: &Value) -> Result<(), ParseError> {
2501    let Some(values) = value.as_array() else {
2502        return Err(metadata_json_error("pbc must be a length-3 boolean array"));
2503    };
2504    if values.len() != 3 || values.iter().any(|entry| !entry.is_boolean()) {
2505        return Err(metadata_json_error("pbc must be a length-3 boolean array"));
2506    }
2507    Ok(())
2508}
2509
2510/// Validate optional `bonds` frame topology metadata.
2511///
2512/// Each element is either a length-2 non-negative integer pair `[i, j]` or an
2513/// object `{"i": i, "j": j, "order"?: integer}`. Indices are 0-based into
2514/// `atom_data` order (parser does not yet know atom count at metadata time;
2515/// bounds are enforced when projecting to chemfiles / selection).
2516fn validate_bonds_metadata(value: &Value) -> Result<(), ParseError> {
2517    let Some(items) = value.as_array() else {
2518        return Err(metadata_json_error("bonds must be an array"));
2519    };
2520    for (idx, item) in items.iter().enumerate() {
2521        if let Some(pair) = item.as_array() {
2522            if pair.len() != 2 {
2523                return Err(metadata_json_error(format!(
2524                    "bonds[{idx}] pair must have exactly two indices"
2525                )));
2526            }
2527            for (k, entry) in pair.iter().enumerate() {
2528                let Some(n) = entry.as_u64() else {
2529                    return Err(metadata_json_error(format!(
2530                        "bonds[{idx}][{k}] must be a non-negative integer"
2531                    )));
2532                };
2533                if n > u32::MAX as u64 {
2534                    return Err(metadata_json_error(format!(
2535                        "bonds[{idx}][{k}] index exceeds u32"
2536                    )));
2537                }
2538            }
2539            continue;
2540        }
2541        if let Some(obj) = item.as_object() {
2542            for key in ["i", "j"] {
2543                let Some(entry) = obj.get(key) else {
2544                    return Err(metadata_json_error(format!(
2545                        "bonds[{idx}] object must include \"{key}\""
2546                    )));
2547                };
2548                let Some(n) = entry.as_u64() else {
2549                    return Err(metadata_json_error(format!(
2550                        "bonds[{idx}].{key} must be a non-negative integer"
2551                    )));
2552                };
2553                if n > u32::MAX as u64 {
2554                    return Err(metadata_json_error(format!(
2555                        "bonds[{idx}].{key} index exceeds u32"
2556                    )));
2557                }
2558            }
2559            if let Some(order) = obj.get("order")
2560                && order.as_i64().is_none()
2561            {
2562                return Err(metadata_json_error(format!(
2563                    "bonds[{idx}].order must be an integer when present"
2564                )));
2565            }
2566            continue;
2567        }
2568        return Err(metadata_json_error(format!(
2569            "bonds[{idx}] must be [i, j] or {{\"i\": i, \"j\": j, \"order\"?: ...}}"
2570        )));
2571    }
2572    Ok(())
2573}
2574
2575fn validate_lattice_vectors_metadata(value: &Value) -> Result<(), ParseError> {
2576    let Some(rows) = value.as_array() else {
2577        return Err(metadata_json_error(
2578            "lattice_vectors must be a 3x3 numeric array",
2579        ));
2580    };
2581    if rows.len() != 3 {
2582        return Err(metadata_json_error(
2583            "lattice_vectors must be a 3x3 numeric array",
2584        ));
2585    }
2586    for row in rows {
2587        let Some(entries) = row.as_array() else {
2588            return Err(metadata_json_error(
2589                "lattice_vectors must be a 3x3 numeric array",
2590            ));
2591        };
2592        if entries.len() != 3
2593            || entries
2594                .iter()
2595                .any(|entry| !entry.as_f64().is_some_and(|n| n.is_finite()))
2596        {
2597            return Err(metadata_json_error(
2598                "lattice_vectors must be a 3x3 numeric array",
2599            ));
2600        }
2601    }
2602    Ok(())
2603}
2604
2605std::thread_local! {
2606    static DECLARED_VELOCITIES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2607}
2608
2609pub(crate) fn note_declared_velocities(yes: bool) {
2610    DECLARED_VELOCITIES.with(|flag| flag.set(yes));
2611}
2612
2613/// True when this thread's current frame declared a velocities section.
2614pub(crate) fn declared_velocities() -> bool {
2615    DECLARED_VELOCITIES.with(|flag| flag.get())
2616}
2617
2618/// Spaces and tabs only. CON-file.4 does not ignore a form feed.
2619fn trim_space_tab(line: &str) -> &str {
2620    line.trim_matches(|c: char| c == ' ' || c == '\t')
2621}
2622
2623/// CON-cell.7. The columnar reader and the frame reader share this check.
2624/// `lattice_vectors` wins over lines 3-4 (CON-cell.1). Lengths and angles
2625/// outside (0, 180) are validate-mode checks (CON-validate.4).
2626pub(crate) fn reject_impossible_cell(
2627    angles: [f64; 3],
2628    has_lattice: bool,
2629) -> Result<(), ParseError> {
2630    if !has_lattice
2631        && angles
2632            .iter()
2633            .all(|angle| angle.is_finite() && *angle > 0.0 && *angle < 180.0)
2634    {
2635        crate::types::require_real_cell(angles)?;
2636    }
2637    Ok(())
2638}
2639
2640/// True when line 2 is a JSON object that carries `lattice_vectors`.
2641pub(crate) fn line_declares_lattice(line: &str) -> bool {
2642    let trimmed = trim_space_tab(line);
2643    if !trimmed.starts_with('{') || !trimmed.contains("lattice_vectors") {
2644        return false;
2645    }
2646    match parse_metadata_value(trimmed) {
2647        Ok(value) => value.get(crate::types::meta::LATTICE_VECTORS).is_some(),
2648        Err(_) => false,
2649    }
2650}
2651
2652/// CON-line2.23. A repeated name in any object on line 2 is
2653/// InvalidMetadataJson. A document this scan does not understand is left to
2654/// the JSON parser, including a nesting depth past 127 (CON-line2.18).
2655fn reject_duplicate_names(line: &str) -> Result<(), ParseError> {
2656    let bytes = line.as_bytes();
2657    let mut i = 0usize;
2658    skip_json_ws(bytes, &mut i);
2659    if i >= bytes.len() || bytes[i] != b'{' {
2660        return Ok(());
2661    }
2662    match scan_json_value(bytes, &mut i, 0) {
2663        JsonScan::Duplicate => Err(metadata_json_error("a JSON object repeats a name")),
2664        JsonScan::Done | JsonScan::Defer => Ok(()),
2665    }
2666}
2667
2668enum JsonScan {
2669    Done,
2670    Duplicate,
2671    Defer,
2672}
2673
2674fn scan_json_value(bytes: &[u8], i: &mut usize, depth: usize) -> JsonScan {
2675    if depth > 127 {
2676        return JsonScan::Defer;
2677    }
2678    skip_json_ws(bytes, i);
2679    if *i >= bytes.len() {
2680        return JsonScan::Defer;
2681    }
2682    match bytes[*i] {
2683        b'{' => scan_json_object(bytes, i, depth),
2684        b'[' => scan_json_array(bytes, i, depth),
2685        b'"' => match scan_json_string(bytes, i) {
2686            Some(_) => JsonScan::Done,
2687            None => JsonScan::Defer,
2688        },
2689        b't' => scan_json_lit(bytes, i, b"true"),
2690        b'f' => scan_json_lit(bytes, i, b"false"),
2691        b'n' => scan_json_lit(bytes, i, b"null"),
2692        b'-' | b'0'..=b'9' => {
2693            skip_json_number(bytes, i);
2694            JsonScan::Done
2695        }
2696        _ => JsonScan::Defer,
2697    }
2698}
2699
2700fn scan_json_object(bytes: &[u8], i: &mut usize, depth: usize) -> JsonScan {
2701    *i += 1;
2702    let mut keys: HashSet<String> = HashSet::new();
2703    loop {
2704        skip_json_ws(bytes, i);
2705        if *i >= bytes.len() {
2706            return JsonScan::Defer;
2707        }
2708        if bytes[*i] == b'}' {
2709            *i += 1;
2710            return JsonScan::Done;
2711        }
2712        if !keys.is_empty() {
2713            if bytes[*i] != b',' {
2714                return JsonScan::Defer;
2715            }
2716            *i += 1;
2717            skip_json_ws(bytes, i);
2718        }
2719        if *i >= bytes.len() || bytes[*i] != b'"' {
2720            return JsonScan::Defer;
2721        }
2722        let Some(key) = scan_json_string(bytes, i) else {
2723            return JsonScan::Defer;
2724        };
2725        if !keys.insert(key) {
2726            return JsonScan::Duplicate;
2727        }
2728        skip_json_ws(bytes, i);
2729        if *i >= bytes.len() || bytes[*i] != b':' {
2730            return JsonScan::Defer;
2731        }
2732        *i += 1;
2733        match scan_json_value(bytes, i, depth + 1) {
2734            JsonScan::Done => {}
2735            other => return other,
2736        }
2737    }
2738}
2739
2740fn scan_json_array(bytes: &[u8], i: &mut usize, depth: usize) -> JsonScan {
2741    *i += 1;
2742    let mut any = false;
2743    loop {
2744        skip_json_ws(bytes, i);
2745        if *i >= bytes.len() {
2746            return JsonScan::Defer;
2747        }
2748        if bytes[*i] == b']' {
2749            *i += 1;
2750            return JsonScan::Done;
2751        }
2752        if any {
2753            if bytes[*i] != b',' {
2754                return JsonScan::Defer;
2755            }
2756            *i += 1;
2757        }
2758        any = true;
2759        match scan_json_value(bytes, i, depth + 1) {
2760            JsonScan::Done => {}
2761            other => return other,
2762        }
2763    }
2764}
2765
2766fn scan_json_lit(bytes: &[u8], i: &mut usize, lit: &[u8]) -> JsonScan {
2767    if bytes[*i..].starts_with(lit) {
2768        *i += lit.len();
2769        JsonScan::Done
2770    } else {
2771        JsonScan::Defer
2772    }
2773}
2774
2775fn skip_json_number(bytes: &[u8], i: &mut usize) {
2776    if bytes.get(*i) == Some(&b'-') {
2777        *i += 1;
2778    }
2779    while matches!(bytes.get(*i), Some(b'0'..=b'9')) {
2780        *i += 1;
2781    }
2782    if bytes.get(*i) == Some(&b'.') {
2783        *i += 1;
2784        while matches!(bytes.get(*i), Some(b'0'..=b'9')) {
2785            *i += 1;
2786        }
2787    }
2788    if matches!(bytes.get(*i), Some(b'e' | b'E')) {
2789        *i += 1;
2790        if matches!(bytes.get(*i), Some(b'+' | b'-')) {
2791            *i += 1;
2792        }
2793        while matches!(bytes.get(*i), Some(b'0'..=b'9')) {
2794            *i += 1;
2795        }
2796    }
2797}
2798
2799fn scan_json_string(bytes: &[u8], i: &mut usize) -> Option<String> {
2800    if bytes.get(*i) != Some(&b'"') {
2801        return None;
2802    }
2803    *i += 1;
2804    let mut out = String::new();
2805    while *i < bytes.len() {
2806        let b = bytes[*i];
2807        *i += 1;
2808        match b {
2809            b'"' => return Some(out),
2810            b'\\' => {
2811                let escaped = *bytes.get(*i)?;
2812                *i += 1;
2813                match escaped {
2814                    b'"' | b'\\' | b'/' => out.push(escaped as char),
2815                    b'b' => out.push('\u{0008}'),
2816                    b'f' => out.push('\u{000c}'),
2817                    b'n' => out.push('\n'),
2818                    b'r' => out.push('\r'),
2819                    b't' => out.push('\t'),
2820                    b'u' => out.push(decode_json_u(bytes, i)?),
2821                    _ => return None,
2822                }
2823            }
2824            c if c < 0x20 => return None,
2825            c if c < 0x80 => out.push(c as char),
2826            _ => {
2827                *i -= 1;
2828                let (ch, width) = utf8_char_at(bytes, *i)?;
2829                out.push(ch);
2830                *i += width;
2831            }
2832        }
2833    }
2834    None
2835}
2836
2837/// One UTF-8 scalar at `i`. Validating the remainder of the line would
2838/// rescan every later byte for each character.
2839fn utf8_char_at(bytes: &[u8], i: usize) -> Option<(char, usize)> {
2840    let width = match *bytes.get(i)? {
2841        0xC2..=0xDF => 2,
2842        0xE0..=0xEF => 3,
2843        0xF0..=0xF4 => 4,
2844        _ => return None,
2845    };
2846    let end = i.checked_add(width)?;
2847    let text = std::str::from_utf8(bytes.get(i..end)?).ok()?;
2848    let ch = text.chars().next()?;
2849    if ch.len_utf8() != width {
2850        return None;
2851    }
2852    Some((ch, width))
2853}
2854
2855fn decode_json_u(bytes: &[u8], i: &mut usize) -> Option<char> {
2856    let unit = json_hex4(bytes, i)?;
2857    if (0xD800..=0xDBFF).contains(&unit) {
2858        if bytes.get(*i) != Some(&b'\\') || bytes.get(*i + 1) != Some(&b'u') {
2859            return None;
2860        }
2861        *i += 2;
2862        let low = json_hex4(bytes, i)?;
2863        if !(0xDC00..=0xDFFF).contains(&low) {
2864            return None;
2865        }
2866        let cp = 0x10000 + (((unit - 0xD800) << 10) | (low - 0xDC00));
2867        return char::from_u32(cp);
2868    }
2869    if (0xDC00..=0xDFFF).contains(&unit) {
2870        return None;
2871    }
2872    char::from_u32(unit)
2873}
2874
2875fn json_hex4(bytes: &[u8], i: &mut usize) -> Option<u32> {
2876    if *i + 4 > bytes.len() {
2877        return None;
2878    }
2879    let text = std::str::from_utf8(&bytes[*i..*i + 4]).ok()?;
2880    let value = u32::from_str_radix(text, 16).ok()?;
2881    *i += 4;
2882    Some(value)
2883}
2884
2885/// Parse line 2. An unreserved number that is not a finite binary64 does not
2886/// reject the frame (CON-line2.21). The metadata line keeps that token. The
2887/// value used for the schema walk is a string of the same spelling, because
2888/// it is not a binary64. A reserved key still rejects (CON-line2.19).
2889pub(crate) fn parse_metadata_value(line: &str) -> Result<serde_json::Value, ParseError> {
2890    reject_duplicate_names(line)?;
2891    match serde_json::from_str(line) {
2892        Ok(value) => Ok(value),
2893        Err(err) => match relax_unreserved_overflow(line) {
2894            Some(relaxed) => serde_json::from_str(&relaxed)
2895                .map_err(|err| ParseError::InvalidMetadataJson(err.to_string())),
2896            None => Err(ParseError::InvalidMetadataJson(err.to_string())),
2897        },
2898    }
2899}
2900
2901/// Replace an out-of-range number under a key this document does not reserve
2902/// with a JSON string of that token. `None` when nothing was replaced, or
2903/// when a reserved key holds the bad number.
2904pub(crate) fn relax_unreserved_overflow(line: &str) -> Option<String> {
2905    let bytes = line.as_bytes();
2906    let mut out = String::with_capacity(line.len() + 2);
2907    let mut i = 0usize;
2908    let mut pending_key: Option<String> = None;
2909    let mut stack: Vec<Option<String>> = Vec::new();
2910    let mut replaced = false;
2911    while i < bytes.len() {
2912        let b = bytes[i];
2913        if b == b'"' {
2914            let start = i;
2915            i += 1;
2916            let mut has_escape = false;
2917            while i < bytes.len() {
2918                let c = bytes[i];
2919                if c == b'\\' && i + 1 < bytes.len() {
2920                    has_escape = true;
2921                    i += 2;
2922                    continue;
2923                }
2924                if c == b'"' {
2925                    i += 1;
2926                    break;
2927                }
2928                i += 1;
2929            }
2930            let raw = &line[start..i];
2931            out.push_str(raw);
2932            let mut j = i;
2933            while j < bytes.len() && is_field_ws(bytes[j]) {
2934                j += 1;
2935            }
2936            if bytes.get(j) == Some(&b':') {
2937                let decoded = if has_escape {
2938                    serde_json::from_str::<String>(raw).ok()?
2939                } else {
2940                    raw.get(1..raw.len().saturating_sub(1))?.to_string()
2941                };
2942                pending_key = Some(decoded);
2943            }
2944            continue;
2945        }
2946        if b == b'{' || b == b'[' {
2947            stack.push(pending_key.take());
2948            out.push(b as char);
2949            i += 1;
2950            continue;
2951        }
2952        if b == b'}' || b == b']' {
2953            stack.pop();
2954            pending_key = None;
2955            out.push(b as char);
2956            i += 1;
2957            continue;
2958        }
2959        if b == b',' {
2960            pending_key = None;
2961            out.push(',');
2962            i += 1;
2963            continue;
2964        }
2965        if b == b'-' || b.is_ascii_digit() {
2966            let start = i;
2967            if bytes[i] == b'-' {
2968                i += 1;
2969            }
2970            while i < bytes.len()
2971                && (bytes[i].is_ascii_digit()
2972                    || matches!(bytes[i], b'.' | b'e' | b'E' | b'+' | b'-'))
2973            {
2974                i += 1;
2975            }
2976            let token = &line[start..i];
2977            // A token outside the JSON number grammar is malformed JSON
2978            // (CON-line2.2), not a number a reader cannot store.
2979            if !is_json_number(token) {
2980                return None;
2981            }
2982            let finite = token.parse::<f64>().ok().filter(|value| value.is_finite());
2983            if finite.is_none() {
2984                let top_key = if stack.len() == 1 {
2985                    pending_key.as_deref()
2986                } else {
2987                    stack.get(1).and_then(Option::as_deref)
2988                };
2989                if top_key.is_some_and(reserved_number_key) {
2990                    return None;
2991                }
2992                out.push('"');
2993                out.push_str(token);
2994                out.push('"');
2995                replaced = true;
2996                pending_key = None;
2997                continue;
2998            }
2999            out.push_str(token);
3000            pending_key = None;
3001            continue;
3002        }
3003        if !b.is_ascii() {
3004            return None;
3005        }
3006        out.push(b as char);
3007        i += 1;
3008    }
3009    replaced.then_some(out)
3010}
3011
3012/// `-? (0 | [1-9][0-9]*) (. [0-9]+)? ([eE] [+-]? [0-9]+)?`, the number of RFC 8259.
3013fn is_json_number(token: &str) -> bool {
3014    let bytes = token.as_bytes();
3015    let mut i = usize::from(bytes.first() == Some(&b'-'));
3016    let digits = |i: &mut usize| {
3017        let start = *i;
3018        while bytes.get(*i).is_some_and(u8::is_ascii_digit) {
3019            *i += 1;
3020        }
3021        *i - start
3022    };
3023    match bytes.get(i) {
3024        Some(b'0') => i += 1,
3025        Some(b'1'..=b'9') => {
3026            digits(&mut i);
3027        }
3028        _ => return false,
3029    }
3030    if bytes.get(i) == Some(&b'.') {
3031        i += 1;
3032        if digits(&mut i) == 0 {
3033            return false;
3034        }
3035    }
3036    if matches!(bytes.get(i), Some(b'e' | b'E')) {
3037        i += 1;
3038        if matches!(bytes.get(i), Some(b'+' | b'-')) {
3039            i += 1;
3040        }
3041        if digits(&mut i) == 0 {
3042            return false;
3043        }
3044    }
3045    i == bytes.len()
3046}
3047
3048fn reserved_number_key(key: &str) -> bool {
3049    matches!(
3050        key,
3051        meta::CON_SPEC_VERSION
3052            | meta::CON_SPEC_MINOR
3053            | meta::CON_SPEC_PATCH
3054            | meta::ENERGY
3055            | meta::TIME
3056            | meta::TIMESTEP
3057            | meta::CONVERGENCE_FMAX
3058            | meta::CONVERGENCE_ENERGY
3059            | meta::FMAX
3060            | meta::FRAME_INDEX
3061            | meta::NEB_BEAD
3062            | meta::NEB_BAND
3063            | meta::LATTICE_VECTORS
3064            | meta::PBC
3065            | meta::SECTION_ARITY
3066    )
3067}
3068
3069/// Parses a line of whitespace-separated values into a vector of a specific type.
3070///
3071/// This generic helper function takes a string slice, splits it by whitespace,
3072/// and attempts to parse each substring into the target type `T`. The type `T`
3073/// must implement `std::str::FromStr`.
3074///
3075/// # Arguments
3076///
3077/// * `line` - A string slice representing a single line of data.
3078/// * `n` - The exact number of values expected on the line.
3079///
3080/// # Errors
3081///
3082/// * `ParseError::InvalidVectorLength` if the number of parsed values is not equal to `n`.
3083/// * Propagates any error from the `parse()` method of the target type `T`.
3084///
3085/// # Example
3086///
3087/// ```
3088/// use readcon_core::parser::parse_line_of_n;
3089/// let line = "10.5 20.0 30.5";
3090/// let values: Vec<f64> = parse_line_of_n(line, 3).unwrap();
3091/// assert_eq!(values, vec![10.5, 20.0, 30.5]);
3092///
3093/// let result = parse_line_of_n::<i32>(line, 2);
3094/// assert!(result.is_err());
3095/// ```
3096pub fn parse_line_of_n<T: std::str::FromStr>(line: &str, n: usize) -> Result<Vec<T>, ParseError>
3097where
3098    ParseError: From<<T as std::str::FromStr>::Err>,
3099{
3100    let values: Vec<T> = line
3101        .split_whitespace()
3102        .map(|s| s.parse::<T>())
3103        .collect::<Result<_, _>>()?;
3104
3105    if values.len() == n {
3106        Ok(values)
3107    } else {
3108        Err(ParseError::InvalidVectorLength {
3109            expected: n,
3110            found: values.len(),
3111        })
3112    }
3113}
3114
3115/// Parses the 9-line header of a `.con` file frame from an iterator.
3116///
3117/// This function consumes the next 9 lines from the given line iterator to
3118/// construct a `FrameHeader`. The iterator is advanced by 9 lines on success.
3119///
3120/// # Arguments
3121///
3122/// * `lines` - A mutable reference to an iterator that yields string slices.
3123///
3124/// # Errors
3125///
3126/// * `ParseError::IncompleteHeader` if the iterator has fewer than 9 lines remaining.
3127/// * Propagates any errors from `parse_line_of_n` if the numeric data within
3128///   the header is malformed.
3129///
3130/// # Panics
3131///
3132/// This function will panic if the intermediate vectors for box dimensions or angles,
3133/// after being successfully parsed, cannot be converted into fixed-size arrays.
3134/// This should not happen if `parse_line_of_n` is used correctly with `n=3`.
3135pub fn parse_frame_header<'a>(
3136    lines: &mut impl Iterator<Item = &'a str>,
3137) -> Result<FrameHeader, ParseError> {
3138    parse_frame_header_inner(lines)
3139}
3140
3141pub(crate) fn parse_frame_header_inner<'a>(
3142    lines: &mut impl Iterator<Item = &'a str>,
3143) -> Result<FrameHeader, ParseError> {
3144    let prebox1 = lines
3145        .next()
3146        .ok_or(ParseError::IncompleteHeader)?
3147        .to_string();
3148    // CON-file.2: no frame may begin with U+FEFF.
3149    if prebox1.starts_with('\u{feff}') {
3150        return Err(ParseError::ValidationError(
3151            "frame begins with a byte-order mark".into(),
3152        ));
3153    }
3154    note_declared_velocities(false);
3155    let prebox2_raw = lines.next().ok_or(ParseError::IncompleteHeader)?;
3156
3157    // Line 2: if it starts with '{', parse as JSON metadata (spec v2+).
3158    // Otherwise treat as a legacy (pre-v2) file with spec_version = 1.
3159    // One JSON object and nothing else (CON-line2.1). Only spaces and tabs
3160    // are ignored around the object (CON-file.4).
3161    let trimmed = trim_space_tab(prebox2_raw);
3162    let (spec_version, sections, validate, sections_declared, has_lattice) =
3163        if trimmed == "{\"con_spec_version\":2}" {
3164            // The line written by every stock trajectory. Same object the
3165            // JSON parser would build: major 2, no extra keys.
3166            (2, Vec::new(), false, false, false)
3167        } else if let Some(ver) = simple_metadata_version(trimmed) {
3168            // A header whose only keys are the spec version, an optional
3169            // minor, and a units object. Every byte is still read. Any
3170            // other key falls through to the general parser.
3171            (ver, Vec::new(), false, false, false)
3172        } else if trimmed.starts_with('{') {
3173            let minor_spans = top_level_minor_spans(trimmed);
3174            if minor_spans.len() > 1 {
3175                return Err(metadata_json_error(DUPLICATE_CON_SPEC_MINOR));
3176            }
3177            // A repeated minor is CON-line2.14. A reserved version field
3178            // whose integer literal does not fit in u64 is CON-line2.22.
3179            // Malformed JSON still surfaces first.
3180            let mut json_val = parse_metadata_value(trimmed)?;
3181            if let Some(field) = oversized_integer_version_field(trimmed) {
3182                return Err(integer_version_field_limit(&field));
3183            }
3184            let json_obj = json_val.as_object_mut().ok_or_else(|| {
3185                ParseError::InvalidMetadataJson("expected a JSON object".to_string())
3186            })?;
3187            let ver_value = json_obj
3188                .get(meta::CON_SPEC_VERSION)
3189                .ok_or(ParseError::MissingSpecVersion)?;
3190            let ver = json_major_version(ver_value).ok_or_else(|| {
3191                ParseError::InvalidMetadataJson(
3192                    "con_spec_version must be a JSON integer, the major version".into(),
3193                )
3194            })?;
3195            if let Some(reported) = rejected_spec_major(ver) {
3196                return Err(ParseError::UnsupportedVersion(reported));
3197            }
3198            let ver = ver as u32;
3199            // JSON majors 0 and 1 are UnsupportedVersion (CON-line2.5).
3200            // An unknown major is UnsupportedVersion (CON-line2.6).
3201            // Unknown minors of a known major are accepted (CON-line2.7, CON-status.1).
3202            if ver == 0 || ver == 1 || ver > crate::CON_SPEC_VERSION {
3203                return Err(ParseError::UnsupportedVersion(ver));
3204            }
3205            if ver >= 3 {
3206                match json_obj.get(meta::UNITS) {
3207                    Some(u) => {
3208                        crate::units::validate_units_metadata_for_version(ver, u)
3209                            .map_err(|e| ParseError::InvalidUnits(format!("v3 units: {e}")))?;
3210                    }
3211                    None => {
3212                        return Err(ParseError::InvalidUnits(
3213                        "con_spec_version >= 3 requires metadata \"units\" with length and energy"
3214                            .into(),
3215                    ));
3216                    }
3217                }
3218            }
3219            if ver >= 2
3220                && let Some(units) = json_obj.get(meta::UNITS)
3221            {
3222                crate::units::enforce_velocity_precedence(ver, units)
3223                    .map_err(|e| ParseError::InvalidUnits(format!("units: {e}")))?;
3224            }
3225
3226            // Single pass over the JSON object: collect sections, capture the
3227            // validate flag, copy the rest into metadata. Folds the previous
3228            // pre-extract get(validate) + re-iterate pattern into one walk.
3229            let mut sections: Vec<String> = Vec::new();
3230            let mut sections_declared = false;
3231            let mut validate = false;
3232            let mut has_lattice = false;
3233            for (k, v) in json_obj.iter() {
3234                match k.as_str() {
3235                    meta::CON_SPEC_VERSION => {}
3236                    meta::CON_SPEC_MINOR | meta::CON_SPEC_PATCH => {
3237                        if json_u64(v).is_none() {
3238                            return Err(integer_version_field_limit(k));
3239                        }
3240                    }
3241                    meta::IDS_PERSISTENT => {
3242                        if !v.is_boolean() {
3243                            return Err(metadata_json_error("ids_persistent must be a boolean"));
3244                        }
3245                    }
3246                    meta::LATTICE_VECTORS => {
3247                        validate_lattice_vectors_metadata(v)?;
3248                        has_lattice = true;
3249                    }
3250                    meta::PBC => validate_pbc_metadata(v)?,
3251                    meta::ENERGY => validate_metadata_number(k, v)?,
3252                    meta::SECTION_ARITY => {
3253                        validate_section_arity_value(v)?;
3254                    }
3255                    meta::SECTIONS => {
3256                        sections_declared = true;
3257                        let arr = v.as_array().ok_or_else(|| {
3258                            metadata_json_error("sections must be an array of strings")
3259                        })?;
3260                        sections.reserve(arr.len());
3261                        let mut seen = HashSet::with_capacity(arr.len());
3262                        for entry in arr {
3263                            let s = entry.as_str().ok_or_else(|| {
3264                                metadata_json_error("sections must be an array of strings")
3265                            })?;
3266                            if !seen.insert(s) {
3267                                return Err(metadata_json_error(format!(
3268                                    "duplicate section name '{s}'"
3269                                )));
3270                            }
3271                            sections.push(s.to_string());
3272                        }
3273                    }
3274                    meta::VALIDATE => {
3275                        validate = match v {
3276                            Value::Bool(b) => *b,
3277                            _ => return Err(metadata_json_error("validate must be a boolean")),
3278                        };
3279                    }
3280                    _ => {}
3281                }
3282            }
3283
3284            // Strict-mode schema check fires only when the file requested
3285            // it. Hot-path parses (validate=false) skip the per-key match.
3286            if validate {
3287                validate_metadata_schema(json_obj)?;
3288            }
3289
3290            // Reserved-key types apply in every mode (CON-line2.13).
3291            validate_reserved_key_types(json_obj)?;
3292
3293            if ver < 3
3294                && let Some(units) = json_obj.get(meta::UNITS)
3295            {
3296                crate::units::validate_present_unit_dimensions(units)?;
3297            }
3298            // Unknown names are line 2 (CON-section.7, CON-section.9, CON-error.4).
3299            let minor =
3300                crate::types::FrameMeta::from_shared(std::sync::Arc::from(trimmed)).spec_minor();
3301            reject_unknown_sections(json_obj, &sections, minor)?;
3302            let has_declared_velocities =
3303                sections_declared && sections.iter().any(|name| name == SECTION_VELOCITIES);
3304            note_declared_velocities(has_declared_velocities);
3305            debug_assert_eq!(declared_velocities(), has_declared_velocities);
3306
3307            (ver, sections, validate, sections_declared, has_lattice)
3308        } else {
3309            // Legacy file: no JSON metadata line.
3310            (1_u32, Vec::new(), false, false, false)
3311        };
3312    let prebox2 = prebox2_raw.to_string();
3313
3314    let boxl_vec = parse_cell_line(lines.next().ok_or(ParseError::IncompleteHeader)?, "boxl")?;
3315    let angles_vec = parse_cell_line(lines.next().ok_or(ParseError::IncompleteHeader)?, "angles")?;
3316    let angles: [f64; 3] = angles_vec.as_slice().try_into().unwrap();
3317    reject_impossible_cell(angles, has_lattice)?;
3318    let postbox1 = lines
3319        .next()
3320        .ok_or(ParseError::IncompleteHeader)?
3321        .to_string();
3322    let postbox2 = lines
3323        .next()
3324        .ok_or(ParseError::IncompleteHeader)?
3325        .to_string();
3326    let natm_types_line = lines.next().ok_or(ParseError::IncompleteHeader)?;
3327    let natm_types = parse_count_line(natm_types_line, 1)?[0];
3328    // A type count of 0 is a zero-atom frame (CON-count.1, CON-count.4).
3329    // A per-type count of 0 is InvalidCount only when the type count is >= 1.
3330    let (natms_per_type, masses_per_type) = if natm_types == 0 {
3331        read_zero_atom_tail(|| lines.next())?;
3332        (Vec::new(), Vec::new())
3333    } else {
3334        let natms_per_type = parse_count_line(
3335            lines.next().ok_or(ParseError::IncompleteHeader)?,
3336            natm_types,
3337        )?;
3338        if natms_per_type.contains(&0) {
3339            return Err(ParseError::InvalidCount(
3340                "each per-type count must be >= 1".into(),
3341            ));
3342        }
3343        let masses_per_type = parse_line_of_n_f64(
3344            lines.next().ok_or(ParseError::IncompleteHeader)?,
3345            natm_types,
3346        )?;
3347        (natms_per_type, masses_per_type)
3348    };
3349    if validate {
3350        validate_header_geometry(&boxl_vec, &angles_vec)?;
3351        validate_masses(&masses_per_type)?;
3352    }
3353    let shared_line = intern_repeated_line(&prebox2);
3354    let metadata = crate::types::FrameMeta::from_shared(std::sync::Arc::clone(&shared_line));
3355    Ok(FrameHeader {
3356        prebox_header: PreboxHeader {
3357            user: prebox1,
3358            metadata_line: shared_line,
3359        },
3360        boxl: boxl_vec.try_into().unwrap(),
3361        angles: angles_vec.try_into().unwrap(),
3362        postbox_header: [postbox1, postbox2],
3363        natm_types,
3364        natms_per_type,
3365        masses_per_type,
3366        spec_version,
3367        metadata,
3368        sections,
3369        strict_validation: validate,
3370        sections_declared,
3371        ids_from_file: true,
3372    })
3373}
3374
3375// A trajectory stamps the same metadata line on every frame. A fresh
3376// `Arc` per frame showed up in the all-frames read.
3377thread_local! {
3378    static SEQUENTIAL_PLAIN: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
3379}
3380
3381pub(crate) fn reset_sequential_plain() {
3382    SEQUENTIAL_PLAIN.with(|flag| flag.set(true));
3383}
3384
3385pub(crate) fn note_not_sequential_plain() {
3386    SEQUENTIAL_PLAIN.with(|flag| flag.set(false));
3387}
3388
3389pub(crate) fn take_sequential_plain() -> bool {
3390    SEQUENTIAL_PLAIN.with(|flag| flag.get())
3391}
3392
3393fn intern_repeated_line(line: &str) -> std::sync::Arc<str> {
3394    thread_local! {
3395        static RECENT: std::cell::RefCell<Vec<std::sync::Arc<str>>> =
3396            const { std::cell::RefCell::new(Vec::new()) };
3397    }
3398    RECENT.with(|slot| {
3399        let mut slot = slot.borrow_mut();
3400        if let Some(found) = slot.iter().find(|item| item.as_ref() == line) {
3401            return std::sync::Arc::clone(found);
3402        }
3403        let fresh: std::sync::Arc<str> = std::sync::Arc::from(line);
3404        if slot.len() == 8 {
3405            slot.remove(0);
3406        }
3407        slot.push(std::sync::Arc::clone(&fresh));
3408        fresh
3409    })
3410}
3411
3412/// Spec line limited to `con_spec_version`, optional `con_spec_minor`, and `units`.
3413///
3414/// Returns the major version when the object is exactly that shape and, for
3415/// version 3 or newer, `length` and `energy` are valid units. Anything else
3416/// is `None` so the general JSON parser can accept or reject it.
3417fn simple_metadata_version(line: &str) -> Option<u32> {
3418    let bytes = line.as_bytes();
3419    let mut i = 0usize;
3420    let skip = |i: &mut usize| {
3421        while *i < bytes.len() && bytes[*i].is_ascii_whitespace() {
3422            *i += 1;
3423        }
3424    };
3425    let eat = |i: &mut usize, byte: u8| -> bool {
3426        skip(i);
3427        if *i < bytes.len() && bytes[*i] == byte {
3428            *i += 1;
3429            true
3430        } else {
3431            false
3432        }
3433    };
3434    let quoted = |i: &mut usize| -> Option<&str> {
3435        skip(i);
3436        if *i >= bytes.len() || bytes[*i] != b'"' {
3437            return None;
3438        }
3439        *i += 1;
3440        let start = *i;
3441        while *i < bytes.len() && bytes[*i] != b'"' {
3442            if bytes[*i] == b'\\' {
3443                return None;
3444            }
3445            *i += 1;
3446        }
3447        if *i >= bytes.len() {
3448            return None;
3449        }
3450        let text = std::str::from_utf8(&bytes[start..*i]).ok()?;
3451        *i += 1;
3452        Some(text)
3453    };
3454    let nonneg_int_token = |i: &mut usize| -> Option<&str> {
3455        skip(i);
3456        let start = *i;
3457        if *i < bytes.len() && bytes[*i] == b'-' {
3458            return None;
3459        }
3460        while *i < bytes.len() && bytes[*i].is_ascii_digit() {
3461            *i += 1;
3462        }
3463        if start == *i || (bytes[start] == b'0' && *i > start + 1) {
3464            return None;
3465        }
3466        std::str::from_utf8(&bytes[start..*i]).ok()
3467    };
3468    let integer = |i: &mut usize| -> Option<u64> { nonneg_int_token(i)?.parse().ok() };
3469    if !eat(&mut i, b'{') {
3470        return None;
3471    }
3472    let mut version = None;
3473    let mut saw_minor = false;
3474    let mut saw_units = false;
3475    let mut length = None;
3476    let mut energy = None;
3477    let mut saw_mass = false;
3478    let mut saw_time = false;
3479    let mut saw_force = false;
3480    loop {
3481        skip(&mut i);
3482        if i < bytes.len() && bytes[i] == b'}' {
3483            i += 1;
3484            break;
3485        }
3486        if (version.is_some() || saw_minor || saw_units) && !eat(&mut i, b',') {
3487            return None;
3488        }
3489        let key = quoted(&mut i)?;
3490        if !eat(&mut i, b':') {
3491            return None;
3492        }
3493        match key {
3494            "con_spec_version" if version.is_none() => version = Some(integer(&mut i)?),
3495            "con_spec_minor" if !saw_minor => {
3496                let tok = nonneg_int_token(&mut i)?;
3497                // CON-line2.22. A minor that does not fit in u64 is the
3498                // general parser's InvalidMetadataJson, shared with patch.
3499                if tok.parse::<u64>().is_err() {
3500                    return None;
3501                }
3502                saw_minor = true;
3503            }
3504            "units" if !saw_units => {
3505                saw_units = true;
3506                if !eat(&mut i, b'{') {
3507                    return None;
3508                }
3509                loop {
3510                    skip(&mut i);
3511                    if i < bytes.len() && bytes[i] == b'}' {
3512                        i += 1;
3513                        break;
3514                    }
3515                    if (length.is_some() || energy.is_some() || saw_mass || saw_time || saw_force)
3516                        && !eat(&mut i, b',')
3517                    {
3518                        return None;
3519                    }
3520                    let ukey = quoted(&mut i)?;
3521                    if !eat(&mut i, b':') {
3522                        return None;
3523                    }
3524                    let value = quoted(&mut i)?;
3525                    match ukey {
3526                        "length" if length.is_none() => length = Some(value),
3527                        "energy" if energy.is_none() => energy = Some(value),
3528                        "mass" if !saw_mass => {
3529                            if crate::units::validate_unit_for_quantity(ukey, value).is_err() {
3530                                return None;
3531                            }
3532                            saw_mass = true;
3533                        }
3534                        "time" if !saw_time => {
3535                            if crate::units::validate_unit_for_quantity(ukey, value).is_err() {
3536                                return None;
3537                            }
3538                            saw_time = true;
3539                        }
3540                        "force" if !saw_force => {
3541                            if crate::units::validate_unit_for_quantity(ukey, value).is_err() {
3542                                return None;
3543                            }
3544                            saw_force = true;
3545                        }
3546                        _ => return None,
3547                    }
3548                }
3549            }
3550            _ => return None,
3551        }
3552    }
3553    skip(&mut i);
3554    if i != bytes.len() {
3555        return None;
3556    }
3557    let ver = u32::try_from(version?).ok()?;
3558    if ver == 0 || ver == 1 || ver > crate::CON_SPEC_VERSION {
3559        return None;
3560    }
3561    if ver >= 3 {
3562        let length = length?;
3563        let energy = energy?;
3564        if length.trim().is_empty() || energy.trim().is_empty() {
3565            return None;
3566        }
3567        crate::units::validate_unit_for_quantity("length", length).ok()?;
3568        crate::units::validate_unit_for_quantity("energy", energy).ok()?;
3569    }
3570    Some(ver)
3571}
3572
3573/// Parses a complete frame from a `.con` file, including its header and atomic data.
3574///
3575/// This function first parses the complete frame header and then uses the information within it
3576/// (specifically the number of atom types and atoms per type) to parse the subsequent
3577/// atom coordinate blocks.
3578///
3579/// Each atom takes one line, so the atom vectors reserve no more rows than the
3580/// upper bound of `lines.size_hint()`. With no upper bound, as for `str::lines`,
3581/// they grow as the rows arrive.
3582///
3583/// # Arguments
3584///
3585/// * `lines` - A mutable reference to an iterator that yields string slices for the frame.
3586///
3587/// # Errors
3588///
3589/// * `ParseError::IncompleteFrame` if the iterator ends before all expected
3590///   atomic data has been read.
3591/// * Propagates any errors from the underlying calls to `parse_frame_header` and
3592///   `parse_line_of_n`.
3593///
3594/// # Example
3595///
3596/// ```
3597/// use readcon_core::parser::parse_single_frame;
3598///
3599/// let frame_text = r#"
3600///Generated by test
3601///{"con_spec_version":2}
3602///10.0 10.0 10.0
3603///90.0 90.0 90.0
3604///POSTBOX LINE 1
3605///POSTBOX LINE 2
3606///2
3607///1 1
3608///12.011 1.008
3609///C
3610///Coordinates of Component 1
3611///1.0 1.0 1.0 0 1
3612///H
3613///Coordinates of Component 2
3614///2.0 2.0 2.0 0 2
3615/// "#;
3616///
3617/// let mut lines = frame_text.trim().lines();
3618/// let con_frame = parse_single_frame(&mut lines).unwrap();
3619///
3620/// assert_eq!(con_frame.header.natm_types, 2);
3621/// assert_eq!(con_frame.atom_data.len(), 2);
3622/// assert_eq!(&*con_frame.atom_data[0].symbol, "C");
3623/// assert_eq!(con_frame.atom_data[1].atom_id, 2);
3624/// ```
3625pub fn parse_single_frame<'a>(
3626    lines: &mut impl Iterator<Item = &'a str>,
3627) -> Result<ConFrame, ParseError> {
3628    // The caller owns the iterator and may not be able to clone it. Section
3629    // detection, which needs a lookahead clone, runs later on a `LineStream`
3630    // that can probe (`MemchrLines`, or a `Peekable` whose source is `Clone`).
3631    let max_rows = lines.size_hint().1;
3632    parse_single_frame_ls(&mut IterStream(lines), max_rows)
3633}
3634
3635/// Iterator adapter so [`parse_single_frame`] can satisfy [`LineStream`]
3636/// without requiring [`Clone`].
3637struct IterStream<I>(I);
3638
3639impl<'a, I> Iterator for IterStream<I>
3640where
3641    I: Iterator<Item = &'a str>,
3642{
3643    type Item = &'a str;
3644    fn next(&mut self) -> Option<&'a str> {
3645        self.0.next()
3646    }
3647}
3648
3649impl<'a, I> LineStream<'a> for IterStream<I>
3650where
3651    I: Iterator<Item = &'a str>,
3652{
3653    fn next_line(&mut self) -> Option<&'a str> {
3654        Iterator::next(self)
3655    }
3656    fn peek_line(&mut self) -> Option<&'a str> {
3657        None
3658    }
3659}
3660
3661struct CoordShell {
3662    atoms: Vec<crate::types::AtomDatum>,
3663    coords: Vec<f64>,
3664    ids: Vec<u64>,
3665}
3666
3667thread_local! {
3668    static COORD_SHELLS: std::cell::RefCell<Vec<CoordShell>> =
3669        const { std::cell::RefCell::new(Vec::new()) };
3670}
3671
3672/// Allocate `n_frames` coordinate shells on this thread before the parse.
3673///
3674/// One tight reservation, then each frame takes a shell. Doing the
3675/// reservations inside the parse mixed the allocator with the float
3676/// parse and made eight threads slower than the bytes they write.
3677#[cfg(feature = "parallel")]
3678pub(crate) fn prestash_coord_shells(n_frames: usize, n_atoms: usize) {
3679    // Small frames (the 32-atom strong-scaling files) are cheaper to
3680    // allocate inside the parse. A burst of shells ahead of those frames
3681    // made eight threads slower. Wide atoms, as in the weak-scaling
3682    // fixture, are the case the burst is for.
3683    if n_frames == 0 || n_atoms < 128 {
3684        return;
3685    }
3686    COORD_SHELLS.with(|pool| {
3687        let mut pool = pool.borrow_mut();
3688        pool.reserve(n_frames);
3689        for _ in 0..n_frames {
3690            pool.push(CoordShell {
3691                atoms: Vec::with_capacity(n_atoms),
3692                coords: Vec::with_capacity(n_atoms.saturating_mul(3)),
3693                ids: Vec::with_capacity(n_atoms),
3694            });
3695        }
3696    });
3697}
3698
3699#[cfg(feature = "parallel")]
3700pub(crate) fn clear_coord_shells() {
3701    COORD_SHELLS.with(|pool| pool.borrow_mut().clear());
3702}
3703
3704fn take_coord_shell(n_atoms: usize) -> Option<CoordShell> {
3705    COORD_SHELLS.with(|pool| {
3706        let shell = pool.borrow_mut().pop()?;
3707        if shell.atoms.capacity() >= n_atoms
3708            && shell.coords.capacity() >= n_atoms.saturating_mul(3)
3709            && shell.ids.capacity() >= n_atoms
3710        {
3711            Some(shell)
3712        } else {
3713            None
3714        }
3715    })
3716}
3717
3718/// Columns every atom line has: x, y, z and the flag (spec "Coordinates",
3719/// CON-num.9). The id column is optional (CON-id.9).
3720const COORD_ROW_MIN_COLUMNS: usize = 4;
3721
3722/// Fewest bytes an atom line takes, as in `0 0 0 0`: one byte for each of
3723/// the [`COORD_ROW_MIN_COLUMNS`] columns and one separator between each
3724/// pair. Newlines and the symbol and label lines only add bytes, so `n`
3725/// unread bytes hold at most `n / MIN_COORD_ROW_BYTES` atom lines.
3726pub(crate) const MIN_COORD_ROW_BYTES: usize = 2 * COORD_ROW_MIN_COLUMNS - 1;
3727
3728/// Frame parse over a [`LineStream`].
3729///
3730/// Coordinate rows go through [`LineStream::next_coord_row`] so the memchr
3731/// cursor can fuse the newline scan with numeric parse. Positions, ids, and
3732/// flags land in flat buffers; [`AtomDatum`] values are built from those
3733/// buffers afterwards (one `Vec` allocation, no per-atom heap traffic).
3734///
3735/// `max_rows` bounds the atom lines the rest of the input can hold, and is
3736/// `None` when that is unknown. The buffers reserve no more atoms than it
3737/// allows, so a header that declares more atoms than the input holds
3738/// cannot force a large allocation. The declared counts still decide how
3739/// many rows are read, and so which error is reported.
3740pub(crate) fn parse_single_frame_ls<'a, L>(
3741    lines: &mut L,
3742    max_rows: Option<usize>,
3743) -> Result<ConFrame, ParseError>
3744where
3745    L: LineStream<'a> + Iterator<Item = &'a str>,
3746{
3747    reset_sequential_plain();
3748    let header = parse_frame_header_inner(lines)?;
3749    // A count the unread input can hold stays in this function, on the same
3750    // reservation and `Arc` bump as before the bound existed. A count that
3751    // cannot fit is a separate cold function so it does not shape this loop.
3752    let Some(total_atoms) = fitting_atom_count(&header.natms_per_type, max_rows) else {
3753        return parse_oversized_frame(lines, header, max_rows);
3754    };
3755    let validate = header.strict_validation;
3756    use crate::storage_dtype::{ElementKind, FloatArray2};
3757    let dt = header.metadata.dtypes();
3758    let f64_positions = dt.positions == ElementKind::Float64;
3759    if !f64_positions {
3760        note_not_sequential_plain();
3761    }
3762    let shell = take_coord_shell(total_atoms);
3763    let (mut pos_flat, mut ids, mut atom_data) = match shell {
3764        Some(shell) => (shell.coords, shell.ids, shell.atoms),
3765        None => (
3766            Vec::with_capacity(total_atoms.saturating_mul(3)),
3767            Vec::with_capacity(total_atoms),
3768            Vec::with_capacity(total_atoms),
3769        ),
3770    };
3771    let mut positions_other = if f64_positions {
3772        None
3773    } else {
3774        Some(FloatArray2::zeros(dt.positions, total_atoms, 3))
3775    };
3776    let mut global_atom_idx: u64 = 0;
3777    for (type_idx, num_atoms) in header.natms_per_type.iter().enumerate() {
3778        let symbol_line = lines.next().ok_or(ParseError::IncompleteFrame)?;
3779        let symbol: Arc<str> = Arc::from(symbol_line.trim());
3780        let coord_label = lines.next().ok_or(ParseError::IncompleteFrame)?;
3781        // CON-coord.1. The label is checked in every mode. The symbol check
3782        // stays inside validate (CON-validate.4).
3783        let expected_label = format!("Coordinates of Component {}", type_idx + 1);
3784        if !labels_equal(coord_label, &expected_label) {
3785            return Err(ParseError::ValidationError(format!(
3786                "expected coordinate label {expected_label:?}, found {coord_label:?}"
3787            )));
3788        }
3789        if validate {
3790            validate_coordinate_component(type_idx, symbol.as_ref(), coord_label)?;
3791        }
3792        global_atom_idx = ingest_coord_rows(
3793            lines,
3794            *num_atoms,
3795            header.spec_version,
3796            global_atom_idx,
3797            &symbol,
3798            CoordSink {
3799                pos_flat: &mut pos_flat,
3800                ids: &mut ids,
3801                positions_other: &mut positions_other,
3802                atom_data: &mut atom_data,
3803            },
3804        )?;
3805    }
3806    let positions = if f64_positions {
3807        FloatArray2::from_f64_row_major(total_atoms, 3, pos_flat)
3808    } else {
3809        positions_other.expect("non-f64 positions allocated")
3810    };
3811    Ok(crate::types::con_frame_coords_only_with_ids(
3812        header, atom_data, positions, ids,
3813    ))
3814}
3815
3816/// Atom total when it can use [`Vec::with_capacity`] safely.
3817///
3818/// `None` means the counts wrap, exceed `isize::MAX / 4`, or exceed the
3819/// unread atom lines. A `u32::MAX` count with no size hint is `None`: that
3820/// reservation is tens of GiB.
3821#[inline]
3822fn fitting_atom_count(counts: &[usize], max_rows: Option<usize>) -> Option<usize> {
3823    let mut total = 0usize;
3824    for &count in counts {
3825        total = total.checked_add(count)?;
3826    }
3827    if total > (isize::MAX as usize) / 4 {
3828        return None;
3829    }
3830    match max_rows {
3831        Some(rows) if total > rows => None,
3832        None if total > (1 << 20) => None,
3833        _ => Some(total),
3834    }
3835}
3836
3837/// A header declared more atoms than the rest of the input can hold.
3838///
3839/// Reservations stay within `max_rows`. Rows are still read up to the
3840/// declared count, so a short file is `IncompleteFrame`.
3841#[cold]
3842#[inline(never)]
3843fn parse_oversized_frame<'a, L>(
3844    lines: &mut L,
3845    header: FrameHeader,
3846    max_rows: Option<usize>,
3847) -> Result<ConFrame, ParseError>
3848where
3849    L: LineStream<'a> + Iterator<Item = &'a str>,
3850{
3851    let validate = header.strict_validation;
3852    let total_atoms = header
3853        .natms_per_type
3854        .iter()
3855        .fold(0usize, |sum, &n| sum.saturating_add(n));
3856    let reserve_atoms = max_rows.map_or(0, |rows| total_atoms.min(rows));
3857    use crate::storage_dtype::FloatArray2;
3858    let dt = header.metadata.dtypes();
3859    let mut pos_flat = Vec::new();
3860    let _ = pos_flat.try_reserve_exact(reserve_atoms.saturating_mul(3));
3861    let mut ids = Vec::new();
3862    let _ = ids.try_reserve_exact(reserve_atoms);
3863    let mut atom_data: Vec<AtomDatum> = Vec::new();
3864    let _ = atom_data.try_reserve_exact(reserve_atoms);
3865
3866    let mut global_atom_idx: u64 = 0;
3867    for (type_idx, num_atoms) in header.natms_per_type.iter().enumerate() {
3868        let symbol_line = lines.next().ok_or(ParseError::IncompleteFrame)?;
3869        let symbol: Arc<str> = Arc::from(symbol_line.trim());
3870        let coord_label = lines.next().ok_or(ParseError::IncompleteFrame)?;
3871        let expected_label = format!("Coordinates of Component {}", type_idx + 1);
3872        if !labels_equal(coord_label, &expected_label) {
3873            return Err(ParseError::ValidationError(format!(
3874                "expected coordinate label {expected_label:?}, found {coord_label:?}"
3875            )));
3876        }
3877        if validate {
3878            validate_coordinate_component(type_idx, symbol.as_ref(), coord_label)?;
3879        }
3880        global_atom_idx = ingest_coord_rows_cloned(
3881            lines,
3882            *num_atoms,
3883            header.spec_version,
3884            global_atom_idx,
3885            &symbol,
3886            ClonedRows {
3887                pos: &mut pos_flat,
3888                ids: &mut ids,
3889                atoms: &mut atom_data,
3890            },
3891        )?;
3892    }
3893    let mut positions = FloatArray2::from_f64_row_major(total_atoms, 3, pos_flat);
3894    positions.project_to(dt.positions);
3895    Ok(crate::types::con_frame_coords_only_with_ids(
3896        header, atom_data, positions, ids,
3897    ))
3898}
3899
3900struct CoordSink<'a> {
3901    pos_flat: &'a mut Vec<f64>,
3902    ids: &'a mut Vec<u64>,
3903    positions_other: &'a mut Option<crate::storage_dtype::FloatArray2>,
3904    atom_data: &'a mut Vec<AtomDatum>,
3905}
3906
3907/// Parse `n` coordinate rows into flat SoA buffers.
3908fn ingest_coord_rows<'a, L>(
3909    lines: &mut L,
3910    n: usize,
3911    spec_version: u32,
3912    global_atom_idx: u64,
3913    symbol: &Arc<str>,
3914    sink: CoordSink<'_>,
3915) -> Result<u64, ParseError>
3916where
3917    L: LineStream<'a>,
3918{
3919    let CoordSink {
3920        pos_flat,
3921        ids,
3922        positions_other,
3923        atom_data,
3924    } = sink;
3925    if positions_other.is_none() {
3926        return ingest_coord_rows_f64(
3927            lines,
3928            n,
3929            spec_version,
3930            global_atom_idx,
3931            symbol,
3932            pos_flat,
3933            ids,
3934            atom_data,
3935        );
3936    }
3937    let mut global_atom_idx = global_atom_idx;
3938    for _ in 0..n {
3939        let (xyz, fixed, atom_id) = lines.next_coord_row(spec_version, global_atom_idx)?;
3940        if let Some(pos) = positions_other.as_mut() {
3941            pos.set_f64_row(ids.len(), xyz);
3942        }
3943        ids.push(atom_id);
3944        // The frame keeps `positions_other`, not `pos_flat`, so an atom
3945        // cannot address `pos_flat` and owns its coordinates instead.
3946        atom_data.push(AtomDatum::coords(
3947            Arc::clone(symbol),
3948            xyz[0],
3949            xyz[1],
3950            xyz[2],
3951            fixed,
3952            atom_id,
3953        ));
3954        global_atom_idx += 1;
3955    }
3956    Ok(global_atom_idx)
3957}
3958
3959/// Coordinate rows for the f64 storage path.
3960///
3961/// The symbol `Arc` is bumped once for the whole block. Cloning it per atom
3962/// was a visible share of the coordinate parse.
3963#[inline(never)]
3964#[allow(clippy::too_many_arguments)]
3965fn ingest_coord_rows_f64<'a, L>(
3966    lines: &mut L,
3967    n: usize,
3968    spec_version: u32,
3969    mut global_atom_idx: u64,
3970    symbol: &Arc<str>,
3971    pos_flat: &mut Vec<f64>,
3972    ids: &mut Vec<u64>,
3973    atom_data: &mut Vec<AtomDatum>,
3974) -> Result<u64, ParseError>
3975where
3976    L: LineStream<'a>,
3977{
3978    let workers = wide_workers();
3979    if workers >= 2 && n >= 4096 {
3980        if let Some(block) =
3981            lines.try_take_coord_block(n, spec_version, global_atom_idx, symbol, workers)
3982        {
3983            // Keep a reservation that covers the whole frame so the next
3984            // species group does not allocate a second positions buffer.
3985            if pos_flat.is_empty() && block.xyz.capacity() >= pos_flat.capacity() {
3986                *pos_flat = block.xyz;
3987            } else {
3988                pos_flat.extend_from_slice(&block.xyz);
3989            }
3990            if ids.is_empty() {
3991                *ids = block.ids;
3992            } else {
3993                ids.extend_from_slice(&block.ids);
3994            }
3995            if atom_data.is_empty() {
3996                *atom_data = block.atoms;
3997            } else {
3998                atom_data.extend(block.atoms);
3999            }
4000            return Ok(global_atom_idx + n as u64);
4001        }
4002    }
4003    let mut shares = symbol_shares(symbol, n);
4004    for _ in 0..n {
4005        let (xyz, fixed, atom_id) = lines.next_coord_row(spec_version, global_atom_idx)?;
4006        if fixed != [false, false, false] || atom_id != global_atom_idx {
4007            note_not_sequential_plain();
4008        }
4009        let sym = shares.take();
4010        pos_flat.extend_from_slice(&xyz);
4011        ids.push(atom_id);
4012        atom_data.push(AtomDatum::coords(
4013            sym, xyz[0], xyz[1], xyz[2], fixed, atom_id,
4014        ));
4015        global_atom_idx += 1;
4016    }
4017    Ok(global_atom_idx)
4018}
4019
4020struct ClonedRows<'a> {
4021    pos: &'a mut Vec<f64>,
4022    ids: &'a mut Vec<u64>,
4023    atoms: &'a mut Vec<AtomDatum>,
4024}
4025
4026/// Coordinate rows when the declared count must not bump an `Arc` by `n`.
4027fn ingest_coord_rows_cloned<'a, L>(
4028    lines: &mut L,
4029    n: usize,
4030    spec_version: u32,
4031    mut global_atom_idx: u64,
4032    symbol: &Arc<str>,
4033    rows: ClonedRows<'_>,
4034) -> Result<u64, ParseError>
4035where
4036    L: LineStream<'a>,
4037{
4038    let ClonedRows {
4039        pos: pos_flat,
4040        ids,
4041        atoms: atom_data,
4042    } = rows;
4043    for _ in 0..n {
4044        let (xyz, fixed, atom_id) = lines.next_coord_row(spec_version, global_atom_idx)?;
4045        pos_flat.extend_from_slice(&xyz);
4046        ids.push(atom_id);
4047        atom_data.push(AtomDatum::coords(
4048            Arc::clone(symbol),
4049            xyz[0],
4050            xyz[1],
4051            xyz[2],
4052            fixed,
4053            atom_id,
4054        ));
4055        global_atom_idx += 1;
4056    }
4057    Ok(global_atom_idx)
4058}
4059
4060/// `n` extra strong references to `symbol`, taken one at a time.
4061///
4062/// `Arc<str>` stores the header (strong count, weak count) immediately
4063/// before the bytes. One `fetch_add` covers the block; each [`SymbolShares::take`]
4064/// turns one of those counts into an `Arc`. Leftovers drop with the guard.
4065struct SymbolShares {
4066    data: *const u8,
4067    len: usize,
4068    left: usize,
4069}
4070
4071impl SymbolShares {
4072    fn raw(&self) -> *const str {
4073        std::ptr::slice_from_raw_parts(self.data, self.len) as *const str
4074    }
4075
4076    fn take(&mut self) -> Arc<str> {
4077        debug_assert!(self.left > 0);
4078        self.left -= 1;
4079        unsafe { Arc::from_raw(self.raw()) }
4080    }
4081}
4082
4083impl Drop for SymbolShares {
4084    fn drop(&mut self) {
4085        for _ in 0..self.left {
4086            drop(unsafe { Arc::from_raw(self.raw()) });
4087        }
4088        self.left = 0;
4089    }
4090}
4091
4092fn symbol_shares(symbol: &Arc<str>, n: usize) -> SymbolShares {
4093    if n == 0 {
4094        return SymbolShares {
4095            data: std::ptr::null(),
4096            len: 0,
4097            left: 0,
4098        };
4099    }
4100    let data = Arc::as_ptr(symbol);
4101    let offset = arc_str_header(symbol.as_ref());
4102    // SAFETY: `Arc::as_ptr` points at the `str` inside the allocation, and
4103    // the two atomic counts sit in front of it. This is the same subtraction
4104    // `Arc::increment_strong_count` performs, done once for `n` clones.
4105    let bytes = data as *const u8;
4106    let strong = unsafe { bytes.sub(offset) as *const AtomicUsize };
4107    unsafe { (*strong).fetch_add(n, Ordering::Relaxed) };
4108    SymbolShares {
4109        data: bytes,
4110        len: symbol.len(),
4111        left: n,
4112    }
4113}
4114
4115fn arc_str_header(text: &str) -> usize {
4116    let header = 2 * std::mem::size_of::<usize>();
4117    let align = std::mem::align_of_val(text);
4118    let rem = header % align;
4119    if rem == 0 {
4120        header
4121    } else {
4122        header + (align - rem)
4123    }
4124}
4125
4126#[cfg(test)]
4127mod symbol_share_tests {
4128    use super::symbol_shares;
4129    use std::sync::Arc;
4130
4131    #[test]
4132    fn one_bump_matches_n_clones() {
4133        for text in ["", "Cu", "Gold", "a-much-longer-component-symbol"] {
4134            let symbol: Arc<str> = Arc::from(text);
4135            let mut shares = symbol_shares(&symbol, 3);
4136            assert_eq!(Arc::strong_count(&symbol), 4);
4137            let owned = [shares.take(), shares.take(), shares.take()];
4138            assert!(owned.iter().all(|arc| arc.as_ref() == text));
4139            drop(owned);
4140            assert_eq!(Arc::strong_count(&symbol), 1);
4141            let mut partial = symbol_shares(&symbol, 2);
4142            let one = partial.take();
4143            drop(partial);
4144            drop(one);
4145            assert_eq!(Arc::strong_count(&symbol), 1);
4146        }
4147    }
4148}
4149
4150/// CON-section.7 and CON-section.9, reported on line 2 (CON-error.4).
4151fn reject_unknown_sections(
4152    obj: &serde_json::Map<String, Value>,
4153    sections: &[String],
4154    minor: u64,
4155) -> Result<(), ParseError> {
4156    let newer = minor > u64::from(crate::CON_SPEC_MINOR);
4157    for name in sections {
4158        if reserved_section_label_prefix(name).is_some() {
4159            continue;
4160        }
4161        let skippable = newer && section_arity_known(obj, name);
4162        if !skippable {
4163            return Err(ParseError::UnknownSection(name.clone()));
4164        }
4165    }
4166    Ok(())
4167}
4168
4169fn section_arity_known(obj: &serde_json::Map<String, Value>, name: &str) -> bool {
4170    obj.get(meta::SECTION_ARITY)
4171        .and_then(|value| value.as_object())
4172        .and_then(|map| map.get(name))
4173        .and_then(|entry| entry.as_u64())
4174        .is_some_and(|n| n >= 1)
4175}
4176
4177fn validate_header_geometry(boxl: &[f64], angles: &[f64]) -> Result<(), ParseError> {
4178    if boxl
4179        .iter()
4180        .any(|length| !length.is_finite() || *length <= 0.0)
4181        || angles
4182            .iter()
4183            .any(|angle| !angle.is_finite() || *angle <= 0.0 || *angle >= 180.0)
4184    {
4185        return Err(ParseError::ValidationError(
4186            "cell geometry must have positive lengths and angles between 0 and 180 degrees"
4187                .to_string(),
4188        ));
4189    }
4190    Ok(())
4191}
4192
4193fn validate_masses(masses_per_type: &[f64]) -> Result<(), ParseError> {
4194    if masses_per_type
4195        .iter()
4196        .any(|mass| !mass.is_finite() || *mass <= 0.0)
4197    {
4198        return Err(ParseError::ValidationError(
4199            "component masses must be positive".to_string(),
4200        ));
4201    }
4202    Ok(())
4203}
4204
4205fn section_label_mismatch(
4206    validate: bool,
4207    section: &str,
4208    expected: &str,
4209    found: &str,
4210) -> ParseError {
4211    if validate {
4212        ParseError::ValidationError(format!(
4213            "expected section label {expected:?}, found {found:?}"
4214        ))
4215    } else {
4216        ParseError::IncompleteSection(section.into())
4217    }
4218}
4219
4220fn validate_coordinate_component(
4221    type_idx: usize,
4222    symbol: &str,
4223    label: &str,
4224) -> Result<(), ParseError> {
4225    let expected_label = format!("Coordinates of Component {}", type_idx + 1);
4226    if !labels_equal(label, &expected_label) {
4227        return Err(ParseError::ValidationError(format!(
4228            "expected coordinate label {expected_label:?}, found {label:?}"
4229        )));
4230    }
4231    if symbol != "X" && symbol_to_atomic_number(symbol) == 0 {
4232        return Err(ParseError::ValidationError(format!(
4233            "unknown component symbol {symbol}"
4234        )));
4235    }
4236    Ok(())
4237}
4238
4239fn validate_section_component(
4240    section: &str,
4241    type_idx: usize,
4242    atom_idx: usize,
4243    symbol: &str,
4244    label: &str,
4245    header: &FrameHeader,
4246    atom_data: &[AtomDatum],
4247) -> Result<(), ParseError> {
4248    let expected_label = format!("{section} of Component {}", type_idx + 1);
4249    if !labels_equal(label, &expected_label) {
4250        return Err(ParseError::ValidationError(format!(
4251            "expected section label {expected_label:?}, found {label:?}"
4252        )));
4253    }
4254
4255    if header.natms_per_type[type_idx] == 0 {
4256        return Ok(());
4257    }
4258
4259    let expected_symbol = atom_data
4260        .get(atom_idx)
4261        .map(|atom| atom.symbol.as_ref())
4262        .ok_or_else(|| {
4263            ParseError::ValidationError(format!(
4264                "{section} component {} has no coordinate atom to validate against",
4265                type_idx + 1
4266            ))
4267        })?;
4268    if symbol != expected_symbol {
4269        return Err(ParseError::ValidationError(format!(
4270            "{section} component {} symbol mismatch: expected {expected_symbol}, found {symbol}",
4271            type_idx + 1
4272        )));
4273    }
4274
4275    Ok(())
4276}
4277
4278/// The symbol check of [`validate_section_component`], before the label is read.
4279///
4280/// The failing line is the symbol line (CON-error.4). Reading the label first
4281/// would report that later line.
4282fn reject_wrong_section_symbol(
4283    section: &str,
4284    type_idx: usize,
4285    atom_idx: usize,
4286    symbol: &str,
4287    header: &FrameHeader,
4288    atom_data: &[AtomDatum],
4289) -> Result<(), ParseError> {
4290    if header.natms_per_type.get(type_idx).copied().unwrap_or(0) == 0 {
4291        return Ok(());
4292    }
4293    let expected_symbol = atom_data
4294        .get(atom_idx)
4295        .map(|atom| atom.symbol.as_ref())
4296        .ok_or_else(|| {
4297            ParseError::ValidationError(format!(
4298                "{section} component {} has no coordinate atom to validate against",
4299                type_idx + 1
4300            ))
4301        })?;
4302    if symbol != expected_symbol {
4303        return Err(ParseError::ValidationError(format!(
4304            "{section} component {} symbol mismatch: expected {expected_symbol}, found {symbol}",
4305            type_idx + 1
4306        )));
4307    }
4308    Ok(())
4309}
4310
4311fn validate_section_atom_identity(
4312    section: &str,
4313    atom_idx: usize,
4314    fixed: [bool; 3],
4315    atom_id: u64,
4316    atom_data: &[AtomDatum],
4317) -> Result<(), ParseError> {
4318    let atom = atom_data.get(atom_idx).ok_or_else(|| {
4319        ParseError::ValidationError(format!(
4320            "{section} row {atom_idx} has no coordinate atom to validate against"
4321        ))
4322    })?;
4323
4324    if atom.fixed() != fixed {
4325        return Err(ParseError::ValidationError(format!(
4326            "{section} row {atom_idx} fixed mask mismatch for atom_id {}",
4327            atom.atom_id
4328        )));
4329    }
4330    if atom.atom_id != atom_id {
4331        return Err(ParseError::ValidationError(format!(
4332            "{section} row {atom_idx} atom_id mismatch: expected {}, found {atom_id}",
4333            atom.atom_id
4334        )));
4335    }
4336
4337    Ok(())
4338}
4339
4340/// Consume the single blank line that opens a section.
4341///
4342/// A blank line followed only by whitespace to EOF does not open a section
4343/// (CON-frame.5). The lines stay in the stream.
4344pub(crate) fn frame_minor(header: &FrameHeader) -> u64 {
4345    header.metadata.spec_minor()
4346}
4347
4348/// Minor this reader implements for `spec_version` (CON-section.8).
4349///
4350/// Major 4 reserves the section table at minor 0. Major 3 reserved it at
4351/// minor 1, and a minor of major 3 does not become "newer" just because
4352/// this reader now implements minor 0 of major 4.
4353fn implemented_minor(spec_version: u32) -> u64 {
4354    if spec_version >= 4 {
4355        u64::from(crate::CON_SPEC_MINOR)
4356    } else if spec_version == 3 {
4357        1
4358    } else {
4359        0
4360    }
4361}
4362
4363pub(crate) fn section_row_arity(header: &FrameHeader, name: &str) -> Option<usize> {
4364    let obj = header.metadata.get(meta::SECTION_ARITY)?.as_object()?;
4365    let n = obj.get(name)?.as_u64()?;
4366    if n >= 1 { Some(n as usize) } else { None }
4367}
4368
4369/// Skip one unknown section of a newer minor.
4370///
4371/// `arity` is the value-field count (CON-section.12). Each data row holds
4372/// that many values, then the flag, and an optional id, so the row has
4373/// `arity + 1` or `arity + 2` tokens (CON-section.14). The label is the
4374/// section name under CON-file.5, then `of Component N` (CON-section.15).
4375fn skip_unknown_section<'a>(
4376    lines: &mut impl LineStream<'a>,
4377    header: &FrameHeader,
4378    name: &str,
4379    arity: usize,
4380) -> Result<(), ParseError> {
4381    if !open_section(lines)? {
4382        return Err(ParseError::IncompleteSection(name.to_string()));
4383    }
4384    let with_flag = arity.saturating_add(1);
4385    let with_id = arity.saturating_add(2);
4386    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
4387        if lines.next_line().is_none() {
4388            return Err(ParseError::IncompleteSection(name.to_string()));
4389        }
4390        let label = lines
4391            .next_line()
4392            .ok_or_else(|| ParseError::IncompleteSection(name.to_string()))?;
4393        let expected = format!("{name} of Component {}", type_idx + 1);
4394        if !labels_equal(label, &expected) {
4395            return Err(ParseError::IncompleteSection(name.to_string()));
4396        }
4397        for _ in 0..num_atoms {
4398            let row = lines
4399                .next_line()
4400                .ok_or_else(|| ParseError::IncompleteSection(name.to_string()))?;
4401            let found = token_count(row);
4402            if found != with_flag && found != with_id {
4403                let expected = if found < with_flag {
4404                    with_flag
4405                } else {
4406                    with_id
4407                };
4408                return Err(ParseError::InvalidVectorLength { expected, found });
4409            }
4410        }
4411    }
4412    Ok(())
4413}
4414
4415fn open_section<'a>(lines: &mut impl LineStream<'a>) -> Result<bool, ParseError> {
4416    match lines.peek_line() {
4417        Some(line) if line.trim().is_empty() => {
4418            if lines.remainder_is_whitespace() {
4419                return Ok(false);
4420            }
4421            lines.next_line();
4422            Ok(true)
4423        }
4424        _ => Ok(false),
4425    }
4426}
4427
4428/// CON-validate.4. The symbol line is the line this error names.
4429fn reject_symbol_mismatch(
4430    section: &str,
4431    type_idx: usize,
4432    atom_idx: usize,
4433    symbol: &str,
4434    header: &FrameHeader,
4435    atom_data: &[AtomDatum],
4436    validate: bool,
4437) -> Result<(), ParseError> {
4438    if !validate || header.natms_per_type.get(type_idx).copied().unwrap_or(0) == 0 {
4439        return Ok(());
4440    }
4441    let expected_symbol = atom_data
4442        .get(atom_idx)
4443        .map(|atom| atom.symbol.as_ref())
4444        .ok_or_else(|| {
4445            ParseError::ValidationError(format!(
4446                "{section} component {} has no coordinate atom to validate against",
4447                type_idx + 1
4448            ))
4449        })?;
4450    if symbol != expected_symbol {
4451        return Err(ParseError::ValidationError(format!(
4452            "{section} component {} symbol mismatch: expected {expected_symbol}, found {symbol}",
4453            type_idx + 1
4454        )));
4455    }
4456    Ok(())
4457}
4458
4459/// Attempts to parse an optional velocity section following coordinate blocks.
4460///
4461/// In `.convel` files, after all coordinate blocks there is a blank separator line
4462/// followed by per-component velocity blocks with the same structure as coordinate
4463/// blocks (symbol line, "Velocities of Component N" line, then atom lines with
4464/// `vx vy vz fixed atomID`).
4465///
4466/// This function peeks at the next line. If it is blank (or contains only whitespace),
4467/// it consumes the blank line and writes each velocity into `column` (row-major
4468/// `n * 3` `f64`s, one allocation). If the next line is not blank (or is absent),
4469/// no velocities are parsed and `column` is left untouched.
4470///
4471/// Returns `Ok(true)` if velocities were found and parsed, `Ok(false)` otherwise.
4472pub fn parse_velocity_section<'a>(
4473    lines: &mut impl LineStream<'a>,
4474    header: &FrameHeader,
4475    atom_data: &mut [AtomDatum],
4476    column: &mut Vec<f64>,
4477) -> Result<bool, ParseError> {
4478    let validate = header.strict_validation;
4479    // CON-section.23. A declared velocities block opens on the blank line.
4480    // A second blank is the symbol line, and the line after it is the label.
4481    // The legacy caller asks blank_opens_velocity_block first, so a blank
4482    // that is line 1 of the next frame is not consumed here.
4483    if !open_section(lines)? {
4484        return Ok(false);
4485    }
4486    // The blank that opened the section is the current line. A declared
4487    // velocities section reports the metadata line instead.
4488    reject_velocities_without_time(header)?;
4489
4490    let n = atom_data.len();
4491    column.clear();
4492    column.resize(n.saturating_mul(3), 0.0);
4493    let mut atom_idx: usize = 0;
4494    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
4495        // Symbol line. A symbol mismatch is this line (CON-validate.4).
4496        let symbol = lines
4497            .next_line()
4498            .ok_or(ParseError::IncompleteSection(SECTION_VELOCITIES.into()))?
4499            .trim();
4500        if validate {
4501            reject_wrong_section_symbol(
4502                "Velocities",
4503                type_idx,
4504                atom_idx,
4505                symbol,
4506                header,
4507                atom_data,
4508            )?;
4509        }
4510
4511        // CON-section.15: the label is exactly "Velocities of Component N".
4512        let comp_line = lines
4513            .next_line()
4514            .ok_or(ParseError::IncompleteSection(SECTION_VELOCITIES.into()))?;
4515        let expected = format!("Velocities of Component {}", type_idx + 1);
4516        if !labels_equal(comp_line, &expected) {
4517            return Err(section_label_mismatch(
4518                validate,
4519                SECTION_VELOCITIES,
4520                &expected,
4521                comp_line,
4522            ));
4523        }
4524        if validate {
4525            validate_section_component(
4526                "Velocities",
4527                type_idx,
4528                atom_idx,
4529                symbol,
4530                comp_line,
4531                header,
4532                atom_data,
4533            )?;
4534        }
4535
4536        for _ in 0..num_atoms {
4537            let (vals, fixed, atom_id) =
4538                take_vector_row(lines, header.spec_version, SECTION_VELOCITIES)?;
4539            if validate {
4540                validate_section_atom_identity("velocities", atom_idx, fixed, atom_id, atom_data)?;
4541            }
4542            if atom_idx < n {
4543                let base = atom_idx * 3;
4544                column[base] = vals[0];
4545                column[base + 1] = vals[1];
4546                column[base + 2] = vals[2];
4547            }
4548            atom_idx += 1;
4549        }
4550    }
4551
4552    Ok(true)
4553}
4554
4555/// Attempts to parse a force section following coordinate (and optional velocity) blocks.
4556///
4557/// Force sections mirror velocity sections: a blank separator line followed by per-component
4558/// force blocks (symbol line, "Forces of Component N" line, then atom lines with
4559/// `fx fy fz fixed_flag atom_id`).
4560///
4561/// Returns `Ok(true)` if forces were found and parsed, `Ok(false)` otherwise.
4562pub fn parse_force_section<'a>(
4563    lines: &mut impl LineStream<'a>,
4564    header: &FrameHeader,
4565    atom_data: &mut [AtomDatum],
4566    column: &mut Vec<f64>,
4567) -> Result<bool, ParseError> {
4568    let validate = header.strict_validation;
4569    if !open_section(lines)? {
4570        return Ok(false);
4571    }
4572
4573    let n = atom_data.len();
4574    column.clear();
4575    column.resize(n.saturating_mul(3), 0.0);
4576    let mut atom_idx: usize = 0;
4577    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
4578        let symbol = lines
4579            .next_line()
4580            .ok_or(ParseError::IncompleteSection(SECTION_FORCES.into()))?
4581            .trim();
4582        reject_symbol_mismatch(
4583            "Forces", type_idx, atom_idx, symbol, header, atom_data, validate,
4584        )?;
4585
4586        let comp_line = lines
4587            .next_line()
4588            .ok_or(ParseError::IncompleteSection(SECTION_FORCES.into()))?;
4589        let expected = format!("Forces of Component {}", type_idx + 1);
4590        if !labels_equal(comp_line, &expected) {
4591            return Err(section_label_mismatch(
4592                validate,
4593                SECTION_FORCES,
4594                &expected,
4595                comp_line,
4596            ));
4597        }
4598        if validate {
4599            validate_section_component(
4600                "Forces", type_idx, atom_idx, symbol, comp_line, header, atom_data,
4601            )?;
4602        }
4603
4604        for _ in 0..num_atoms {
4605            let (vals, fixed, atom_id) =
4606                take_vector_row(lines, header.spec_version, SECTION_FORCES)?;
4607            if validate {
4608                validate_section_atom_identity("forces", atom_idx, fixed, atom_id, atom_data)?;
4609            }
4610            if atom_idx < n {
4611                let base = atom_idx * 3;
4612                column[base] = vals[0];
4613                column[base + 1] = vals[1];
4614                column[base + 2] = vals[2];
4615            }
4616            atom_idx += 1;
4617        }
4618    }
4619
4620    Ok(true)
4621}
4622
4623/// Attempts to parse an energies section following coordinate (and optional
4624/// velocity / force) blocks.
4625///
4626/// Energy sections mirror force sections but with one scalar per atom:
4627/// blank separator, then per-component blocks of (symbol, "Energies of
4628/// Component N", and atom lines `e fixed_flag atom_id`). The two
4629/// trailing identity columns are optional and used only for strict
4630/// validation; in non-strict mode any whitespace after the energy is
4631/// ignored.
4632///
4633/// Returns `Ok(true)` if energies were found and parsed, `Ok(false)`
4634/// otherwise.
4635pub fn parse_energy_section<'a>(
4636    lines: &mut impl LineStream<'a>,
4637    header: &FrameHeader,
4638    atom_data: &mut [AtomDatum],
4639) -> Result<bool, ParseError> {
4640    let validate = header.strict_validation;
4641    if !open_section(lines)? {
4642        return Ok(false);
4643    }
4644
4645    let mut atom_idx: usize = 0;
4646    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
4647        let symbol = lines
4648            .next_line()
4649            .ok_or(ParseError::IncompleteSection(SECTION_ENERGIES.into()))?
4650            .trim();
4651        reject_symbol_mismatch(
4652            "Energies", type_idx, atom_idx, symbol, header, atom_data, validate,
4653        )?;
4654
4655        let comp_line = lines
4656            .next_line()
4657            .ok_or(ParseError::IncompleteSection(SECTION_ENERGIES.into()))?;
4658        let expected = format!("Energies of Component {}", type_idx + 1);
4659        if !labels_equal(comp_line, &expected) {
4660            return Err(section_label_mismatch(
4661                validate,
4662                SECTION_ENERGIES,
4663                &expected,
4664                comp_line,
4665            ));
4666        }
4667        if validate {
4668            validate_section_component(
4669                "Energies", type_idx, atom_idx, symbol, comp_line, header, atom_data,
4670            )?;
4671        }
4672
4673        for _ in 0..num_atoms {
4674            let energy_line = lines
4675                .next_line()
4676                .ok_or(ParseError::IncompleteSection(SECTION_ENERGIES.into()))?;
4677            let (value, fixed, atom_id) =
4678                parse_scalar_section_row(energy_line, header.spec_version)?;
4679            if validate {
4680                validate_section_atom_identity("energies", atom_idx, fixed, atom_id, atom_data)?;
4681            }
4682            if atom_idx < atom_data.len() {
4683                atom_data[atom_idx].set_energy(Some(value));
4684            }
4685            atom_idx += 1;
4686        }
4687    }
4688
4689    Ok(true)
4690}
4691
4692/// Parses declared sections from a frame's header metadata.
4693///
4694/// If `header.sections` is non-empty (v2 file with `"sections"` key in JSON),
4695/// parses each declared section in order. Otherwise falls back to legacy
4696/// blank-separator velocity detection.
4697pub fn parse_declared_sections<'a>(
4698    lines: &mut impl LineStream<'a>,
4699    frame: &mut ConFrame,
4700) -> Result<usize, ParseError> {
4701    let mut applied = 0usize;
4702    // A zero-atom frame has no coordinate block and no section block.
4703    // The legacy velocity fallback must not run (CON-count.1).
4704    if frame.header.natm_types == 0 {
4705        if !frame.header.sections.is_empty() {
4706            return Err(ParseError::InvalidCount(
4707                "a zero-atom frame cannot declare sections".into(),
4708            ));
4709        }
4710        return Ok(0);
4711    }
4712    if !frame.header.sections_declared && frame.header.sections.is_empty() {
4713        // Legacy: try velocity detection via blank separator. A blank
4714        // line can also be the empty line 1 of the next frame, so look for
4715        // the velocity label before committing (CON-frame.5).
4716        let mut column = Vec::new();
4717        let found = lines.blank_opens_velocity_block()
4718            && parse_velocity_section(lines, &frame.header, &mut frame.atom_data, &mut column)?;
4719        if found {
4720            frame.adopt_velocity_column(column);
4721            frame.header.sections.push(SECTION_VELOCITIES.into());
4722            applied = 1;
4723        }
4724    } else {
4725        let sections = std::mem::take(&mut frame.header.sections);
4726        for section in &sections {
4727            match section.as_str() {
4728                SECTION_VELOCITIES => {
4729                    let mut column = Vec::new();
4730                    let found = parse_velocity_section(
4731                        lines,
4732                        &frame.header,
4733                        &mut frame.atom_data,
4734                        &mut column,
4735                    )?;
4736                    if !found {
4737                        return Err(ParseError::IncompleteSection(SECTION_VELOCITIES.into()));
4738                    }
4739                    frame.adopt_velocity_column(column);
4740                    applied += 1;
4741                }
4742                SECTION_FORCES => {
4743                    let mut column = Vec::new();
4744                    let found = parse_force_section(
4745                        lines,
4746                        &frame.header,
4747                        &mut frame.atom_data,
4748                        &mut column,
4749                    )?;
4750                    if !found {
4751                        return Err(ParseError::IncompleteSection(SECTION_FORCES.into()));
4752                    }
4753                    frame.adopt_force_column(column);
4754                    applied += 1;
4755                }
4756                SECTION_ENERGIES => {
4757                    let found = parse_energy_section(lines, &frame.header, &mut frame.atom_data)?;
4758                    if !found {
4759                        return Err(ParseError::IncompleteSection(SECTION_ENERGIES.into()));
4760                    }
4761                    applied += 1;
4762                }
4763                SECTION_CHARGES => {
4764                    let found = parse_charge_section(lines, &frame.header, &mut frame.atom_data)?;
4765                    if !found {
4766                        return Err(ParseError::IncompleteSection(SECTION_CHARGES.into()));
4767                    }
4768                    applied += 1;
4769                }
4770                SECTION_SPINS => {
4771                    let found = parse_spin_section(lines, &frame.header, &mut frame.atom_data)?;
4772                    if !found {
4773                        return Err(ParseError::IncompleteSection(SECTION_SPINS.into()));
4774                    }
4775                    applied += 1;
4776                }
4777                SECTION_MAGMOMS => {
4778                    let found = parse_magmom_section(lines, &frame.header, &mut frame.atom_data)?;
4779                    if !found {
4780                        return Err(ParseError::IncompleteSection(SECTION_MAGMOMS.into()));
4781                    }
4782                    applied += 1;
4783                }
4784                SECTION_DISPLACEMENTS => {
4785                    let found =
4786                        parse_displacement_section(lines, &frame.header, &mut frame.atom_data)?;
4787                    if !found {
4788                        return Err(ParseError::IncompleteSection(SECTION_DISPLACEMENTS.into()));
4789                    }
4790                    applied += 1;
4791                }
4792                SECTION_SPREADS => {
4793                    let found = parse_spread_section(lines, &frame.header, &mut frame.atom_data)?;
4794                    if !found {
4795                        return Err(ParseError::IncompleteSection(SECTION_SPREADS.into()));
4796                    }
4797                    applied += 1;
4798                }
4799                other => {
4800                    if frame_minor(&frame.header) > implemented_minor(frame.header.spec_version)
4801                        && let Some(arity) = section_row_arity(&frame.header, other)
4802                    {
4803                        skip_unknown_section(lines, &frame.header, other, arity)?;
4804                        continue;
4805                    }
4806                    return Err(ParseError::UnknownSection(other.to_string()));
4807                }
4808            }
4809        }
4810        frame.header.sections = sections;
4811    }
4812    Ok(applied)
4813}
4814
4815/// CON-units.11. Versions 1, 2, and every minor of major 3 do not require
4816/// `units.time` (CON-units.8, CON-units.9). Major 4 and later require the
4817/// key when a velocities section is present.
4818fn reject_velocities_without_time(header: &FrameHeader) -> Result<(), ParseError> {
4819    if header.spec_version < 4 {
4820        return Ok(());
4821    }
4822    // This runs as the velocities block is opened. `header.sections` is
4823    // filled after the block, so the call itself is the evidence that the
4824    // section is present.
4825    let time_ok = header
4826        .metadata
4827        .get(meta::UNITS)
4828        .and_then(|units| units.get("time"))
4829        .and_then(|value| value.as_str())
4830        .is_some_and(|unit| !unit.trim().is_empty());
4831    if time_ok {
4832        Ok(())
4833    } else {
4834        Err(ParseError::InvalidUnits(
4835            "major >= 4 requires units.time when a velocities section is present".into(),
4836        ))
4837    }
4838}
4839
4840/// Scalar per-atom section: blank separator + per-type blocks
4841/// (`symbol`, `"X of Component N"`, lines `value fixed atom_id`).
4842fn parse_scalar_atom_section<'a>(
4843    lines: &mut impl LineStream<'a>,
4844    header: &FrameHeader,
4845    atom_data: &mut [AtomDatum],
4846    section_name: &str,
4847    component_label: &str,
4848    mut set_value: impl FnMut(&mut AtomDatum, f64),
4849) -> Result<bool, ParseError> {
4850    let validate = header.strict_validation;
4851    if !open_section(lines)? {
4852        return Ok(false);
4853    }
4854
4855    let mut atom_idx: usize = 0;
4856    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
4857        let symbol = lines
4858            .next_line()
4859            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?
4860            .trim();
4861        reject_symbol_mismatch(
4862            component_label.trim_end_matches(" of Component").trim(),
4863            type_idx,
4864            atom_idx,
4865            symbol,
4866            header,
4867            atom_data,
4868            validate,
4869        )?;
4870
4871        let comp_line = lines
4872            .next_line()
4873            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?;
4874        let expected = format!("{} {}", component_label.trim_end(), type_idx + 1);
4875        if !labels_equal(comp_line, &expected) {
4876            return Err(section_label_mismatch(
4877                validate,
4878                section_name,
4879                &expected,
4880                comp_line,
4881            ));
4882        }
4883        if validate {
4884            validate_section_component(
4885                component_label.trim_end_matches(" of Component").trim(),
4886                type_idx,
4887                atom_idx,
4888                symbol,
4889                comp_line,
4890                header,
4891                atom_data,
4892            )?;
4893        }
4894
4895        for _ in 0..num_atoms {
4896            let data_line = lines
4897                .next_line()
4898                .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?;
4899            let (value, fixed, atom_id) = parse_scalar_section_row(data_line, header.spec_version)?;
4900            if validate {
4901                validate_section_atom_identity(section_name, atom_idx, fixed, atom_id, atom_data)?;
4902            }
4903            if atom_idx < atom_data.len() {
4904                set_value(&mut atom_data[atom_idx], value);
4905            }
4906            atom_idx += 1;
4907        }
4908    }
4909    Ok(true)
4910}
4911
4912pub fn parse_charge_section<'a>(
4913    lines: &mut impl LineStream<'a>,
4914    header: &FrameHeader,
4915    atom_data: &mut [AtomDatum],
4916) -> Result<bool, ParseError> {
4917    parse_scalar_atom_section(
4918        lines,
4919        header,
4920        atom_data,
4921        SECTION_CHARGES,
4922        "Charges of Component",
4923        |a, v| a.set_charge(Some(v)),
4924    )
4925}
4926
4927pub fn parse_spin_section<'a>(
4928    lines: &mut impl LineStream<'a>,
4929    header: &FrameHeader,
4930    atom_data: &mut [AtomDatum],
4931) -> Result<bool, ParseError> {
4932    parse_scalar_atom_section(
4933        lines,
4934        header,
4935        atom_data,
4936        SECTION_SPINS,
4937        "Spins of Component",
4938        |a, v| a.set_spin(Some(v)),
4939    )
4940}
4941
4942fn parse_vector_named_section<'a>(
4943    lines: &mut impl LineStream<'a>,
4944    header: &FrameHeader,
4945    atom_data: &mut [AtomDatum],
4946    names: (&str, &str, &str),
4947    mut set_value: impl FnMut(&mut AtomDatum, [f64; 3]),
4948    mut check_row: impl FnMut(usize, [f64; 3]) -> Result<(), ParseError>,
4949) -> Result<bool, ParseError> {
4950    let (section_name, component_label, label_kind) = names;
4951    let validate = header.strict_validation;
4952    if !open_section(lines)? {
4953        return Ok(false);
4954    }
4955    let mut atom_idx: usize = 0;
4956    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
4957        let symbol = lines
4958            .next_line()
4959            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?
4960            .trim();
4961        reject_symbol_mismatch(
4962            label_kind, type_idx, atom_idx, symbol, header, atom_data, validate,
4963        )?;
4964        let comp_line = lines
4965            .next_line()
4966            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?;
4967        let expected = format!("{} {}", component_label.trim_end(), type_idx + 1);
4968        if !labels_equal(comp_line, &expected) {
4969            return Err(section_label_mismatch(
4970                validate,
4971                section_name,
4972                &expected,
4973                comp_line,
4974            ));
4975        }
4976        if validate {
4977            validate_section_component(
4978                label_kind, type_idx, atom_idx, symbol, comp_line, header, atom_data,
4979            )?;
4980        }
4981        for _ in 0..num_atoms {
4982            let (vals, fixed, atom_id) = take_vector_row(lines, header.spec_version, section_name)?;
4983            check_row(atom_idx, vals)?;
4984            if validate {
4985                validate_section_atom_identity(section_name, atom_idx, fixed, atom_id, atom_data)?;
4986            }
4987            if atom_idx < atom_data.len() {
4988                set_value(&mut atom_data[atom_idx], vals);
4989            }
4990            atom_idx += 1;
4991        }
4992    }
4993    Ok(true)
4994}
4995
4996/// Magmoms: 3-vector per atom, same layout as velocities/forces.
4997pub fn parse_magmom_section<'a>(
4998    lines: &mut impl LineStream<'a>,
4999    header: &FrameHeader,
5000    atom_data: &mut [AtomDatum],
5001) -> Result<bool, ParseError> {
5002    parse_vector_named_section(
5003        lines,
5004        header,
5005        atom_data,
5006        (SECTION_MAGMOMS, "Magmoms of Component", "Magmoms"),
5007        |a, v| a.set_magmom(Some(v)),
5008        |_, _| Ok(()),
5009    )
5010}
5011
5012/// Displacements: 3-vector per atom (Angstrom), same layout as velocities/forces.
5013pub fn parse_displacement_section<'a>(
5014    lines: &mut impl LineStream<'a>,
5015    header: &FrameHeader,
5016    atom_data: &mut [AtomDatum],
5017) -> Result<bool, ParseError> {
5018    parse_vector_named_section(
5019        lines,
5020        header,
5021        atom_data,
5022        (
5023            SECTION_DISPLACEMENTS,
5024            "Displacements of Component",
5025            "Displacements",
5026        ),
5027        |a, v| a.set_displacement(Some(v)),
5028        |_, _| Ok(()),
5029    )
5030}
5031
5032/// Spreads: per-atom root-mean-square spread `[sx, sy, sz]` (Angstrom, each
5033/// non-negative), same layout as velocities/forces.
5034pub fn parse_spread_section<'a>(
5035    lines: &mut impl LineStream<'a>,
5036    header: &FrameHeader,
5037    atom_data: &mut [AtomDatum],
5038) -> Result<bool, ParseError> {
5039    parse_vector_named_section(
5040        lines,
5041        header,
5042        atom_data,
5043        (SECTION_SPREADS, "Spreads of Component", "Spreads"),
5044        |a, v| a.set_spread(Some(v)),
5045        |atom_idx, vals| {
5046            if !vals.iter().all(|v| v.is_finite()) {
5047                return Err(ParseError::NonFiniteValue(format!(
5048                    "spreads atom {atom_idx}"
5049                )));
5050            }
5051            if vals.iter().any(|v| *v < 0.0) {
5052                return Err(crate::types::invalid_spread(atom_idx));
5053            }
5054            Ok(())
5055        },
5056    )
5057}
5058
5059#[cfg(test)]
5060mod tests {
5061    use super::*;
5062    use crate::iterators::ConFrameIterator;
5063
5064    #[cfg(all(unix, not(miri)))]
5065    #[test]
5066    fn per_process_replaces_a_mutex_held_across_fork() {
5067        static CACHE: PerProcess<std::sync::Mutex<()>> = PerProcess::new();
5068        let mutex = CACHE.get_or_init(|| std::sync::Mutex::new(()));
5069        let (held_tx, held_rx) = std::sync::mpsc::channel();
5070        let (release_tx, release_rx) = std::sync::mpsc::channel();
5071        let holder = std::thread::spawn(move || {
5072            let _guard = mutex.lock().expect("parent cache lock");
5073            held_tx.send(()).expect("announce held lock");
5074            release_rx.recv().expect("release parent lock");
5075        });
5076        held_rx.recv().expect("wait for held lock");
5077
5078        let pid = unsafe { libc::fork() };
5079        assert!(pid >= 0, "fork failed");
5080        if pid == 0 {
5081            unsafe { libc::alarm(5) };
5082            let child_mutex = CACHE.get_or_init(|| std::sync::Mutex::new(()));
5083            let ok = child_mutex.lock().is_ok();
5084            unsafe { libc::_exit(if ok { 0 } else { 1 }) };
5085        }
5086
5087        release_tx.send(()).expect("release holder");
5088        holder.join().expect("holder thread");
5089        let mut status = 0;
5090        assert_eq!(unsafe { libc::waitpid(pid, &mut status, 0) }, pid);
5091        assert!(
5092            libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
5093            "forked child reused the held parent mutex, status {status:#x}"
5094        );
5095    }
5096
5097    #[test]
5098    fn test_parse_line_of_n_success() {
5099        let line = "1.0 2.5 -3.0";
5100        let values = parse_line_of_n::<f64>(line, 3).unwrap();
5101        assert_eq!(values, vec![1.0, 2.5, -3.0]);
5102    }
5103
5104    #[test]
5105    fn test_parse_line_of_n_too_short() {
5106        let line = "1.0 2.5";
5107        let result = parse_line_of_n::<f64>(line, 3);
5108        assert!(result.is_err());
5109        assert!(matches!(
5110            result.unwrap_err(),
5111            ParseError::InvalidVectorLength {
5112                expected: 3,
5113                found: 2
5114            }
5115        ));
5116    }
5117
5118    #[test]
5119    fn test_parse_line_of_n_too_long() {
5120        let line = "1.0 2.5 -3.0 4.0";
5121        let result = parse_line_of_n::<f64>(line, 3);
5122        assert!(result.is_err());
5123        assert!(matches!(
5124            result.unwrap_err(),
5125            ParseError::InvalidVectorLength {
5126                expected: 3,
5127                found: 4
5128            }
5129        ));
5130    }
5131
5132    #[test]
5133    fn test_parse_line_of_n_invalid_float() {
5134        let line = "1.0 abc -3.0";
5135        let result = parse_line_of_n::<f64>(line, 3);
5136        assert!(result.is_err());
5137        assert!(matches!(
5138            result.unwrap_err(),
5139            ParseError::InvalidNumberFormat(_)
5140        ));
5141    }
5142
5143    #[test]
5144    fn test_parse_frame_header_success() {
5145        let lines = [
5146            "PREBOX1",
5147            "{\"con_spec_version\":2}",
5148            "10.0 20.0 30.0",
5149            "90.0 90.0 90.0",
5150            "POSTBOX1",
5151            "POSTBOX2",
5152            "2",
5153            "1 1",
5154            "12.011 1.008",
5155        ];
5156        let mut line_it = lines.iter().copied();
5157        match parse_frame_header(&mut line_it) {
5158            Ok(header) => {
5159                assert_eq!(header.prebox_header.user, "PREBOX1");
5160                assert_eq!(header.spec_version, 2);
5161                assert_eq!(header.boxl, [10.0, 20.0, 30.0]);
5162                assert_eq!(header.angles, [90.0, 90.0, 90.0]);
5163                assert_eq!(header.postbox_header, ["POSTBOX1", "POSTBOX2"]);
5164                assert_eq!(header.natm_types, 2);
5165                assert_eq!(header.natms_per_type, vec![1, 1]);
5166                assert_eq!(header.masses_per_type, vec![12.011, 1.008]);
5167            }
5168            Err(e) => {
5169                panic!("Parsing failed when it should have succeeded. Error: {e:?}");
5170            }
5171        }
5172    }
5173
5174    #[test]
5175    fn test_parse_frame_header_missing_line() {
5176        let lines = [
5177            "PREBOX1",
5178            "{\"con_spec_version\":2}",
5179            "10.0 20.0 30.0",
5180            "90.0 90.0 90.0",
5181            "POSTBOX1",
5182            "POSTBOX2",
5183            "2",
5184            "1 1",
5185            // Missing masses_per_type
5186        ];
5187        let mut line_it = lines.iter().copied();
5188        let result = parse_frame_header(&mut line_it);
5189        assert!(result.is_err());
5190        assert!(matches!(result.unwrap_err(), ParseError::IncompleteHeader));
5191    }
5192
5193    #[test]
5194    fn test_parse_frame_header_missing_spec_version() {
5195        let lines = [
5196            "PREBOX1",
5197            "{}",
5198            "10.0 20.0 30.0",
5199            "90.0 90.0 90.0",
5200            "POSTBOX1",
5201            "POSTBOX2",
5202            "2",
5203            "1 1",
5204            "12.011 1.008",
5205        ];
5206        let mut line_it = lines.iter().copied();
5207        let result = parse_frame_header(&mut line_it);
5208        assert!(result.is_err());
5209        assert!(matches!(
5210            result.unwrap_err(),
5211            ParseError::MissingSpecVersion
5212        ));
5213    }
5214
5215    #[test]
5216    fn test_parse_frame_header_legacy_no_json() {
5217        // A non-JSON line 2 is treated as a legacy (v1) file.
5218        let lines = [
5219            "PREBOX1",
5220            "0.0000 TIME",
5221            "10.0 20.0 30.0",
5222            "90.0 90.0 90.0",
5223            "POSTBOX1",
5224            "POSTBOX2",
5225            "2",
5226            "1 1",
5227            "12.011 1.008",
5228        ];
5229        let mut line_it = lines.iter().copied();
5230        let header = parse_frame_header(&mut line_it).unwrap();
5231        assert_eq!(header.spec_version, 1);
5232        assert!(header.metadata.is_empty());
5233    }
5234
5235    #[test]
5236    fn test_parse_frame_header_malformed_json() {
5237        // Line 2 starts with '{' but is not valid JSON -- this IS an error.
5238        let lines = [
5239            "PREBOX1",
5240            "{broken json",
5241            "10.0 20.0 30.0",
5242            "90.0 90.0 90.0",
5243            "POSTBOX1",
5244            "POSTBOX2",
5245            "2",
5246            "1 1",
5247            "12.011 1.008",
5248        ];
5249        let mut line_it = lines.iter().copied();
5250        let result = parse_frame_header(&mut line_it);
5251        assert!(result.is_err());
5252        assert!(matches!(
5253            result.unwrap_err(),
5254            ParseError::InvalidMetadataJson(_)
5255        ));
5256    }
5257
5258    #[test]
5259    fn test_parse_frame_header_unsupported_version() {
5260        let lines = [
5261            "PREBOX1",
5262            "{\"con_spec_version\":999}",
5263            "10.0 20.0 30.0",
5264            "90.0 90.0 90.0",
5265            "POSTBOX1",
5266            "POSTBOX2",
5267            "2",
5268            "1 1",
5269            "12.011 1.008",
5270        ];
5271        let mut line_it = lines.iter().copied();
5272        let result = parse_frame_header(&mut line_it);
5273        assert!(result.is_err());
5274        assert!(matches!(
5275            result.unwrap_err(),
5276            ParseError::UnsupportedVersion(999)
5277        ));
5278    }
5279
5280    #[test]
5281    fn test_v3_missing_units_rejected() {
5282        let lines = [
5283            "PREBOX1",
5284            "{\"con_spec_version\":3}",
5285            "10.0 20.0 30.0",
5286            "90.0 90.0 90.0",
5287            "POSTBOX1",
5288            "POSTBOX2",
5289            "1",
5290            "1",
5291            "1.0",
5292        ];
5293        let mut line_it = lines.iter().copied();
5294        let err = parse_frame_header(&mut line_it).unwrap_err();
5295        let msg = err.to_string();
5296        assert!(
5297            msg.contains("units") || msg.contains("v3"),
5298            "expected units error, got {msg}"
5299        );
5300    }
5301
5302    #[test]
5303    fn test_v3_invalid_units_rejected() {
5304        let lines = [
5305            "PREBOX1",
5306            r#"{"con_spec_version":3,"units":{"length":"eV","energy":"angstrom"}}"#,
5307            "10.0 20.0 30.0",
5308            "90.0 90.0 90.0",
5309            "POSTBOX1",
5310            "POSTBOX2",
5311            "1",
5312            "1",
5313            "1.0",
5314        ];
5315        let mut line_it = lines.iter().copied();
5316        assert!(parse_frame_header(&mut line_it).is_err());
5317    }
5318
5319    #[test]
5320    fn test_v3_valid_units_exposes_length_energy() {
5321        let lines = [
5322            "PREBOX1",
5323            r#"{"con_spec_version":3,"units":{"length":"angstrom","energy":"eV","mass":"amu","time":"fs"}}"#,
5324            "10.0 20.0 30.0",
5325            "90.0 90.0 90.0",
5326            "POSTBOX1",
5327            "POSTBOX2",
5328            "1",
5329            "1",
5330            "1.0",
5331        ];
5332        let mut line_it = lines.iter().copied();
5333        let header = parse_frame_header(&mut line_it).unwrap();
5334        assert_eq!(header.spec_version, 3);
5335        assert_eq!(header.length_unit(), Some("angstrom"));
5336        assert_eq!(header.energy_unit(), Some("eV"));
5337        let f = header.conversion_factor_to("length", "nm").unwrap();
5338        assert!((f - 0.1).abs() < 1e-12);
5339    }
5340
5341    #[test]
5342    fn test_parse_frame_header_extra_metadata_preserved() {
5343        let lines = [
5344            "PREBOX1",
5345            "{\"con_spec_version\":2,\"generator\":\"test\"}",
5346            "10.0 20.0 30.0",
5347            "90.0 90.0 90.0",
5348            "POSTBOX1",
5349            "POSTBOX2",
5350            "2",
5351            "1 1",
5352            "12.011 1.008",
5353        ];
5354        let mut line_it = lines.iter().copied();
5355        let header = parse_frame_header(&mut line_it).unwrap();
5356        assert_eq!(header.spec_version, 2);
5357        assert_eq!(
5358            header.metadata.get("generator"),
5359            Some(&serde_json::Value::String("test".to_string()))
5360        );
5361    }
5362
5363    #[test]
5364    fn test_parse_frame_header_invalid_natms_per_type() {
5365        let lines = [
5366            "PREBOX1",
5367            "{\"con_spec_version\":2}",
5368            "10.0 20.0 30.0",
5369            "90.0 90.0 90.0",
5370            "POSTBOX1",
5371            "POSTBOX2",
5372            "2",
5373            "1 1 1", // 3 values, but natm_types is 2
5374            "12.011 1.008",
5375        ];
5376        let mut line_it = lines.iter().copied();
5377        let result = parse_frame_header(&mut line_it);
5378        assert!(result.is_err());
5379        assert!(matches!(
5380            result.unwrap_err(),
5381            ParseError::InvalidVectorLength {
5382                expected: 2,
5383                found: 3
5384            }
5385        ));
5386    }
5387
5388    #[test]
5389    fn test_parse_single_frame_success() {
5390        let lines = vec![
5391            "PREBOX1",
5392            "{\"con_spec_version\":2}",
5393            "10.0 20.0 30.0",
5394            "90.0 90.0 90.0",
5395            "POSTBOX1",
5396            "POSTBOX2",
5397            "2",
5398            "3 3",
5399            "12.011 1.008",
5400            "1",
5401            "Coordinates of Component 1",
5402            "0.0 0.0 0.0 0 1",
5403            "1.0940 0.0 0.0 0 2",
5404            "-0.5470 0.9499 0.0 0 3",
5405            "2",
5406            "Coordinates of Component 2",
5407            "5.0 5.0 5.0 0 4",
5408            "6.0940 5.0 5.0 0 5",
5409            "5.5470 5.9499 5.0 0 6",
5410        ];
5411        let mut line_it = lines.iter().copied();
5412        let frame = parse_single_frame(&mut line_it).unwrap();
5413
5414        assert_eq!(frame.header.natm_types, 2);
5415        assert_eq!(frame.header.natms_per_type, vec![3, 3]);
5416        assert_eq!(frame.header.masses_per_type, vec![12.011, 1.008]);
5417        assert_eq!(frame.atom_data.len(), 6);
5418        assert_eq!(&*frame.atom_data[0].symbol, "1");
5419        assert_eq!(frame.atom_data[0].atom_id, 1);
5420        assert_eq!(&*frame.atom_data[5].symbol, "2");
5421        assert_eq!(frame.atom_data[5].atom_id, 6);
5422    }
5423
5424    #[test]
5425    fn test_column_4_value_1_is_x_only_on_spec_2() {
5426        let lines = [
5427            "Generated by probe",
5428            "{\"con_spec_version\":2}",
5429            "20.0 20.0 20.0",
5430            "90.0 90.0 90.0",
5431            "",
5432            "",
5433            "1",
5434            "1",
5435            "63.5",
5436            "Cu",
5437            "Coordinates of component   1",
5438            "1.0 2.0 3.0 1 1",
5439        ];
5440        let mut line_it = lines.iter().copied();
5441        let frame = parse_single_frame(&mut line_it).unwrap();
5442        assert_eq!(frame.header.spec_version, 2);
5443        assert_eq!(frame.atom_data[0].fixed(), [true, false, false]);
5444    }
5445
5446    #[test]
5447    fn test_column_4_value_1_is_all_fixed_on_spec_1() {
5448        let lines = [
5449            "Generated by probe",
5450            "0.0000 TIME",
5451            "20.0 20.0 20.0",
5452            "90.0 90.0 90.0",
5453            "",
5454            "",
5455            "1",
5456            "1",
5457            "63.5",
5458            "Cu",
5459            "Coordinates of component   1",
5460            "1.0 2.0 3.0 1 1",
5461        ];
5462        let mut line_it = lines.iter().copied();
5463        let frame = parse_single_frame(&mut line_it).unwrap();
5464        assert_eq!(frame.header.spec_version, 1);
5465        assert_eq!(frame.atom_data[0].fixed(), [true, true, true]);
5466    }
5467
5468    #[test]
5469    fn test_parse_single_frame_missing_line() {
5470        // With a valid header but truncated atom data, we get IncompleteFrame.
5471        let lines = vec![
5472            "PREBOX1",
5473            "{\"con_spec_version\":2}",
5474            "10.0 20.0 30.0",
5475            "90.0 90.0 90.0",
5476            "POSTBOX1",
5477            "POSTBOX2",
5478            "2",
5479            "3 3",
5480            "12.011 1.008",
5481            "1",
5482            "Coordinates of Component 1",
5483            "0.0 0.0 0.0 0 1",
5484            "1.0940 0.0 0.0 0 2",
5485            "-0.5470 0.9499 0.0 0 3",
5486            // Missing Component 2 entirely
5487        ];
5488        let mut line_it = lines.iter().copied();
5489        let result = parse_single_frame(&mut line_it);
5490        assert!(result.is_err());
5491        assert!(matches!(result.unwrap_err(), ParseError::IncompleteFrame));
5492    }
5493
5494    #[test]
5495    fn test_parse_single_frame_missing_atom_index_defaults_sequential() {
5496        // Column 5 (atom_index) is optional; when absent, defaults to sequential.
5497        let lines = vec![
5498            "PREBOX1",
5499            "{\"con_spec_version\":2}",
5500            "10.0 20.0 30.0",
5501            "90.0 90.0 90.0",
5502            "POSTBOX1",
5503            "POSTBOX2",
5504            "2",
5505            "3 3",
5506            "12.011 1.008",
5507            "1",
5508            "Coordinates of Component 1",
5509            "0.0 0.0 0.0 0 1",
5510            "1.0940 0.0 0.0 0 2",
5511            "-0.5470 0.9499 0.0 0 3",
5512            "2",
5513            "Coordinates of Component 2",
5514            "5.0 5.0 5.0 0",       // No atom_index: defaults to 3
5515            "6.0940 5.0 5.0 0 10", // Explicit atom_index: 10
5516            "5.5470 5.9499 5.0 0", // No atom_index: defaults to 5
5517        ];
5518        let mut line_it = lines.iter().copied();
5519        let frame = parse_single_frame(&mut line_it).unwrap();
5520        assert_eq!(frame.atom_data.len(), 6);
5521        // First type: explicit atom_index values
5522        assert_eq!(frame.atom_data[0].atom_id, 1);
5523        assert_eq!(frame.atom_data[1].atom_id, 2);
5524        assert_eq!(frame.atom_data[2].atom_id, 3);
5525        // Second type: mixed explicit and defaulted
5526        assert_eq!(frame.atom_data[3].atom_id, 3); // defaulted (global idx 3)
5527        assert_eq!(frame.atom_data[4].atom_id, 10); // explicit
5528        assert_eq!(frame.atom_data[5].atom_id, 5); // defaulted (global idx 5)
5529    }
5530
5531    #[test]
5532    fn test_parse_single_frame_too_few_columns_fails() {
5533        // Only 3 columns (missing fixed_flag too) should still fail.
5534        let lines = [
5535            "PREBOX1",
5536            "{\"con_spec_version\":2}",
5537            "10.0 20.0 30.0",
5538            "90.0 90.0 90.0",
5539            "POSTBOX1",
5540            "POSTBOX2",
5541            "1",
5542            "1",
5543            "12.011",
5544            "C",
5545            "Coordinates of Component 1",
5546            "0.0 0.0 0.0", // Only 3 values
5547        ];
5548        let mut line_it = lines.iter().copied();
5549        let result = parse_single_frame(&mut line_it);
5550        assert!(result.is_err());
5551        assert!(matches!(
5552            result.unwrap_err(),
5553            ParseError::InvalidVectorLength {
5554                expected: 5,
5555                found: 3
5556            }
5557        ));
5558    }
5559
5560    #[test]
5561    fn test_parse_velocity_section_present() {
5562        let lines = vec![
5563            "PREBOX1",
5564            "{\"con_spec_version\":2}",
5565            "10.0 20.0 30.0",
5566            "90.0 90.0 90.0",
5567            "POSTBOX1",
5568            "POSTBOX2",
5569            "2",
5570            "1 1",
5571            "63.546 1.008",
5572            "Cu",
5573            "Coordinates of Component 1",
5574            "0.0 0.0 0.0 1 0",
5575            "H",
5576            "Coordinates of Component 2",
5577            "1.0 2.0 3.0 0 1",
5578            "",
5579            "Cu",
5580            "Velocities of Component 1",
5581            "0.1 0.2 0.3 1 0",
5582            "H",
5583            "Velocities of Component 2",
5584            "0.4 0.5 0.6 0 1",
5585        ];
5586        let mut line_it = lines.iter().copied().peekable();
5587        // Parse the frame first (consuming 15 lines)
5588        let mut frame =
5589            parse_single_frame(&mut line_it).expect("coordinate parsing should succeed");
5590        assert!(!frame.has_velocities());
5591
5592        // Now parse the velocity section
5593        let mut column = Vec::new();
5594        let has_vel = parse_velocity_section(
5595            &mut line_it,
5596            &frame.header,
5597            &mut frame.atom_data,
5598            &mut column,
5599        )
5600        .expect("velocity parsing should succeed");
5601        assert!(has_vel);
5602        frame.adopt_velocity_column(column);
5603        assert_eq!(frame.atom_data[0].velocity(), Some([0.1, 0.2, 0.3]));
5604        assert_eq!(frame.atom_data[1].velocity(), Some([0.4, 0.5, 0.6]));
5605    }
5606
5607    #[test]
5608    fn test_validate_true_accepts_matching_section_identity() {
5609        let text = r#"
5610PREBOX1
5611{"con_spec_version":2,"sections":["velocities"],"validate":true}
561210.0 20.0 30.0
561390.0 90.0 90.0
5614POSTBOX1
5615POSTBOX2
56162
56171 1
561863.546 1.008
5619Cu
5620Coordinates of Component 1
56210.0 0.0 0.0 5 0
5622H
5623Coordinates of Component 2
56241.0 2.0 3.0 0 1
5625
5626Cu
5627Velocities of Component 1
56280.1 0.2 0.3 5 0
5629H
5630Velocities of Component 2
56310.4 0.5 0.6 0 1
5632"#;
5633        let mut iter = ConFrameIterator::new(text.trim());
5634        let frame = iter.next().unwrap().unwrap();
5635
5636        assert!(frame.has_velocities());
5637        assert_eq!(
5638            frame
5639                .header
5640                .metadata
5641                .get("validate")
5642                .and_then(|v| v.as_bool()),
5643            Some(true)
5644        );
5645    }
5646
5647    #[test]
5648    fn test_validate_true_rejects_section_atom_id_mismatch() {
5649        let text = r#"
5650PREBOX1
5651{"con_spec_version":2,"sections":["velocities"],"validate":true}
565210.0 20.0 30.0
565390.0 90.0 90.0
5654POSTBOX1
5655POSTBOX2
56561
56571
565863.546
5659Cu
5660Coordinates of Component 1
56610.0 0.0 0.0 5 0
5662
5663Cu
5664Velocities of Component 1
56650.1 0.2 0.3 5 99
5666"#;
5667        let mut iter = ConFrameIterator::new(text.trim());
5668        let err = iter.next().unwrap().unwrap_err();
5669
5670        assert!(matches!(err, ParseError::ValidationError(_)));
5671        assert!(err.to_string().contains("atom_id mismatch"));
5672    }
5673
5674    #[test]
5675    fn test_validate_true_rejects_section_symbol_mismatch() {
5676        let text = r#"
5677PREBOX1
5678{"con_spec_version":2,"sections":["forces"],"validate":true}
567910.0 20.0 30.0
568090.0 90.0 90.0
5681POSTBOX1
5682POSTBOX2
56831
56841
568563.546
5686Cu
5687Coordinates of Component 1
56880.0 0.0 0.0 5 0
5689
5690H
5691Forces of Component 1
56920.1 0.2 0.3 5 0
5693"#;
5694        let mut iter = ConFrameIterator::new(text.trim());
5695        let err = iter.next().unwrap().unwrap_err();
5696
5697        assert!(matches!(err, ParseError::ValidationError(_)));
5698        assert!(err.to_string().contains("symbol mismatch"));
5699    }
5700
5701    #[test]
5702    fn test_validate_absent_allows_legacy_duplicate_identity_mismatch() {
5703        let text = r#"
5704PREBOX1
5705{"con_spec_version":2,"sections":["velocities"]}
570610.0 20.0 30.0
570790.0 90.0 90.0
5708POSTBOX1
5709POSTBOX2
57101
57111
571263.546
5713Cu
5714Coordinates of Component 1
57150.0 0.0 0.0 5 0
5716
5717Cu
5718Velocities of Component 1
57190.1 0.2 0.3 0 99
5720"#;
5721        let mut iter = ConFrameIterator::new(text.trim());
5722        let frame = iter.next().unwrap().unwrap();
5723
5724        assert!(frame.has_velocities());
5725        assert_eq!(frame.atom_data[0].atom_id, 0);
5726        assert_eq!(frame.atom_data[0].fixed(), [true, false, true]);
5727    }
5728
5729    #[test]
5730    fn test_validate_must_be_boolean_when_present() {
5731        let lines = [
5732            "PREBOX1",
5733            "{\"con_spec_version\":2,\"validate\":\"yes\",\"sections\":[]}",
5734            "10.0 20.0 30.0",
5735            "90.0 90.0 90.0",
5736            "POSTBOX1",
5737            "POSTBOX2",
5738            "1",
5739            "1",
5740            "12.011",
5741        ];
5742        let mut line_it = lines.iter().copied();
5743        let err = parse_frame_header(&mut line_it).unwrap_err();
5744
5745        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
5746        assert!(err.to_string().contains("validate"));
5747    }
5748
5749    #[test]
5750    fn test_validate_true_requires_sections_key() {
5751        let lines = [
5752            "PREBOX1",
5753            "{\"con_spec_version\":2,\"validate\":true}",
5754            "10.0 20.0 30.0",
5755            "90.0 90.0 90.0",
5756            "POSTBOX1",
5757            "POSTBOX2",
5758            "1",
5759            "1",
5760            "12.011",
5761        ];
5762        let mut line_it = lines.iter().copied();
5763        let err = parse_frame_header(&mut line_it).unwrap_err();
5764
5765        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
5766        assert!(err.to_string().contains("sections"));
5767    }
5768
5769    #[test]
5770    fn test_sections_must_be_string_array_when_present() {
5771        let lines = [
5772            "PREBOX1",
5773            "{\"con_spec_version\":2,\"sections\":[\"velocities\",7]}",
5774            "10.0 20.0 30.0",
5775            "90.0 90.0 90.0",
5776            "POSTBOX1",
5777            "POSTBOX2",
5778            "1",
5779            "1",
5780            "12.011",
5781        ];
5782        let mut line_it = lines.iter().copied();
5783        let err = parse_frame_header(&mut line_it).unwrap_err();
5784
5785        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
5786        assert!(err.to_string().contains("sections"));
5787    }
5788
5789    #[test]
5790    fn test_validate_true_rejects_non_integer_coordinate_identity_columns() {
5791        let text = r#"
5792PREBOX1
5793{"con_spec_version":2,"sections":[],"validate":true}
579410.0 20.0 30.0
579590.0 90.0 90.0
5796POSTBOX1
5797POSTBOX2
57981
57991
580063.546
5801Cu
5802Coordinates of Component 1
58030.0 0.0 0.0 5.0 0
5804"#;
5805        let mut iter = ConFrameIterator::new(text.trim());
5806        let err = iter.next().unwrap().unwrap_err();
5807
5808        assert!(matches!(err, ParseError::InvalidFixedFlag(_)));
5809        assert!(err.to_string().contains("5.0"));
5810    }
5811
5812    #[test]
5813    fn test_validate_true_rejects_non_exact_coordinate_label() {
5814        let text = r#"
5815PREBOX1
5816{"con_spec_version":2,"sections":[],"validate":true}
581710.0 20.0 30.0
581890.0 90.0 90.0
5819POSTBOX1
5820POSTBOX2
58211
58221
582363.546
5824Cu
5825Coordinates Component 1
58260.0 0.0 0.0 5 0
5827"#;
5828        let mut iter = ConFrameIterator::new(text.trim());
5829        let err = iter.next().unwrap().unwrap_err();
5830
5831        assert!(matches!(err, ParseError::ValidationError(_)));
5832        assert!(err.to_string().contains("Coordinates of Component 1"));
5833    }
5834
5835    #[test]
5836    fn test_validate_true_rejects_unknown_component_symbol() {
5837        let text = r#"
5838PREBOX1
5839{"con_spec_version":2,"sections":[],"validate":true}
584010.0 20.0 30.0
584190.0 90.0 90.0
5842POSTBOX1
5843POSTBOX2
58441
58451
584663.546
5847Qq
5848Coordinates of Component 1
58490.0 0.0 0.0 0 0
5850"#;
5851        let mut iter = ConFrameIterator::new(text.trim());
5852        let err = iter.next().unwrap().unwrap_err();
5853
5854        assert!(matches!(err, ParseError::ValidationError(_)));
5855        assert!(err.to_string().contains("symbol"));
5856    }
5857
5858    #[test]
5859    fn test_declared_section_must_be_present() {
5860        let text = r#"
5861PREBOX1
5862{"con_spec_version":2,"sections":["velocities"]}
586310.0 20.0 30.0
586490.0 90.0 90.0
5865POSTBOX1
5866POSTBOX2
58671
58681
586963.546
5870Cu
5871Coordinates of Component 1
58720.0 0.0 0.0 0 0
5873"#;
5874        let mut iter = ConFrameIterator::new(text.trim());
5875        let err = iter.next().unwrap().unwrap_err();
5876
5877        assert!(matches!(
5878            err,
5879            ParseError::IncompleteSection(ref name) if name == "velocities"
5880        ));
5881    }
5882
5883    #[test]
5884    fn test_non_finite_cell_geometry_rejected_in_strict_mode() {
5885        let lines = [
5886            "PREBOX1",
5887            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true}",
5888            "10.0 NaN 30.0",
5889            "90.0 90.0 90.0",
5890            "POSTBOX1",
5891            "POSTBOX2",
5892            "1",
5893            "1",
5894            "12.011",
5895        ];
5896        let mut line_it = lines.iter().copied();
5897        let err = parse_frame_header(&mut line_it).unwrap_err();
5898
5899        assert!(matches!(err, ParseError::NonFiniteValue(_)));
5900        assert!(err.to_string().contains("NaN"));
5901    }
5902
5903    #[test]
5904    fn test_validate_true_rejects_non_physical_cell_geometry() {
5905        let lines = [
5906            "PREBOX1",
5907            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true}",
5908            "0.0 20.0 30.0",
5909            "90.0 180.0 90.0",
5910            "POSTBOX1",
5911            "POSTBOX2",
5912            "1",
5913            "1",
5914            "12.011",
5915        ];
5916        let mut line_it = lines.iter().copied();
5917        let err = parse_frame_header(&mut line_it).unwrap_err();
5918
5919        assert!(matches!(err, ParseError::ValidationError(_)));
5920        assert!(err.to_string().contains("cell"));
5921    }
5922
5923    #[test]
5924    fn test_validate_true_rejects_reserved_metadata_type_mismatch() {
5925        let lines = [
5926            "PREBOX1",
5927            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true,\"energy\":\"low\"}",
5928            "10.0 20.0 30.0",
5929            "90.0 90.0 90.0",
5930            "POSTBOX1",
5931            "POSTBOX2",
5932            "1",
5933            "1",
5934            "12.011",
5935        ];
5936        let mut line_it = lines.iter().copied();
5937        let err = parse_frame_header(&mut line_it).unwrap_err();
5938
5939        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
5940        assert!(err.to_string().contains("energy"));
5941    }
5942
5943    #[test]
5944    fn test_validate_true_rejects_malformed_bonds() {
5945        let lines = [
5946            "PREBOX1",
5947            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true,\"bonds\":[[0]]}",
5948            "10.0 20.0 30.0",
5949            "90.0 90.0 90.0",
5950            "POSTBOX1",
5951            "POSTBOX2",
5952            "1",
5953            "1",
5954            "12.011",
5955        ];
5956        let mut line_it = lines.iter().copied();
5957        let err = parse_frame_header(&mut line_it).unwrap_err();
5958        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
5959        assert!(err.to_string().contains("bonds"));
5960    }
5961
5962    #[test]
5963    fn test_bonds_metadata_round_trip_in_header() {
5964        use crate::types::{Bond, meta};
5965        let lines = [
5966            "PREBOX1",
5967            "{\"con_spec_version\":2,\"bonds\":[[0,1],{\"i\":0,\"j\":2,\"order\":1}]}",
5968            "10.0 20.0 30.0",
5969            "90.0 90.0 90.0",
5970            "POSTBOX1",
5971            "POSTBOX2",
5972            "1",
5973            "1",
5974            "12.011",
5975        ];
5976        let mut line_it = lines.iter().copied();
5977        let header = parse_frame_header(&mut line_it).expect("header");
5978        let bonds = header.bonds();
5979        assert_eq!(bonds.len(), 2);
5980        assert_eq!(bonds[0], Bond::new(0, 1));
5981        assert_eq!(bonds[1].i, 0);
5982        assert_eq!(bonds[1].j, 2);
5983        assert_eq!(bonds[1].order, Some(1));
5984        assert!(header.metadata.contains_key(meta::BONDS));
5985    }
5986
5987    #[test]
5988    fn test_parse_velocity_section_absent() {
5989        let lines = [
5990            "PREBOX1",
5991            "{\"con_spec_version\":2}",
5992            "10.0 20.0 30.0",
5993            "90.0 90.0 90.0",
5994            "POSTBOX1",
5995            "POSTBOX2",
5996            "1",
5997            "1",
5998            "12.011",
5999            "C",
6000            "Coordinates of Component 1",
6001            "0.0 0.0 0.0 0 1",
6002        ];
6003        let mut line_it = lines.iter().copied().peekable();
6004        let mut frame = parse_single_frame(&mut line_it).expect("parse should succeed");
6005        let mut column = Vec::new();
6006        let has_vel = parse_velocity_section(
6007            &mut line_it,
6008            &frame.header,
6009            &mut frame.atom_data,
6010            &mut column,
6011        )
6012        .expect("should succeed with no velocities");
6013        assert!(!has_vel);
6014        assert!(column.is_empty());
6015        assert_eq!(frame.atom_data[0].velocity(), None);
6016    }
6017
6018    /// The velocity column is the storage `atom.velocity` reads. Writing the
6019    /// atom updates that buffer in place, and the bytes match the file.
6020    #[test]
6021    fn velocity_column_aliases_soa_bytes() {
6022        let text = "\
6023bulk
6024{\"con_spec_version\":2}
60254.0 5.0 6.0
602690.0 90.0 90.0
60270 0
60280 0
60291
60302
603163.546
6032Cu
6033Coordinates of Component 1
60340.0 0.0 0.0 7 0
60351.0 0.0 0.0 0 1
6036
6037Cu
6038Velocities of Component 1
60390.125 -0.25 0.5 7 0
6040-0.125 0.25 -0.5 0 1
6041";
6042        let mut frame = ConFrameIterator::new(text)
6043            .next()
6044            .expect("frame")
6045            .expect("parse");
6046        {
6047            let soa = frame.velocities.f64_slice().expect("f64 column");
6048            let mut packed = Vec::with_capacity(soa.len());
6049            for atom in &frame.atom_data {
6050                packed.extend_from_slice(&atom.velocity().expect("velocity"));
6051            }
6052            assert_eq!(soa, packed.as_slice());
6053            assert_eq!(soa, &[0.125, -0.25, 0.5, -0.125, 0.25, -0.5][..]);
6054            assert_eq!(frame.atom_data[0].velocity_slot(), soa.as_ptr());
6055        }
6056        frame.atom_data[0].set_velocity(Some([9.0, 8.0, 7.0]));
6057        assert_eq!(frame.velocities.as_f64_row(0), [9.0, 8.0, 7.0]);
6058        assert_eq!(frame.velocities.as_f64_row(1), [-0.125, 0.25, -0.5]);
6059    }
6060
6061    #[test]
6062    fn force_column_aliases_soa_bytes() {
6063        let text = "\
6064bulk
6065{\"con_spec_version\":2,\"sections\":[\"forces\"]}
60664.0 5.0 6.0
606790.0 90.0 90.0
60680 0
60690 0
60701
60712
607263.546
6073Cu
6074Coordinates of Component 1
60750.0 0.0 0.0 0 0
60761.0 1.0 1.0 7 1
6077
6078Cu
6079Forces of Component 1
60800.1 0.2 0.3 0 0
6081-0.4 0.5 -0.6 7 1
6082";
6083        let mut frame = ConFrameIterator::new(text)
6084            .next()
6085            .expect("frame")
6086            .expect("parse");
6087        {
6088            let soa = frame.forces.f64_slice().expect("f64 column");
6089            let mut packed = Vec::with_capacity(soa.len());
6090            for atom in &frame.atom_data {
6091                packed.extend_from_slice(&atom.force().expect("force"));
6092            }
6093            assert_eq!(soa, packed.as_slice());
6094            assert_eq!(soa, &[0.1, 0.2, 0.3, -0.4, 0.5, -0.6][..]);
6095            assert_eq!(frame.atom_data[0].force_slot(), soa.as_ptr());
6096        }
6097        frame.atom_data[1].set_force(Some([1.0, 2.0, 3.0]));
6098        assert_eq!(frame.forces.as_f64_row(1), [1.0, 2.0, 3.0]);
6099    }
6100
6101    #[test]
6102    fn convel_column_parse_shares_the_velocity_slab() {
6103        let n = 8usize;
6104        let mut text = String::new();
6105        text.push_str("bench\n{\"con_spec_version\":2}\n4 5 6\n90 90 90\n0 0\n0 0\n1\n");
6106        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
6107        for i in 0..n {
6108            text.push_str(&format!("0 0 0 0 {i}\n"));
6109        }
6110        text.push_str("\nCu\nVelocities of Component 1\n");
6111        for i in 0..n {
6112            let v = (i % 1000) as f64 * 0.001;
6113            text.push_str(&format!("{v} 0 0 0 {i}\n"));
6114        }
6115        let frame = ConFrameIterator::new(&text)
6116            .next()
6117            .expect("frame")
6118            .expect("parse");
6119        let soa = frame.velocities.f64_slice().expect("f64");
6120        assert_eq!(frame.atom_data[0].velocity_slot(), soa.as_ptr());
6121        assert_eq!(frame.atom_data[n - 1].velocity().unwrap()[0], 0.007);
6122        assert_eq!(soa[(n - 1) * 3], 0.007);
6123        let bytes = text.into_bytes();
6124        let again = ConFrameIterator::from_bytes(&bytes)
6125            .next()
6126            .expect("frame")
6127            .expect("parse");
6128        let again_soa = again.velocities.f64_slice().expect("f64");
6129        assert_eq!(again.atom_data[0].velocity_slot(), again_soa.as_ptr());
6130        assert_eq!(
6131            again.atom_data[0].velocity().unwrap(),
6132            again.velocities.as_f64_row(0)
6133        );
6134    }
6135
6136    #[test]
6137    fn test_parse_line_of_range_f64_exact() {
6138        let vals = parse_line_of_range_f64("1.0 2.0 3.0 0.0 42", 4, 5, &[0.0; 5]).unwrap();
6139        assert_eq!(vals, vec![1.0, 2.0, 3.0, 0.0, 42.0]);
6140    }
6141
6142    #[test]
6143    fn test_byte_scan_stack_parses_realistic_coord_line() {
6144        // Typical CON atom line: x y z fixed_mask [atom_id]
6145        let line = "   0.63939999999999997    0.90449999999999997   -0.00009999999999977 1    0";
6146        let defaults = [0.0, 0.0, 0.0, 0.0, 99.0];
6147        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
6148        let n = parse_line_of_range_f64_stack(line, 4, 5, &defaults, &mut buf).unwrap();
6149        assert_eq!(n, 5);
6150        assert!((buf[0] - 0.6394).abs() < 1e-4);
6151        assert!((buf[1] - 0.9045).abs() < 1e-4);
6152        assert_eq!(buf[3] as u8, 1);
6153        assert_eq!(buf[4] as u64, 0);
6154        // trailing junk must error
6155        let bad = "1.0 2.0 3.0 1 0 EXTRA";
6156        assert!(parse_line_of_range_f64_stack(bad, 4, 5, &defaults, &mut buf).is_err());
6157        // partial non-boundary token must error
6158        let glued = "1.0 2.0 3.0abc 1 0";
6159        assert!(parse_line_of_range_f64_stack(glued, 4, 5, &defaults, &mut buf).is_err());
6160    }
6161
6162    #[test]
6163    fn test_parse_line_of_range_f64_stack_matches_vec_api() {
6164        let defaults = [0.0, 0.0, 0.0, 0.0, 7.0];
6165        let line = "1.0 2.0 3.0 0.0";
6166        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
6167        parse_line_of_range_f64_stack(line, 4, 5, &defaults, &mut buf).unwrap();
6168        let via_vec = parse_line_of_range_f64(line, 4, 5, &defaults).unwrap();
6169        assert_eq!(&buf[..5], via_vec.as_slice());
6170        assert_eq!(buf[4], 7.0);
6171    }
6172
6173    #[test]
6174    fn test_parse_line_of_range_f64_padded() {
6175        let defaults = [0.0, 0.0, 0.0, 0.0, 99.0];
6176        let vals = parse_line_of_range_f64("1.0 2.0 3.0 0.0", 4, 5, &defaults).unwrap();
6177        assert_eq!(vals, vec![1.0, 2.0, 3.0, 0.0, 99.0]);
6178    }
6179
6180    #[test]
6181    fn test_parse_line_of_range_f64_too_few() {
6182        let result = parse_line_of_range_f64("1.0 2.0 3.0", 4, 5, &[0.0; 5]);
6183        assert!(result.is_err());
6184    }
6185
6186    #[test]
6187    fn test_parse_line_of_range_f64_too_many() {
6188        let result = parse_line_of_range_f64("1.0 2.0 3.0 0.0 5.0 6.0", 4, 5, &[0.0; 5]);
6189        assert!(result.is_err());
6190    }
6191
6192    #[test]
6193    fn test_parse_all_four_column_lines() {
6194        // All atom lines have only 4 columns; atom_index defaults to sequential.
6195        let lines = [
6196            "PREBOX1",
6197            "{\"con_spec_version\":2}",
6198            "10.0 10.0 10.0",
6199            "90.0 90.0 90.0",
6200            "POSTBOX1",
6201            "POSTBOX2",
6202            "1",
6203            "3",
6204            "12.011",
6205            "C",
6206            "Coordinates of Component 1",
6207            "0.0 0.0 0.0 0",
6208            "1.0 0.0 0.0 0",
6209            "2.0 0.0 0.0 1",
6210        ];
6211        let mut line_it = lines.iter().copied();
6212        let frame = parse_single_frame(&mut line_it).unwrap();
6213        assert_eq!(frame.atom_data[0].atom_id, 0);
6214        assert_eq!(frame.atom_data[1].atom_id, 1);
6215        assert_eq!(frame.atom_data[2].atom_id, 2);
6216        assert!(frame.atom_data[2].is_fixed());
6217    }
6218
6219    #[test]
6220    fn test_positions_take_the_storage_dtype_of_the_metadata() {
6221        use crate::storage_dtype::{ElementKind, FloatArray2};
6222        let rows = [[0.5, -1.25, 3.0], [1.0e-3, 2.5e4, -7.75]];
6223        let atom_lines: Vec<String> = rows
6224            .iter()
6225            .enumerate()
6226            .map(|(id, [x, y, z])| format!("{x} {y} {z} 0 {id}"))
6227            .collect();
6228        for &kind in ElementKind::all_hosted() {
6229            let metadata = format!(
6230                "{{\"con_spec_version\":3,\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\"}},\
6231                 \"storage_dtypes\":{{\"positions\":\"{}\"}}}}",
6232                kind.as_str()
6233            );
6234            let mut lines = vec![
6235                "PREBOX1",
6236                metadata.as_str(),
6237                "10.0 10.0 10.0",
6238                "90.0 90.0 90.0",
6239                "POSTBOX1",
6240                "POSTBOX2",
6241                "1",
6242                "2",
6243                "1.008",
6244                "H",
6245                "Coordinates of Component 1",
6246            ];
6247            lines.extend(atom_lines.iter().map(String::as_str));
6248            let frame = parse_single_frame(&mut lines.iter().copied()).unwrap();
6249            assert_eq!(frame.positions.kind(), kind);
6250            assert_eq!(frame.positions.nrows(), rows.len());
6251            for (i, &xyz) in rows.iter().enumerate() {
6252                let mut expected = FloatArray2::zeros(kind, 1, 3);
6253                expected.set_f64_row(0, xyz);
6254                assert_eq!(
6255                    frame.positions.as_f64_row(i),
6256                    expected.as_f64_row(0),
6257                    "{kind:?} row {i}"
6258                );
6259            }
6260        }
6261    }
6262
6263    #[test]
6264    fn accessors_read_the_positions_column_when_it_is_not_f64() {
6265        use crate::storage_dtype::ElementKind;
6266        let rows = [[0.5, -1.25, 3.0], [1.0e-3, 2.5e4, -7.75]];
6267        for &kind in ElementKind::all_hosted() {
6268            if kind == ElementKind::Float64 {
6269                continue;
6270            }
6271            let mut text = format!(
6272                "PREBOX1\n{{\"con_spec_version\":3,\"units\":{{\"length\":\"angstrom\",\
6273                 \"energy\":\"eV\"}},\"storage_dtypes\":{{\"positions\":\"{}\"}}}}\n\
6274                 10.0 10.0 10.0\n90.0 90.0 90.0\nPOSTBOX1\nPOSTBOX2\n1\n2\n1.008\nH\n\
6275                 Coordinates of Component 1\n",
6276                kind.as_str()
6277            );
6278            for (id, [x, y, z]) in rows.iter().enumerate() {
6279                text.push_str(&format!("{x} {y} {z} 0 {id}\n"));
6280            }
6281            let frame = ConFrameIterator::new(&text)
6282                .next()
6283                .expect("frame")
6284                .expect("parse");
6285            assert_eq!(frame.positions.kind(), kind);
6286            for i in 0..frame.atom_data.len() {
6287                assert_eq!(
6288                    frame.xyz_at(i),
6289                    frame.positions.as_f64_row(i),
6290                    "{kind:?} atom {i}"
6291                );
6292            }
6293        }
6294    }
6295
6296    #[test]
6297    fn test_arbitrary_size_con_spec_minor_accepted_and_preserved() {
6298        const TWO_POW_64: &str = "18446744073709551616";
6299        const TWO_POW_64_PLUS_1: &str = "18446744073709551617";
6300        const FORTY_DIGITS: &str = "1000000000000000000000000000000000000007";
6301        let three_hundred_digits = format!("1{}7", "0".repeat(298));
6302
6303        for minor in [
6304            TWO_POW_64,
6305            TWO_POW_64_PLUS_1,
6306            FORTY_DIGITS,
6307            three_hundred_digits.as_str(),
6308        ] {
6309            let meta_general = format!(
6310                r#"{{"con_spec_version":3,"con_spec_minor":{minor},"units":{{"length":"angstrom","energy":"eV"}},"sections":[],"validate":true,"probe":1}}"#
6311            );
6312            let lines_general = [
6313                "PREBOX1",
6314                meta_general.as_str(),
6315                "10.0 10.0 10.0",
6316                "90.0 90.0 90.0",
6317                "POSTBOX1",
6318                "POSTBOX2",
6319                "1",
6320                "1",
6321                "63.546",
6322                "Cu",
6323                "Coordinates of Component 1",
6324                "0.0 0.0 0.0 0 0",
6325            ];
6326            let err = parse_single_frame(&mut lines_general.iter().copied()).unwrap_err();
6327            assert_eq!(err.class_name(), "InvalidMetadataJson", "{minor}: {err}");
6328            assert_eq!(err.line(), 2, "{minor}");
6329            assert!(
6330                err.to_string()
6331                    .contains("fits in an unsigned 64-bit integer"),
6332                "{minor}: {err}"
6333            );
6334
6335            let meta_fast = format!(
6336                r#"{{"con_spec_version":3,"con_spec_minor":{minor},"units":{{"length":"angstrom","energy":"eV"}}}}"#
6337            );
6338            let lines_fast = [
6339                "PREBOX1",
6340                meta_fast.as_str(),
6341                "10.0 10.0 10.0",
6342                "90.0 90.0 90.0",
6343                "POSTBOX1",
6344                "POSTBOX2",
6345                "1",
6346                "1",
6347                "63.546",
6348                "Cu",
6349                "Coordinates of Component 1",
6350                "0.0 0.0 0.0 0 0",
6351            ];
6352            let fast_err = parse_single_frame(&mut lines_fast.iter().copied()).unwrap_err();
6353            assert_eq!(fast_err.class_name(), "InvalidMetadataJson", "{minor}");
6354            assert_eq!(fast_err.line(), 2, "{minor}");
6355
6356            let mut builder = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6357            let built_err = builder.set_metadata_json(&meta_general).unwrap_err();
6358            assert_eq!(built_err.class_name(), "InvalidMetadataJson", "{minor}");
6359            assert!(
6360                built_err
6361                    .to_string()
6362                    .contains("fits in an unsigned 64-bit integer"),
6363                "{minor}: {built_err}"
6364            );
6365        }
6366
6367        // Integers exceeding f64::MAX (such as 400 digits) are rejected by serde_json at BASE
6368        // and are left untouched so both general and fast paths surface BASE InvalidMetadataJson.
6369        let four_hundred_digits = format!("1{}7", "0".repeat(398));
6370        for meta_line in [
6371            format!(
6372                r#"{{"con_spec_version":3,"con_spec_minor":{four_hundred_digits},"units":{{"length":"angstrom","energy":"eV"}}}}"#
6373            ),
6374            format!(
6375                r#"{{"con_spec_version":3,"con_spec_minor":{four_hundred_digits},"units":{{"length":"angstrom","energy":"eV"}},"probe":1}}"#
6376            ),
6377        ] {
6378            let lines = [
6379                "PREBOX1",
6380                meta_line.as_str(),
6381                "10.0 10.0 10.0",
6382                "90.0 90.0 90.0",
6383                "POSTBOX1",
6384                "POSTBOX2",
6385                "1",
6386                "1",
6387                "63.546",
6388                "Cu",
6389                "Coordinates of Component 1",
6390                "0.0 0.0 0.0 0 0",
6391            ];
6392            let err = parse_frame_header(&mut lines.iter().copied()).unwrap_err();
6393            assert_eq!(err.class_name(), "InvalidMetadataJson");
6394            assert!(
6395                err.to_string()
6396                    .contains("number out of range at line 1 column 439"),
6397                "{err}"
6398            );
6399        }
6400        let mut b400 = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6401        assert_eq!(
6402            b400.set_con_spec_minor_str(&four_hundred_digits)
6403                .unwrap_err()
6404                .class_name(),
6405            "InvalidMetadataJson"
6406        );
6407    }
6408
6409    #[test]
6410    fn test_arbitrary_size_con_spec_minor_keeps_later_minor_semantics() {
6411        const FORTY_DIGITS: &str = "1000000000000000000000000000000000000007";
6412        // CON-units.9: every minor of major 3 ignores units.time, and a
6413        // missing units.time must not reject the frame.
6414        let no_time = format!(
6415            "PRE\n{{\"con_spec_version\":3,\"con_spec_minor\":{FORTY_DIGITS},\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\"}},\"sections\":[\"velocities\"]}}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n\nH\nVelocities of Component 1\n0.1 0 0 0 0\n"
6416        );
6417        let err = crate::iterators::ConFrameIterator::new(&no_time)
6418            .next()
6419            .unwrap()
6420            .unwrap_err();
6421        assert_eq!(err.class_name(), "InvalidMetadataJson");
6422        assert_eq!(err.line(), 2);
6423
6424        // A minor that does not fit in u64 is line 2, before section rules.
6425        let unknown_sec = format!(
6426            "PRE\n{{\"con_spec_version\":3,\"con_spec_minor\":{FORTY_DIGITS},\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\"}},\"sections\":[\"widgets\"],\"section_arity\":{{\"widgets\":2}}}}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n\nH\nWidgets of Component 1\n1.0 2.0 0 0\n"
6427        );
6428        let err = crate::iterators::ConFrameIterator::new(&unknown_sec)
6429            .next()
6430            .unwrap()
6431            .unwrap_err();
6432        assert_eq!(err.class_name(), "InvalidMetadataJson");
6433        assert_eq!(err.line(), 2);
6434
6435        // A new builder writes major 4 and materialises the natural time
6436        // unit required by CON-units.12. An integer minor above u64 is
6437        // rejected by the same check the reader uses, so the write uses
6438        // a minor that fits.
6439        let mut rejected = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6440        let rejected_err = rejected.set_con_spec_minor_str(FORTY_DIGITS).unwrap_err();
6441        assert!(
6442            rejected_err
6443                .to_string()
6444                .contains("fits in an unsigned 64-bit integer"),
6445            "{rejected_err}"
6446        );
6447        let mut vel_builder = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6448        vel_builder
6449            .set_units(serde_json::json!({"length": "angstrom", "energy": "eV"}))
6450            .unwrap();
6451        vel_builder
6452            .add_atom("H", 0.0, 0.0, 0.0, [false; 3], 0, 1.0)
6453            .with_velocity([0.1, 0.0, 0.0]);
6454        let vel_frame = vel_builder.build().unwrap();
6455        let mut out = Vec::new();
6456        crate::writer::ConFrameWriter::new(&mut out)
6457            .write_frame(&vel_frame)
6458            .unwrap();
6459        let written = String::from_utf8(out).unwrap();
6460        assert!(written.contains(crate::units::NATURAL_TIME_UNIT));
6461    }
6462
6463    #[test]
6464    fn binary64_half_ulp_minor_matches_serde_json() {
6465        let (plus_one, last_finite, overflow) = f64_max_minor_edge_digits();
6466        assert!(
6467            plus_one.starts_with("179769313486231570814527") && plus_one.ends_with("24858369"),
6468            "{plus_one}"
6469        );
6470        assert!(is_substitutable_huge_minor(&plus_one));
6471        assert!(is_substitutable_huge_minor(&last_finite));
6472        assert!(!is_substitutable_huge_minor(&overflow));
6473
6474        for digits in [&plus_one, &last_finite] {
6475            let with_time = format!(
6476                "PRE\n{{\"con_spec_version\":3,\"con_spec_minor\":{digits},\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\",\"time\":\"fs\"}},\"sections\":[\"velocities\"]}}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n\nH\nVelocities of Component 1\n0.1 0 0 0 0\n"
6477            );
6478            let err = ConFrameIterator::new(&with_time)
6479                .next()
6480                .unwrap()
6481                .unwrap_err();
6482            assert_eq!(err.class_name(), "InvalidMetadataJson", "{digits}: {err}");
6483            assert_eq!(err.line(), 2, "{digits}");
6484
6485            let no_time = format!(
6486                "PRE\n{{\"con_spec_version\":3,\"con_spec_minor\":{digits},\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\"}},\"sections\":[\"velocities\"]}}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n\nH\nVelocities of Component 1\n0.1 0 0 0 0\n"
6487            );
6488            let err = ConFrameIterator::new(&no_time).next().unwrap().unwrap_err();
6489            assert_eq!(err.class_name(), "InvalidMetadataJson", "{digits}: {err}");
6490            assert_eq!(err.line(), 2, "{digits}");
6491
6492            let mut builder = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6493            let set_err = builder.set_con_spec_minor_str(digits).unwrap_err();
6494            assert!(
6495                set_err
6496                    .to_string()
6497                    .contains("fits in an unsigned 64-bit integer"),
6498                "{digits}: {set_err}"
6499            );
6500        }
6501
6502        let over = format!(
6503            "PRE\n{{\"con_spec_version\":3,\"con_spec_minor\":{overflow},\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\",\"time\":\"fs\"}}}}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n"
6504        );
6505        let err = ConFrameIterator::new(&over).next().unwrap().unwrap_err();
6506        assert!(err.to_string().contains("number out of range"), "{err}");
6507        let mut builder = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6508        let set_err = builder.set_con_spec_minor_str(&overflow).unwrap_err();
6509        assert!(
6510            set_err.to_string().contains("number out of range"),
6511            "{set_err}"
6512        );
6513    }
6514
6515    #[test]
6516    /// CON-line2.14 rejects a repeated top-level `con_spec_minor` key.
6517    fn test_invalid_con_spec_minor_and_duplicate_semantics() {
6518        for bad in [
6519            "-1",
6520            "-18446744073709551616",
6521            "-0",
6522            "+1",
6523            "01",
6524            "1.0",
6525            "1.5",
6526            "18446744073709551616.0",
6527            "1e0",
6528            "1e2",
6529            "1E20",
6530            "\"1\"",
6531            "\"18446744073709551616\"",
6532            "true",
6533            "null",
6534        ] {
6535            for extra in ["", r#","probe":1"#] {
6536                let meta = format!(
6537                    r#"{{"con_spec_version":3,"con_spec_minor":{bad},"units":{{"length":"angstrom","energy":"eV"}}{extra}}}"#
6538                );
6539                let lines = [
6540                    "PRE",
6541                    meta.as_str(),
6542                    "10.0 10.0 10.0",
6543                    "90.0 90.0 90.0",
6544                    "",
6545                    "",
6546                    "1",
6547                    "1",
6548                    "1.0",
6549                    "H",
6550                    "Coordinates of Component 1",
6551                    "0.0 0.0 0.0 0 0",
6552                ];
6553                let err = parse_frame_header(&mut lines.iter().copied())
6554                    .expect_err(&format!("expected error for minor {bad}"));
6555                assert_eq!(
6556                    err.class_name(),
6557                    "InvalidMetadataJson",
6558                    "minor {bad} gave {err:?}"
6559                );
6560            }
6561        }
6562
6563        // A repeated top-level con_spec_minor is rejected (CON-line2.14),
6564        // including an earlier invalid token, a later in-range token, a
6565        // later huge token, and a key spelled with a JSON escape.
6566        for dup in [
6567            r#"{"con_spec_version":3,"con_spec_minor":0,"con_spec_minor":-0,"units":{"length":"angstrom","energy":"eV"}}"#,
6568            r#"{"con_spec_version":3,"con_spec_minor":18446744073709551616,"con_spec_minor":-0,"units":{"length":"angstrom","energy":"eV"}}"#,
6569            r#"{"con_spec_version":3,"con_spec_minor":-0,"con_spec_minor":0,"units":{"length":"angstrom","energy":"eV"}}"#,
6570            r#"{"con_spec_version":3,"con_spec_minor":-0,"con_spec_minor":18446744073709551616,"units":{"length":"angstrom","energy":"eV"}}"#,
6571            r#"{"con_spec_version":3,"con_spec_minor":18446744073709551616,"con_spec_minor":7,"units":{"length":"angstrom","energy":"eV"}}"#,
6572            r#"{"con_spec_version":3,"con_spec_minor":7,"con_spec_minor":18446744073709551616,"units":{"length":"angstrom","energy":"eV"}}"#,
6573            "{\"con_spec_version\":3,\"con_spec_minor\":1,\"\\u0063on_spec_minor\":2,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}",
6574        ] {
6575            let lines = ["PRE", dup, "10 10 10", "90 90 90", "", "", "0", "", ""];
6576            let err = parse_frame_header(&mut lines.iter().copied()).unwrap_err();
6577            assert_eq!(err.class_name(), "InvalidMetadataJson", "{dup}: {err}");
6578            assert!(
6579                err.to_string().contains(DUPLICATE_CON_SPEC_MINOR),
6580                "{dup}: {err}"
6581            );
6582        }
6583
6584        // CON-line2.23 rejects repeated names in every metadata object.
6585        let dup_major = [
6586            "PRE",
6587            r#"{"con_spec_version":-0,"con_spec_version":3,"units":{"length":"angstrom","energy":"eV"}}"#,
6588            "10 10 10",
6589            "90 90 90",
6590            "",
6591            "",
6592            "0",
6593            "",
6594            "",
6595        ];
6596        let err = parse_frame_header(&mut dup_major.iter().copied()).unwrap_err();
6597        assert_eq!(err.class_name(), "InvalidMetadataJson");
6598        let dup_arity = [
6599            "PRE",
6600            r#"{"con_spec_version":2,"section_arity":{"widgets":-0,"widgets":2}}"#,
6601            "10 10 10",
6602            "90 90 90",
6603            "",
6604            "",
6605            "0",
6606            "",
6607            "",
6608        ];
6609        let err = parse_frame_header(&mut dup_arity.iter().copied()).unwrap_err();
6610        assert_eq!(err.class_name(), "InvalidMetadataJson");
6611    }
6612
6613    #[test]
6614    fn test_v4_blocker_guarantees_and_base_parity() {
6615        // section_arity is left untouched (2^64 / 40-digit rejected as InvalidMetadataJson).
6616        for line2 in [
6617            r#"{"con_spec_version":2,"section_arity":{"widgets":18446744073709551616}}"#,
6618            r#"{"con_spec_version":2,"section_arity":{"widgets":1000000000000000000000000000000000000007}}"#,
6619            r#"{"con_spec_version":3,"units":{"length":"angstrom","energy":"eV"},"section_arity":{"velocities":18446744073709551616}}"#,
6620        ] {
6621            let lines = ["PRE", line2, "10 10 10", "90 90 90", "", "", "0", "", ""];
6622            let err = parse_frame_header(&mut lines.iter().copied()).unwrap_err();
6623            assert_eq!(err.class_name(), "InvalidMetadataJson", "{line2}: {err}");
6624        }
6625
6626        // Length-preserving placeholder preserves exact BASE error column after serde-valid
6627        // huge con_spec_minor (2^64, 40 digits, 300 digits), while > f64::MAX (400 digits)
6628        // is left untouched so BASE's own column 418 error surfaces.
6629        let twenty = format!(
6630            r#"{{"con_spec_minor":{},"energy":1e999,"con_spec_version":2}}"#,
6631            "18446744073709551616"
6632        );
6633        let twenty_one = format!(
6634            r#"{{"con_spec_minor":{}1,"energy":1e999,"con_spec_version":2}}"#,
6635            "18446744073709551616"
6636        );
6637        let forty = format!(
6638            r#"{{"con_spec_minor":{},"energy":1e999,"con_spec_version":2}}"#,
6639            "1000000000000000000000000000000000000007"
6640        );
6641        let forty_syntax = format!(
6642            r#"{{"con_spec_minor":{},"energy":, "con_spec_version":2}}"#,
6643            "1000000000000000000000000000000000000007"
6644        );
6645        let three_hundred = format!(
6646            r#"{{"con_spec_minor":1{}7,"energy":1e999,"con_spec_version":2}}"#,
6647            "0".repeat(298)
6648        );
6649        let four_hundred = format!(
6650            r#"{{"con_spec_minor":1{}7,"energy":1e999,"con_spec_version":2}}"#,
6651            "0".repeat(398)
6652        );
6653        for (line2, expected_substr) in [
6654            (twenty.as_str(), "number out of range at line 1 column 53"),
6655            (
6656                twenty_one.as_str(),
6657                "number out of range at line 1 column 54",
6658            ),
6659            (forty.as_str(), "number out of range at line 1 column 73"),
6660            (forty_syntax.as_str(), "expected value at line 1 column 69"),
6661            (
6662                three_hundred.as_str(),
6663                "number out of range at line 1 column 333",
6664            ),
6665            (
6666                four_hundred.as_str(),
6667                "number out of range at line 1 column 418",
6668            ),
6669        ] {
6670            let lines = ["PRE", line2, "10 10 10", "90 90 90", "", "", "0", "", ""];
6671            let err = parse_frame_header(&mut lines.iter().copied()).unwrap_err();
6672            assert_eq!(err.class_name(), "InvalidMetadataJson", "{err}");
6673            assert!(err.to_string().contains(expected_substr), "{err}");
6674        }
6675
6676        // con_spec_version overflow keeps BASE error kind and column.
6677        let major_2pow64 = [
6678            "PRE",
6679            r#"{"con_spec_version":18446744073709551616}"#,
6680            "10 10 10",
6681            "90 90 90",
6682            "",
6683            "",
6684            "0",
6685            "",
6686            "",
6687        ];
6688        let err_m64 = parse_frame_header(&mut major_2pow64.iter().copied()).unwrap_err();
6689        assert_eq!(err_m64.class_name(), "InvalidMetadataJson");
6690        assert!(
6691            err_m64
6692                .to_string()
6693                .contains("con_spec_version must be a JSON integer"),
6694            "{err_m64}"
6695        );
6696
6697        let major_400_line = format!(r#"{{"con_spec_version":1{}7}}"#, "0".repeat(398));
6698        let major_400 = [
6699            "PRE",
6700            major_400_line.as_str(),
6701            "10 10 10",
6702            "90 90 90",
6703            "",
6704            "",
6705            "0",
6706            "",
6707            "",
6708        ];
6709        let err_m400 = parse_frame_header(&mut major_400.iter().copied()).unwrap_err();
6710        assert_eq!(err_m400.class_name(), "InvalidMetadataJson");
6711        assert!(
6712            err_m400
6713                .to_string()
6714                .contains("number out of range at line 1 column 420"),
6715            "{err_m400}"
6716        );
6717
6718        let neg_zero_major = [
6719            "PRE",
6720            r#"{"con_spec_version":-0}"#,
6721            "10 10 10",
6722            "90 90 90",
6723            "",
6724            "",
6725            "0",
6726            "",
6727            "",
6728        ];
6729        // -0 is the JSON number 0. Major 0 is UnsupportedVersion (CON-line2.5).
6730        assert_eq!(
6731            parse_frame_header(&mut neg_zero_major.iter().copied())
6732                .unwrap_err()
6733                .class_name(),
6734            "UnsupportedVersion"
6735        );
6736
6737        // Value equality, -0 float preservation, frame_index:-0, section_arity:-0, 1e400/1e999.
6738        let v_one_zero: Value = serde_json::from_str("1.0").unwrap();
6739        let v_one_zero_zero: Value = serde_json::from_str("1.00").unwrap();
6740        let v_exp: Value = serde_json::from_str("1e2").unwrap();
6741        let v_hundred: Value = serde_json::from_str("100.0").unwrap();
6742        assert_eq!(v_one_zero, v_one_zero_zero);
6743        assert_eq!(v_exp, v_hundred);
6744
6745        let neg_zero_energy = [
6746            "PRE",
6747            r#"{"con_spec_version":2,"energy":-0}"#,
6748            "10 10 10",
6749            "90 90 90",
6750            "",
6751            "",
6752            "0",
6753            "",
6754            "",
6755        ];
6756        let h_neg_zero = parse_frame_header(&mut neg_zero_energy.iter().copied()).unwrap();
6757        let energy_val = h_neg_zero.metadata.get("energy").unwrap();
6758        assert!(energy_val.is_f64());
6759        assert_eq!(energy_val.as_f64().unwrap().to_bits(), (-0.0_f64).to_bits());
6760
6761        let bad_frame_idx = [
6762            "PRE",
6763            r#"{"con_spec_version":2,"sections":[],"validate":true,"frame_index":-0}"#,
6764            "10 10 10",
6765            "90 90 90",
6766            "",
6767            "",
6768            "0",
6769            "",
6770            "",
6771        ];
6772        assert_eq!(
6773            parse_frame_header(&mut bad_frame_idx.iter().copied())
6774                .unwrap_err()
6775                .class_name(),
6776            "InvalidMetadataJson"
6777        );
6778
6779        let arity_neg_zero = [
6780            "PRE",
6781            r#"{"con_spec_version":2,"section_arity":{"widgets":-0}}"#,
6782            "10 10 10",
6783            "90 90 90",
6784            "",
6785            "",
6786            "0",
6787            "",
6788            "",
6789        ];
6790        assert_eq!(
6791            parse_frame_header(&mut arity_neg_zero.iter().copied())
6792                .unwrap_err()
6793                .class_name(),
6794            "InvalidMetadataJson"
6795        );
6796        let arity_zero = [
6797            "PRE",
6798            r#"{"con_spec_version":2,"section_arity":{"widgets":0}}"#,
6799            "10 10 10",
6800            "90 90 90",
6801            "",
6802            "",
6803            "0",
6804            "",
6805            "",
6806        ];
6807        assert_eq!(
6808            parse_frame_header(&mut arity_zero.iter().copied())
6809                .unwrap_err()
6810                .class_name(),
6811            "InvalidCount"
6812        );
6813
6814        let mut b = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
6815        let b_err = b
6816            .set_metadata_json(r#"{"con_spec_version":2,"energy":1e400}"#)
6817            .unwrap_err();
6818        assert_eq!(b_err.class_name(), "InvalidMetadataJson");
6819        assert!(
6820            b_err
6821                .to_string()
6822                .contains("number out of range at line 1 column 36"),
6823            "{b_err}"
6824        );
6825
6826        // FrameMeta::insert, remove, and generic serde::Serialize stay consistent.
6827        let mut fm = crate::types::FrameMeta::from_line(
6828            r#"{"con_spec_version":2,"con_spec_minor":18446744073709551616}"#,
6829        );
6830        assert_eq!(fm.spec_minor(), u64::MAX);
6831        assert_eq!(fm.spec_minor_str(), "18446744073709551616");
6832        fm.insert("energy".into(), serde_json::json!(-1.2));
6833        assert_eq!(fm.spec_minor_str(), "18446744073709551616");
6834        let ser_json = serde_json::to_string(&fm).unwrap();
6835        assert!(
6836            ser_json.contains("\"con_spec_minor\":18446744073709551616"),
6837            "{ser_json}"
6838        );
6839        assert!(
6840            !ser_json.contains("18446744073709551615"),
6841            "must not emit saturated u64::MAX: {ser_json}"
6842        );
6843        let set_err = fm
6844            .set_con_spec_minor_str("18446744073709551616")
6845            .unwrap_err();
6846        assert!(
6847            set_err
6848                .to_string()
6849                .contains("fits in an unsigned 64-bit integer"),
6850            "{set_err}"
6851        );
6852        // Float minor >= 2^64 via FrameMeta::insert behaves identically to BASE (stays float, clears minor_raw).
6853        fm.insert(meta::CON_SPEC_MINOR.into(), serde_json::json!(1e20));
6854        assert_eq!(fm.spec_minor(), 0);
6855        assert_eq!(fm.spec_minor_str(), "0");
6856        fm.remove(meta::CON_SPEC_MINOR);
6857        assert_eq!(fm.spec_minor(), 0);
6858        assert_eq!(fm.spec_minor_str(), "0");
6859
6860        // CON-line2.10 says a missing minor is 0. A nested key, or the same
6861        // text inside a string, does not supply it. The nested value stays.
6862        let escaped = crate::types::FrameMeta::from_line(
6863            r#"{"con_spec_version":2,"note":"\"con_spec_minor\":99","nested":{"con_spec_minor":77}}"#,
6864        );
6865        assert_eq!(escaped.spec_minor(), 0);
6866        assert_eq!(escaped.spec_minor_str(), "0");
6867        assert_eq!(
6868            escaped
6869                .get("nested")
6870                .and_then(|v| v.get("con_spec_minor"))
6871                .and_then(|v| v.as_u64()),
6872            Some(77)
6873        );
6874
6875        // The unicode escape is still the top-level minor. An integer above
6876        // u64 is InvalidMetadataJson with the fits sentence.
6877        let unicode_key = [
6878            "PRE",
6879            r#"{"con_spec_version":3,"\u0063on_spec_minor":18446744073709551616,"units":{"length":"angstrom","energy":"eV"}}"#,
6880            "10 10 10",
6881            "90 90 90",
6882            "",
6883            "",
6884            "0",
6885            "",
6886            "",
6887        ];
6888        let h_unicode = parse_frame_header(&mut unicode_key.iter().copied()).unwrap_err();
6889        assert_eq!(h_unicode.class_name(), "InvalidMetadataJson");
6890        assert_eq!(h_unicode.line(), 2);
6891        assert!(
6892            h_unicode
6893                .to_string()
6894                .contains("fits in an unsigned 64-bit integer"),
6895            "{h_unicode}"
6896        );
6897
6898        // -1.20 normalized to -1.2 by writer.
6899        let neb_line = [
6900            "PRE",
6901            r#"{"con_spec_version":2,"energy":-1.20}"#,
6902            "10 10 10",
6903            "90 90 90",
6904            "",
6905            "",
6906            "1",
6907            "1",
6908            "1.0",
6909            "H",
6910            "Coordinates of Component 1",
6911            "0 0 0 0 0",
6912        ];
6913        let neb_frame = parse_single_frame(&mut neb_line.iter().copied()).unwrap();
6914        let mut neb_out = Vec::new();
6915        crate::writer::ConFrameWriter::new(&mut neb_out)
6916            .write_frame(&neb_frame)
6917            .unwrap();
6918        let neb_written = String::from_utf8(neb_out).unwrap();
6919        assert!(neb_written.contains("\"energy\":-1.2}"), "{neb_written}");
6920        assert!(!neb_written.contains("-1.20"), "{neb_written}");
6921    }
6922
6923    /// CON-line2.10 says a missing minor is 0. Read as the top-level field:
6924    /// a nested key, an array element, or a dotted name does not supply it
6925    /// and must be kept (CON-line2.8). It must not shadow the top-level
6926    /// minor, `units.length` (CON-header.3, CON-units.1), or the minor used
6927    /// by CON-units.11 and CON-section.7. A rewrite must not flip that minor.
6928    #[test]
6929    fn nested_and_dotted_metadata_keys_follow_spec() {
6930        let nested_only = crate::types::FrameMeta::from_line(
6931            r#"{"con_spec_version":2,"note":"\"con_spec_minor\":99","nested":{"con_spec_minor":77,"a.b":1}}"#,
6932        );
6933        assert_eq!(nested_only.spec_minor(), 0);
6934        assert_eq!(nested_only.spec_minor_str(), "0");
6935        assert_eq!(
6936            nested_only
6937                .get("nested")
6938                .and_then(|v| v.get("con_spec_minor"))
6939                .and_then(|v| v.as_u64()),
6940            Some(77)
6941        );
6942        assert_eq!(
6943            nested_only
6944                .get("nested")
6945                .and_then(|v| v.get("a.b"))
6946                .and_then(|v| v.as_u64()),
6947            Some(1)
6948        );
6949
6950        let shadowed = crate::types::FrameMeta::from_line(
6951            r#"{"con_spec_version":3,"nest":{"con_spec_minor":9},"con_spec_minor":0}"#,
6952        );
6953        assert_eq!(shadowed.spec_minor(), 0);
6954        assert_eq!(
6955            shadowed
6956                .get("nest")
6957                .and_then(|v| v.get("con_spec_minor"))
6958                .and_then(|v| v.as_u64()),
6959            Some(9)
6960        );
6961
6962        let dotted = crate::types::FrameMeta::from_line(
6963            r#"{"con_spec_version":2,"arr":[{"con_spec_minor":4}],"a.con_spec_minor":8}"#,
6964        );
6965        assert_eq!(dotted.spec_minor(), 0);
6966        assert_eq!(
6967            dotted.get("a.con_spec_minor").and_then(|v| v.as_u64()),
6968            Some(8)
6969        );
6970
6971        let velocities = concat!(
6972            "PRE\n",
6973            r#"{"con_spec_version":3,"x":{"con_spec_minor":1},"units":{"length":"angstrom","energy":"eV"},"sections":["velocities"]}"#,
6974            "\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\n",
6975            "Coordinates of Component 1\n0 0 0 0 0\n\n",
6976            "H\nVelocities of Component 1\n0.1 0 0 0 0\n",
6977        );
6978        let read = crate::iterators::frames_from_text(velocities, None)
6979            .expect("nested minor is not minor >= 1");
6980        assert_eq!(read[0].header.con_spec_minor_saturating(), 0);
6981
6982        let shadowed_vel = concat!(
6983            "PRE\n",
6984            r#"{"con_spec_version":3,"x":{"con_spec_minor":1},"con_spec_minor":0,"units":{"length":"angstrom","energy":"eV"},"sections":["velocities"]}"#,
6985            "\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\n",
6986            "Coordinates of Component 1\n0 0 0 0 0\n\n",
6987            "H\nVelocities of Component 1\n0.1 0 0 0 0\n",
6988        );
6989        let read = crate::iterators::frames_from_text(shadowed_vel, None)
6990            .expect("top-level minor 0 allows velocities without units.time");
6991        assert_eq!(read[0].header.con_spec_minor_saturating(), 0);
6992
6993        let unknown = concat!(
6994            "PRE\n",
6995            r#"{"con_spec_version":3,"nest":{"con_spec_minor":99},"units":{"length":"angstrom","energy":"eV"},"sections":["widgets"],"section_arity":{"widgets":2}}"#,
6996            "\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\n",
6997            "Coordinates of Component 1\n0 0 0 0 0\n\n",
6998            "H\nWidgets of Component 1\n1.0 2.0 0 0\n",
6999        );
7000        let err = crate::iterators::frames_from_text(unknown, None)
7001            .expect_err("minor 0 must not skip an unknown section");
7002        assert_eq!(err.class_name(), "UnknownSection", "{err}");
7003
7004        let round = concat!(
7005            "PRE\n",
7006            r#"{"con_spec_version":3,"nest":{"con_spec_minor":9,"a.b":1},"con_spec_minor":0,"units":{"length":"angstrom","energy":"eV"},"units.length":"bohr"}"#,
7007            "\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\n",
7008            "Coordinates of Component 1\n0 0 0 0 0\n",
7009        );
7010        let frames = crate::iterators::frames_from_text(round, None).unwrap();
7011        let frame = &frames[0];
7012        assert_eq!(frame.header.con_spec_minor_saturating(), 0);
7013        assert_eq!(frame.header.length_unit(), Some("angstrom"));
7014        assert_eq!(
7015            frame
7016                .header
7017                .metadata
7018                .get("units.length")
7019                .and_then(|v| v.as_str()),
7020            Some("bohr")
7021        );
7022        assert_eq!(
7023            frame
7024                .header
7025                .metadata
7026                .get("nest")
7027                .and_then(|v| v.get("a.b"))
7028                .and_then(|v| v.as_u64()),
7029            Some(1)
7030        );
7031        let mut out = Vec::new();
7032        crate::writer::ConFrameWriter::new(&mut out)
7033            .write_frame(frame)
7034            .unwrap();
7035        let written = String::from_utf8(out).unwrap();
7036        let again = crate::iterators::frames_from_text(&written, None).unwrap();
7037        assert_eq!(
7038            again[0].header.con_spec_minor_saturating(),
7039            frame.header.con_spec_minor_saturating()
7040        );
7041        assert_eq!(again[0].header.length_unit(), Some("angstrom"));
7042        assert_eq!(
7043            again[0]
7044                .header
7045                .metadata
7046                .get("units.length")
7047                .and_then(|v| v.as_str()),
7048            Some("bohr")
7049        );
7050        assert_eq!(
7051            again[0]
7052                .header
7053                .metadata
7054                .get("nest")
7055                .and_then(|v| v.get("con_spec_minor"))
7056                .and_then(|v| v.as_u64()),
7057            Some(9)
7058        );
7059        assert_eq!(
7060            again[0]
7061                .header
7062                .metadata
7063                .get("nest")
7064                .and_then(|v| v.get("a.b"))
7065                .and_then(|v| v.as_u64()),
7066            Some(1)
7067        );
7068    }
7069
7070    /// ASCII whitespace between line-2 tokens includes a form feed, and
7071    /// the fast path skips it. A decoded top-level escape is that key.
7072    /// Major 3 keeps a frame that has velocities and no units.time.
7073    #[test]
7074    fn form_feed_and_escaped_top_level_minor_match_the_fast_path() {
7075        let ff = '\u{000c}';
7076        let minor_lines = [
7077            format!(r#"{{"con_spec_version":2,{ff}"con_spec_minor":5}}"#),
7078            format!(r#"{{"con_spec_version":2,"con_spec_minor"{ff}:5}}"#),
7079            format!(r#"{{{ff}"con_spec_version":2,"con_spec_minor":5}}"#),
7080            format!(
7081                r#"{{"con_spec_version":2,"units":{ff}{{"length":"angstrom"}},"con_spec_minor":5}}"#
7082            ),
7083        ];
7084        for line in &minor_lines {
7085            let meta = crate::types::FrameMeta::from_line(line.as_str());
7086            assert_eq!(meta.spec_minor(), 5, "{line:?}");
7087        }
7088        let escaped =
7089            crate::types::FrameMeta::from_line(r#"{"con_spec_version":2,"con_spec_\u006dinor":5}"#);
7090        assert_eq!(escaped.spec_minor(), 5);
7091
7092        let units = r#"{"length":"angstrom","energy":"eV"}"#;
7093        let velocity_lines = [
7094            format!(r#"{{"con_spec_version":3,{ff}"con_spec_minor":1,"units":{units}}}"#),
7095            format!(r#"{{"con_spec_version":3,"con_spec_minor"{ff}:1,"units":{units}}}"#),
7096            format!(r#"{{{ff}"con_spec_version":3,"con_spec_minor":1,"units":{units}}}"#),
7097            format!(r#"{{"con_spec_version":3,"units":{ff}{units},"con_spec_minor":1}}"#),
7098        ];
7099        for line2 in &velocity_lines {
7100            let text = format!(
7101                "PRE\n{line2}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 0\n\nH\nVelocities of Component 1\n0.1 0 0 0 0\n"
7102            );
7103            let frames = crate::iterators::frames_from_text(&text, None)
7104                .unwrap_or_else(|err| panic!("{line2:?}: {err}"));
7105            assert_eq!(frames[0].header.metadata.spec_minor(), 1, "{line2:?}");
7106        }
7107    }
7108    #[test]
7109    fn nonfinite_prefix_with_trailing_junk_is_invalid_number_format() {
7110        let coord = "pre\n{\"con_spec_version\":2}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n-Inf{inity 0 0 0 0\n";
7111        let err = crate::iterators::ConFrameIterator::new(coord)
7112            .next()
7113            .unwrap()
7114            .unwrap_err();
7115        assert_eq!(err.class_name(), "InvalidNumberFormat", "{err}");
7116
7117        let box_line = "pre\n{\"con_spec_version\":2}\n-Inf{inity 10 10\n90 90 90\n\n\n0\n\n\n";
7118        let err = crate::iterators::ConFrameIterator::new(box_line)
7119            .next()
7120            .unwrap()
7121            .unwrap_err();
7122        assert_eq!(err.class_name(), "InvalidNumberFormat", "{err}");
7123    }
7124
7125    #[test]
7126    fn leading_space_or_tab_on_line2_is_trimmed_and_reserved_types_checked() {
7127        let tabbed_valid = "pre\n\t{\"con_spec_version\":2}\n10 10 10\n90 90 90\n\n\n0\n\n\n";
7128        let fr = crate::iterators::ConFrameIterator::new(tabbed_valid)
7129            .next()
7130            .unwrap()
7131            .unwrap();
7132        assert_eq!(fr.header.spec_version, 2);
7133
7134        let tabbed_bad = "pre\n\t{\"con_spec_version\":2,\"bad\":\n10 10 10\n90 90 90\n\n\n0\n\n\n";
7135        let err = crate::iterators::ConFrameIterator::new(tabbed_bad)
7136            .next()
7137            .unwrap()
7138            .unwrap_err();
7139        assert_eq!(err.class_name(), "InvalidMetadataJson", "{err}");
7140
7141        for bad_meta in [
7142            r#"{"con_spec_version":2,"time":"fs"}"#,
7143            r#"{"con_spec_version":2,"timestep":"1.0"}"#,
7144            r#"{"con_spec_version":2,"frame_index":-1}"#,
7145            r#"{"con_spec_version":2,"neb_bead":"0"}"#,
7146            r#"{"con_spec_version":2,"neb_band":1.5}"#,
7147            r#"{"con_spec_version":2,"generator":123}"#,
7148            r#"{"con_spec_version":2,"potential":"lj"}"#,
7149            r#"{"con_spec_version":2,"potential":{"type":7}}"#,
7150            r#"{"con_spec_version":2,"converged":"yes"}"#,
7151            r#"{"con_spec_version":2,"fmax":"0.1"}"#,
7152            r#"{"con_spec_version":2,"convergence_fmax":true}"#,
7153            r#"{"con_spec_version":2,"convergence_energy":"0"}"#,
7154        ] {
7155            let text = format!("pre\n{bad_meta}\n10 10 10\n90 90 90\n\n\n0\n\n\n");
7156            let err = crate::iterators::ConFrameIterator::new(&text)
7157                .next()
7158                .unwrap()
7159                .unwrap_err();
7160            assert_eq!(err.class_name(), "InvalidMetadataJson", "{bad_meta}: {err}");
7161        }
7162
7163        // CON-bonds.3: unknown `bonds` shapes stay preserved when validate=false.
7164        let bonds_open =
7165            "pre\n{\"con_spec_version\":2,\"bonds\":\"legacy\"}\n10 10 10\n90 90 90\n\n\n0\n\n\n";
7166        assert!(
7167            crate::iterators::ConFrameIterator::new(bonds_open)
7168                .next()
7169                .unwrap()
7170                .is_ok()
7171        );
7172    }
7173
7174    #[test]
7175    fn form_feed_on_cell_or_count_line_is_not_separator_or_trailing_ws() {
7176        let cell_ff = "pre\n{\"con_spec_version\":3,\"con_spec_minor\":1,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}\n10 10 10\n90 90 90\x0c\n\n\n0\n\n\n";
7177        let err = crate::iterators::ConFrameIterator::new(cell_ff)
7178            .next()
7179            .unwrap()
7180            .unwrap_err();
7181        assert_eq!(err.class_name(), "InvalidNumberFormat", "{err}");
7182
7183        let count_ff = "pre\n{\"con_spec_version\":3,\"con_spec_minor\":1,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}\n10 10 10\n90 90 90\n\n\n1\x0c\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0\n";
7184        let err = crate::iterators::ConFrameIterator::new(count_ff)
7185            .next()
7186            .unwrap()
7187            .unwrap_err();
7188        assert_eq!(err.class_name(), "InvalidCount", "{err}");
7189    }
7190
7191    /// Exponent, float, and negative forms of an integer version field.
7192    /// The reader, the builder, and the RPC metadata parser agree on
7193    /// `tests/fixtures/version_field_forms.json`. The independent reader
7194    /// asserts the same file. CON-line2.22 rejects an integer literal
7195    /// above `u64` on `con_spec_version`, `con_spec_minor`, and
7196    /// `con_spec_patch` only, matched by exact name. A negative integer
7197    /// is rejected for `con_spec_minor` and `con_spec_patch`.
7198    /// `schema_version` `-1` parses. A decimal and `1e309` on
7199    /// `schema_version` stay accepted. `4294967295.0` stays an unknown
7200    /// major, so the u32 bound stays `<=`. Negative zero (`-0`, `-0.0`,
7201    /// `-0e0`) on `schema_version`, `generator_version`, and `abi_version`
7202    /// stays accepted. `con_spec_version` `-0` stays `UnsupportedVersion`
7203    /// `unsupported con_spec_version: 0`.
7204    #[test]
7205    fn integer_version_forms_agree_on_reader_builder_and_rpc() {
7206        let units = r#""units":{"length":"angstrom","energy":"eV","mass":"amu"},"sections":[]"#;
7207        let cases: Vec<serde_json::Value> =
7208            serde_json::from_str(include_str!("../tests/fixtures/version_field_forms.json"))
7209                .unwrap();
7210        for case in cases {
7211            let field = case["field"].as_str().unwrap();
7212            let token = case["token"].as_str().unwrap();
7213            let sentence = case.get("sentence").and_then(|value| value.as_str());
7214            let class = case.get("class").and_then(|value| value.as_str());
7215            let meta = if field == "con_spec_version" {
7216                format!(r#"{{"{field}":{token}}}"#)
7217            } else {
7218                format!(r#"{{"con_spec_version":4,{units},"{field}":{token}}}"#)
7219            };
7220            let text = format!(
7221                "t\n{meta}\n10 10 10\n90 90 90\n\n\n1\n1\n1.0\nH\nCoordinates of Component 1\n0 0 0 0 1\n"
7222            );
7223            let read = crate::iterators::ConFrameIterator::new(&text)
7224                .next()
7225                .unwrap();
7226            let mut builder = crate::types::ConFrameBuilder::new([10.0; 3], [90.0; 3]);
7227            let built = builder.set_metadata_json(&meta);
7228            let rpc = parse_metadata_map_with_minor_raw(&meta);
7229            let label = format!("{field} {token}");
7230            match (class, sentence) {
7231                (Some(class_name), Some(sentence)) => {
7232                    let err = read.expect_err(&label);
7233                    assert_eq!(err.class_name(), class_name, "{label}: {err}");
7234                    assert!(err.to_string().contains(sentence), "{label}: {err}");
7235                    let err = built.expect_err(&label);
7236                    assert_eq!(err.class_name(), class_name, "{label}: {err}");
7237                    assert!(err.to_string().contains(sentence), "{label}: {err}");
7238                    let err = rpc.expect_err(&label);
7239                    assert!(err.to_string().contains(sentence), "{label} rpc: {err}");
7240                }
7241                (None, Some(sentence)) => {
7242                    let err = read.expect_err(&label);
7243                    assert_eq!(err.class_name(), "InvalidMetadataJson", "{label}: {err}");
7244                    assert!(err.to_string().contains(sentence), "{label}: {err}");
7245                    let err = built.expect_err(&label);
7246                    assert_eq!(err.class_name(), "InvalidMetadataJson", "{label}: {err}");
7247                    assert!(err.to_string().contains(sentence), "{label}: {err}");
7248                    let err = rpc.expect_err(&label);
7249                    assert!(err.to_string().contains(sentence), "{label} rpc: {err}");
7250                }
7251                (None, None) => {
7252                    let rpc_label = format!("{label} rpc");
7253                    read.expect(&label);
7254                    built.expect(&label);
7255                    rpc.expect(&rpc_label);
7256                }
7257                (Some(class_name), None) => {
7258                    panic!("{label} names class {class_name} without a sentence");
7259                }
7260            }
7261        }
7262    }
7263}
7264
7265#[cfg(all(test, feature = "parallel"))]
7266mod newline_index_bench {
7267    use super::newline_index_at;
7268
7269    #[test]
7270    fn index_matches_memchr() {
7271        let mut bytes = vec![b'x'; 80_000];
7272        for index in (20..bytes.len()).step_by(23) {
7273            bytes[index] = b'\n';
7274        }
7275        let serial: Vec<usize> = memchr::memchr_iter(b'\n', &bytes).collect();
7276        assert_eq!(newline_index_at(&bytes, 0, 8), serial);
7277        // Above the 1 MiB serial cutoff, including a buffer of bare newlines.
7278        let mut long = Vec::new();
7279        while long.len() < (1 << 20) + 64 {
7280            long.extend_from_slice(b"01234567 1.25 -2.5 3.5 0 7\n");
7281        }
7282        let long_serial: Vec<usize> = memchr::memchr_iter(b'\n', &long).collect();
7283        assert_eq!(newline_index_at(&long, 40, 8), {
7284            let mut shifted = long_serial.clone();
7285            for offset in &mut shifted {
7286                *offset += 40;
7287            }
7288            shifted
7289        });
7290        let bare = vec![b'\n'; (1 << 20) + 64];
7291        let bare_serial: Vec<usize> = memchr::memchr_iter(b'\n', &bare).collect();
7292        assert_eq!(newline_index_at(&bare, 0, 8), bare_serial);
7293    }
7294}