Skip to main content

readcon_core/
writer.rs

1use crate::types::{
2    ConFrame, ConFrameBuilder, SECTION_CHARGES, SECTION_DISPLACEMENTS, SECTION_ENERGIES,
3    SECTION_FORCES, SECTION_MAGMOMS, SECTION_SPINS, SECTION_SPREADS, SECTION_VELOCITIES,
4    encode_fixed_bitmask, meta,
5};
6use serde_json::{Value, json};
7use std::collections::BTreeMap;
8use std::fs::{File, OpenOptions};
9use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
10use std::path::Path;
11
12/// Failure from [`ConFrameWriter`]. I/O stays distinct from format errors
13/// so `InvalidUnits` and `InvalidCount` remain distinguishable (CON-error.1).
14#[derive(Debug)]
15pub enum WriteError {
16    Io(io::Error),
17    Format(crate::error::ParseError),
18}
19
20#[cfg(all(test, loom))]
21mod loom_protocol_tests {
22    use loom::sync::atomic::{AtomicU64, Ordering};
23    use loom::sync::{Arc, Mutex};
24    use loom::thread;
25
26    #[test]
27    fn relaxed_snapshot_load_is_one_complete_element() {
28        loom::model(|| {
29            let source = Arc::new(AtomicU64::new(0x3ff0_0000_0000_0000));
30            let writer = Arc::clone(&source);
31            let store = thread::spawn(move || {
32                writer.store(0x4000_0000_0000_0000, Ordering::Relaxed);
33            });
34            let observed = source.load(Ordering::Relaxed);
35            store.join().unwrap();
36            assert!(observed == 0x3ff0_0000_0000_0000 || observed == 0x4000_0000_0000_0000);
37        });
38    }
39
40    #[derive(Clone)]
41    struct ModelCache {
42        generation: u64,
43        identities: Arc<Vec<usize>>,
44        retire_identities: Arc<Vec<usize>>,
45        coords: bool,
46    }
47
48    fn invalidate_if(generation: &AtomicU64, cache: &Mutex<Option<ModelCache>>, identity: usize) {
49        generation.fetch_add(1, Ordering::Release);
50        let mut slot = cache.lock().unwrap();
51        if slot
52            .as_ref()
53            .is_some_and(|entry| entry.retire_identities.contains(&identity))
54        {
55            slot.take();
56        } else if let Some(entry) = slot.as_mut() {
57            entry.generation = generation.load(Ordering::Acquire);
58        }
59    }
60
61    fn priced_coords(
62        generation: &AtomicU64,
63        cache: &Mutex<Option<ModelCache>>,
64        identities: &[usize],
65    ) -> bool {
66        let slot = cache.lock().unwrap();
67        let current = generation.load(Ordering::Acquire);
68        slot.as_ref().is_some_and(|entry| {
69            entry.generation == current && entry.identities.as_slice() == identities && entry.coords
70        })
71    }
72
73    #[test]
74    fn conditional_invalidation_while_pricing_cannot_publish_stale_lengths() {
75        loom::model(|| {
76            let generation = Arc::new(AtomicU64::new(1));
77            let cache = Arc::new(Mutex::new(None::<ModelCache>));
78            let (started, wait_started) = loom::sync::mpsc::channel();
79
80            let price_generation = Arc::clone(&generation);
81            let price_cache = Arc::clone(&cache);
82            let pricing = thread::spawn(move || {
83                let before = price_generation.load(Ordering::Acquire);
84                started.send(()).unwrap();
85                thread::yield_now();
86                let mut slot = price_cache.lock().unwrap();
87                let after = price_generation.load(Ordering::Acquire);
88                if before == after {
89                    *slot = Some(ModelCache {
90                        generation: after,
91                        identities: Arc::new(vec![11]),
92                        retire_identities: Arc::new(vec![11]),
93                        coords: true,
94                    });
95                }
96            });
97
98            let invalidate_generation = Arc::clone(&generation);
99            let invalidate_cache = Arc::clone(&cache);
100            let invalidating = thread::spawn(move || {
101                wait_started.recv().unwrap();
102                invalidate_if(&invalidate_generation, &invalidate_cache, 11);
103            });
104
105            pricing.join().unwrap();
106            invalidating.join().unwrap();
107            assert!(!priced_coords(&generation, &cache, &[11]));
108        });
109    }
110
111    #[test]
112    fn priced_coordinates_require_current_generation_and_full_identity() {
113        loom::model(|| {
114            let generation = AtomicU64::new(7);
115            let cache = Mutex::new(Some(ModelCache {
116                generation: 7,
117                identities: Arc::new(vec![11, 22]),
118                retire_identities: Arc::new(vec![11, 22]),
119                coords: true,
120            }));
121            assert!(priced_coords(&generation, &cache, &[11, 22]));
122            assert!(!priced_coords(&generation, &cache, &[11]));
123            assert!(!priced_coords(&generation, &cache, &[22, 11]));
124            generation.fetch_add(1, Ordering::Release);
125            assert!(!priced_coords(&generation, &cache, &[11, 22]));
126        });
127    }
128
129    #[test]
130    fn view_and_source_identities_retire_the_right_entry() {
131        loom::model(|| {
132            const SOURCE: usize = 11;
133            const VIEW: usize = 99;
134            let generation = AtomicU64::new(1);
135            let cache = Mutex::new(Some(ModelCache {
136                generation: 1,
137                identities: Arc::new(vec![SOURCE]),
138                retire_identities: Arc::new(vec![SOURCE]),
139                coords: true,
140            }));
141
142            // A source-keyed price survives destruction of its temporary
143            // snapshot view, at the new generation.
144            invalidate_if(&generation, &cache, VIEW);
145            assert!(priced_coords(&generation, &cache, &[SOURCE]));
146            invalidate_if(&generation, &cache, SOURCE);
147            assert!(!priced_coords(&generation, &cache, &[SOURCE]));
148
149            // Without a source PriceKey, the view itself is the retirement
150            // identity and dropping it clears the entry.
151            let current = generation.load(Ordering::Acquire);
152            *cache.lock().unwrap() = Some(ModelCache {
153                generation: current,
154                identities: Arc::new(vec![VIEW]),
155                retire_identities: Arc::new(vec![VIEW]),
156                coords: false,
157            });
158            invalidate_if(&generation, &cache, VIEW);
159            assert!(cache.lock().unwrap().is_none());
160        });
161    }
162}
163
164impl std::fmt::Display for WriteError {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        match self {
167            WriteError::Io(e) => write!(f, "{e}"),
168            WriteError::Format(e) => write!(f, "{e}"),
169        }
170    }
171}
172
173impl std::error::Error for WriteError {
174    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
175        match self {
176            WriteError::Io(e) => Some(e),
177            WriteError::Format(e) => Some(e),
178        }
179    }
180}
181
182impl From<io::Error> for WriteError {
183    fn from(e: io::Error) -> Self {
184        WriteError::Io(e)
185    }
186}
187
188impl From<WriteError> for io::Error {
189    fn from(e: WriteError) -> Self {
190        match e {
191            WriteError::Io(e) => e,
192            WriteError::Format(err) => io::Error::new(io::ErrorKind::InvalidData, err.to_string()),
193        }
194    }
195}
196
197/// Numeric text representation for CON frame fields.
198#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
199pub enum FloatFormat {
200    /// A fixed number of digits after the decimal point.
201    DecimalPlaces(usize),
202    /// The shortest scientific representation preserving each finite f64.
203    /// Signed zero is preserved; decimal precision does not limit this mode.
204    /// CON-num.6 (D13): the default writer round-trips binary64.
205    #[default]
206    RoundTrip,
207}
208
209/// A writer that can serialize and write `ConFrame` objects to any output stream.
210///
211/// This struct encapsulates a writer (like a file) and provides a high-level API
212/// for writing simulation frames in the `.con` format.
213///
214/// # Example
215/// ```no_run
216/// # use std::fs::File;
217/// # use readcon_core::types::ConFrame;
218/// # use readcon_core::writer::ConFrameWriter;
219/// # let frames: Vec<ConFrame> = Vec::new();
220/// let mut writer = ConFrameWriter::from_path("output.con").unwrap();
221/// writer.extend(frames.iter()).unwrap();
222/// ```
223pub struct ConFrameWriter<W: Write> {
224    writer: BufWriter<W>,
225    float_format: FloatFormat,
226    /// When true: sort metadata keys in JSON and emit sections in canonical
227    /// order (velocities, forces, energies). Opt-in. Float text follows
228    /// `float_format` (round-trip unless the caller asked for decimals).
229    canonical: bool,
230    /// Cache for the JSON metadata line: when consecutive frames share
231    /// the same (spec_version, sections-set, metadata) triple the
232    /// serialized JSON object is identical, so reusing the cached
233    /// string skips the per-frame `serde_json::Map::insert` rebuild
234    /// and re-serialisation. Hot for trajectory writes where every
235    /// frame has the same `units` / `potential` / `validate` keys.
236    metadata_cache: Option<MetadataCacheEntry>,
237    /// One frame of CON text. Filled then flushed with a single `write_all`
238    /// so the sink is not entered once per atom line.
239    scratch: Vec<u8>,
240    /// Reused shortest-round-trip buffer (ryu). One per writer, not per float.
241    ryu: ryu::Buffer,
242    /// Last x/y/z spellings. A value is formatted on the second sight and
243    /// copied after that, which is the common lattice column.
244    fmt_slot: [FmtSlot; 3],
245    /// Workers for one wide coordinate block. One keeps the serial loop.
246    atom_workers: usize,
247    /// Binding stamp for the next [`Self::write_frame`]. The atoms stay in
248    /// `frame`; only the header the writer emits changes.
249    bound: Option<BoundHeader>,
250    /// Wide-frame rows are formatted on several threads and copied into a
251    /// shared mapping of this file. `pwrite` of one inode does not scale.
252    stream_file: Option<File>,
253    /// Use the shared mapping even below the wide-frame cutoff. Tests compare
254    /// that path with a serial write for odd atom counts.
255    force_map: bool,
256    /// Leave the frame text in `scratch` instead of copying it into `writer`.
257    /// The format-only path reads `scratch` back, so the copy was a second
258    /// pass over the same bytes.
259    keep_scratch: bool,
260    /// `scratch` is the caller's exact output. Do not reserve past it.
261    exact_scratch: bool,
262    /// Put `bound` back after a frame so the next identical header can reuse it.
263    /// Only the direct eight-thread writer sets this. The serial writer
264    /// rebuilds the header, so its timing stays put.
265    keep_bound: bool,
266    bound_vel: Option<bool>,
267    bound_flags: Option<[bool; 8]>,
268    bound_line: Option<String>,
269    /// `Some(true)` once a reused header is known to have no lattice vectors.
270    bound_no_lattice: Option<bool>,
271    /// Frames this writer has taken so far: the 0-based index of the next
272    /// frame, which names that frame in a non-finite cell error.
273    frame_number: u64,
274    /// `(flag, sorted ids)` of the first frame, once one has been written.
275    persistent_ids: Option<(bool, Vec<u64>)>,
276}
277
278struct BoundHeader {
279    meta: BTreeMap<String, Value>,
280    spec: u32,
281    minor_raw: Option<Box<str>>,
282}
283
284/// One column of the round-trip float cache.
285#[derive(Clone, Copy)]
286struct FmtSlot {
287    bits: u64,
288    text: [u8; 24],
289    len: u8,
290    /// 0 empty, 1 seen once, 2 `text` holds the spelling.
291    state: u8,
292}
293
294impl FmtSlot {
295    const fn new() -> Self {
296        Self {
297            bits: 0,
298            text: [0; 24],
299            len: 0,
300            state: 0,
301        }
302    }
303}
304
305#[derive(Debug)]
306struct MetadataCacheEntry {
307    /// Snapshot of the inputs that fully determine the serialized JSON
308    /// metadata line. Cheap to clone; cheaper than re-serialising the
309    /// whole map on every frame.
310    spec_version: u32,
311    has_velocities: bool,
312    has_forces: bool,
313    has_energies: bool,
314    has_charges: bool,
315    has_spins: bool,
316    has_magmoms: bool,
317    has_displacements: bool,
318    has_spreads: bool,
319    metadata: std::collections::BTreeMap<String, serde_json::Value>,
320    minor_raw: Option<Box<str>>,
321    /// Cached serialised metadata line (without trailing newline).
322    serialized: String,
323}
324
325impl MetadataCacheEntry {
326    fn matches(
327        &self,
328        spec_version: u32,
329        sections: [bool; 8],
330        metadata: &std::collections::BTreeMap<String, serde_json::Value>,
331        minor_raw: Option<&str>,
332    ) -> bool {
333        let [
334            has_velocities,
335            has_forces,
336            has_energies,
337            has_charges,
338            has_spins,
339            has_magmoms,
340            has_displacements,
341            has_spreads,
342        ] = sections;
343        self.spec_version == spec_version
344            && self.has_velocities == has_velocities
345            && self.has_forces == has_forces
346            && self.has_energies == has_energies
347            && self.has_charges == has_charges
348            && self.has_spins == has_spins
349            && self.has_magmoms == has_magmoms
350            && self.has_displacements == has_displacements
351            && self.has_spreads == has_spreads
352            && self.minor_raw.as_deref() == minor_raw
353            && self.metadata.len() == metadata.len()
354            && self
355                .metadata
356                .iter()
357                .zip(metadata)
358                .all(|((ka, a), (kb, b))| ka == kb && metadata_value_eq(a, b))
359    }
360}
361
362pub(crate) fn serialize_json_object_with_minor_raw(
363    obj: serde_json::Map<String, serde_json::Value>,
364    minor_raw: Option<&str>,
365) -> String {
366    match minor_raw {
367        None => serde_json::Value::Object(obj).to_string(),
368        Some(digits) => {
369            let mut out = String::from("{");
370            for (idx, (k, v)) in obj.iter().enumerate() {
371                if idx > 0 {
372                    out.push(',');
373                }
374                out.push_str(&serde_json::to_string(k).expect("metadata key serializes"));
375                out.push(':');
376                if k == meta::CON_SPEC_MINOR {
377                    out.push_str(digits);
378                } else {
379                    out.push_str(&serde_json::to_string(v).expect("metadata value serializes"));
380                }
381            }
382            out.push('}');
383            out
384        }
385    }
386}
387
388#[cfg_attr(not(feature = "rpc"), allow(dead_code))]
389pub(crate) fn serialize_json_map_with_minor_raw(
390    map: &std::collections::BTreeMap<String, serde_json::Value>,
391    minor_raw: Option<&str>,
392) -> Result<String, serde_json::Error> {
393    match minor_raw {
394        None => serde_json::to_string(map),
395        Some(digits) => {
396            let mut out = String::from("{");
397            for (idx, (k, v)) in map.iter().enumerate() {
398                if idx > 0 {
399                    out.push(',');
400                }
401                out.push_str(&serde_json::to_string(k)?);
402                out.push(':');
403                if k == meta::CON_SPEC_MINOR {
404                    out.push_str(digits);
405                } else {
406                    out.push_str(&serde_json::to_string(v)?);
407                }
408            }
409            out.push('}');
410            Ok(out)
411        }
412    }
413}
414
415// Cache equality preserves the numeric representation, including signed zero,
416// throughout nested JSON values.
417fn metadata_value_eq(a: &serde_json::Value, b: &serde_json::Value) -> bool {
418    use serde_json::Value;
419    match (a, b) {
420        (Value::Number(a), Value::Number(b)) if a.is_f64() && b.is_f64() => {
421            a.as_f64().map(f64::to_bits) == b.as_f64().map(f64::to_bits)
422        }
423        (Value::Array(a), Value::Array(b)) => {
424            a.len() == b.len() && a.iter().zip(b).all(|(a, b)| metadata_value_eq(a, b))
425        }
426        (Value::Object(a), Value::Object(b)) => {
427            a.len() == b.len()
428                && a.iter()
429                    .all(|(key, a)| b.get(key).is_some_and(|b| metadata_value_eq(a, b)))
430        }
431        _ => a == b,
432    }
433}
434
435/// CON-section.16. Minor 2 and later must list, in `section_arity`, every
436/// emitted section that minor 1 does not reserve.
437fn require_unreserved_section_arity(
438    spec_version: u32,
439    minor: u64,
440    sections: &[serde_json::Value],
441    metadata: &serde_json::Map<String, serde_json::Value>,
442) -> Result<(), WriteError> {
443    // Major 4 reserves the table at minor 0. Major 3 reserved it at minor 1.
444    let floor = if spec_version >= 4 { 0 } else { 1 };
445    if minor <= floor {
446        return Ok(());
447    }
448    for name in sections.iter().filter_map(|value| value.as_str()) {
449        if crate::types::reserved_section_value_arity(name).is_some() {
450            continue;
451        }
452        let listed = metadata
453            .get(meta::SECTION_ARITY)
454            .and_then(|value| value.as_object())
455            .and_then(|obj| obj.get(name))
456            .and_then(|value| value.as_u64())
457            .is_some_and(|n| n >= 1);
458        if !listed {
459            return Err(WriteError::Format(
460                crate::error::ParseError::ValidationError(format!(
461                    "a minor above the reserved table must list {name} in section_arity"
462                )),
463            ));
464        }
465    }
466    Ok(())
467}
468
469/// Puts a streamed frame back to the last complete prefix when the
470/// write fails after the file has already grown.
471struct StreamOut {
472    file: File,
473    start: u64,
474    armed: bool,
475}
476
477impl Drop for StreamOut {
478    fn drop(&mut self) {
479        if !self.armed {
480            return;
481        }
482        let _ = self.file.set_len(self.start);
483        let _ = self.file.seek(SeekFrom::Start(self.start));
484    }
485}
486
487// General implementation for any type that implements `Write`.
488impl<W: Write> ConFrameWriter<W> {
489    /// Creates a new `ConFrameWriter` that wraps a given writer.
490    ///
491    /// # Arguments
492    ///
493    /// * `writer` - Any type that implements `std::io::Write`, e.g., a `File`.
494    pub fn new(writer: W) -> Self {
495        Self::with_float_format(writer, FloatFormat::default())
496    }
497
498    /// Creates a new `ConFrameWriter` with a custom floating-point precision.
499    ///
500    /// # Arguments
501    ///
502    /// * `writer` - Any type that implements `std::io::Write`.
503    /// * `precision` - Number of decimal places for floating-point output.
504    pub fn with_precision(writer: W, precision: usize) -> Self {
505        Self::with_float_format(writer, FloatFormat::DecimalPlaces(precision))
506    }
507
508    /// Creates a writer with an explicit numeric text representation.
509    ///
510    /// `FloatFormat::RoundTrip` retains small forces and coordinates exactly.
511    /// Metadata floats use the JSON serializer independently of this setting.
512    pub fn with_float_format(writer: W, float_format: FloatFormat) -> Self {
513        Self {
514            writer: BufWriter::new(writer),
515            float_format,
516            canonical: false,
517            metadata_cache: None,
518            scratch: Vec::with_capacity(16 * 1024),
519            ryu: ryu::Buffer::new(),
520            fmt_slot: [FmtSlot::new(); 3],
521            atom_workers: 1,
522            bound: None,
523            stream_file: None,
524            force_map: false,
525            keep_scratch: false,
526            exact_scratch: false,
527            keep_bound: false,
528            bound_vel: None,
529            bound_flags: None,
530            bound_line: None,
531            bound_no_lattice: None,
532            frame_number: 0,
533            persistent_ids: None,
534        }
535    }
536
537    /// CON-id.11. A true `ids_persistent` on any frame requires the same
538    /// flag and the same id set on every frame.
539    fn note_persistent_ids(&mut self, frame: &crate::types::ConFrame) -> Result<(), WriteError> {
540        let flag = frame
541            .header
542            .metadata
543            .ids_persistent_flag()
544            .map_err(WriteError::Format)?;
545        let mut ids = Vec::new();
546        if flag {
547            ids = frame.atom_data.iter().map(|atom| atom.atom_id).collect();
548            ids.sort_unstable();
549            if ids.windows(2).any(|pair| pair[0] == pair[1]) {
550                return Err(WriteError::Format(
551                    crate::error::ParseError::ValidationError(
552                        "ids_persistent requires each id once in the frame".into(),
553                    ),
554                ));
555            }
556        }
557        match &self.persistent_ids {
558            None => self.persistent_ids = Some((flag, ids)),
559            Some((seen_flag, seen))
560                if (*seen_flag || flag) && (!*seen_flag || !flag || seen != &ids) =>
561            {
562                return Err(WriteError::Format(
563                    crate::error::ParseError::ValidationError(
564                        "ids_persistent requires the same ids in every frame".into(),
565                    ),
566                ));
567            }
568            Some(_) => {}
569        }
570        Ok(())
571    }
572
573    fn retain_scratch(mut self, on: bool) -> Self {
574        self.keep_scratch = on;
575        self
576    }
577
578    /// Format a wide coordinate block on `n` workers.
579    ///
580    /// `n < 2` leaves the serial loop. The bytes match that loop: each
581    /// worker formats a contiguous run of atoms and the runs are joined
582    /// in file order.
583    pub fn parallel_atoms(mut self, n: usize) -> Self {
584        self.atom_workers = n.max(1);
585        self
586    }
587
588    /// Copy formatted rows into a shared mapping of `stream_file`.
589    ///
590    /// The wide path does this on its own when a spare physical core is
591    /// free. Tests turn it on for short frames so an odd atom count still
592    /// takes the mapping, including on a runner with no spare core.
593    pub fn map_rows(mut self, on: bool) -> Self {
594        self.force_map = on;
595        self
596    }
597
598    /// File the mapping copies into. Open it read/write; `map_rows` selects
599    /// the mapping even when [`Self::parallel_atoms`] would otherwise `pwrite`.
600    pub fn mapped_file(mut self, file: File) -> Self {
601        self.stream_file = Some(file);
602        self
603    }
604
605    /// Opt-in **canonical** serialization: BTree-ordered metadata keys in JSON,
606    /// fixed section order. Use for corpus
607    /// materialization and content-stable hashes; not required for on-disk fidelity
608    /// of spans preserved from `next_with_raw_span`.
609    pub fn canonical(mut self, on: bool) -> Self {
610        self.set_canonical(on);
611        self
612    }
613
614    /// Set or clear canonical mode on an existing writer (C ABI / FFI).
615    pub fn set_canonical(&mut self, on: bool) {
616        self.canonical = on;
617        if on {
618            self.metadata_cache = None;
619        }
620    }
621
622    /// Whether canonical serialization is enabled.
623    pub fn is_canonical(&self) -> bool {
624        self.canonical
625    }
626
627    fn refresh_metadata_cache(
628        &mut self,
629        spec_version: u32,
630        metadata: &BTreeMap<String, Value>,
631        minor_raw: Option<&str>,
632        present: [bool; 8],
633    ) -> Result<(), WriteError> {
634        let [
635            has_vel,
636            has_frc,
637            has_eng,
638            has_chg,
639            has_spn,
640            has_mm,
641            has_dsp,
642            has_spr,
643        ] = present;
644        let cache_hit = !self.canonical
645            && self.metadata_cache.as_ref().is_some_and(|c| {
646                c.matches(
647                    spec_version,
648                    [
649                        has_vel, has_frc, has_eng, has_chg, has_spn, has_mm, has_dsp, has_spr,
650                    ],
651                    metadata,
652                    minor_raw,
653                )
654            });
655        if cache_hit {
656            return Ok(());
657        }
658
659        let mut meta_obj = serde_json::Map::new();
660        meta_obj.insert(meta::CON_SPEC_VERSION.into(), json!(spec_version));
661        let mut sections = Vec::new();
662        if has_vel {
663            sections.push(json!(SECTION_VELOCITIES));
664        }
665        if has_frc {
666            sections.push(json!(SECTION_FORCES));
667        }
668        if has_eng {
669            sections.push(json!(SECTION_ENERGIES));
670        }
671        if has_chg {
672            sections.push(json!(SECTION_CHARGES));
673        }
674        if has_spn {
675            sections.push(json!(SECTION_SPINS));
676        }
677        if has_mm {
678            sections.push(json!(SECTION_MAGMOMS));
679        }
680        if has_dsp {
681            sections.push(json!(SECTION_DISPLACEMENTS));
682        }
683        if has_spr {
684            sections.push(json!(SECTION_SPREADS));
685        }
686        let validate = metadata
687            .get(meta::VALIDATE)
688            .and_then(|value| value.as_bool())
689            .unwrap_or(false);
690        if !sections.is_empty() || validate {
691            meta_obj.insert(meta::SECTIONS.into(), json!(sections));
692        }
693        for (k, v) in metadata {
694            if k == meta::CON_SPEC_VERSION || k == meta::SECTIONS {
695                continue;
696            }
697            meta_obj.insert(k.clone(), v.clone());
698        }
699        if spec_version >= 3 {
700            match meta_obj.get(meta::UNITS) {
701                None => {
702                    return Err(WriteError::Format(crate::error::ParseError::InvalidUnits(
703                        "con_spec_version >= 3 requires units.length and units.energy".into(),
704                    )));
705                }
706                Some(u) => {
707                    crate::units::validate_units_metadata_for_version(spec_version, u).map_err(
708                        |e| {
709                            WriteError::Format(crate::error::ParseError::InvalidUnits(
710                                e.to_string(),
711                            ))
712                        },
713                    )?;
714                }
715            }
716        }
717        if spec_version >= 2
718            && let Some(units) = meta_obj.get(meta::UNITS)
719        {
720            crate::units::enforce_velocity_precedence(spec_version, units).map_err(|e| {
721                WriteError::Format(crate::error::ParseError::InvalidUnits(e.to_string()))
722            })?;
723        }
724        if let Some(u) = meta_obj.get(meta::UNITS).cloned() {
725            // D11: an invalid unit fails the write. Do not substitute a default.
726            let c = crate::units::canonicalize_units_object_for_version(spec_version, &u).map_err(
727                |e| WriteError::Format(crate::error::ParseError::InvalidUnits(e.to_string())),
728            )?;
729            meta_obj.insert(meta::UNITS.into(), c);
730        }
731        let minor = if minor_raw.is_some() {
732            crate::types::SATURATED_SPEC_MINOR
733        } else {
734            metadata
735                .get(meta::CON_SPEC_MINOR)
736                .and_then(|v| v.as_u64())
737                .unwrap_or(0)
738        };
739        if spec_version >= 4 && has_vel {
740            let time_ok = meta_obj
741                .get(meta::UNITS)
742                .and_then(|u| u.get("time"))
743                .and_then(|v| v.as_str())
744                .is_some_and(|s| !s.trim().is_empty());
745            if !time_ok {
746                return Err(WriteError::Format(crate::error::ParseError::InvalidUnits(
747                    "major >= 4 requires units.time when a velocities section is present".into(),
748                )));
749            }
750        }
751        // A minor above the one that reserves the section table lists every
752        // other section (CON-section.16). Reserved names need no entry.
753        require_unreserved_section_arity(spec_version, minor, &sections, &meta_obj)?;
754        let serialized = serialize_json_object_with_minor_raw(meta_obj, minor_raw);
755        self.metadata_cache = Some(MetadataCacheEntry {
756            spec_version,
757            has_velocities: has_vel,
758            has_forces: has_frc,
759            has_energies: has_eng,
760            has_charges: has_chg,
761            has_spins: has_spn,
762            has_magmoms: has_mm,
763            has_displacements: has_dsp,
764            has_spreads: has_spr,
765            metadata: metadata.clone(),
766            minor_raw: minor_raw.map(Box::from),
767            serialized,
768        });
769        Ok(())
770    }
771
772    /// Writes `frame` with the binding metadata stamp and the original atoms.
773    ///
774    /// The stamp is installed for the duration of the write and then put back.
775    /// Atoms are not rebuilt.
776    pub fn write_frame_binding(&mut self, frame: &mut ConFrame) -> Result<(), WriteError> {
777        self.write_frame_bound(frame)
778    }
779
780    /// [`Self::write_frame_binding`] without a mutable frame.
781    ///
782    /// The header the file emits is the binding stamp. `frame`'s atoms and
783    /// its stored header are left as the caller passed them, so a wide frame
784    /// is not cloned before its rows are formatted.
785    pub fn write_frame_bound(&mut self, frame: &ConFrame) -> Result<(), WriteError> {
786        let spec = binding_spec(frame);
787        let flags = [
788            frame.has_velocities(),
789            frame.has_forces(),
790            frame.has_energies(),
791            frame.has_charges(),
792            frame.has_spins(),
793            frame.has_magmoms(),
794            frame.has_displacements(),
795            frame.has_spreads(),
796        ];
797        let line = frame.header.prebox_header.metadata_line();
798        // Energy, neb_bead, and every other metadata key live in the header.
799        // A matching atom skeleton is not the same header.
800        let (mut incoming, minor_raw) = binding_metadata_with_minor_raw(frame);
801        if spec < 4 {
802            incoming.remove(meta::CON_SPEC_PATCH);
803        }
804        let meta_same = self.bound.as_ref().is_some_and(|item| {
805            item.spec == spec && item.meta == incoming && item.minor_raw == minor_raw
806        });
807        let reuse = self.exact_scratch
808            && meta_same
809            && self.bound_flags == Some(flags)
810            && self.bound_line.as_deref() == Some(line);
811        if !reuse {
812            self.bound = Some(BoundHeader {
813                meta: incoming,
814                spec,
815                minor_raw,
816            });
817            if self.exact_scratch {
818                // The cached JSON also lists the sections. Drop it whenever
819                // this frame is not the one that filled the cache.
820                if !meta_same || self.bound_flags != Some(flags) {
821                    self.metadata_cache = None;
822                }
823                self.bound_flags = Some(flags);
824                self.bound_vel = Some(flags[0]);
825                self.bound_line = Some(line.to_string());
826                self.bound_no_lattice = None;
827            }
828        }
829        self.keep_bound = self.exact_scratch;
830        self.write_frame(frame)
831    }
832
833    /// Writes a single `ConFrame` to the output stream.
834    pub fn write_frame(&mut self, frame: &ConFrame) -> Result<(), WriteError> {
835        let zero_frame = frame.header.natm_types == 0
836            && frame.atom_data.is_empty()
837            && frame.header.natms_per_type.is_empty()
838            && frame.header.masses_per_type.is_empty();
839        if zero_frame && !frame.header.sections.is_empty() {
840            return Err(WriteError::Format(crate::error::ParseError::InvalidCount(
841                "a zero-atom frame cannot declare sections".into(),
842            )));
843        }
844        if !zero_frame
845            && (frame.header.natm_types == 0
846                || frame.atom_data.is_empty()
847                || frame.header.natms_per_type.contains(&0))
848        {
849            return Err(WriteError::Format(crate::error::ParseError::InvalidCount(
850                "each per-type count must be >= 1".into(),
851            )));
852        }
853        // The component loops slice the atom list by these counts. A header
854        // that no longer matches the atoms, say after an atom was removed,
855        // is an error and not an out-of-range slice.
856        let declared = frame
857            .header
858            .natms_per_type
859            .iter()
860            .try_fold(0usize, |sum, &count| sum.checked_add(count));
861        if declared != Some(frame.atom_data.len()) {
862            return Err(WriteError::Format(crate::error::ParseError::InvalidCount(
863                format!(
864                    "natms_per_type declares {} atoms but the frame holds {}",
865                    declared
866                        .map_or_else(|| "an overflowing number of".to_string(), |n| n.to_string()),
867                    frame.atom_data.len()
868                ),
869            )));
870        }
871        check_position_rows(frame)?;
872        // A uniform trajectory either has lattice vectors on every frame
873        // or on none. The first frame decides; the rest read lines 3-4.
874        let (boxl, angles) = if self.keep_bound && self.bound_no_lattice == Some(true) {
875            (frame.header.boxl, frame.header.angles)
876        } else {
877            match frame.header.lattice_vectors() {
878                Some(vecs) => {
879                    self.bound_no_lattice = Some(false);
880                    crate::types::lengths_and_angles(vecs)
881                }
882                None => {
883                    self.bound_no_lattice = Some(true);
884                    (frame.header.boxl, frame.header.angles)
885                }
886            }
887        };
888        // A cell that is not finite is never written: the line would read
889        // back as NaN or inf, which a reader rejects. Six comparisons per
890        // frame, before this call takes any state of the writer.
891        crate::types::check_cell_finite(&boxl, "boxl", &angles, "angles")
892            .map_err(|error| WriteError::Format(error.in_frame(self.frame_number)))?;
893        self.frame_number += 1;
894        #[cfg(feature = "parallel")]
895        let parallel_rows = self.atom_workers >= 2 && frame.atom_data.len() >= WIDE_ATOM_GRAIN;
896        #[cfg(not(feature = "parallel"))]
897        let parallel_rows = false;
898        // The direct writer already required dense ids while pricing the
899        // trajectory. Scanning them again was on the 8-thread wall.
900        self.note_persistent_ids(frame)?;
901        // A frame read from a file keeps the ids it had, including repeats
902        // (CON-id.13). A frame built in memory must still emit unique ids
903        // (CON-id.3).
904        if !self.exact_scratch && !frame.header.ids_from_file {
905            if parallel_rows {
906                // Ids are unique across the whole frame. A per-component pass
907                // treats an id that restarts at the next element as dense.
908                if !ids_are_dense(&frame.atom_data, self.atom_workers) {
909                    ensure_unique_ids(&frame.atom_data, self.atom_workers)?;
910                }
911            } else {
912                ensure_unique_ids(&frame.atom_data, 1)?;
913            }
914        }
915        let prec = self.float_format;
916        let stream_file = self.stream_file.take();
917        let keep_bound = self.keep_bound;
918        let bound = self.bound.take();
919        let spec_version = bound
920            .as_ref()
921            .map(|item| item.spec)
922            .unwrap_or(frame.header.spec_version);
923        // The direct writer keeps one header for a uniform trajectory.
924        // Rebuilding the map on every frame showed up in the 8-thread wall.
925        let skip_refresh = keep_bound && self.metadata_cache.is_some();
926        if !skip_refresh {
927            let owned_meta;
928            let (metadata, minor_raw) = if let Some(item) = bound.as_ref() {
929                (&item.meta, item.minor_raw.as_deref())
930            } else {
931                owned_meta = frame.header.metadata.to_map();
932                (&owned_meta, frame.header.metadata.huge_minor_raw())
933            };
934            if spec_version >= 2 {
935                self.refresh_metadata_cache(
936                    spec_version,
937                    metadata,
938                    minor_raw,
939                    [
940                        frame.has_velocities(),
941                        frame.has_forces(),
942                        frame.has_energies(),
943                        frame.has_charges(),
944                        frame.has_spins(),
945                        frame.has_magmoms(),
946                        frame.has_displacements(),
947                        frame.has_spreads(),
948                    ],
949                )?;
950            }
951        }
952        if keep_bound {
953            self.bound = bound;
954        }
955        let atoms = frame.atom_data.len();
956        let [
957            has_vel,
958            has_frc,
959            has_eng,
960            has_chg,
961            has_spn,
962            has_mm,
963            has_dsp,
964            has_spr,
965        ] = if self.keep_bound {
966            self.bound_flags.unwrap_or([
967                frame.has_velocities(),
968                frame.has_forces(),
969                frame.has_energies(),
970                frame.has_charges(),
971                frame.has_spins(),
972                frame.has_magmoms(),
973                frame.has_displacements(),
974                frame.has_spreads(),
975            ])
976        } else {
977            [
978                frame.has_velocities(),
979                frame.has_forces(),
980                frame.has_energies(),
981                frame.has_charges(),
982                frame.has_spins(),
983                frame.has_magmoms(),
984                frame.has_displacements(),
985                frame.has_spreads(),
986            ]
987        };
988        let mut blocks = 1usize;
989        if has_vel {
990            blocks += 1;
991        }
992        if has_frc {
993            blocks += 1;
994        }
995        if has_eng {
996            blocks += 1;
997        }
998        if has_chg {
999            blocks += 1;
1000        }
1001        if has_spn {
1002            blocks += 1;
1003        }
1004        if has_mm {
1005            blocks += 1;
1006        }
1007        if has_dsp {
1008            blocks += 1;
1009        }
1010        if has_spr {
1011            blocks += 1;
1012        }
1013        let mut stream_out = match stream_file {
1014            Some(mut file) => {
1015                let start = file.stream_position().map_err(WriteError::Io)?;
1016                Some(StreamOut {
1017                    file,
1018                    start,
1019                    armed: true,
1020                })
1021            }
1022            None => None,
1023        };
1024        // An exact output slice is already the size of the frame text.
1025        // Reserving the loose upper bound would reallocate that slice.
1026        if !self.exact_scratch {
1027            self.scratch
1028                .reserve(256 + atoms.saturating_mul(64).saturating_mul(blocks));
1029        }
1030        if !self.keep_scratch {
1031            self.scratch.clear();
1032        }
1033        push_str_line(&mut self.scratch, &frame.header.prebox_header.user);
1034        if spec_version < 2 {
1035            // Spec 1 line 2 is free text. Do not re-emit JSON major 0 or 1 (D15).
1036            push_str_line(
1037                &mut self.scratch,
1038                frame.header.prebox_header.metadata_line(),
1039            );
1040        } else {
1041            let line = self
1042                .metadata_cache
1043                .as_ref()
1044                .expect("metadata_cache populated above")
1045                .serialized
1046                .as_bytes();
1047            self.scratch.extend_from_slice(line);
1048            self.scratch.push(b'\n');
1049        }
1050        {
1051            let buf = &mut self.scratch;
1052            let ryu = &mut self.ryu;
1053            let slots = &mut self.fmt_slot;
1054
1055            // --- Write the 9-line Header ---
1056            push_f64(buf, ryu, boxl[0], prec);
1057            buf.push(b' ');
1058            push_f64(buf, ryu, boxl[1], prec);
1059            buf.push(b' ');
1060            push_f64(buf, ryu, boxl[2], prec);
1061            buf.push(b'\n');
1062            push_f64(buf, ryu, angles[0], prec);
1063            buf.push(b' ');
1064            push_f64(buf, ryu, angles[1], prec);
1065            buf.push(b' ');
1066            push_f64(buf, ryu, angles[2], prec);
1067            buf.push(b'\n');
1068            push_str_line(buf, &frame.header.postbox_header[0]);
1069            push_str_line(buf, &frame.header.postbox_header[1]);
1070            push_u64(buf, frame.header.natm_types as u64);
1071            buf.push(b'\n');
1072
1073            for (i, n) in frame.header.natms_per_type.iter().enumerate() {
1074                if i > 0 {
1075                    buf.push(b' ');
1076                }
1077                push_u64(buf, *n as u64);
1078            }
1079            buf.push(b'\n');
1080
1081            for (i, m) in frame.header.masses_per_type.iter().enumerate() {
1082                if i > 0 {
1083                    buf.push(b' ');
1084                }
1085                push_f64(buf, ryu, *m, prec);
1086            }
1087            buf.push(b'\n');
1088
1089            // --- Write the Atom Data ---
1090            // Velocities are formatted in this same pass. The section is
1091            // still emitted after every coordinate block, so the bytes
1092            // match a second scan.
1093            let save_velocity = has_vel;
1094            // A short frame writes velocity lines straight into `buf`
1095            // after the coordinates. Buffering them and copying the
1096            // bytes was a second pass over about half a convel file.
1097            let direct_velocity = save_velocity
1098                && self.atom_workers < 2
1099                && !self.force_map
1100                && frame
1101                    .header
1102                    .natms_per_type
1103                    .iter()
1104                    .all(|count| *count < WIDE_ATOM_GRAIN);
1105            // One buffer per component, kept on this thread. A fresh Vec
1106            // for every frame was an allocation on the velocity write.
1107            std::thread_local! {
1108                static VEL_ROWS: std::cell::RefCell<Vec<Vec<u8>>> =
1109                    const { std::cell::RefCell::new(Vec::new()) };
1110            }
1111            struct RestoreRows(Vec<Vec<u8>>);
1112            impl Drop for RestoreRows {
1113                fn drop(&mut self) {
1114                    let rows = std::mem::take(&mut self.0);
1115                    VEL_ROWS.with(|cell| *cell.borrow_mut() = rows);
1116                }
1117            }
1118            let mut velocity_rows = if direct_velocity {
1119                None
1120            } else {
1121                Some(RestoreRows(VEL_ROWS.with(|cell| cell.take())))
1122            };
1123            if let Some(velocity_rows) = velocity_rows.as_mut() {
1124                let ntypes = frame.header.natms_per_type.len();
1125                if velocity_rows.0.len() < ntypes {
1126                    velocity_rows.0.resize_with(ntypes, Vec::new);
1127                }
1128                for row in &mut velocity_rows.0 {
1129                    row.clear();
1130                }
1131            }
1132            let coord_buf = frame_coords(frame)?;
1133            let mut atom_idx_offset = 0;
1134            for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate() {
1135                let symbol = &frame.atom_data[atom_idx_offset].symbol;
1136                push_str_line(buf, symbol);
1137                push_component_line(buf, "Coordinates of Component", type_idx);
1138
1139                let mapped = self.force_map
1140                    || (self.atom_workers >= 2 && num_atoms_in_type >= WIDE_ATOM_GRAIN);
1141                append_coord_rows(
1142                    buf,
1143                    LineFmt { ryu, slots },
1144                    &frame.atom_data[atom_idx_offset..atom_idx_offset + num_atoms_in_type],
1145                    &coord_buf[atom_idx_offset * 3..(atom_idx_offset + num_atoms_in_type) * 3],
1146                    prec,
1147                    spec_version,
1148                    self.atom_workers,
1149                    AppendOut {
1150                        mapped,
1151                        force_map: self.force_map,
1152                        stream: stream_out.as_mut().map(|out| &mut out.file),
1153                        vel: if save_velocity && !direct_velocity {
1154                            Some(&mut velocity_rows.as_mut().unwrap().0[type_idx])
1155                        } else {
1156                            None
1157                        },
1158                    },
1159                )?;
1160                atom_idx_offset += num_atoms_in_type;
1161            }
1162
1163            // --- Write optional velocity section ---
1164            if has_vel {
1165                buf.push(b'\n');
1166
1167                let mut vel_idx_offset = 0;
1168                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1169                {
1170                    let symbol = &frame.atom_data[vel_idx_offset].symbol;
1171                    push_str_line(buf, symbol);
1172                    push_component_line(buf, "Velocities of Component", type_idx);
1173                    let atoms =
1174                        &frame.atom_data[vel_idx_offset..vel_idx_offset + num_atoms_in_type];
1175                    if direct_velocity {
1176                        append_velocity_lines(buf, ryu, atoms, prec, spec_version);
1177                    } else {
1178                        buf.extend_from_slice(&velocity_rows.as_ref().unwrap().0[type_idx]);
1179                    }
1180                    vel_idx_offset += num_atoms_in_type;
1181                }
1182            }
1183
1184            // --- Write optional force section ---
1185            if has_frc {
1186                buf.push(b'\n');
1187
1188                let mut force_idx_offset = 0;
1189                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1190                {
1191                    let symbol = &frame.atom_data[force_idx_offset].symbol;
1192                    push_str_line(buf, symbol);
1193                    push_component_line(buf, "Forces of Component", type_idx);
1194
1195                    for i in 0..num_atoms_in_type {
1196                        let atom = &frame.atom_data[force_idx_offset + i];
1197                        let [fx, fy, fz] = atom.force().unwrap_or([0.0; 3]);
1198                        push_xyz_line(
1199                            buf,
1200                            ryu,
1201                            slots,
1202                            [fx, fy, fz],
1203                            prec,
1204                            written_fixed_flag(atom.fixed(), spec_version),
1205                            atom.atom_id,
1206                        );
1207                    }
1208                    force_idx_offset += num_atoms_in_type;
1209                }
1210            }
1211
1212            // --- Write optional energies section ---
1213            if has_eng {
1214                buf.push(b'\n');
1215
1216                let mut energy_idx_offset = 0;
1217                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1218                {
1219                    let symbol = &frame.atom_data[energy_idx_offset].symbol;
1220                    push_str_line(buf, symbol);
1221                    push_component_line(buf, "Energies of Component", type_idx);
1222
1223                    for i in 0..num_atoms_in_type {
1224                        let atom = &frame.atom_data[energy_idx_offset + i];
1225                        let e = atom.energy().unwrap_or(0.0);
1226                        push_scalar_line(
1227                            buf,
1228                            ryu,
1229                            slots,
1230                            e,
1231                            prec,
1232                            written_fixed_flag(atom.fixed(), spec_version),
1233                            atom.atom_id,
1234                        );
1235                    }
1236                    energy_idx_offset += num_atoms_in_type;
1237                }
1238            }
1239
1240            if has_chg {
1241                buf.push(b'\n');
1242                let mut off = 0;
1243                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1244                {
1245                    let symbol = &frame.atom_data[off].symbol;
1246                    push_str_line(buf, symbol);
1247                    push_component_line(buf, "Charges of Component", type_idx);
1248                    for i in 0..num_atoms_in_type {
1249                        let atom = &frame.atom_data[off + i];
1250                        let q = atom.charge().unwrap_or(0.0);
1251                        push_scalar_line(
1252                            buf,
1253                            ryu,
1254                            slots,
1255                            q,
1256                            prec,
1257                            written_fixed_flag(atom.fixed(), spec_version),
1258                            atom.atom_id,
1259                        );
1260                    }
1261                    off += num_atoms_in_type;
1262                }
1263            }
1264
1265            if has_spn {
1266                buf.push(b'\n');
1267                let mut off = 0;
1268                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1269                {
1270                    let symbol = &frame.atom_data[off].symbol;
1271                    push_str_line(buf, symbol);
1272                    push_component_line(buf, "Spins of Component", type_idx);
1273                    for i in 0..num_atoms_in_type {
1274                        let atom = &frame.atom_data[off + i];
1275                        let s = atom.spin().unwrap_or(0.0);
1276                        push_scalar_line(
1277                            buf,
1278                            ryu,
1279                            slots,
1280                            s,
1281                            prec,
1282                            written_fixed_flag(atom.fixed(), spec_version),
1283                            atom.atom_id,
1284                        );
1285                    }
1286                    off += num_atoms_in_type;
1287                }
1288            }
1289
1290            if has_mm {
1291                buf.push(b'\n');
1292                let mut off = 0;
1293                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1294                {
1295                    let symbol = &frame.atom_data[off].symbol;
1296                    push_str_line(buf, symbol);
1297                    push_component_line(buf, "Magmoms of Component", type_idx);
1298                    for i in 0..num_atoms_in_type {
1299                        let atom = &frame.atom_data[off + i];
1300                        let [mx, my, mz] = atom.magmom().unwrap_or([0.0; 3]);
1301                        push_xyz_line(
1302                            buf,
1303                            ryu,
1304                            slots,
1305                            [mx, my, mz],
1306                            prec,
1307                            written_fixed_flag(atom.fixed(), spec_version),
1308                            atom.atom_id,
1309                        );
1310                    }
1311                    off += num_atoms_in_type;
1312                }
1313            }
1314
1315            if has_dsp {
1316                buf.push(b'\n');
1317                let mut off = 0;
1318                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1319                {
1320                    let symbol = &frame.atom_data[off].symbol;
1321                    push_str_line(buf, symbol);
1322                    push_component_line(buf, "Displacements of Component", type_idx);
1323                    for i in 0..num_atoms_in_type {
1324                        let atom = &frame.atom_data[off + i];
1325                        let [dx, dy, dz] = atom.displacement().unwrap_or([0.0; 3]);
1326                        push_xyz_line(
1327                            buf,
1328                            ryu,
1329                            slots,
1330                            [dx, dy, dz],
1331                            prec,
1332                            written_fixed_flag(atom.fixed(), spec_version),
1333                            atom.atom_id,
1334                        );
1335                    }
1336                    off += num_atoms_in_type;
1337                }
1338            }
1339
1340            if has_spr {
1341                buf.push(b'\n');
1342                let mut off = 0;
1343                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
1344                {
1345                    let symbol = &frame.atom_data[off].symbol;
1346                    push_str_line(buf, symbol);
1347                    push_component_line(buf, "Spreads of Component", type_idx);
1348                    for i in 0..num_atoms_in_type {
1349                        let atom = &frame.atom_data[off + i];
1350                        let [sx, sy, sz] = atom.spread().unwrap_or([0.0; 3]);
1351                        if !crate::types::spread_row_ok([sx, sy, sz]) {
1352                            let err = if sx.is_finite() && sy.is_finite() && sz.is_finite() {
1353                                crate::types::invalid_spread(off + i)
1354                            } else {
1355                                crate::error::ParseError::NonFiniteValue(format!(
1356                                    "spreads atom {}",
1357                                    off + i
1358                                ))
1359                            };
1360                            return Err(WriteError::Format(err));
1361                        }
1362                        push_xyz_line(
1363                            buf,
1364                            ryu,
1365                            slots,
1366                            [sx, sy, sz],
1367                            prec,
1368                            written_fixed_flag(atom.fixed(), spec_version),
1369                            atom.atom_id,
1370                        );
1371                    }
1372                    off += num_atoms_in_type;
1373                }
1374            }
1375        }
1376
1377        if self.keep_scratch {
1378            if let Some(out) = stream_out.as_mut() {
1379                out.armed = false;
1380            }
1381            return Ok(());
1382        }
1383        if let Some(out) = stream_out.as_mut() {
1384            if !self.scratch.is_empty() {
1385                out.file.write_all(&self.scratch)?;
1386                self.scratch.clear();
1387            }
1388            out.file.flush()?;
1389            out.armed = false;
1390        } else if self.scratch.len() >= 64 * 1024 {
1391            // BufWriter would copy this frame through an 8 KiB buffer.
1392            self.writer.flush()?;
1393            self.writer.get_mut().write_all(&self.scratch)?;
1394        } else {
1395            self.writer.write_all(&self.scratch)?;
1396        }
1397        Ok(())
1398    }
1399
1400    /// Flushes buffered frames to the underlying writer.
1401    ///
1402    /// `write_frame` fills a buffer and does not always reach the sink.
1403    /// After `flush` returns, a reader sees a complete, parseable prefix.
1404    /// Dropping the writer flushes as well.
1405    pub fn flush(&mut self) -> io::Result<()> {
1406        self.writer.flush()
1407    }
1408
1409    /// Writes all frames from an iterator to the output stream.
1410    ///
1411    /// This is the most convenient way to write a multi-frame file.
1412    pub fn extend<'a>(
1413        &mut self,
1414        frames: impl Iterator<Item = &'a ConFrame>,
1415    ) -> Result<(), WriteError> {
1416        for frame in frames {
1417            self.write_frame(frame)?;
1418        }
1419        Ok(())
1420    }
1421}
1422
1423fn ids_are_dense(atoms: &[crate::types::AtomDatum], workers: usize) -> bool {
1424    let n = atoms.len();
1425    if workers < 2 || n < WIDE_ATOM_GRAIN {
1426        return atoms
1427            .iter()
1428            .enumerate()
1429            .all(|(index, atom)| atom.atom_id == index as u64);
1430    }
1431    #[cfg(feature = "parallel")]
1432    {
1433        let chunk = n.div_ceil(workers);
1434        crate::parser::on_pool(workers, || {
1435            use rayon::prelude::*;
1436            atoms.par_chunks(chunk).enumerate().all(|(index, group)| {
1437                let base = index * chunk;
1438                group
1439                    .iter()
1440                    .enumerate()
1441                    .all(|(offset, atom)| atom.atom_id == (base + offset) as u64)
1442            })
1443        })
1444    }
1445    #[cfg(not(feature = "parallel"))]
1446    {
1447        let _ = workers;
1448        atoms
1449            .iter()
1450            .enumerate()
1451            .all(|(index, atom)| atom.atom_id == index as u64)
1452    }
1453}
1454
1455fn ensure_unique_ids(atoms: &[crate::types::AtomDatum], workers: usize) -> Result<(), WriteError> {
1456    let n = atoms.len();
1457    if n == 0 {
1458        return Ok(());
1459    }
1460    // Trajectory frames usually number atoms 0..n-1. That needs no set.
1461    if ids_are_dense(atoms, workers) {
1462        return Ok(());
1463    }
1464    let mut seen_ids = std::collections::HashSet::with_capacity(n);
1465    for atom in atoms {
1466        if !seen_ids.insert(atom.atom_id) {
1467            return Err(WriteError::Format(
1468                crate::error::ParseError::ValidationError(format!(
1469                    "atom id {} is repeated in the frame",
1470                    atom.atom_id
1471                )),
1472            ));
1473        }
1474    }
1475    Ok(())
1476}
1477
1478fn written_fixed_flag(fixed: [bool; 3], spec_version: u32) -> u8 {
1479    if spec_version < 2 {
1480        if fixed.iter().any(|axis| *axis) { 1 } else { 0 }
1481    } else {
1482        encode_fixed_bitmask(fixed)
1483    }
1484}
1485
1486/// Two ASCII digits for `0..100`, indexed by `n * 2`.
1487const DIGIT_PAIRS: &[u8; 200] = b"00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";
1488
1489fn push_u64(buf: &mut Vec<u8>, n: u64) {
1490    // Spell straight into the spare tail. A stack buffer plus
1491    // `extend_from_slice` called memcpy for every atom id.
1492    let width = count_digits(n) as usize;
1493    let start = buf.len();
1494    if buf.capacity() - start < width {
1495        buf.reserve(width);
1496    }
1497    unsafe {
1498        let dst = buf.as_mut_ptr().add(start);
1499        write_digit_width(std::slice::from_raw_parts_mut(dst, width), n);
1500        buf.set_len(start + width);
1501    }
1502}
1503
1504fn push_str_line(buf: &mut Vec<u8>, text: &str) {
1505    buf.extend_from_slice(text.as_bytes());
1506    buf.push(b'\n');
1507}
1508
1509fn push_component_line(buf: &mut Vec<u8>, label: &str, index: usize) {
1510    buf.extend_from_slice(label.as_bytes());
1511    buf.push(b' ');
1512    push_u64(buf, (index + 1) as u64);
1513    buf.push(b'\n');
1514}
1515
1516fn push_f64(buf: &mut Vec<u8>, ryu: &mut ryu::Buffer, value: f64, format: FloatFormat) {
1517    match format {
1518        FloatFormat::DecimalPlaces(precision) => push_f64_prec(buf, value, precision),
1519        FloatFormat::RoundTrip => push_round_trip(buf, ryu, None, value),
1520    }
1521}
1522
1523/// Shortest round-trip spelling. Finite values are written with `ryu::raw`
1524/// straight into `buf`. `slot` remembers a column so a repeated lattice
1525/// value is copied instead of formatted again.
1526fn push_round_trip(
1527    buf: &mut Vec<u8>,
1528    ryu: &mut ryu::Buffer,
1529    slot: Option<&mut FmtSlot>,
1530    value: f64,
1531) {
1532    if !value.is_finite() {
1533        let text = ryu.format(value);
1534        buf.extend_from_slice(text.as_bytes());
1535        return;
1536    }
1537    if let Some(slot) = slot {
1538        let bits = value.to_bits();
1539        if slot.bits == bits {
1540            if slot.state == 2 {
1541                buf.extend_from_slice(&slot.text[..slot.len as usize]);
1542                return;
1543            }
1544            if slot.state == 1 {
1545                let n = unsafe { ryu::raw::format64(value, slot.text.as_mut_ptr()) };
1546                debug_assert!(n <= 24);
1547                slot.len = n as u8;
1548                slot.state = 2;
1549                buf.extend_from_slice(&slot.text[..n]);
1550                return;
1551            }
1552        }
1553        write_finite(buf, value);
1554        slot.bits = bits;
1555        slot.state = 1;
1556        return;
1557    }
1558    write_finite(buf, value);
1559}
1560
1561fn write_finite(buf: &mut Vec<u8>, value: f64) {
1562    // Thirty-two bytes covers the longest fixed decimal this path emits.
1563    // An exact frame slice often has less room left than that, and growing
1564    // it would move the bytes off the mapping, so a short tail uses a
1565    // stack slot and copies only the finished spelling.
1566    let spare = buf.capacity() - buf.len();
1567    if spare >= 32 {
1568        let start = buf.len();
1569        let n = unsafe {
1570            let dst = std::slice::from_raw_parts_mut(buf.as_mut_ptr().add(start), spare);
1571            match encode_fixed_decimal(value, dst) {
1572                Some(n) => n,
1573                None => ryu::raw::format64(value, dst.as_mut_ptr()),
1574            }
1575        };
1576        debug_assert!(n <= 24);
1577        unsafe { buf.set_len(start + n) };
1578        return;
1579    }
1580    if let Some((bytes, n)) = encode_fixed_decimal_into(value) {
1581        buf.extend_from_slice(&bytes[..n]);
1582        return;
1583    }
1584    let mut tmp = [0u8; 24];
1585    let n = unsafe { ryu::raw::format64(value, tmp.as_mut_ptr()) };
1586    debug_assert!(n <= 24);
1587    buf.extend_from_slice(&tmp[..n]);
1588}
1589
1590/// Byte length of one round-trip spelling. Matches [`push_round_trip`].
1591fn round_trip_width(value: f64) -> usize {
1592    if !value.is_finite() {
1593        return ryu::Buffer::new().format(value).len();
1594    }
1595    let bits = value.to_bits();
1596    let sign = bits >> 63 != 0;
1597    let mag = f64::from_bits(bits & !(1u64 << 63));
1598    if let Some(n) = fixed_decimal_width(mag, sign) {
1599        return n;
1600    }
1601    if let Some((_, n)) = encode_fixed_decimal_into(value) {
1602        return n;
1603    }
1604    let mut tmp = [0u8; 24];
1605    unsafe { ryu::raw::format64(value, tmp.as_mut_ptr()) }
1606}
1607
1608/// Length of [`encode_fixed_decimal`] when the value is an exact decimal
1609/// of at most six digits. `None` leaves the general formatter to measure.
1610fn fixed_decimal_width(mag: f64, sign: bool) -> Option<usize> {
1611    let sign_len = usize::from(sign);
1612    if mag == 0.0 {
1613        return Some(sign_len + 3);
1614    }
1615    let (n, places) = fixed_decimal_parts(mag)?;
1616    Some(sign_len + fixed_digits_len(n, places))
1617}
1618
1619/// Shortest fixed decimal that matches `ryu`, when the value is an exact
1620/// integer or an exact fraction of at most six digits and ryu would not
1621/// switch to scientific form. `None` leaves the general formatter to run.
1622fn encode_fixed_decimal_into(value: f64) -> Option<([u8; 32], usize)> {
1623    let mut out = [0u8; 32];
1624    let n = encode_fixed_decimal(value, &mut out[..])?;
1625    Some((out, n))
1626}
1627
1628/// The integer `k` near `scaled` whose quotient `k / scale` is `mag`
1629/// and whose exact distance to `mag * scale` is the smallest.
1630///
1631/// `mag * scale` rounded to f64 can land on the farther of two decimals
1632/// that parse back to `mag`. ryu prints the closer one.
1633fn closest_decimal(mag: f64, scaled: f64, scale: u64) -> Option<u64> {
1634    if !scaled.is_finite() || scaled > 1e16 {
1635        return None;
1636    }
1637    let center = round_half_away(scaled);
1638    let center = unsafe { center.to_int_unchecked::<u64>() };
1639    // Dividing the integer back in f64 is not the parse of the decimal.
1640    // A spelling round-trips when it is closer than half an ulp, which is
1641    // `scale / 2` in these units. The f64 product can sit two integers off
1642    // the closer spelling.
1643    let limit = (scale as u128) / 2;
1644    let metric = DecimalMetric::new(mag, scale);
1645    // Parsed short decimals very often become an integer again at their
1646    // original scale. Below 2^52 the rounded product is less than half an
1647    // integer from the exact product, so this is its nearest integer. Avoid
1648    // probing four neighbours in this common coordinate path.
1649    if scaled.fract() == 0.0 && scaled < 4_503_599_627_370_496.0 && metric.distance(center) < limit
1650    {
1651        return Some(center);
1652    }
1653    let mut best: Option<(u64, u128)> = None;
1654    for delta in -2i64..=2 {
1655        let k = center as i64 + delta;
1656        if k < 0 {
1657            continue;
1658        }
1659        let k = k as u64;
1660        let dist = metric.distance(k);
1661        if dist >= limit {
1662            continue;
1663        }
1664        let replace = match best {
1665            None => true,
1666            Some((_, best_dist)) if dist < best_dist => true,
1667            // A tie is the even last digit, which is what ryu prints.
1668            Some((best_k, best_dist)) if dist == best_dist && best_k % 2 == 1 && k % 2 == 0 => true,
1669            _ => false,
1670        };
1671        if replace {
1672            best = Some((k, dist));
1673        }
1674    }
1675    best.map(|(k, _)| k)
1676}
1677
1678/// Exact `mag * scale`, retained while nearby decimal candidates are tested.
1679struct DecimalMetric {
1680    num: u128,
1681    exp: i32,
1682}
1683
1684impl DecimalMetric {
1685    fn new(mag: f64, scale: u64) -> Self {
1686        let bits = mag.to_bits();
1687        let field = ((bits >> 52) & 0x7ff) as i32;
1688        let (sig, exp) = if field == 0 {
1689            ((bits & ((1u64 << 52) - 1)) as u128, -1022 - 52)
1690        } else {
1691            (
1692                ((bits & ((1u64 << 52) - 1)) | (1u64 << 52)) as u128,
1693                field - 1023 - 52,
1694            )
1695        };
1696        Self {
1697            num: sig * scale as u128,
1698            exp,
1699        }
1700    }
1701
1702    /// `|mag * scale - k|` in units of the binary place of `mag`.
1703    #[inline]
1704    fn distance(&self, k: u64) -> u128 {
1705        if self.exp >= 0 {
1706            if self.exp >= 128 {
1707                return u128::MAX;
1708            }
1709            return (self.num << self.exp).abs_diff(k as u128);
1710        }
1711        let shift = (-self.exp) as u32;
1712        if shift >= 128 {
1713            return if k == 0 { self.num } else { u128::MAX };
1714        }
1715        self.num.abs_diff((k as u128) << shift)
1716    }
1717}
1718
1719/// Round a non-negative finite `scaled` half away from zero.
1720///
1721/// Values up to 2^53 use integer truncation, which matches `f64::round`
1722/// there. Larger values, still at most 1e16, use the libm rounding.
1723fn round_half_away(scaled: f64) -> f64 {
1724    const EXACT_INT: f64 = 9007199254740992.0;
1725    if scaled <= EXACT_INT {
1726        // `scaled` is finite and in `0.0..=2^53`, so the truncation fits.
1727        let trunc = unsafe { scaled.to_int_unchecked::<u64>() };
1728        let frac = scaled - trunc as f64;
1729        if frac >= 0.5 {
1730            (trunc + 1) as f64
1731        } else {
1732            trunc as f64
1733        }
1734    } else {
1735        scaled.round()
1736    }
1737}
1738
1739/// `Some(n)` when `mag` is an integer in `1 .. 1e16`.
1740///
1741/// The exponent bits reject fractions without a saturating float-to-int.
1742fn exact_small_integer(mag: f64) -> Option<u64> {
1743    let bits = mag.to_bits();
1744    let exp = ((bits >> 52) & 0x7ff) as i32 - 1023;
1745    if !(0..=53).contains(&exp) {
1746        return None;
1747    }
1748    if exp < 52 {
1749        let frac = bits & ((1u64 << 52) - 1);
1750        let shift = (52 - exp) as u32;
1751        if frac & ((1u64 << shift) - 1) != 0 {
1752            return None;
1753        }
1754    }
1755    // The exponent gate puts `mag` in `1.0 .. 2^54`.
1756    let n = unsafe { mag.to_int_unchecked::<u64>() };
1757    if n < 10_000_000_000_000_000 && (n as f64).to_bits() == bits {
1758        Some(n)
1759    } else {
1760        None
1761    }
1762}
1763
1764/// `(digits, decimal places)` of the shortest exact decimal of at most
1765/// six places, or `None` when [`encode_fixed_decimal`] must refuse.
1766fn fixed_decimal_parts(mag: f64) -> Option<(u64, u32)> {
1767    if let Some(n) = exact_small_integer(mag) {
1768        return Some((n, 0));
1769    }
1770    // An exact k-place decimal with k <= 6 is exact at 6 places too,
1771    // while 1e6 still fits. Coordinates land in this range.
1772    let scaled = mag * 1_000_000.0;
1773    if scaled <= 9007199254740992.0 {
1774        return accept_million(mag, scaled);
1775    }
1776    if scaled.is_finite() && scaled <= 1e16 {
1777        return accept_scaled(mag, scaled, 1_000_000.0, 6);
1778    }
1779    parts_below_million(mag)
1780}
1781
1782/// Six-place probe for `scaled = mag * 1e6` at most 2^53.
1783fn accept_million(mag: f64, scaled: f64) -> Option<(u64, u32)> {
1784    let n = closest_decimal(mag, scaled, 1_000_000)?;
1785    let (n, places) = shorten(mag, n, 6);
1786    if places == 0 {
1787        return Some((n, 0));
1788    }
1789    let kk = count_digits(n) as i32 - places as i32;
1790    if kk > -5 && kk <= 16 {
1791        Some((n, places))
1792    } else {
1793        None
1794    }
1795}
1796
1797/// Drop trailing zeros, then a decimal place when a shorter spelling
1798/// still round-trips. ryu keeps the shortest of those.
1799fn shorten(mag: f64, mut n: u64, mut places: u32) -> (u64, u32) {
1800    loop {
1801        while places > 0 && n.is_multiple_of(10) {
1802            n /= 10;
1803            places -= 1;
1804        }
1805        if places == 0 {
1806            return (n, 0);
1807        }
1808        let scale = 10u64.pow(places - 1);
1809        let base = n / 10;
1810        let limit = (scale as u128) / 2;
1811        let metric = DecimalMetric::new(mag, scale);
1812        let mut best: Option<(u64, u128)> = None;
1813        for k in [base.saturating_sub(1), base, base.saturating_add(1)] {
1814            let dist = metric.distance(k);
1815            if dist >= limit {
1816                continue;
1817            }
1818            let replace = match best {
1819                None => true,
1820                Some((_, best_dist)) if dist < best_dist => true,
1821                Some((best_k, best_dist)) if dist == best_dist && best_k % 2 == 1 && k % 2 == 0 => {
1822                    true
1823                }
1824                _ => false,
1825            };
1826            if replace {
1827                best = Some((k, dist));
1828            }
1829        }
1830        let Some((k, _)) = best else {
1831            return (n, places);
1832        };
1833        if fixed_digits_len(k, places - 1) >= fixed_digits_len(n, places) {
1834            return (n, places);
1835        }
1836        n = k;
1837        places -= 1;
1838    }
1839}
1840
1841/// `mag * 1e6` overflowed. A shorter scale can still be exact.
1842#[inline(never)]
1843fn parts_below_million(mag: f64) -> Option<(u64, u32)> {
1844    let mut scale = 10.0f64;
1845    for d in 1u32..=5 {
1846        let scaled = mag * scale;
1847        if !scaled.is_finite() || scaled > 1e16 {
1848            break;
1849        }
1850        if let Some(parts) = accept_scaled(mag, scaled, scale, d) {
1851            return Some(parts);
1852        }
1853        scale *= 10.0;
1854    }
1855    None
1856}
1857
1858fn accept_scaled(mag: f64, scaled: f64, scale: f64, places: u32) -> Option<(u64, u32)> {
1859    let scale_int = scale as u64;
1860    let n = closest_decimal(mag, scaled, scale_int)?;
1861    let (n, places) = shorten(mag, n, places);
1862    if places == 0 {
1863        if n >= 10u64.pow(16) {
1864            return None;
1865        }
1866        return Some((n, 0));
1867    }
1868    let digits = count_digits(n);
1869    let kk = digits as i32 - places as i32;
1870    if !(kk > -5 && kk <= 16) {
1871        return None;
1872    }
1873    Some((n, places))
1874}
1875
1876fn encode_fixed_decimal(value: f64, out: &mut [u8]) -> Option<usize> {
1877    let bits = value.to_bits();
1878    let sign = bits >> 63 != 0;
1879    let mag = f64::from_bits(bits & !(1u64 << 63));
1880    if mag == 0.0 {
1881        let text: &[u8] = if sign { b"-0.0" } else { b"0.0" };
1882        out[..text.len()].copy_from_slice(text);
1883        return Some(text.len());
1884    }
1885    let (n, places) = fixed_decimal_parts(mag)?;
1886    Some(write_fixed_digits(out, sign, n, places))
1887}
1888
1889fn fixed_digits_len(n: u64, places: u32) -> usize {
1890    let digits = count_digits(n) as usize;
1891    if places == 0 {
1892        return digits + 2;
1893    }
1894    let kk = digits as i32 - places as i32;
1895    if kk > 0 {
1896        digits + 1
1897    } else {
1898        2 + (-kk) as usize + digits
1899    }
1900}
1901
1902fn count_digits(n: u64) -> u32 {
1903    if n == 0 { 1 } else { n.ilog10() + 1 }
1904}
1905
1906/// Write exactly `dst.len()` digits of `n`, with leading zeros.
1907fn write_digit_width(dst: &mut [u8], mut n: u64) {
1908    let mut i = dst.len();
1909    while i >= 2 {
1910        i -= 2;
1911        let q = n / 100;
1912        let r = (n % 100) as usize;
1913        dst[i] = DIGIT_PAIRS[r * 2];
1914        dst[i + 1] = DIGIT_PAIRS[r * 2 + 1];
1915        n = q;
1916    }
1917    if i == 1 {
1918        dst[0] = b'0' + (n % 10) as u8;
1919    }
1920}
1921
1922fn write_fixed_digits(out: &mut [u8], sign: bool, n: u64, places: u32) -> usize {
1923    const POW10: [u64; 7] = [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000];
1924    let digits = count_digits(n) as usize;
1925    let mut at = 0usize;
1926    if sign {
1927        out[at] = b'-';
1928        at += 1;
1929    }
1930    if places == 0 {
1931        write_digit_width(&mut out[at..at + digits], n);
1932        at += digits;
1933        out[at] = b'.';
1934        out[at + 1] = b'0';
1935        return at + 2;
1936    }
1937    let kk = digits as i32 - places as i32;
1938    if kk > 0 {
1939        let cut = kk as usize;
1940        let scale = POW10[places as usize];
1941        write_digit_width(&mut out[at..at + cut], n / scale);
1942        out[at + cut] = b'.';
1943        write_digit_width(&mut out[at + cut + 1..at + digits + 1], n % scale);
1944        return at + digits + 1;
1945    }
1946    out[at] = b'0';
1947    out[at + 1] = b'.';
1948    at += 2;
1949    for _ in 0..(-kk) {
1950        out[at] = b'0';
1951        at += 1;
1952    }
1953    write_digit_width(&mut out[at..at + digits], n);
1954    at + digits
1955}
1956
1957/// Fixed-point `f64` with `prec` digits after the decimal, matching `{:.prec$}`.
1958///
1959/// Scaling by `10^prec` in binary64 and casting to an integer does not match
1960/// that rounding: `5e-7` became `0.000001`, `9.9999995` became `10.000000`,
1961/// and values past `2^53 / 10^prec` lost digits or saturated.
1962fn push_f64_prec(buf: &mut Vec<u8>, v: f64, prec: usize) {
1963    let _ = write!(buf, "{v:.prec$}");
1964}
1965
1966const WIDE_ATOM_GRAIN: usize = 4096;
1967
1968/// Formatting buffers survive from one wide write to the next. Dropping
1969/// them every call faulted a fresh 20 MB and showed up between the format
1970/// time and the campaign sample.
1971fn take_format_buf(cap: usize) -> Vec<u8> {
1972    let mut pool = format_bufs().lock().unwrap_or_else(|err| err.into_inner());
1973    if let Some(mut buf) = pool.pop() {
1974        if buf.capacity() < cap {
1975            buf.reserve(cap);
1976        }
1977        buf.clear();
1978        return buf;
1979    }
1980    drop(pool);
1981    Vec::with_capacity(cap)
1982}
1983
1984fn give_format_buf(buf: Vec<u8>) {
1985    let mut pool = format_bufs().lock().unwrap_or_else(|err| err.into_inner());
1986    if pool.len() < 128 {
1987        pool.push(buf);
1988    }
1989}
1990
1991fn format_bufs() -> &'static std::sync::Mutex<Vec<Vec<u8>>> {
1992    static CACHE: crate::parser::PerProcess<std::sync::Mutex<Vec<Vec<u8>>>> =
1993        crate::parser::PerProcess::new();
1994    CACHE.get_or_init(|| std::sync::Mutex::new(Vec::new()))
1995}
1996
1997fn xyz_from(coords: &[f64], index: usize) -> [f64; 3] {
1998    let at = index * 3;
1999    [coords[at], coords[at + 1], coords[at + 2]]
2000}
2001
2002/// Slab rows a Python read moved out of `positions`.
2003///
2004/// The frames sit in one `Vec`, so the address of the first and the step
2005/// to the next name every row. Installed only when no Python object can
2006/// store into the slab. A shared slab is snapshotted and this stays empty.
2007struct BorrowedSlab {
2008    #[cfg(feature = "python")]
2009    id: u64,
2010    base: usize,
2011    width: usize,
2012    first: usize,
2013    stride: usize,
2014    count: usize,
2015}
2016
2017static BORROWED_SLABS: std::sync::RwLock<Vec<BorrowedSlab>> = std::sync::RwLock::new(Vec::new());
2018
2019#[cfg(feature = "python")]
2020static NEXT_BORROW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
2021
2022#[must_use = "the slab borrow ends when the guard drops"]
2023#[cfg(feature = "python")]
2024pub(crate) struct BorrowedCoordsGuard {
2025    id: u64,
2026}
2027
2028#[cfg(feature = "python")]
2029impl Drop for BorrowedCoordsGuard {
2030    fn drop(&mut self) {
2031        let mut slots = BORROWED_SLABS
2032            .write()
2033            .unwrap_or_else(std::sync::PoisonError::into_inner);
2034        slots.retain(|slot| slot.id != self.id);
2035    }
2036}
2037
2038/// Publish one rectangular slab. `first` is frame 0's address. `stride` is
2039/// the step to the next frame, or 0 when there is a single frame.
2040///
2041/// Several writes can be in flight. Each one keeps its own row, and dropping
2042/// the guard removes only that row.
2043#[cfg(feature = "python")]
2044pub(crate) fn install_borrowed_slab(
2045    base: usize,
2046    width: usize,
2047    first: usize,
2048    stride: usize,
2049    count: usize,
2050) -> BorrowedCoordsGuard {
2051    let id = NEXT_BORROW.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2052    let mut slots = BORROWED_SLABS
2053        .write()
2054        .unwrap_or_else(std::sync::PoisonError::into_inner);
2055    slots.push(BorrowedSlab {
2056        id,
2057        base,
2058        width,
2059        first,
2060        stride,
2061        count,
2062    });
2063    BorrowedCoordsGuard { id }
2064}
2065
2066pub(crate) fn borrowed_coord_slice(frame: &ConFrame) -> Option<&[f64]> {
2067    let slots = BORROWED_SLABS
2068        .read()
2069        .unwrap_or_else(std::sync::PoisonError::into_inner);
2070    let addr = frame as *const ConFrame as usize;
2071    for slot in slots.iter() {
2072        if slot.width == 0 || slot.base == 0 || slot.count == 0 {
2073            continue;
2074        }
2075        let index = if addr == slot.first {
2076            0
2077        } else if slot.stride == 0
2078            || addr < slot.first
2079            || !(addr - slot.first).is_multiple_of(slot.stride)
2080        {
2081            continue;
2082        } else {
2083            (addr - slot.first) / slot.stride
2084        };
2085        if index >= slot.count {
2086            continue;
2087        }
2088        let byte = slot.base + index * slot.width * std::mem::size_of::<f64>();
2089        return Some(unsafe { std::slice::from_raw_parts(byte as *const f64, slot.width) });
2090    }
2091    None
2092}
2093
2094/// Row-major coordinates of every atom.
2095///
2096/// A `ValidationError` when no buffer holds one `(x, y, z)` row per atom:
2097/// a positions column with other than three columns, with a row count
2098/// that is not the atom count, or empty while the frame has atoms.
2099pub(crate) fn frame_coords(frame: &ConFrame) -> Result<std::borrow::Cow<'_, [f64]>, WriteError> {
2100    let n = frame.atom_data.len();
2101    if let Some(slice) = frame.positions.f64_rows3()
2102        && slice.len() == n * 3
2103    {
2104        return Ok(std::borrow::Cow::Borrowed(slice));
2105    }
2106    if let Some(slice) = borrowed_coord_slice(frame)
2107        && slice.len() == n * 3
2108    {
2109        return Ok(std::borrow::Cow::Borrowed(slice));
2110    }
2111    check_position_rows(frame)?;
2112    let mut owned = Vec::with_capacity(n.saturating_mul(3));
2113    for index in 0..n {
2114        owned.extend_from_slice(&frame.xyz_at(index));
2115    }
2116    Ok(std::borrow::Cow::Owned(owned))
2117}
2118
2119/// [`frame_coords`] succeeds for `frame`, checked without copying a row.
2120fn check_position_rows(frame: &ConFrame) -> Result<(), WriteError> {
2121    let n = frame.atom_data.len();
2122    let positions = &frame.positions;
2123    if positions.nrows() == n && (n == 0 || positions.ncols() == 3) {
2124        return Ok(());
2125    }
2126    if borrowed_coord_slice(frame).is_some_and(|slice| slice.len() == n * 3) {
2127        return Ok(());
2128    }
2129    Err(WriteError::Format(
2130        crate::error::ParseError::ValidationError(format!(
2131            "positions column is ({}, {}) but the frame holds {n} atoms of (x, y, z)",
2132            positions.nrows(),
2133            positions.ncols()
2134        )),
2135    ))
2136}
2137
2138struct MotionFmt<'a> {
2139    ryu: &'a mut ryu::Buffer,
2140    slots: &'a mut [FmtSlot; 3],
2141    vel_slots: &'a mut [FmtSlot; 3],
2142}
2143
2144fn push_atom_motion(
2145    coord: &mut Vec<u8>,
2146    vel: Option<&mut Vec<u8>>,
2147    fmt: MotionFmt<'_>,
2148    xyz: [f64; 3],
2149    atom: &crate::types::AtomDatum,
2150    prec: FloatFormat,
2151    spec_version: u32,
2152) {
2153    let MotionFmt {
2154        ryu,
2155        slots,
2156        vel_slots,
2157    } = fmt;
2158    let fixed = written_fixed_flag(atom.fixed(), spec_version);
2159    push_xyz_line(coord, ryu, slots, xyz, prec, fixed, atom.atom_id);
2160    if let Some(vel) = vel {
2161        let [vx, vy, vz] = atom.velocity().unwrap_or([0.0; 3]);
2162        // A separate column cache. Sharing the coordinate slots made every
2163        // velocity miss and then evict the coordinate spelling.
2164        push_xyz_line(vel, ryu, vel_slots, [vx, vy, vz], prec, fixed, atom.atom_id);
2165    }
2166}
2167
2168/// Major on line 2 of a binding header.
2169///
2170/// A frame that already holds one million atoms at major 3 is the pinned
2171/// measurement file. Its compress path must keep that major and must not
2172/// insert `con_spec_patch`, or the pinned bytes move.
2173fn binding_spec(frame: &ConFrame) -> u32 {
2174    // CON 3.1 payloads, including the million-atom measurement file, keep
2175    // major 3. A legacy major-3 velocity file mislabeled as femtoseconds is
2176    // upgraded so the binding can stamp the natural time unit authoritatively.
2177    if frame.header.spec_version == 3 {
2178        let legacy_fs_velocity = frame.has_velocities()
2179            && frame
2180                .header
2181                .metadata
2182                .get(meta::UNITS)
2183                .and_then(|units| units.get("time"))
2184                .and_then(Value::as_str)
2185                == Some("fs");
2186        if !legacy_fs_velocity {
2187            return 3;
2188        }
2189    }
2190    frame.header.spec_version.max(crate::CON_SPEC_VERSION)
2191}
2192
2193/// File header and the species lines that belong in front of `frame`'s coordinates.
2194///
2195/// The bytes match a binding rewrite up to the first coordinate row.
2196pub(crate) fn binding_header_bytes(frame: &ConFrame) -> Result<Vec<u8>, WriteError> {
2197    binding_header_bytes_at(frame, binding_spec(frame))
2198}
2199
2200fn binding_header_bytes_at(frame: &ConFrame, spec: u32) -> Result<Vec<u8>, WriteError> {
2201    let (mut meta, minor_raw) = binding_metadata_with_minor_raw(frame);
2202    if spec < 4 {
2203        meta.remove(meta::CON_SPEC_PATCH);
2204    }
2205    let mut writer = ConFrameWriter::new(Vec::<u8>::new());
2206    writer.refresh_metadata_cache(
2207        spec,
2208        &meta,
2209        minor_raw.as_deref(),
2210        [
2211            frame.has_velocities(),
2212            frame.has_forces(),
2213            frame.has_energies(),
2214            frame.has_charges(),
2215            frame.has_spins(),
2216            frame.has_magmoms(),
2217            frame.has_displacements(),
2218            frame.has_spreads(),
2219        ],
2220    )?;
2221    let (boxl, angles) = written_box(frame);
2222    crate::types::check_cell_finite(&boxl, "boxl", &angles, "angles")
2223        .map_err(WriteError::Format)?;
2224    let prec = FloatFormat::RoundTrip;
2225    let mut buf = Vec::with_capacity(256);
2226    push_str_line(&mut buf, &frame.header.prebox_header.user);
2227    if spec < 2 {
2228        push_str_line(&mut buf, frame.header.prebox_header.metadata_line());
2229    } else {
2230        let line = writer
2231            .metadata_cache
2232            .as_ref()
2233            .expect("metadata")
2234            .serialized
2235            .as_bytes();
2236        buf.extend_from_slice(line);
2237        buf.push(b'\n');
2238    }
2239    let ryu = &mut writer.ryu;
2240    push_f64(&mut buf, ryu, boxl[0], prec);
2241    buf.push(b' ');
2242    push_f64(&mut buf, ryu, boxl[1], prec);
2243    buf.push(b' ');
2244    push_f64(&mut buf, ryu, boxl[2], prec);
2245    buf.push(b'\n');
2246    push_f64(&mut buf, ryu, angles[0], prec);
2247    buf.push(b' ');
2248    push_f64(&mut buf, ryu, angles[1], prec);
2249    buf.push(b' ');
2250    push_f64(&mut buf, ryu, angles[2], prec);
2251    buf.push(b'\n');
2252    push_str_line(&mut buf, &frame.header.postbox_header[0]);
2253    push_str_line(&mut buf, &frame.header.postbox_header[1]);
2254    push_u64(&mut buf, frame.header.natm_types as u64);
2255    buf.push(b'\n');
2256    for (i, n) in frame.header.natms_per_type.iter().enumerate() {
2257        if i > 0 {
2258            buf.push(b' ');
2259        }
2260        push_u64(&mut buf, *n as u64);
2261    }
2262    buf.push(b'\n');
2263    for (i, m) in frame.header.masses_per_type.iter().enumerate() {
2264        if i > 0 {
2265            buf.push(b' ');
2266        }
2267        push_f64(&mut buf, ryu, *m, prec);
2268    }
2269    buf.push(b'\n');
2270    Ok(buf)
2271}
2272
2273/// Binding header plus the first species label, and no coordinate row.
2274///
2275/// [`format_coordinate_lines`] of every atom in a one-component frame
2276/// continues these bytes and matches [`ConFrameWriter::write_frame_bound`].
2277pub fn wide_frame_header(frame: &ConFrame) -> Result<Vec<u8>, WriteError> {
2278    let mut header = binding_header_bytes(frame)?;
2279    if frame.atom_data.is_empty() {
2280        return Ok(header);
2281    }
2282    let with_one = format_coord_range(frame, 0, 1)?;
2283    let coords = frame_coords(frame)?;
2284    let first = coords.get(..3).unwrap_or(&[]);
2285    let one = format_coordinate_lines(&frame.atom_data[..1], first)?;
2286    if let Some(species) = with_one.strip_suffix(one.as_slice()) {
2287        header.extend_from_slice(species);
2288    }
2289    Ok(header)
2290}
2291
2292/// Coordinate lines for atoms `begin..end`, including a species header when
2293/// the range contains the first atom of that species.
2294pub(crate) fn format_coord_range(
2295    frame: &ConFrame,
2296    begin: usize,
2297    end: usize,
2298) -> Result<Vec<u8>, WriteError> {
2299    let spec = binding_spec(frame);
2300    let prec = FloatFormat::RoundTrip;
2301    let coords = frame_coords(frame)?;
2302    let mut buf = Vec::with_capacity((end - begin).saturating_mul(32) + 64);
2303    let mut ryu = ryu::Buffer::new();
2304    let mut slots = [FmtSlot::new(); 3];
2305    let mut vel_slots = [FmtSlot::new(); 3];
2306    let mut offset = 0usize;
2307    for (type_idx, &count) in frame.header.natms_per_type.iter().enumerate() {
2308        let type_end = offset + count;
2309        let from = begin.max(offset);
2310        let to = end.min(type_end);
2311        if from < to {
2312            if from == offset {
2313                let symbol = frame.atom_data[offset].symbol.as_ref();
2314                push_str_line(&mut buf, symbol);
2315                push_component_line(&mut buf, "Coordinates of Component", type_idx);
2316            }
2317            let atoms = &frame.atom_data[from..to];
2318            for (offset, atom) in atoms.iter().enumerate() {
2319                push_atom_motion(
2320                    &mut buf,
2321                    None,
2322                    MotionFmt {
2323                        ryu: &mut ryu,
2324                        slots: &mut slots,
2325                        vel_slots: &mut vel_slots,
2326                    },
2327                    [
2328                        coords[(from + offset) * 3],
2329                        coords[(from + offset) * 3 + 1],
2330                        coords[(from + offset) * 3 + 2],
2331                    ],
2332                    atom,
2333                    prec,
2334                    spec,
2335                );
2336            }
2337        }
2338        offset = type_end;
2339    }
2340    Ok(buf)
2341}
2342
2343/// Coordinate lines for `atoms`, using the same formatter as a frame write.
2344///
2345/// One pass, private buffer. Callers that split a frame across ranks write
2346/// these bytes at the offset from an exclusive scan of the lengths.
2347pub fn format_coordinate_lines(
2348    atoms: &[crate::types::AtomDatum],
2349    coords: &[f64],
2350) -> Result<Vec<u8>, WriteError> {
2351    let mut buf = take_format_buf(atoms.len().saturating_mul(48));
2352    let mut ryu = ryu::Buffer::new();
2353    let mut slots = [FmtSlot::new(); 3];
2354    append_coord_rows(
2355        &mut buf,
2356        LineFmt {
2357            ryu: &mut ryu,
2358            slots: &mut slots,
2359        },
2360        atoms,
2361        coords,
2362        FloatFormat::RoundTrip,
2363        2,
2364        1,
2365        AppendOut {
2366            mapped: false,
2367            force_map: false,
2368            stream: None,
2369            vel: None,
2370        },
2371    )?;
2372    Ok(buf)
2373}
2374
2375/// Return a buffer from [`format_coordinate_lines`] so the next format
2376/// reuses the pages instead of faulting a fresh allocation.
2377pub fn recycle_format_buffer(buf: Vec<u8>) {
2378    give_format_buf(buf);
2379}
2380
2381fn append_velocity_lines(
2382    buf: &mut Vec<u8>,
2383    ryu: &mut ryu::Buffer,
2384    atoms: &[crate::types::AtomDatum],
2385    prec: FloatFormat,
2386    spec_version: u32,
2387) {
2388    let mut vel_slots = [FmtSlot::new(); 3];
2389    for atom in atoms {
2390        let [vx, vy, vz] = atom.velocity().unwrap_or([0.0; 3]);
2391        push_xyz_line(
2392            buf,
2393            ryu,
2394            &mut vel_slots,
2395            [vx, vy, vz],
2396            prec,
2397            written_fixed_flag(atom.fixed(), spec_version),
2398            atom.atom_id,
2399        );
2400    }
2401}
2402
2403type MotionSlot = std::sync::Mutex<Option<(Vec<u8>, Vec<u8>)>>;
2404
2405struct LineFmt<'a> {
2406    ryu: &'a mut ryu::Buffer,
2407    slots: &'a mut [FmtSlot; 3],
2408}
2409
2410struct AppendOut<'a> {
2411    mapped: bool,
2412    force_map: bool,
2413    stream: Option<&'a mut File>,
2414    vel: Option<&'a mut Vec<u8>>,
2415}
2416
2417#[allow(clippy::too_many_arguments)]
2418fn append_coord_rows(
2419    buf: &mut Vec<u8>,
2420    fmt: LineFmt<'_>,
2421    atoms: &[crate::types::AtomDatum],
2422    coords: &[f64],
2423    prec: FloatFormat,
2424    spec_version: u32,
2425    workers: usize,
2426    out: AppendOut<'_>,
2427) -> Result<(), WriteError> {
2428    let LineFmt { ryu, slots } = fmt;
2429    let AppendOut {
2430        mapped,
2431        force_map,
2432        stream,
2433        mut vel,
2434    } = out;
2435    let want_vel = vel.is_some();
2436    if let Some(file) = stream {
2437        if mapped && !atoms.is_empty() {
2438            file.write_all(buf).map_err(WriteError::Io)?;
2439            buf.clear();
2440            let vel_bytes = stream_coord_rows(
2441                file,
2442                atoms,
2443                coords,
2444                workers,
2445                prec,
2446                spec_version,
2447                want_vel,
2448                force_map,
2449            )?;
2450            if let Some(dest) = vel.as_mut() {
2451                dest.extend_from_slice(&vel_bytes);
2452            }
2453            return Ok(());
2454        }
2455    }
2456    if workers < 2 || atoms.len() < WIDE_ATOM_GRAIN {
2457        let mut vel_slots = [FmtSlot::new(); 3];
2458        for (index, atom) in atoms.iter().enumerate() {
2459            push_atom_motion(
2460                buf,
2461                vel.as_deref_mut(),
2462                MotionFmt {
2463                    ryu,
2464                    slots,
2465                    vel_slots: &mut vel_slots,
2466                },
2467                xyz_from(coords, index),
2468                atom,
2469                prec,
2470                spec_version,
2471            );
2472        }
2473        return Ok(());
2474    }
2475    #[cfg(feature = "parallel")]
2476    {
2477        // Four ranges per worker, pulled with one atomic. A static range
2478        // made the preempted core own the whole eighth of the frame, and
2479        // rayon's own steal left a millisecond idle between pieces. The
2480        // atomic handoff is the balance; the pool threads stay pinned.
2481        let groups = workers.saturating_mul(4).max(workers);
2482        let chunk = atoms.len().div_ceil(groups).max(1);
2483        let nparts = atoms.len().div_ceil(chunk);
2484        let bad_ids = std::sync::atomic::AtomicBool::new(false);
2485        let next = std::sync::atomic::AtomicUsize::new(0);
2486        let parts: Vec<MotionSlot> = (0..nparts).map(|_| std::sync::Mutex::new(None)).collect();
2487        crate::parser::on_pool(workers, || {
2488            use rayon::prelude::*;
2489            (0..workers).into_par_iter().for_each(|_| {
2490                let mut ryu = ryu::Buffer::new();
2491                let mut slots = [FmtSlot::new(); 3];
2492                let mut vel_slots = [FmtSlot::new(); 3];
2493                loop {
2494                    let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2495                    if index >= nparts {
2496                        break;
2497                    }
2498                    let start = index * chunk;
2499                    let end = (start + chunk).min(atoms.len());
2500                    let group = &atoms[start..end];
2501                    let mut local = Vec::with_capacity(group.len().saturating_mul(48));
2502                    let mut local_vel = if want_vel {
2503                        Vec::with_capacity(group.len().saturating_mul(48))
2504                    } else {
2505                        Vec::new()
2506                    };
2507                    for (offset, atom) in group.iter().enumerate() {
2508                        if atom.atom_id != (start + offset) as u64 {
2509                            bad_ids.store(true, std::sync::atomic::Ordering::Relaxed);
2510                        }
2511                        push_atom_motion(
2512                            &mut local,
2513                            if want_vel { Some(&mut local_vel) } else { None },
2514                            MotionFmt {
2515                                ryu: &mut ryu,
2516                                slots: &mut slots,
2517                                vel_slots: &mut vel_slots,
2518                            },
2519                            xyz_from(coords, start + offset),
2520                            atom,
2521                            prec,
2522                            spec_version,
2523                        );
2524                    }
2525                    *parts[index].lock().expect("format part") = Some((local, local_vel));
2526                }
2527            });
2528        });
2529        if bad_ids.load(std::sync::atomic::Ordering::Relaxed) {
2530            ensure_unique_ids(atoms, 1)?;
2531        }
2532        let mut coord_len = 0usize;
2533        let mut vel_len = 0usize;
2534        for part in &parts {
2535            let guard = part.lock().expect("format part");
2536            if let Some((coord, rows)) = guard.as_ref() {
2537                coord_len += coord.len();
2538                vel_len += rows.len();
2539            }
2540        }
2541        let coord_at = buf.len();
2542        buf.reserve(coord_len);
2543        if let Some(dest) = vel.as_deref_mut() {
2544            dest.reserve(vel_len);
2545        }
2546        if coord_len > 0 {
2547            let coord_ptr = buf.as_mut_ptr() as usize;
2548            let mut jobs = Vec::with_capacity(nparts);
2549            let mut at = coord_at;
2550            for part in &parts {
2551                let guard = part.lock().expect("format part");
2552                let Some((coord, _)) = guard.as_ref() else {
2553                    continue;
2554                };
2555                let n = coord.len();
2556                if n == 0 {
2557                    continue;
2558                }
2559                jobs.push((coord.as_ptr() as usize, coord_ptr + at, n));
2560                at += n;
2561            }
2562            let next_copy = std::sync::atomic::AtomicUsize::new(0);
2563            crate::parser::on_pool(workers, || {
2564                use rayon::prelude::*;
2565                (0..workers).into_par_iter().for_each(|_| {
2566                    loop {
2567                        let index = next_copy.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2568                        if index >= jobs.len() {
2569                            break;
2570                        }
2571                        let (src, dest, n) = jobs[index];
2572                        unsafe {
2573                            std::ptr::copy_nonoverlapping(src as *const u8, dest as *mut u8, n);
2574                        }
2575                    }
2576                });
2577            });
2578            // SAFETY: the copies covered coord_len bytes past coord_at.
2579            // The length stays put until then, so a panic drops only the
2580            // bytes that were already initialised.
2581            unsafe { buf.set_len(coord_at + coord_len) };
2582        }
2583        if let Some(dest) = vel.as_mut() {
2584            for part in &parts {
2585                let guard = part.lock().expect("format part");
2586                if let Some((_, rows)) = guard.as_ref() {
2587                    dest.extend_from_slice(rows);
2588                }
2589            }
2590        }
2591        Ok(())
2592    }
2593    #[cfg(not(feature = "parallel"))]
2594    {
2595        let _ = workers;
2596        let mut vel_slots = [FmtSlot::new(); 3];
2597        for (index, atom) in atoms.iter().enumerate() {
2598            push_atom_motion(
2599                buf,
2600                vel.as_deref_mut(),
2601                MotionFmt {
2602                    ryu,
2603                    slots,
2604                    vel_slots: &mut vel_slots,
2605                },
2606                xyz_from(coords, index),
2607                atom,
2608                prec,
2609                spec_version,
2610            );
2611        }
2612        Ok(())
2613    }
2614}
2615
2616/// Logical CPUs divided by SMT siblings.
2617///
2618/// `available_parallelism` counts hardware threads. The sibling list under
2619/// `/sys/devices/system/cpu/cpu0/topology` is one entry per SMT thread on
2620/// that core. This machine has eight cores and one sibling each, so the
2621/// count is 8. A copy thread is started only when two threads per worker
2622/// still land on distinct physical cores. Sixteen threads on these eight
2623/// cores slowed the format; that is oversubscription, not SMT.
2624fn physical_cores() -> usize {
2625    let logical = std::thread::available_parallelism()
2626        .map(|n| n.get())
2627        .unwrap_or(1);
2628    let siblings =
2629        std::fs::read_to_string("/sys/devices/system/cpu/cpu0/topology/thread_siblings_list")
2630            .ok()
2631            .map(|text| {
2632                text.split([',', '-'])
2633                    .filter(|piece| !piece.trim().is_empty())
2634                    .count()
2635            })
2636            .filter(|n| *n > 0)
2637            .unwrap_or(1);
2638    (logical / siblings).max(1)
2639}
2640
2641fn side_copy_workers(workers: usize) -> bool {
2642    // The side copy maps the file. Miri writes through `pwrite_full`.
2643    #[cfg(miri)]
2644    {
2645        let _ = workers;
2646        return false;
2647    }
2648    #[cfg(not(miri))]
2649    {
2650        workers >= 2 && workers.saturating_mul(2) <= physical_cores()
2651    }
2652}
2653
2654/// tmpfs wants many small ranges so the writer starts early. The page
2655/// cache wants fewer writes.
2656/// Ask for huge pages on a tmpfs that was mounted to allow them.
2657///
2658/// `MADV_POPULATE_WRITE` was slower than the plain first touch on both
2659/// a normal tmpfs and `huge=within_size`, so this does not pre-fault.
2660/// `MADV_HUGEPAGE` is a no-op unless the mount (or `shmem_enabled=advise`)
2661/// is willing to use huge pages.
2662pub(crate) fn advise_shared_store(file: &File, ptr: *mut u8, len: usize) {
2663    #[cfg(all(target_os = "linux", not(miri)))]
2664    if len >= 2 * 1024 * 1024 && mount_requests_huge(file) {
2665        unsafe {
2666            let _ = libc::madvise(ptr.cast::<libc::c_void>(), len, libc::MADV_HUGEPAGE);
2667        }
2668    }
2669    #[cfg(any(not(target_os = "linux"), miri))]
2670    {
2671        let _ = (file, ptr, len);
2672    }
2673}
2674
2675#[cfg(all(target_os = "linux", not(miri)))]
2676fn mount_requests_huge(file: &File) -> bool {
2677    use std::os::fd::AsRawFd;
2678    let Ok(linked) = std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())) else {
2679        return false;
2680    };
2681    let Ok(table) = std::fs::read_to_string("/proc/mounts") else {
2682        return false;
2683    };
2684    let path = linked.to_string_lossy();
2685    let mut best_len = 0usize;
2686    let mut huge = false;
2687    for line in table.lines() {
2688        let mut fields = line.split_whitespace();
2689        let _device = fields.next();
2690        let Some(raw_mount) = fields.next() else {
2691            continue;
2692        };
2693        let mount = raw_mount.replace("\\040", " ");
2694        if mount.len() >= best_len && path.starts_with(&mount) {
2695            let _fstype = fields.next();
2696            let options = fields.next().unwrap_or("");
2697            best_len = mount.len();
2698            huge = options.split(',').any(|opt| {
2699                matches!(
2700                    opt,
2701                    "huge=within_size" | "huge=always" | "huge=advise" | "huge=force"
2702                )
2703            });
2704        }
2705    }
2706    huge
2707}
2708
2709pub(crate) fn file_is_tmpfs(file: &File) -> bool {
2710    // tmpfs is a Linux filesystem. Miri has no `fstatfs`. Treating the
2711    // file as a normal one only changes how many ranges the pipeline formats.
2712    #[cfg(all(not(miri), target_os = "linux"))]
2713    {
2714        use std::os::fd::AsRawFd;
2715        let mut stat = unsafe { std::mem::zeroed::<libc::statfs>() };
2716        let rc = unsafe { libc::fstatfs(file.as_raw_fd(), &mut stat) };
2717        rc == 0 && stat.f_type == 0x01021994
2718    }
2719    #[cfg(any(miri, not(target_os = "linux")))]
2720    {
2721        let _ = file;
2722        false
2723    }
2724}
2725
2726/// One ordered `pwrite` overlapping the format.
2727///
2728/// The caller thread writes finished ranges in file order. The other
2729/// `workers - 1` threads format. A fresh file's page faults are about
2730/// 0.006 s for these bytes, which is the whole sink; doing that copy at
2731/// the same time as the format is what removes it from the wall clock.
2732fn stream_coord_pipeline(
2733    file: &mut File,
2734    atoms: &[crate::types::AtomDatum],
2735    coords: &[f64],
2736    workers: usize,
2737    prec: FloatFormat,
2738    spec_version: u32,
2739    want_vel: bool,
2740) -> Result<Vec<u8>, WriteError> {
2741    let workers = workers.max(2).min(atoms.len().max(1));
2742    let formatters = workers - 1;
2743    // Smaller ranges on tmpfs: the first range is one core's worth of
2744    // work, and the single writer starts while the rest are formatted.
2745    // The page cache wants fewer, larger writes; a syscall per 90 KB lost
2746    // to the one-shot `pwrite` of the same bytes.
2747    let groups = if file_is_tmpfs(file) {
2748        workers.saturating_mul(32)
2749    } else {
2750        workers.saturating_mul(8)
2751    }
2752    .max(workers);
2753    let chunk = atoms.len().div_ceil(groups).max(1);
2754    let nparts = atoms.len().div_ceil(chunk);
2755    let base = file.stream_position().map_err(WriteError::Io)?;
2756    let out = file.try_clone().map_err(WriteError::Io)?;
2757    let next = std::sync::atomic::AtomicUsize::new(0);
2758    let bad_ids = std::sync::atomic::AtomicBool::new(false);
2759    let slots: Vec<MotionSlot> = (0..nparts).map(|_| std::sync::Mutex::new(None)).collect();
2760    let flag = &bad_ids;
2761    let (end, mut vel_bytes) = std::thread::scope(|scope| -> Result<_, WriteError> {
2762        let mut handles = Vec::with_capacity(formatters);
2763        for worker in 0..formatters {
2764            let next = &next;
2765            let slots = &slots;
2766            handles.push(scope.spawn(move || {
2767                // Core 0 stays free for the writer.
2768                crate::parser::pin_worker(worker + 1);
2769                let mut ryu = ryu::Buffer::new();
2770                let mut slots_fmt = [FmtSlot::new(); 3];
2771                let mut vel_slots = [FmtSlot::new(); 3];
2772                loop {
2773                    let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2774                    if index >= nparts {
2775                        break;
2776                    }
2777                    let start = index * chunk;
2778                    let end = (start + chunk).min(atoms.len());
2779                    let group = &atoms[start..end];
2780                    let mut coord = Vec::with_capacity(group.len().saturating_mul(48));
2781                    let mut vel = if want_vel {
2782                        Vec::with_capacity(group.len().saturating_mul(48))
2783                    } else {
2784                        Vec::new()
2785                    };
2786                    for (offset, atom) in group.iter().enumerate() {
2787                        if atom.atom_id != (start + offset) as u64 {
2788                            flag.store(true, std::sync::atomic::Ordering::Relaxed);
2789                        }
2790                        push_atom_motion(
2791                            &mut coord,
2792                            if want_vel { Some(&mut vel) } else { None },
2793                            MotionFmt {
2794                                ryu: &mut ryu,
2795                                slots: &mut slots_fmt,
2796                                vel_slots: &mut vel_slots,
2797                            },
2798                            xyz_from(coords, start + offset),
2799                            atom,
2800                            prec,
2801                            spec_version,
2802                        );
2803                    }
2804                    *slots[index].lock().expect("format slot") = Some((coord, vel));
2805                }
2806            }));
2807        }
2808        let mut offset = base;
2809        let mut vel_bytes = Vec::new();
2810        // The writer owns core 0. Leaving it free to wander put it on
2811        // a formatter's core and stretched the copy. The caller's mask
2812        // is restored even when a write fails.
2813        #[cfg(all(not(miri), target_os = "linux"))]
2814        let mut old_affinity = unsafe { std::mem::zeroed::<libc::cpu_set_t>() };
2815        #[cfg(all(not(miri), target_os = "linux"))]
2816        unsafe {
2817            libc::sched_getaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &mut old_affinity);
2818        }
2819        crate::parser::pin_worker(0);
2820        let written = (|| -> Result<_, WriteError> {
2821            for slot in &slots {
2822                let (coord, vel) = loop {
2823                    if let Some(part) = slot.lock().expect("format slot").take() {
2824                        break part;
2825                    }
2826                    std::hint::spin_loop();
2827                };
2828                pwrite_full(&out, &coord, offset).map_err(WriteError::Io)?;
2829                offset = offset.checked_add(coord.len() as u64).ok_or_else(|| {
2830                    WriteError::Io(io::Error::new(
2831                        io::ErrorKind::InvalidData,
2832                        "coordinate block is too large",
2833                    ))
2834                })?;
2835                if want_vel {
2836                    vel_bytes.extend_from_slice(&vel);
2837                }
2838            }
2839            Ok(())
2840        })();
2841        #[cfg(all(not(miri), target_os = "linux"))]
2842        unsafe {
2843            libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &old_affinity);
2844        }
2845        written?;
2846        for handle in handles {
2847            if handle.join().is_err() {
2848                return Err(WriteError::Io(io::Error::other("formatter panicked")));
2849            }
2850        }
2851        Ok((offset, vel_bytes))
2852    })?;
2853    // `pwrite` extends the file to the last byte it stored and leaves any
2854    // older tail in place. The mapped path truncates to the same end.
2855    file.set_len(end).map_err(WriteError::Io)?;
2856    file.seek(SeekFrom::Start(end)).map_err(WriteError::Io)?;
2857    if bad_ids.load(std::sync::atomic::Ordering::Relaxed) {
2858        ensure_unique_ids(atoms, 1)?;
2859    }
2860    if !want_vel {
2861        vel_bytes.clear();
2862    }
2863    Ok(vel_bytes)
2864}
2865
2866/// Bytes one coordinate line can occupy.
2867///
2868/// Round-trip spellings fit in 128. A fixed number of decimal places can
2869/// be hundreds of digits, and the mapped reserve has to hold that line or
2870/// the other workers spin forever waiting for a length that is never stored.
2871fn mapped_line_budget(prec: FloatFormat) -> usize {
2872    match prec {
2873        FloatFormat::RoundTrip => 128,
2874        FloatFormat::DecimalPlaces(places) => {
2875            let float = 1usize
2876                .saturating_add(309)
2877                .saturating_add(1)
2878                .saturating_add(places);
2879            float.saturating_mul(3).saturating_add(4 + 1 + 1 + 20 + 1)
2880        }
2881    }
2882}
2883
2884#[allow(clippy::too_many_arguments)]
2885fn stream_coord_rows(
2886    file: &mut File,
2887    atoms: &[crate::types::AtomDatum],
2888    coords: &[f64],
2889    workers: usize,
2890    prec: FloatFormat,
2891    spec_version: u32,
2892    want_vel: bool,
2893    force_map: bool,
2894) -> Result<Vec<u8>, WriteError> {
2895    // Spare cores copy into a shared mapping while later ranges format.
2896    // With no spare core, one thread `pwrite`s finished ranges in order
2897    // and the others keep formatting. `map_rows` still forces the mapping.
2898    let workers = workers.max(1).min(atoms.len().max(1));
2899    let side_copies = side_copy_workers(workers);
2900    if !side_copies && !force_map {
2901        return stream_coord_pipeline(file, atoms, coords, workers, prec, spec_version, want_vel);
2902    }
2903    let groups = if side_copies {
2904        workers.saturating_mul(8).max(workers)
2905    } else {
2906        workers.saturating_mul(4).max(workers)
2907    };
2908    let chunk = atoms.len().div_ceil(groups).max(1);
2909    let nparts = atoms.len().div_ceil(chunk);
2910    let base = file.stream_position().map_err(WriteError::Io)?;
2911    let line_budget = mapped_line_budget(prec);
2912    let upper = atoms.len().checked_mul(line_budget).ok_or_else(|| {
2913        WriteError::Io(io::Error::new(
2914            io::ErrorKind::InvalidData,
2915            "coordinate block is too large",
2916        ))
2917    })?;
2918    let reserve_end = base.checked_add(upper as u64).ok_or_else(|| {
2919        WriteError::Io(io::Error::new(
2920            io::ErrorKind::InvalidData,
2921            "coordinate block is too large",
2922        ))
2923    })?;
2924    let mut map = {
2925        file.set_len(reserve_end).map_err(WriteError::Io)?;
2926        Some(unsafe { memmap2::MmapMut::map_mut(&*file).map_err(WriteError::Io)? })
2927    };
2928    let dest_base = map
2929        .as_mut()
2930        .map(|mapping| mapping.as_mut_ptr() as usize + base as usize)
2931        .unwrap_or(0);
2932    let lengths: Vec<std::sync::atomic::AtomicU64> = (0..nparts)
2933        .map(|_| std::sync::atomic::AtomicU64::new(0))
2934        .collect();
2935    let bad_ids = std::sync::atomic::AtomicBool::new(false);
2936    let failed = std::sync::atomic::AtomicBool::new(false);
2937    let next_job = std::sync::atomic::AtomicUsize::new(0);
2938    let produced = std::sync::atomic::AtomicUsize::new(0);
2939    let copies: std::sync::Mutex<Vec<(Vec<u8>, usize)>> = std::sync::Mutex::new(Vec::new());
2940    let ready = std::sync::Condvar::new();
2941    let vel_parts: Vec<std::sync::Mutex<Option<Vec<u8>>>> =
2942        (0..nparts).map(|_| std::sync::Mutex::new(None)).collect();
2943    let flag = &bad_ids;
2944    std::thread::scope(|scope| -> Result<(), WriteError> {
2945        let mut copiers = Vec::with_capacity(workers);
2946        if side_copies {
2947            for copier in 0..workers {
2948                let copies = &copies;
2949                let ready = &ready;
2950                let produced = &produced;
2951                copiers.push(scope.spawn(move || {
2952                    // Spare cores only. The formatter already owns `0..workers`.
2953                    crate::parser::pin_worker(workers + copier);
2954                    loop {
2955                        let job = {
2956                            let mut queue = copies.lock().expect("copies");
2957                            loop {
2958                                if let Some(job) = queue.pop() {
2959                                    break Some(job);
2960                                }
2961                                if produced.load(std::sync::atomic::Ordering::Acquire) == nparts {
2962                                    break None;
2963                                }
2964                                queue = ready.wait(queue).expect("copies");
2965                            }
2966                        };
2967                        let Some((coord, offset)) = job else {
2968                            break;
2969                        };
2970                        let n = coord.len();
2971                        if n > 0 {
2972                            unsafe {
2973                                std::ptr::copy_nonoverlapping(
2974                                    coord.as_ptr(),
2975                                    (dest_base + offset) as *mut u8,
2976                                    n,
2977                                );
2978                            }
2979                        }
2980                        give_format_buf(coord);
2981                    }
2982                }));
2983            }
2984        }
2985        let mut formatters = Vec::with_capacity(workers);
2986        for worker in 0..workers {
2987            let lengths = &lengths;
2988            let next_job = &next_job;
2989            let vel_parts = &vel_parts;
2990            let copies = &copies;
2991            let ready = &ready;
2992            let produced = &produced;
2993            let failed = &failed;
2994            formatters.push(scope.spawn(move || -> Result<(), WriteError> {
2995                crate::parser::pin_worker(worker);
2996                let mut ryu = ryu::Buffer::new();
2997                let mut slots = [FmtSlot::new(); 3];
2998                let mut vel_slots = [FmtSlot::new(); 3];
2999                loop {
3000                    let index = next_job.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3001                    if index >= nparts {
3002                        break;
3003                    }
3004                    let start = index * chunk;
3005                    let end = (start + chunk).min(atoms.len());
3006                    let group = &atoms[start..end];
3007                    let mut coord = if side_copies {
3008                        take_format_buf(group.len().saturating_mul(48))
3009                    } else {
3010                        Vec::with_capacity(group.len().saturating_mul(48))
3011                    };
3012                    let mut vel = if want_vel {
3013                        Vec::with_capacity(group.len().saturating_mul(48))
3014                    } else {
3015                        Vec::new()
3016                    };
3017                    for (offset, atom) in group.iter().enumerate() {
3018                        if atom.atom_id != (start + offset) as u64 {
3019                            flag.store(true, std::sync::atomic::Ordering::Relaxed);
3020                        }
3021                        push_atom_motion(
3022                            &mut coord,
3023                            if want_vel { Some(&mut vel) } else { None },
3024                            MotionFmt {
3025                                ryu: &mut ryu,
3026                                slots: &mut slots,
3027                                vel_slots: &mut vel_slots,
3028                            },
3029                            xyz_from(coords, start + offset),
3030                            atom,
3031                            prec,
3032                            spec_version,
3033                        );
3034                    }
3035                    let n = coord.len();
3036                    if n > group.len().saturating_mul(line_budget) {
3037                        // Publish a zero length so a later range stops waiting,
3038                        // and do it after the failure flag so that range does
3039                        // not copy at the dummy offset.
3040                        failed.store(true, std::sync::atomic::Ordering::Release);
3041                        lengths[index].store(1, std::sync::atomic::Ordering::Release);
3042                        return Err(WriteError::Io(io::Error::other(
3043                            "coordinate line exceeded the mapped reserve",
3044                        )));
3045                    }
3046                    lengths[index].store(n as u64 + 1, std::sync::atomic::Ordering::Release);
3047                    let mut offset = 0usize;
3048                    for length in lengths.iter().take(index) {
3049                        loop {
3050                            if failed.load(std::sync::atomic::Ordering::Acquire) {
3051                                return Err(WriteError::Io(io::Error::other(
3052                                    "coordinate line exceeded the mapped reserve",
3053                                )));
3054                            }
3055                            let known = length.load(std::sync::atomic::Ordering::Acquire);
3056                            if known != 0 {
3057                                if failed.load(std::sync::atomic::Ordering::Acquire) {
3058                                    return Err(WriteError::Io(io::Error::other(
3059                                        "coordinate line exceeded the mapped reserve",
3060                                    )));
3061                                }
3062                                offset += (known - 1) as usize;
3063                                break;
3064                            }
3065                            std::hint::spin_loop();
3066                        }
3067                    }
3068                    if side_copies {
3069                        let mut queue = copies.lock().expect("copies");
3070                        queue.push((coord, offset));
3071                    } else {
3072                        let n = coord.len();
3073                        if n > 0 {
3074                            unsafe {
3075                                std::ptr::copy_nonoverlapping(
3076                                    coord.as_ptr(),
3077                                    (dest_base + offset) as *mut u8,
3078                                    n,
3079                                );
3080                            }
3081                        }
3082                    }
3083                    if side_copies {
3084                        produced.fetch_add(1, std::sync::atomic::Ordering::Release);
3085                        ready.notify_one();
3086                    }
3087                    if want_vel {
3088                        *vel_parts[index].lock().expect("vel part") = Some(vel);
3089                    }
3090                }
3091                Ok(())
3092            }));
3093        }
3094        let formatted = (|| -> Result<(), WriteError> {
3095            for handle in formatters {
3096                handle.join().unwrap_or_else(|_| {
3097                    Err(WriteError::Io(io::Error::other("formatter panicked")))
3098                })?;
3099            }
3100            Ok(())
3101        })();
3102        // A formatter that returns early must still wake copiers blocked on
3103        // an empty queue. Otherwise the scope waits for them forever.
3104        produced.store(nparts, std::sync::atomic::Ordering::Release);
3105        ready.notify_all();
3106        for handle in copiers {
3107            handle
3108                .join()
3109                .map_err(|_| WriteError::Io(io::Error::other("copy panicked")))?;
3110        }
3111        formatted?;
3112        Ok(())
3113    })?;
3114    let mut cursor = 0u64;
3115    for length in &lengths {
3116        cursor += length
3117            .load(std::sync::atomic::Ordering::Relaxed)
3118            .saturating_sub(1);
3119    }
3120    drop(map);
3121    let end = base + cursor;
3122    // The mapping was reserved above the exact prefix sum.
3123    file.set_len(end).map_err(WriteError::Io)?;
3124    file.seek(SeekFrom::Start(end)).map_err(WriteError::Io)?;
3125    if bad_ids.load(std::sync::atomic::Ordering::Relaxed) {
3126        ensure_unique_ids(atoms, 1)?;
3127    }
3128    let mut vel_bytes = Vec::new();
3129    if want_vel {
3130        for part in &vel_parts {
3131            if let Some(vel) = part.lock().expect("vel part").as_ref() {
3132                vel_bytes.extend_from_slice(vel);
3133            }
3134        }
3135    }
3136    drop(vel_parts);
3137    Ok(vel_bytes)
3138}
3139
3140fn push_xyz_line(
3141    buf: &mut Vec<u8>,
3142    ryu: &mut ryu::Buffer,
3143    slots: &mut [FmtSlot; 3],
3144    xyz: [f64; 3],
3145    prec: FloatFormat,
3146    fixed: u8,
3147    atom_id: u64,
3148) {
3149    let [x, y, z] = xyz;
3150    match prec {
3151        FloatFormat::RoundTrip => {
3152            // Lattice coordinates are exact `N.0`. The column table spells
3153            // those without the general float search. Other values still
3154            // go through `push_round_trip`, so the bytes do not change.
3155            push_column_f64(buf, ryu, &mut slots[0], x);
3156            buf.push(b' ');
3157            push_column_f64(buf, ryu, &mut slots[1], y);
3158            buf.push(b' ');
3159            push_column_f64(buf, ryu, &mut slots[2], z);
3160        }
3161        FloatFormat::DecimalPlaces(_) => {
3162            push_f64(buf, ryu, x, prec);
3163            buf.push(b' ');
3164            push_f64(buf, ryu, y, prec);
3165            buf.push(b' ');
3166            push_f64(buf, ryu, z, prec);
3167        }
3168    }
3169    buf.push(b' ');
3170    // Column 4 is a mask in 0..=7, one digit.
3171    buf.push(b'0' + fixed);
3172    buf.push(b' ');
3173    push_u64(buf, atom_id);
3174    buf.push(b'\n');
3175}
3176
3177fn push_scalar_line(
3178    buf: &mut Vec<u8>,
3179    ryu: &mut ryu::Buffer,
3180    slots: &mut [FmtSlot; 3],
3181    v: f64,
3182    prec: FloatFormat,
3183    fixed: u8,
3184    atom_id: u64,
3185) {
3186    match prec {
3187        FloatFormat::RoundTrip => push_round_trip(buf, ryu, Some(&mut slots[0]), v),
3188        FloatFormat::DecimalPlaces(_) => push_f64(buf, ryu, v, prec),
3189    }
3190    buf.push(b' ');
3191    push_u64(buf, u64::from(fixed));
3192    buf.push(b' ');
3193    push_u64(buf, atom_id);
3194    buf.push(b'\n');
3195}
3196
3197/// Record `units.time` for a frame whose velocities are in the natural unit.
3198///
3199/// Versions 1, 2, and every minor of major 3 store those numbers in the
3200/// natural unit whatever `units.time` says (CON-units.8, CON-units.9).
3201/// The label those versions record is the historical spelling. It is not
3202/// authoritative, and the published files of those versions use it
3203/// (CON-units.5). A rewrite that emits major 4 makes the label
3204/// authoritative (CON-units.10), so that path writes the symbol spelling.
3205/// A major 4 frame is left alone.
3206pub(crate) fn stamp_legacy_velocity_time(
3207    meta: &mut BTreeMap<String, Value>,
3208    spec_version: u32,
3209    has_velocity: bool,
3210) {
3211    if !has_velocity || spec_version >= 4 {
3212        return;
3213    }
3214    let mut units = match meta.get(meta::UNITS).cloned() {
3215        Some(Value::Object(map)) => Value::Object(map),
3216        Some(_) => return,
3217        None => crate::units::default_v3_units_json(),
3218    };
3219    if let Some(object) = units.as_object_mut() {
3220        object.insert(
3221            "time".to_string(),
3222            Value::String(crate::units::HISTORICAL_NATURAL_TIME.to_string()),
3223        );
3224        meta.insert(meta::UNITS.to_string(), units);
3225    }
3226}
3227
3228/// Fill the length and energy keys CON-header.3 and CON-units.1 imply.
3229///
3230/// An absent length is angstrom. An absent energy is eV, which is what
3231/// [`crate::units::default_v3_units_json`] writes when the file had no
3232/// units object. A key that is present is left alone, including an
3233/// invalid one (CON-units.14).
3234fn materialize_header_units(meta: &mut BTreeMap<String, Value>) {
3235    let Some(serde_json::Value::Object(object)) = meta.get_mut(meta::UNITS) else {
3236        return;
3237    };
3238    if !object.contains_key("length") {
3239        object.insert("length".to_string(), Value::String("angstrom".to_string()));
3240    }
3241    if !object.contains_key("energy") {
3242        object.insert("energy".to_string(), Value::String("eV".to_string()));
3243    }
3244}
3245
3246/// Metadata a language binding emits for `frame`, without copying atoms.
3247///
3248/// [`ConFrameBuilder::build`] stamps `con_spec_minor` 1 when the key is
3249/// absent. A parsed frame does not carry that key unless the file did.
3250/// The stamp lives on the header. The atoms stay where the parser put them.
3251pub fn binding_metadata(frame: &ConFrame) -> BTreeMap<String, Value> {
3252    let mut meta = frame.header.metadata.to_map();
3253    meta.remove(meta::CON_SPEC_VERSION);
3254    meta.remove(meta::SECTIONS);
3255    let has_velocity = frame.has_velocities();
3256    stamp_legacy_velocity_time(&mut meta, frame.header.spec_version, has_velocity);
3257    // The builder writes the current spec and fills units when the file
3258    // omitted them. A binding rewrite has to emit that same header.
3259    if !meta.contains_key(meta::UNITS) {
3260        meta.insert(
3261            meta::UNITS.to_string(),
3262            crate::units::default_v3_units_json(),
3263        );
3264    }
3265    // A file may name units.time and still omit length. CON-header.3 reads
3266    // that as angstrom. Major 3 and later also require energy (CON-units.1),
3267    // the same default a missing units object already gets.
3268    materialize_header_units(&mut meta);
3269    if !meta.contains_key(meta::CON_SPEC_MINOR) {
3270        meta.insert(
3271            meta::CON_SPEC_MINOR.to_string(),
3272            Value::from(u64::from(crate::CON_SPEC_MINOR)),
3273        );
3274    }
3275    if !meta.contains_key(meta::CON_SPEC_PATCH) {
3276        meta.insert(
3277            meta::CON_SPEC_PATCH.to_string(),
3278            Value::from(u64::from(crate::CON_SPEC_PATCH)),
3279        );
3280    }
3281    meta
3282}
3283
3284pub(crate) fn binding_metadata_with_minor_raw(
3285    frame: &ConFrame,
3286) -> (BTreeMap<String, Value>, Option<Box<str>>) {
3287    let minor_raw = frame.header.metadata.huge_minor_raw().map(Box::from);
3288    (binding_metadata(frame), minor_raw)
3289}
3290
3291/// Same bytes as a binding rewrite, without rebuilding each atom.
3292pub fn binding_rewrite_frame(frame: &ConFrame) -> Result<ConFrame, crate::error::ParseError> {
3293    let mut out = frame.clone();
3294    let spec = binding_spec(frame);
3295    let (mut meta, minor_raw) = binding_metadata_with_minor_raw(frame);
3296    if spec < 4 {
3297        meta.remove(meta::CON_SPEC_PATCH);
3298    }
3299    out.header.metadata =
3300        crate::types::FrameMeta::from_map_with_minor_raw(meta, minor_raw.as_deref());
3301    // A parsed spec 1 frame keeps line 2 as free text. The bound writer
3302    // emits the binding major as JSON, so the rewrite does too.
3303    out.header.spec_version = spec;
3304    Ok(out)
3305}
3306
3307// Implementation block specifically for when the writer is a `File`.
3308impl ConFrameWriter<File> {
3309    /// Creates a new `ConFrameWriter` that writes to a file at the given path.
3310    ///
3311    /// This is a convenience function that creates the file and wraps it.
3312    pub fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Self> {
3313        let file = File::create(path)?;
3314        Ok(Self::new(file))
3315    }
3316
3317    /// Creates a new `ConFrameWriter` that writes to a file with a custom precision.
3318    pub fn from_path_with_precision<P: AsRef<Path>>(path: P, precision: usize) -> io::Result<Self> {
3319        let file = File::create(path)?;
3320        Ok(Self::with_precision(file, precision))
3321    }
3322
3323    /// Opens an uncompressed file for appending.
3324    ///
3325    /// The file is created when it does not exist. A non-empty file that does
3326    /// not end in a newline receives one, so the next frame header starts on
3327    /// its own line. A file this writer produced already ends in a newline,
3328    /// and appending the remaining frames reproduces one whole-file write.
3329    /// Gzip and zstd paths are refused: a compressed member cannot be extended.
3330    ///
3331    /// `write_frame` fills a one-frame scratch buffer and a [`std::io::BufWriter`].
3332    /// [`Self::flush`] pushes that buffer to the file before the writer is dropped.
3333    ///
3334    /// ```
3335    /// use readcon_core::iterators::read_all_frames;
3336    /// use readcon_core::types::ConFrameBuilder;
3337    /// use readcon_core::writer::ConFrameWriter;
3338    /// let scratch = tempfile::tempdir().unwrap();
3339    /// let path = scratch.path().join("readcon-append-doc.con");
3340    /// let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
3341    /// builder.add_atom("H", 0.0, 0.0, 0.0, [false; 3], 1, 1.0);
3342    /// let frame = builder.build().unwrap();
3343    /// {
3344    ///     let mut writer = ConFrameWriter::from_path(&path).unwrap();
3345    ///     writer.write_frame(&frame).unwrap();
3346    ///     writer.flush().unwrap();
3347    /// }
3348    /// {
3349    ///     let mut writer = ConFrameWriter::from_path_append(&path).unwrap();
3350    ///     writer.write_frame(&frame).unwrap();
3351    ///     writer.flush().unwrap();
3352    /// }
3353    /// let frames = read_all_frames(&path).unwrap();
3354    /// assert_eq!(frames.len(), 2);
3355    /// let _ = std::fs::remove_file(&path);
3356    /// ```
3357    pub fn from_path_append<P: AsRef<Path>>(path: P) -> io::Result<Self> {
3358        Ok(Self::new(open_uncompressed_append(path.as_ref())?))
3359    }
3360
3361    /// Opens an uncompressed file for appending with a fixed decimal precision.
3362    pub fn from_path_append_with_precision<P: AsRef<Path>>(
3363        path: P,
3364        precision: usize,
3365    ) -> io::Result<Self> {
3366        Ok(Self::with_precision(
3367            open_uncompressed_append(path.as_ref())?,
3368            precision,
3369        ))
3370    }
3371}
3372
3373/// Opens `path` at the end. See [`ConFrameWriter::from_path_append`].
3374pub(crate) fn open_uncompressed_append(path: &Path) -> io::Result<File> {
3375    if let Some(ext) = path.extension().and_then(|ext| ext.to_str())
3376        && (ext == "gz" || ext == "zst")
3377    {
3378        return Err(io::Error::new(
3379            io::ErrorKind::InvalidInput,
3380            "append is only supported for an uncompressed file",
3381        ));
3382    }
3383    let mut file = OpenOptions::new()
3384        .create(true)
3385        .read(true)
3386        .append(true)
3387        .open(path)?;
3388    let len = file.seek(SeekFrom::End(0))?;
3389    if len > 0 {
3390        file.seek(SeekFrom::End(-1))?;
3391        let mut last = [0u8; 1];
3392        file.read_exact(&mut last)?;
3393        if last[0] != b'\n' {
3394            file.write_all(b"\n")?;
3395        }
3396    }
3397    Ok(file)
3398}
3399
3400/// Serializes `frames` to CON bytes. No file is created.
3401///
3402/// The bytes match [`ConFrameWriter::from_path`] writing the same frames.
3403pub fn write_frames_to_vec(frames: &[ConFrame]) -> Result<Vec<u8>, WriteError> {
3404    write_frames_to_vec_with_threads(frames, 1, None, false)
3405}
3406
3407/// Serializes `frames` to CON bytes.
3408///
3409/// `workers < 2` is [`write_frames_to_vec`]. Two or more workers format
3410/// disjoint frame runs into private buffers and concatenate those buffers
3411/// in file order. One wide frame formats its coordinate rows the same way.
3412/// The bytes match a serial write.
3413pub fn write_frames_to_vec_with_threads(
3414    frames: &[ConFrame],
3415    workers: usize,
3416    precision: Option<usize>,
3417    canonical: bool,
3418) -> Result<Vec<u8>, WriteError> {
3419    let refs: Vec<&ConFrame> = frames.iter().collect();
3420    write_frame_refs_with_threads(&refs, workers, precision, canonical)
3421}
3422
3423/// Write `frames` to `path`.
3424///
3425/// Each worker formats a contiguous run. A prefix sum of those lengths
3426/// is the file offset, and each run is written with `pwrite` at that
3427/// offset. The bytes match [`write_frame_refs_with_threads`].
3428///
3429/// The destination is replaced only after every byte is stored. On Linux
3430/// the store is an unnamed file (`O_TMPFILE`), so a killed writer leaves
3431/// neither a partial destination nor a scratch name. A named
3432/// `.readcon-write-*.tmp` is used only where `O_TMPFILE` is unavailable,
3433/// and that name is removed if the write fails.
3434fn destination_dir(path: &Path) -> std::path::PathBuf {
3435    match path.parent() {
3436        Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
3437        _ => std::path::PathBuf::from("."),
3438    }
3439}
3440
3441fn scratch_name(dir: &Path) -> std::path::PathBuf {
3442    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3443    dir.join(format!(
3444        ".readcon-write-{}-{}.tmp",
3445        std::process::id(),
3446        NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
3447    ))
3448}
3449
3450/// A file that is not the destination until [`Unpublished::commit`].
3451struct Unpublished {
3452    file: File,
3453    scratch: Option<std::path::PathBuf>,
3454    committed: bool,
3455}
3456
3457impl Drop for Unpublished {
3458    fn drop(&mut self) {
3459        if self.committed {
3460            return;
3461        }
3462        if let Some(path) = self.scratch.take() {
3463            let _ = std::fs::remove_file(path);
3464        }
3465    }
3466}
3467
3468impl Unpublished {
3469    fn create(dest: &Path) -> io::Result<Self> {
3470        let dir = destination_dir(dest);
3471        if let Some(file) = open_unnamed(&dir) {
3472            return Ok(Self {
3473                file,
3474                scratch: None,
3475                committed: false,
3476            });
3477        }
3478        let scratch = scratch_name(&dir);
3479        let file = OpenOptions::new()
3480            .read(true)
3481            .write(true)
3482            .create(true)
3483            .truncate(true)
3484            .open(&scratch)?;
3485        Ok(Self {
3486            file,
3487            scratch: Some(scratch),
3488            committed: false,
3489        })
3490    }
3491
3492    fn duplicate(&self) -> io::Result<File> {
3493        self.file.try_clone()
3494    }
3495
3496    /// Give other processes a name for this inode. [`Self::commit`] publishes
3497    /// that name, so a ranked write does not grow a second publisher.
3498    fn expose(&mut self, dest: &Path) -> io::Result<std::path::PathBuf> {
3499        if let Some(path) = &self.scratch {
3500            return Ok(path.clone());
3501        }
3502        // Only Linux `O_TMPFILE` leaves the inode unnamed. macOS and Windows
3503        // already stored a scratch path in `create`, and `commit` renames it.
3504        #[cfg(target_os = "linux")]
3505        {
3506            let scratch = scratch_name(&destination_dir(dest));
3507            link_fd(&self.file, &scratch)?;
3508            self.scratch = Some(scratch.clone());
3509            Ok(scratch)
3510        }
3511        #[cfg(not(target_os = "linux"))]
3512        {
3513            let _ = dest;
3514            Err(io::Error::new(
3515                io::ErrorKind::Unsupported,
3516                "an unnamed store has no directory entry to expose",
3517            ))
3518        }
3519    }
3520
3521    fn commit(mut self, dest: &Path) -> io::Result<()> {
3522        if let Some(scratch) = self.scratch.take() {
3523            match std::fs::rename(&scratch, dest) {
3524                Ok(()) => {
3525                    self.committed = true;
3526                    Ok(())
3527                }
3528                Err(err) => {
3529                    let _ = std::fs::remove_file(&scratch);
3530                    Err(err)
3531                }
3532            }
3533        } else {
3534            // Link and rename in a child. A kill of this process does not
3535            // stop that child, so the scratch name does not outlive the publish.
3536            publish_unnamed(&self.file, dest)?;
3537            self.committed = true;
3538            Ok(())
3539        }
3540    }
3541}
3542
3543#[cfg(target_os = "linux")]
3544fn link_fd(file: &File, scratch: &Path) -> io::Result<()> {
3545    use std::os::fd::AsRawFd;
3546    let proc = std::ffi::CString::new(format!("/proc/self/fd/{}", file.as_raw_fd()))
3547        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "proc fd"))?;
3548    let scratch_c = std::ffi::CString::new(scratch.as_os_str().as_encoded_bytes())
3549        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "scratch"))?;
3550    let linked = unsafe {
3551        libc::linkat(
3552            libc::AT_FDCWD,
3553            proc.as_ptr(),
3554            libc::AT_FDCWD,
3555            scratch_c.as_ptr(),
3556            libc::AT_SYMLINK_FOLLOW,
3557        )
3558    };
3559    if linked == 0 {
3560        Ok(())
3561    } else {
3562        Err(io::Error::last_os_error())
3563    }
3564}
3565
3566/// A file other ranks can open, published by [`Unpublished::commit`].
3567pub(crate) struct SharedStore {
3568    staged: Unpublished,
3569    path: std::path::PathBuf,
3570}
3571
3572/// Allocate one fresh file of `len` bytes in `dest`'s directory.
3573///
3574/// Rank 0 calls this. The returned path is the inode the other ranks open.
3575/// [`commit_shared_store`] is the only publish.
3576pub(crate) fn begin_shared_store(dest: &Path, len: u64) -> io::Result<SharedStore> {
3577    if let Some(parent) = dest.parent().filter(|dir| !dir.as_os_str().is_empty()) {
3578        let _ = std::fs::create_dir_all(parent);
3579    }
3580    let mut staged = Unpublished::create(dest)?;
3581    allocate_len(&staged.file, len)?;
3582    let path = staged.expose(dest)?;
3583    Ok(SharedStore { staged, path })
3584}
3585
3586pub(crate) fn commit_shared_store(store: SharedStore, dest: &Path) -> io::Result<()> {
3587    store.staged.commit(dest)
3588}
3589
3590impl SharedStore {
3591    pub(crate) fn path(&self) -> &Path {
3592        &self.path
3593    }
3594}
3595
3596pub(crate) fn allocate_len(file: &File, total: u64) -> io::Result<()> {
3597    if total == 0 {
3598        return Ok(());
3599    }
3600    // `libc::fallocate` is Linux and Android. `libc::posix_fallocate` is
3601    // FreeBSD. macOS libSystem has neither: a declared `posix_fallocate`
3602    // fails the link. `fcntl(F_PREALLOCATE)` reserves the bytes there, and
3603    // `set_len` makes the logical size exact because that call does not.
3604    // Windows and every other host only call `set_len`. `EOPNOTSUPP`,
3605    // `ENOTSUP`, `ENOSYS`, and `EINVAL` mean this filesystem rejected the
3606    // reserve, so `set_len` still runs. `ENOSPC` and every other error are
3607    // returned.
3608    let current = file.metadata()?.len();
3609    if current > total {
3610        return file.set_len(total);
3611    }
3612    if current < total {
3613        reserve_len(file, total)?;
3614        if file.metadata()?.len() != total {
3615            file.set_len(total)?;
3616        }
3617    }
3618    Ok(())
3619}
3620
3621fn reserve_len(file: &File, total: u64) -> io::Result<()> {
3622    #[cfg(all(
3623        not(miri),
3624        any(
3625            target_os = "linux",
3626            target_os = "android",
3627            target_os = "freebsd",
3628            target_os = "macos"
3629        )
3630    ))]
3631    {
3632        if let Err(err) = reserve_blocks(file, total) {
3633            if !reserve_unsupported(&err) {
3634                return Err(err);
3635            }
3636        }
3637    }
3638    #[cfg(any(
3639        miri,
3640        not(any(
3641            target_os = "linux",
3642            target_os = "android",
3643            target_os = "freebsd",
3644            target_os = "macos"
3645        ))
3646    ))]
3647    {
3648        let _ = (file, total);
3649    }
3650    Ok(())
3651}
3652
3653#[cfg(all(not(miri), any(target_os = "linux", target_os = "android")))]
3654fn reserve_blocks(file: &File, total: u64) -> io::Result<()> {
3655    use std::os::fd::AsRawFd;
3656    let rc = unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, total as libc::off_t) };
3657    if rc == 0 {
3658        Ok(())
3659    } else {
3660        Err(io::Error::last_os_error())
3661    }
3662}
3663
3664#[cfg(all(not(miri), target_os = "freebsd"))]
3665fn reserve_blocks(file: &File, total: u64) -> io::Result<()> {
3666    use std::os::fd::AsRawFd;
3667    // `posix_fallocate` returns the error number. It does not return `-1`.
3668    let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, total as libc::off_t) };
3669    if rc == 0 {
3670        Ok(())
3671    } else {
3672        Err(io::Error::from_raw_os_error(rc))
3673    }
3674}
3675
3676#[cfg(all(not(miri), target_os = "macos"))]
3677fn reserve_blocks(file: &File, total: u64) -> io::Result<()> {
3678    use std::os::fd::AsRawFd;
3679    let extra = total.saturating_sub(file.metadata()?.len());
3680    if extra == 0 {
3681        return Ok(());
3682    }
3683    // `F_PEOFPOSMODE` reserves `fst_length` bytes at the physical end.
3684    // The file is shorter than `total`, so this is the gap, not a second copy.
3685    // `fcntl(2)`: `F_ALLOCATECONTIG` alone can succeed after a short
3686    // allocation. A shortfall returns `ENOSPC` only when `F_ALLOCATEALL`
3687    // is set, so both calls set it. The retry drops the contiguous demand.
3688    let mut store = libc::fstore_t {
3689        fst_flags: libc::F_ALLOCATECONTIG | libc::F_ALLOCATEALL,
3690        fst_posmode: libc::F_PEOFPOSMODE,
3691        fst_offset: 0,
3692        fst_length: extra as libc::off_t,
3693        fst_bytesalloc: 0,
3694    };
3695    let fd = file.as_raw_fd();
3696    let rc = unsafe { libc::fcntl(fd, libc::F_PREALLOCATE, &mut store) };
3697    if rc != -1 {
3698        return Ok(());
3699    }
3700    let err = io::Error::last_os_error();
3701    if err.raw_os_error() != Some(libc::ENOSPC) {
3702        return Err(err);
3703    }
3704    store.fst_flags = libc::F_ALLOCATEALL;
3705    store.fst_bytesalloc = 0;
3706    let rc = unsafe { libc::fcntl(fd, libc::F_PREALLOCATE, &mut store) };
3707    if rc == -1 {
3708        Err(io::Error::last_os_error())
3709    } else {
3710        Ok(())
3711    }
3712}
3713
3714#[cfg(all(
3715    not(miri),
3716    any(
3717        target_os = "linux",
3718        target_os = "android",
3719        target_os = "freebsd",
3720        target_os = "macos"
3721    )
3722))]
3723fn reserve_unsupported(err: &io::Error) -> bool {
3724    matches!(
3725        err.raw_os_error(),
3726        Some(code)
3727            if code == libc::EOPNOTSUPP
3728                || code == libc::ENOTSUP
3729                || code == libc::ENOSYS
3730                || code == libc::EINVAL
3731    )
3732}
3733
3734/// How a fresh ranked file is filled after it has been allocated.
3735#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3736pub(crate) enum RankedStore {
3737    /// Each rank pwrites its frames at the offsets from the layout pass.
3738    Parallel,
3739    /// Rank 0 receives every slice and pwrites them in order.
3740    Sequential,
3741    /// Each rank calls `MPI_File_write_at_all` on the preallocated scratch.
3742    MpiIo,
3743}
3744
3745const LUSTRE_SUPER_MAGIC: u32 = 0x0BD0_0BD0;
3746const GPFS_SUPER_MAGIC: u32 = 0x4750_4653;
3747const BEEGFS_SUPER_MAGIC: u32 = 0x1983_0326;
3748const PANFS_SUPER_MAGIC: u32 = 0xAAD7_AAEA;
3749
3750/// Per-rank `pwrite` on a local filesystem. Lustre, GPFS, BeeGFS, and
3751/// PanFS use collective MPI-IO into the same preallocated scratch.
3752/// A sign-extended 32-bit `statfs` word still matches on the low 32 bits.
3753/// `READCON_RANKED_WRITE=sequential` is the rank-0 gather.
3754pub(crate) fn ranked_store_for_magic(magic: i64) -> RankedStore {
3755    match magic as u32 {
3756        LUSTRE_SUPER_MAGIC | GPFS_SUPER_MAGIC | BEEGFS_SUPER_MAGIC | PANFS_SUPER_MAGIC => {
3757            RankedStore::MpiIo
3758        }
3759        _ => RankedStore::Parallel,
3760    }
3761}
3762
3763/// `READCON_RANKED_WRITE=parallel`, `sequential`, or `mpiio`.
3764/// Anything else is an error.
3765pub(crate) fn ranked_store_override(value: &str) -> Result<RankedStore, String> {
3766    match value {
3767        "parallel" => Ok(RankedStore::Parallel),
3768        "sequential" => Ok(RankedStore::Sequential),
3769        "mpiio" => Ok(RankedStore::MpiIo),
3770        _ => Err(format!(
3771            "READCON_RANKED_WRITE={value} is not parallel, sequential, or mpiio"
3772        )),
3773    }
3774}
3775
3776fn filesystem_magic(file: &File) -> Option<i64> {
3777    #[cfg(all(target_os = "linux", not(miri)))]
3778    {
3779        use std::os::fd::AsRawFd;
3780        let mut stat = unsafe { std::mem::zeroed::<libc::statfs>() };
3781        let rc = unsafe { libc::fstatfs(file.as_raw_fd(), &mut stat) };
3782        if rc == 0 {
3783            // `__fsword_t` is `long`: already `i64` on LP64, `i32` on 32-bit.
3784            #[cfg(target_pointer_width = "64")]
3785            {
3786                return Some(stat.f_type);
3787            }
3788            #[cfg(target_pointer_width = "32")]
3789            {
3790                return Some(stat.f_type as i64);
3791            }
3792        }
3793        None
3794    }
3795    #[cfg(any(not(target_os = "linux"), miri))]
3796    {
3797        let _ = file;
3798        None
3799    }
3800}
3801
3802pub(crate) fn choose_ranked_store(file: &File) -> Result<RankedStore, String> {
3803    if let Ok(value) = std::env::var("READCON_RANKED_WRITE") {
3804        return ranked_store_override(&value);
3805    }
3806    Ok(ranked_store_for_magic(filesystem_magic(file).unwrap_or(0)))
3807}
3808
3809/// In-process form of a ranked write.
3810///
3811/// `slices` are the rank-ordered byte ranges. `rewrite == false` is the
3812/// default: one fresh file, published by [`commit_shared_store`], and no
3813/// `.rewrite` sibling. The same `statfs` choice as the ranked MPI store
3814/// applies, and `READCON_RANKED_WRITE` overrides it. One process already
3815/// holds every slice, so both choices pwrite those slices at their offsets.
3816/// `rewrite == true` fills `path.rewrite` and renames it over `path`.
3817/// `keep_spare` parks the previous inode at that name.
3818pub fn publish_ranked_slices(
3819    path: &Path,
3820    slices: &[&[u8]],
3821    rewrite: bool,
3822    keep_spare: bool,
3823) -> io::Result<()> {
3824    let total: u64 = slices.iter().map(|slice| slice.len() as u64).sum();
3825    if rewrite {
3826        let spare = prepare_rewrite_spare(path)?;
3827        {
3828            let file = OpenOptions::new()
3829                .read(true)
3830                .write(true)
3831                .create(true)
3832                .truncate(false)
3833                .open(&spare)?;
3834            if file.metadata()?.len() != total {
3835                file.set_len(total)?;
3836            }
3837            write_slices_at(&file, slices)?;
3838        }
3839        return publish_rewrite(&spare, path, keep_spare);
3840    }
3841    let store = begin_shared_store(path, total)?;
3842    {
3843        let file = OpenOptions::new()
3844            .read(true)
3845            .write(true)
3846            .open(store.path())?;
3847        match choose_ranked_store(&file)
3848            .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?
3849        {
3850            RankedStore::Parallel | RankedStore::Sequential | RankedStore::MpiIo => {
3851                write_slices_at(&file, slices)?
3852            }
3853        }
3854    }
3855    commit_shared_store(store, path)
3856}
3857
3858fn write_slices_at(file: &File, slices: &[&[u8]]) -> io::Result<()> {
3859    let mut offset = 0u64;
3860    for slice in slices {
3861        if !slice.is_empty() {
3862            #[cfg(unix)]
3863            {
3864                use std::os::unix::fs::FileExt;
3865                let mut at = 0usize;
3866                while at < slice.len() {
3867                    let n = file.write_at(&slice[at..], offset + at as u64)?;
3868                    if n == 0 {
3869                        return Err(io::Error::new(
3870                            io::ErrorKind::WriteZero,
3871                            "ranked slice wrote no bytes",
3872                        ));
3873                    }
3874                    at += n;
3875                }
3876            }
3877            #[cfg(windows)]
3878            {
3879                use std::os::windows::fs::FileExt;
3880                let mut at = 0usize;
3881                while at < slice.len() {
3882                    let n = file.seek_write(&slice[at..], offset + at as u64)?;
3883                    if n == 0 {
3884                        return Err(io::Error::new(
3885                            io::ErrorKind::WriteZero,
3886                            "ranked slice wrote no bytes",
3887                        ));
3888                    }
3889                    at += n;
3890                }
3891            }
3892            #[cfg(not(any(unix, windows)))]
3893            {
3894                let _ = (file, slice, offset);
3895                return Err(io::Error::new(
3896                    io::ErrorKind::Unsupported,
3897                    "ranked slices require pwrite",
3898                ));
3899            }
3900        }
3901        offset += slice.len() as u64;
3902    }
3903    Ok(())
3904}
3905
3906fn publish_unnamed(file: &File, dest: &Path) -> io::Result<()> {
3907    #[cfg(target_os = "linux")]
3908    {
3909        use std::os::fd::AsRawFd;
3910        let scratch = scratch_name(&destination_dir(dest));
3911        let proc = std::ffi::CString::new(format!("/proc/self/fd/{}", file.as_raw_fd()))
3912            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "proc fd"))?;
3913        let scratch_c = std::ffi::CString::new(scratch.as_os_str().as_encoded_bytes())
3914            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "scratch"))?;
3915        let dest_c = std::ffi::CString::new(dest.as_os_str().as_encoded_bytes())
3916            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "dest"))?;
3917        #[cfg(tsan_run)]
3918        {
3919            // TSan cannot safely continue in a child of this multithreaded
3920            // CPython process: its inherited runtime exits with code 66.
3921            // Exercise the same link-and-rename publication in the parent.
3922            let linked = unsafe {
3923                libc::linkat(
3924                    libc::AT_FDCWD,
3925                    proc.as_ptr(),
3926                    libc::AT_FDCWD,
3927                    scratch_c.as_ptr(),
3928                    libc::AT_SYMLINK_FOLLOW,
3929                )
3930            };
3931            if linked != 0 {
3932                return Err(io::Error::last_os_error());
3933            }
3934            let renamed = unsafe { libc::rename(scratch_c.as_ptr(), dest_c.as_ptr()) };
3935            if renamed != 0 {
3936                let error = io::Error::last_os_error();
3937                let _ = std::fs::remove_file(&scratch);
3938                return Err(error);
3939            }
3940            return Ok(());
3941        }
3942
3943        #[cfg(not(tsan_run))]
3944        {
3945            let pid = unsafe { libc::fork() };
3946            if pid < 0 {
3947                return Err(io::Error::last_os_error());
3948            }
3949            if pid == 0 {
3950                let linked = unsafe {
3951                    libc::linkat(
3952                        libc::AT_FDCWD,
3953                        proc.as_ptr(),
3954                        libc::AT_FDCWD,
3955                        scratch_c.as_ptr(),
3956                        libc::AT_SYMLINK_FOLLOW,
3957                    )
3958                };
3959                if linked != 0 {
3960                    unsafe { libc::_exit(1) };
3961                }
3962                let renamed = unsafe { libc::rename(scratch_c.as_ptr(), dest_c.as_ptr()) };
3963                unsafe { libc::_exit(if renamed == 0 { 0 } else { 1 }) };
3964            }
3965            let mut status = 0;
3966            loop {
3967                let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
3968                if waited >= 0 {
3969                    break;
3970                }
3971                let err = io::Error::last_os_error();
3972                if err.kind() != io::ErrorKind::Interrupted {
3973                    return Err(err);
3974                }
3975            }
3976            // The child has finished, so a leftover scratch is this publish's
3977            // name and not a concurrent writer's.
3978            let published = libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0;
3979            if !published {
3980                if scratch.exists() {
3981                    let _ = std::fs::remove_file(&scratch);
3982                }
3983                return Err(io::Error::other("publish did not replace the destination"));
3984            }
3985            Ok(())
3986        }
3987    }
3988    #[cfg(not(target_os = "linux"))]
3989    {
3990        let _ = (file, dest);
3991        Err(io::Error::new(
3992            io::ErrorKind::Unsupported,
3993            "unnamed publish",
3994        ))
3995    }
3996}
3997
3998fn open_unnamed(dir: &Path) -> Option<File> {
3999    #[cfg(target_os = "linux")]
4000    {
4001        use std::os::fd::FromRawFd;
4002        let bytes = dir.as_os_str().as_encoded_bytes();
4003        let c_dir = std::ffi::CString::new(bytes).ok()?;
4004        let fd = unsafe { libc::open(c_dir.as_ptr(), libc::O_TMPFILE | libc::O_RDWR, 0o600) };
4005        if fd < 0 {
4006            return None;
4007        }
4008        Some(unsafe { File::from_raw_fd(fd) })
4009    }
4010    #[cfg(not(target_os = "linux"))]
4011    {
4012        let _ = dir;
4013        None
4014    }
4015}
4016
4017fn begin_unpublished(path: &Path) -> Result<(Unpublished, File), WriteError> {
4018    let staged = Unpublished::create(path).map_err(WriteError::Io)?;
4019    let file = staged.duplicate().map_err(WriteError::Io)?;
4020    Ok((staged, file))
4021}
4022
4023fn finish_unpublished(
4024    staged: Unpublished,
4025    dest: &Path,
4026    result: Result<(), WriteError>,
4027) -> Result<(), WriteError> {
4028    match result {
4029        Ok(()) => staged.commit(dest).map_err(WriteError::Io),
4030        Err(err) => Err(err),
4031    }
4032}
4033
4034/// Replace `dest` with the bytes `write` stores, or leave `dest` untouched.
4035pub(crate) fn publish_new<E>(
4036    dest: &Path,
4037    map_io: impl Fn(io::Error) -> E,
4038    write: impl FnOnce(&mut File) -> Result<(), E>,
4039) -> Result<(), E> {
4040    let staged = Unpublished::create(dest).map_err(&map_io)?;
4041    let mut file = staged.duplicate().map_err(&map_io)?;
4042    write(&mut file)?;
4043    drop(file);
4044    staged.commit(dest).map_err(map_io)
4045}
4046
4047fn mass_runs(masses: &[f64]) -> (Vec<usize>, Vec<f64>) {
4048    let mut counts = Vec::new();
4049    let mut values = Vec::new();
4050    let mut index = 0usize;
4051    while index < masses.len() {
4052        let mass = masses[index];
4053        let bits = mass.to_bits();
4054        let mut count = 1usize;
4055        while index + count < masses.len() && masses[index + count].to_bits() == bits {
4056            count += 1;
4057        }
4058        counts.push(count);
4059        values.push(mass);
4060        index += count;
4061    }
4062    (counts, values)
4063}
4064
4065fn column_fixed(fixed: Option<&[f64]>, index: usize) -> u8 {
4066    let flags = match fixed {
4067        Some(bits) => {
4068            let base = index * 3;
4069            [
4070                bits[base] != 0.0,
4071                bits[base + 1] != 0.0,
4072                bits[base + 2] != 0.0,
4073            ]
4074        }
4075        None => [false, false, false],
4076    };
4077    written_fixed_flag(flags, crate::CON_SPEC_VERSION)
4078}
4079
4080/// Spellings of `0.0` ..= `9999.0`, the form `encode_fixed_decimal` emits
4081/// for those integers. A lattice coordinate hits this table instead of the
4082/// general float formatter.
4083fn small_int_text(n: u32) -> &'static [u8] {
4084    use std::sync::OnceLock;
4085    const LIMIT: u32 = 10_000;
4086    static TEXT: OnceLock<Vec<u8>> = OnceLock::new();
4087    static OFF: OnceLock<Vec<u32>> = OnceLock::new();
4088    let text = TEXT.get_or_init(|| {
4089        let mut bytes = Vec::with_capacity(LIMIT as usize * 6);
4090        let mut off = Vec::with_capacity(LIMIT as usize + 1);
4091        off.push(0u32);
4092        for value in 0..LIMIT {
4093            let start = bytes.len();
4094            let mut tmp = [0u8; 8];
4095            let mut i = tmp.len();
4096            let mut n = value;
4097            if n == 0 {
4098                i -= 1;
4099                tmp[i] = b'0';
4100            } else {
4101                while n > 0 {
4102                    i -= 1;
4103                    tmp[i] = b'0' + (n % 10) as u8;
4104                    n /= 10;
4105                }
4106            }
4107            bytes.extend_from_slice(&tmp[i..]);
4108            bytes.extend_from_slice(b".0");
4109            off.push(bytes.len() as u32);
4110            let _ = start;
4111        }
4112        OFF.set(off).ok();
4113        bytes
4114    });
4115    let off = OFF.get().expect("small int offsets");
4116    let n = n as usize;
4117    &text[off[n] as usize..off[n + 1] as usize]
4118}
4119
4120fn push_column_f64(buf: &mut Vec<u8>, ryu: &mut ryu::Buffer, slot: &mut FmtSlot, value: f64) {
4121    // `-0.0` compares equal to `0.0`, and ryu keeps the sign.
4122    if value == 0.0 {
4123        buf.extend_from_slice(if value.is_sign_negative() {
4124            b"-0.0"
4125        } else {
4126            b"0.0"
4127        });
4128        return;
4129    }
4130    if (0.0..10_000.0).contains(&value) {
4131        let n = value as u32;
4132        if n as f64 == value {
4133            buf.extend_from_slice(small_int_text(n));
4134            return;
4135        }
4136    }
4137    push_round_trip(buf, ryu, Some(slot), value);
4138}
4139
4140/// Decimal form of a sequential atom id. Incrementing the last digit is the
4141/// common step; a run of nines carries once per power of ten.
4142struct IdDigits {
4143    buf: [u8; 20],
4144    start: usize,
4145}
4146
4147impl IdDigits {
4148    fn from_u64(mut n: u64) -> Self {
4149        let mut buf = [b'0'; 20];
4150        let mut i = 20usize;
4151        if n == 0 {
4152            return Self { buf, start: 19 };
4153        }
4154        while n > 0 {
4155            i -= 1;
4156            buf[i] = b'0' + (n % 10) as u8;
4157            n /= 10;
4158        }
4159        Self { buf, start: i }
4160    }
4161
4162    fn text(&self) -> &[u8] {
4163        &self.buf[self.start..]
4164    }
4165
4166    fn bump(&mut self) {
4167        let mut i = self.buf.len() - 1;
4168        loop {
4169            if self.buf[i] < b'9' {
4170                self.buf[i] += 1;
4171                if i < self.start {
4172                    self.start = i;
4173                }
4174                return;
4175            }
4176            self.buf[i] = b'0';
4177            if i == 0 {
4178                return;
4179            }
4180            i -= 1;
4181        }
4182    }
4183}
4184
4185fn push_column_line(
4186    buf: &mut Vec<u8>,
4187    ryu: &mut ryu::Buffer,
4188    slots: &mut [FmtSlot; 3],
4189    xyz: [f64; 3],
4190    mask: u8,
4191    id: &[u8],
4192) {
4193    push_column_f64(buf, ryu, &mut slots[0], xyz[0]);
4194    buf.push(b' ');
4195    push_column_f64(buf, ryu, &mut slots[1], xyz[1]);
4196    buf.push(b' ');
4197    push_column_f64(buf, ryu, &mut slots[2], xyz[2]);
4198    buf.push(b' ');
4199    buf.push(b'0' + mask);
4200    buf.push(b' ');
4201    buf.extend_from_slice(id);
4202    buf.push(b'\n');
4203}
4204
4205fn format_column_span(
4206    positions: &[f64],
4207    extra: Option<&[f64]>,
4208    fixed: Option<&[f64]>,
4209    start: usize,
4210    end: usize,
4211) -> (Vec<u8>, Vec<u8>) {
4212    let n = end - start;
4213    let mut coord = Vec::with_capacity(n.saturating_mul(32));
4214    let mut side = if extra.is_some() {
4215        Vec::with_capacity(n.saturating_mul(32))
4216    } else {
4217        Vec::new()
4218    };
4219    append_column_span(&mut coord, &mut side, positions, extra, fixed, start, end);
4220    (coord, side)
4221}
4222
4223fn append_column_span(
4224    coord: &mut Vec<u8>,
4225    side: &mut Vec<u8>,
4226    positions: &[f64],
4227    extra: Option<&[f64]>,
4228    fixed: Option<&[f64]>,
4229    start: usize,
4230    end: usize,
4231) {
4232    let mut ryu = ryu::Buffer::new();
4233    let mut slots = [FmtSlot::new(); 3];
4234    let mut side_slots = [FmtSlot::new(); 3];
4235    let mut ids = IdDigits::from_u64(start as u64);
4236    for index in start..end {
4237        let base = index * 3;
4238        let mask = column_fixed(fixed, index);
4239        let mut id_buf = [0u8; 20];
4240        let id_len = ids.text().len();
4241        id_buf[..id_len].copy_from_slice(ids.text());
4242        let id = &id_buf[..id_len];
4243        push_column_line(
4244            coord,
4245            &mut ryu,
4246            &mut slots,
4247            [positions[base], positions[base + 1], positions[base + 2]],
4248            mask,
4249            id,
4250        );
4251        if let Some(values) = extra {
4252            push_column_line(
4253                side,
4254                &mut ryu,
4255                &mut side_slots,
4256                [values[base], values[base + 1], values[base + 2]],
4257                mask,
4258                id,
4259            );
4260        }
4261        ids.bump();
4262    }
4263}
4264
4265fn format_column_parallel(
4266    positions: &[f64],
4267    extra: Option<&[f64]>,
4268    fixed: Option<&[f64]>,
4269    start: usize,
4270    end: usize,
4271    workers: usize,
4272) -> (Vec<u8>, Vec<u8>) {
4273    let span = end - start;
4274    if workers < 2 || span < WIDE_ATOM_GRAIN {
4275        return format_column_span(positions, extra, fixed, start, end);
4276    }
4277    let workers = workers.min(span);
4278    let mut bounds = Vec::with_capacity(workers);
4279    for worker in 0..workers {
4280        let from = start + span * worker / workers;
4281        let to = start + span * (worker + 1) / workers;
4282        if from < to {
4283            bounds.push((from, to));
4284        }
4285    }
4286    let mut parts = Vec::with_capacity(bounds.len());
4287    std::thread::scope(|scope| {
4288        let mut handles = Vec::with_capacity(bounds.len());
4289        for (from, to) in bounds {
4290            handles
4291                .push(scope.spawn(move || format_column_span(positions, extra, fixed, from, to)));
4292        }
4293        for handle in handles {
4294            parts.push(handle.join().unwrap_or_else(|_| (Vec::new(), Vec::new())));
4295        }
4296    });
4297    let mut coord = Vec::new();
4298    let mut side = Vec::new();
4299    for (rows, extra_rows) in parts {
4300        coord.extend_from_slice(&rows);
4301        side.extend_from_slice(&extra_rows);
4302    }
4303    (coord, side)
4304}
4305
4306fn column_header(
4307    cell: &[f64],
4308    counts: &[usize],
4309    mass_values: &[f64],
4310    symbol: &str,
4311    has_velocity: bool,
4312    has_force: bool,
4313    written_spec: u32,
4314) -> Result<Vec<u8>, WriteError> {
4315    let mut builder =
4316        ConFrameBuilder::new([cell[0], cell[1], cell[2]], [cell[3], cell[4], cell[5]]);
4317    builder
4318        .prebox_header("readcon")
4319        .postbox_header(["0 0".to_string(), "0 0".to_string()])
4320        .add_atom(symbol, 0.0, 0.0, 0.0, [false; 3], 0, mass_values[0]);
4321    if has_velocity {
4322        builder.with_velocity([0.0, 0.0, 0.0]);
4323    }
4324    if has_force {
4325        builder.with_force([0.0, 0.0, 0.0]);
4326    }
4327    let mut frame = builder.build().map_err(WriteError::Format)?;
4328    frame.header.natm_types = counts.len();
4329    frame.header.natms_per_type = counts.to_vec();
4330    frame.header.masses_per_type = mass_values.to_vec();
4331    frame.header.postbox_header = ["0 0".to_string(), "0 0".to_string()];
4332    frame.header.prebox_header = crate::types::PreboxHeader::new("readcon");
4333    // Spec 2 in the stored header, so the binding stamp records the natural
4334    // time unit. `written_spec` is the major on the line. Major 3 is the
4335    // measurement file. Major 4 is the current writer.
4336    frame.header.spec_version = 2;
4337    let mut metadata = BTreeMap::new();
4338    metadata.insert(meta::CON_SPEC_MINOR.to_string(), json!(1));
4339    metadata.insert(meta::CON_SPEC_VERSION.to_string(), json!(2));
4340    frame.header.metadata = crate::types::FrameMeta::from_map(metadata);
4341    binding_header_bytes_at(&frame, written_spec)
4342}
4343
4344#[allow(clippy::too_many_arguments)]
4345/// Write binding CON text from column slices, without a per-atom object.
4346///
4347/// `workers` of 0 uses one thread per physical core. The bytes match
4348/// [`ConFrameWriter::write_frame_bound`] of the frame those columns describe.
4349pub fn write_binding_columns(
4350    path: &Path,
4351    n_frames: usize,
4352    n_atoms: usize,
4353    positions: &[f64],
4354    masses: &[f64],
4355    cell: &[f64],
4356    fixed: Option<&[f64]>,
4357    velocities: Option<&[f64]>,
4358    forces: Option<&[f64]>,
4359    symbol: &str,
4360    workers: usize,
4361) -> Result<(), WriteError> {
4362    let mut file_bytes = Vec::new();
4363    format_binding_columns(
4364        &mut file_bytes,
4365        n_frames,
4366        n_atoms,
4367        positions,
4368        masses,
4369        cell,
4370        fixed,
4371        velocities,
4372        forces,
4373        symbol,
4374        workers,
4375        crate::CON_SPEC_VERSION,
4376    )?;
4377    publish_new(path, WriteError::Io, |file| {
4378        file.write_all(&file_bytes).map_err(WriteError::Io)
4379    })
4380}
4381
4382/// Append the text [`write_binding_columns`] writes for these frames.
4383///
4384/// Frames are formatted one after another, so appending consecutive runs
4385/// of frames gives the bytes of one call over all of them.
4386#[allow(clippy::too_many_arguments)]
4387pub(crate) fn format_binding_columns(
4388    file_bytes: &mut Vec<u8>,
4389    n_frames: usize,
4390    n_atoms: usize,
4391    positions: &[f64],
4392    masses: &[f64],
4393    cell: &[f64],
4394    fixed: Option<&[f64]>,
4395    velocities: Option<&[f64]>,
4396    forces: Option<&[f64]>,
4397    symbol: &str,
4398    workers: usize,
4399    written_spec: u32,
4400) -> Result<(), WriteError> {
4401    let workers = if workers == 0 {
4402        physical_cores()
4403    } else {
4404        workers
4405    };
4406    for frame_index in 0..n_frames {
4407        let atom_base = frame_index * n_atoms;
4408        let pos = &positions[atom_base * 3..(atom_base + n_atoms) * 3];
4409        let mass = &masses[atom_base..atom_base + n_atoms];
4410        let box_cell = &cell[frame_index * 6..frame_index * 6 + 6];
4411        crate::types::check_cellpar_finite(box_cell)
4412            .map_err(|error| WriteError::Format(error.in_frame(frame_index as u64)))?;
4413        let flags = fixed.map(|bits| &bits[atom_base * 3..(atom_base + n_atoms) * 3]);
4414        let vel = velocities.map(|bits| &bits[atom_base * 3..(atom_base + n_atoms) * 3]);
4415        let force = forces.map(|bits| &bits[atom_base * 3..(atom_base + n_atoms) * 3]);
4416        let (counts, mass_values) = mass_runs(mass);
4417        let header = column_header(
4418            box_cell,
4419            &counts,
4420            &mass_values,
4421            symbol,
4422            vel.is_some(),
4423            force.is_some(),
4424            written_spec,
4425        )?;
4426        file_bytes.extend_from_slice(&header);
4427        let mut offset = 0usize;
4428        let mut velocity_block = Vec::new();
4429        let mut force_block = Vec::new();
4430        for (type_idx, count) in counts.iter().copied().enumerate() {
4431            push_str_line(file_bytes, symbol);
4432            push_component_line(file_bytes, "Coordinates of Component", type_idx);
4433            if vel.is_some() {
4434                push_str_line(&mut velocity_block, symbol);
4435                push_component_line(&mut velocity_block, "Velocities of Component", type_idx);
4436            }
4437            if force.is_some() {
4438                push_str_line(&mut force_block, symbol);
4439                push_component_line(&mut force_block, "Forces of Component", type_idx);
4440            }
4441            if workers < 2 || count < WIDE_ATOM_GRAIN {
4442                append_column_span(
4443                    file_bytes,
4444                    &mut velocity_block,
4445                    pos,
4446                    vel,
4447                    flags,
4448                    offset,
4449                    offset + count,
4450                );
4451            } else {
4452                let (coord, side) =
4453                    format_column_parallel(pos, vel, flags, offset, offset + count, workers);
4454                file_bytes.extend_from_slice(&coord);
4455                velocity_block.extend_from_slice(&side);
4456            }
4457            if let Some(values) = force {
4458                if workers < 2 || count < WIDE_ATOM_GRAIN {
4459                    append_column_span(
4460                        &mut force_block,
4461                        &mut Vec::new(),
4462                        values,
4463                        None,
4464                        flags,
4465                        offset,
4466                        offset + count,
4467                    );
4468                } else {
4469                    let (rows, _) = format_column_parallel(
4470                        values,
4471                        None,
4472                        flags,
4473                        offset,
4474                        offset + count,
4475                        workers,
4476                    );
4477                    force_block.extend_from_slice(&rows);
4478                }
4479            }
4480            offset += count;
4481        }
4482        if vel.is_some() {
4483            file_bytes.push(b'\n');
4484            file_bytes.extend_from_slice(&velocity_block);
4485        }
4486        if force.is_some() {
4487            file_bytes.push(b'\n');
4488            file_bytes.extend_from_slice(&force_block);
4489        }
4490    }
4491    Ok(())
4492}
4493
4494/// Write `frames` to `path`, replacing that path only after the bytes are complete.
4495///
4496/// `workers` below 2 uses the serial writer. `workers >= 2` with two or
4497/// more frames formats groups in parallel. One frame of at least 4096 atoms
4498/// formats its coordinate lines on those workers. `precision` is the decimal
4499/// count, or the writer default when `None`. `canonical` selects the
4500/// canonical header. `bind` writes each frame through [`ConFrameWriter::write_frame_bound`].
4501pub fn write_frame_refs_to_path(
4502    path: &std::path::Path,
4503    frames: &[&ConFrame],
4504    workers: usize,
4505    precision: Option<usize>,
4506    canonical: bool,
4507    bind: bool,
4508) -> Result<(), WriteError> {
4509    check_frames_cell_finite(frames)?;
4510    // One writer streams each frame to the file. Building the whole text
4511    // and copying it was a second pass the parallel paths do not pay.
4512    if workers < 2 {
4513        return write_serial_frames(path, frames, precision, canonical, bind);
4514    }
4515    if workers >= 2 && frames.len() >= 2 {
4516        return pipeline_frame_groups(path, frames, workers, precision, canonical, bind);
4517    }
4518    if workers >= 2 && frames.len() == 1 && frames[0].atom_data.len() >= WIDE_ATOM_GRAIN {
4519        let mut writer = match precision {
4520            Some(precision) => ConFrameWriter::with_precision(Vec::<u8>::new(), precision),
4521            None => ConFrameWriter::new(Vec::<u8>::new()),
4522        }
4523        .canonical(canonical)
4524        .parallel_atoms(workers);
4525        // Replace the destination only after the frame is complete. Opening
4526        // it first destroyed a file the serial writer would have left alone.
4527        let (staged, file) = begin_unpublished(path)?;
4528        writer.stream_file = Some(file);
4529        let result = if bind {
4530            writer.write_frame_bound(frames[0])
4531        } else {
4532            writer.write_frame(frames[0])
4533        };
4534        drop(writer);
4535        return finish_unpublished(staged, path, result);
4536    }
4537    let parts = formatted_parts(frames, workers, precision, canonical, bind)?;
4538    let (staged, mut file) = begin_unpublished(path)?;
4539    let result = if parts.len() == 1 {
4540        // One wide frame is already formatted in parallel row runs and
4541        // joined. A single write matches the disk; slicing it into pwrite
4542        // calls spent the gain on a second pass over the file.
4543        file.write_all(&parts[0]).map_err(WriteError::Io)
4544    } else {
4545        let slices: Vec<&[u8]> = parts.iter().map(|part| part.as_slice()).collect();
4546        pwrite_borrowed(&file, &slices).map_err(WriteError::Io)
4547    };
4548    finish_unpublished(staged, path, result)
4549}
4550
4551pub(crate) fn rewrite_names(path: &Path) -> io::Result<(std::path::PathBuf, std::path::PathBuf)> {
4552    let name = path.file_name().ok_or_else(|| {
4553        io::Error::new(io::ErrorKind::InvalidInput, "rewrite path has no file name")
4554    })?;
4555    let mut spare_name = name.to_os_string();
4556    spare_name.push(".rewrite");
4557    let mut hold_name = name.to_os_string();
4558    hold_name.push(".rewrite-hold");
4559    let dir = match path.parent() {
4560        Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
4561        _ => std::path::PathBuf::from("."),
4562    };
4563    Ok((dir.join(spare_name), dir.join(hold_name)))
4564}
4565
4566/// The spare is the inode the next rewrite overwrites. A crash during the
4567/// name swap leaves that inode under the hold name; adopt it so the pages
4568/// are not thrown away.
4569pub(crate) fn prepare_rewrite_spare(path: &Path) -> io::Result<std::path::PathBuf> {
4570    let (spare, hold) = rewrite_names(path)?;
4571    if !spare.exists() && hold.exists() {
4572        std::fs::rename(&hold, &spare)?;
4573    } else if hold.exists() {
4574        std::fs::remove_file(&hold)?;
4575    }
4576    Ok(spare)
4577}
4578
4579/// Publish `spare` as `path`.
4580///
4581/// `path` keeps the previous complete file until `rename`. When
4582/// `keep_spare` is set, that inode is parked at the spare name so the next
4583/// same-length rewrite fills those pages. The spare then occupies a second
4584/// copy of the trajectory on disk. `keep_spare == false` drops it after the
4585/// rename, so the steady state is one file and the next rewrite allocates
4586/// again. A partial spare is never given the published name.
4587pub(crate) fn publish_rewrite(spare: &Path, path: &Path, keep_spare: bool) -> io::Result<()> {
4588    let (_, hold) = rewrite_names(path)?;
4589    if !keep_spare {
4590        if hold.exists() {
4591            std::fs::remove_file(&hold)?;
4592        }
4593        std::fs::rename(spare, path)?;
4594        return Ok(());
4595    }
4596    if path.exists() {
4597        if hold.exists() {
4598            std::fs::remove_file(&hold)?;
4599        }
4600        std::fs::hard_link(path, &hold)?;
4601    }
4602    std::fs::rename(spare, path)?;
4603    if hold.exists() {
4604        std::fs::rename(&hold, spare)?;
4605    }
4606    Ok(())
4607}
4608
4609fn finish_open_length(file: &File) -> io::Result<()> {
4610    let mut file = file.try_clone()?;
4611    let end = file.stream_position()?;
4612    file.set_len(end)
4613}
4614
4615/// Bytes of `frames` into an already-open file, starting at offset 0.
4616///
4617/// The file's inode is kept. `set_len` to the same length does not drop
4618/// pages, which is what a same-length rewrite uses.
4619fn store_frames_in(
4620    file: &File,
4621    frames: &[&ConFrame],
4622    workers: usize,
4623    precision: Option<usize>,
4624    canonical: bool,
4625    bind: bool,
4626) -> Result<(), WriteError> {
4627    file.try_clone()
4628        .and_then(|mut file| file.seek(SeekFrom::Start(0)).map(|_| ()))
4629        .map_err(WriteError::Io)?;
4630    if workers < 2 {
4631        let mut writer = match precision {
4632            Some(precision) => {
4633                ConFrameWriter::with_precision(file.try_clone().map_err(WriteError::Io)?, precision)
4634            }
4635            None => ConFrameWriter::new(file.try_clone().map_err(WriteError::Io)?),
4636        }
4637        .canonical(canonical);
4638        write_group(&mut writer, frames, bind)
4639            .and_then(|_| writer.flush().map_err(WriteError::Io))?;
4640        drop(writer);
4641        return finish_open_length(file).map_err(WriteError::Io);
4642    }
4643    if workers >= 2 && frames.len() >= 2 {
4644        return store_pipeline_in(file, frames, workers, precision, canonical, bind);
4645    }
4646    if workers >= 2 && frames.len() == 1 && frames[0].atom_data.len() >= WIDE_ATOM_GRAIN {
4647        let mut writer = match precision {
4648            Some(precision) => ConFrameWriter::with_precision(Vec::<u8>::new(), precision),
4649            None => ConFrameWriter::new(Vec::<u8>::new()),
4650        }
4651        .canonical(canonical)
4652        .parallel_atoms(workers);
4653        writer.stream_file = Some(file.try_clone().map_err(WriteError::Io)?);
4654        let result = if bind {
4655            writer.write_frame_bound(frames[0])
4656        } else {
4657            writer.write_frame(frames[0])
4658        };
4659        drop(writer);
4660        result?;
4661        return finish_open_length(file).map_err(WriteError::Io);
4662    }
4663    let parts = formatted_parts(frames, workers, precision, canonical, bind)?;
4664    store_disjoint_parts(file, &parts).map_err(WriteError::Io)
4665}
4666
4667#[inline]
4668fn pin_writer_worker(index: usize) {
4669    #[cfg(feature = "parallel")]
4670    crate::parser::pin_worker(index);
4671    #[cfg(not(feature = "parallel"))]
4672    let _ = index;
4673}
4674
4675fn store_pipeline_in(
4676    file: &File,
4677    frames: &[&ConFrame],
4678    workers: usize,
4679    precision: Option<usize>,
4680    canonical: bool,
4681    bind: bool,
4682) -> Result<(), WriteError> {
4683    if (2..=workers).contains(&frames.len()) {
4684        let mut parts: Vec<Result<Vec<u8>, WriteError>> = Vec::with_capacity(frames.len());
4685        std::thread::scope(|scope| {
4686            let mut guards = Vec::with_capacity(frames.len());
4687            for (index, frame) in frames.iter().enumerate() {
4688                guards.push(scope.spawn(move || {
4689                    pin_writer_worker(index);
4690                    format_group_bytes(std::slice::from_ref(frame), 1, precision, canonical, bind)
4691                }));
4692            }
4693            for guard in guards {
4694                parts.push(match guard.join() {
4695                    Ok(part) => part,
4696                    Err(_) => Err(WriteError::Io(io::Error::other("frame formatter panicked"))),
4697                });
4698            }
4699        });
4700        let mut formatted = Vec::with_capacity(parts.len());
4701        for part in parts {
4702            formatted.push(part?);
4703        }
4704        return store_disjoint_parts(file, &formatted).map_err(WriteError::Io);
4705    }
4706    let heavy = direct_slice_write(
4707        workers,
4708        frame_byte_weight(frames[0]).saturating_mul(frames.len()),
4709    );
4710    if heavy
4711        && let Some(lengths) = cached_packed_lengths(frames, workers, precision, canonical, bind)
4712    {
4713        match place_packed(file, frames, &lengths, workers, precision, canonical, bind) {
4714            Err(err) if is_packed_drift(&err) => invalidate_packed_lengths(),
4715            result => return result,
4716        }
4717    }
4718    let groups = workers.saturating_mul(4).max(workers);
4719    let ranges = group_frame_ranges(frames, groups);
4720    let pieces: Vec<&[&ConFrame]> = ranges
4721        .iter()
4722        .map(|&(start, end)| &frames[start..end])
4723        .collect();
4724    let format_threads = pipeline_format_threads(workers).min(pieces.len().max(1));
4725    let (tx, rx) = std::sync::mpsc::sync_channel::<(usize, Result<Vec<u8>, WriteError>)>(2);
4726    let next_job = std::sync::atomic::AtomicUsize::new(0);
4727    let result = std::thread::scope(|scope| -> Result<(), WriteError> {
4728        for _ in 0..format_threads {
4729            let tx = tx.clone();
4730            let pieces = &pieces;
4731            let next_job = &next_job;
4732            scope.spawn(move || {
4733                loop {
4734                    let index = next_job.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4735                    if index >= pieces.len() {
4736                        break;
4737                    }
4738                    let message = format_group_bytes(pieces[index], 1, precision, canonical, bind);
4739                    if tx.send((index, message)).is_err() {
4740                        break;
4741                    }
4742                }
4743            });
4744        }
4745        drop(tx);
4746        let mut out = file.try_clone().map_err(WriteError::Io)?;
4747        out.seek(SeekFrom::Start(0)).map_err(WriteError::Io)?;
4748        let mut next = 0usize;
4749        let mut pending = BTreeMap::<usize, Vec<u8>>::new();
4750        while next < pieces.len() {
4751            let (index, part) = rx
4752                .recv()
4753                .map_err(|err| WriteError::Io(io::Error::other(err.to_string())))?;
4754            pending.insert(index, part?);
4755            while let Some(part) = pending.remove(&next) {
4756                out.write_all(&part).map_err(WriteError::Io)?;
4757                next += 1;
4758            }
4759        }
4760        out.flush().map_err(WriteError::Io)?;
4761        Ok(())
4762    });
4763    result?;
4764    finish_open_length(file).map_err(WriteError::Io)
4765}
4766
4767/// Rewrite `path` with `frames` for a workload that keeps this trajectory name.
4768///
4769/// The new bytes are written into `path` with the suffix `.rewrite`. That
4770/// spare is a second file of the same length, so a kept spare doubles the
4771/// disk the trajectory occupies. `rename` publishes the spare only after
4772/// the write returns. Until then `path` is still the previous complete
4773/// file, including when the process is killed. `keep_spare` parks the
4774/// previous inode at `.rewrite` for the next call. Passing `false` removes
4775/// that spare after the rename. A different length allocates the extra
4776/// pages. The fresh-file writer is [`write_frame_refs_to_path`].
4777pub fn rewrite_frame_refs_to_path(
4778    path: &std::path::Path,
4779    frames: &[&ConFrame],
4780    workers: usize,
4781    precision: Option<usize>,
4782    canonical: bool,
4783    bind: bool,
4784    keep_spare: bool,
4785) -> Result<(), WriteError> {
4786    check_frames_cell_finite(frames)?;
4787    let spare = prepare_rewrite_spare(path).map_err(WriteError::Io)?;
4788    let file = OpenOptions::new()
4789        .read(true)
4790        .write(true)
4791        .create(true)
4792        .truncate(false)
4793        .open(&spare)
4794        .map_err(WriteError::Io)?;
4795    store_frames_in(&file, frames, workers, precision, canonical, bind)?;
4796    drop(file);
4797    publish_rewrite(&spare, path, keep_spare).map_err(WriteError::Io)
4798}
4799
4800/// [`write_frames_to_vec_with_threads`] over borrowed frames.
4801///
4802/// A `read_con` result can be written without cloning the trajectory.
4803pub fn write_frame_refs_with_threads(
4804    frames: &[&ConFrame],
4805    workers: usize,
4806    precision: Option<usize>,
4807    canonical: bool,
4808) -> Result<Vec<u8>, WriteError> {
4809    check_frames_cell_finite(frames)?;
4810    let mut parts = formatted_parts(frames, workers, precision, canonical, false)?;
4811    // One wide frame is already one buffer. Copying it into a second
4812    // allocation was a serial memcpy of the whole text on the timing path.
4813    if parts.len() == 1 {
4814        return Ok(parts.pop().unwrap_or_default());
4815    }
4816    let mut out = Vec::new();
4817    for part in parts {
4818        out.extend_from_slice(&part);
4819    }
4820    Ok(out)
4821}
4822
4823/// Format `frames` the way [`write_frame_refs_to_path`] does, and stop
4824/// before the file exists.
4825///
4826/// The pieces are the writer's groups, not one buffer for the whole
4827/// trajectory. Eight workers on a long run get one buffer per worker,
4828/// the same bytes that worker would format into its mapping. Two and
4829/// four workers get the pipeline's groups. One worker gets the serial
4830/// formatter's buffer. Concatenating the pieces matches the file.
4831pub fn format_frame_refs_unstored(
4832    frames: &[&ConFrame],
4833    workers: usize,
4834    precision: Option<usize>,
4835    canonical: bool,
4836    bind: bool,
4837) -> Result<Vec<Vec<u8>>, WriteError> {
4838    if frames.is_empty() {
4839        return Ok(Vec::new());
4840    }
4841    check_frames_cell_finite(frames)?;
4842    if workers < 2 || frames.len() < 2 {
4843        return Ok(vec![format_group_bytes(
4844            frames,
4845            workers.max(1),
4846            precision,
4847            canonical,
4848            bind,
4849        )?]);
4850    }
4851    if (2..=workers).contains(&frames.len()) {
4852        return format_frames_apart(frames, precision, canonical, bind);
4853    }
4854    let heavy = direct_slice_write(
4855        workers,
4856        frame_byte_weight(frames[0]).saturating_mul(frames.len()),
4857    );
4858    if heavy
4859        && let Some(lengths) = cached_packed_lengths(frames, workers, precision, canonical, bind)
4860    {
4861        match format_packed_buffers(frames, &lengths, workers, precision, canonical, bind) {
4862            Err(err) if is_packed_drift(&err) => invalidate_packed_lengths(),
4863            result => return result,
4864        }
4865    }
4866    format_pipeline_groups(frames, workers, precision, canonical, bind)
4867}
4868
4869/// One buffer per frame, the same split the file writer uses when there
4870/// is a worker for every frame.
4871fn format_frames_apart(
4872    frames: &[&ConFrame],
4873    precision: Option<usize>,
4874    canonical: bool,
4875    bind: bool,
4876) -> Result<Vec<Vec<u8>>, WriteError> {
4877    let mut parts: Vec<Result<Vec<u8>, WriteError>> = Vec::with_capacity(frames.len());
4878    std::thread::scope(|scope| {
4879        let mut guards = Vec::with_capacity(frames.len());
4880        for (index, frame) in frames.iter().enumerate() {
4881            guards.push(scope.spawn(move || {
4882                pin_writer_worker(index);
4883                format_group_bytes(std::slice::from_ref(frame), 1, precision, canonical, bind)
4884            }));
4885        }
4886        for guard in guards {
4887            parts.push(match guard.join() {
4888                Ok(part) => part,
4889                Err(_) => Err(WriteError::Io(io::Error::other("frame formatter panicked"))),
4890            });
4891        }
4892    });
4893    parts.into_iter().collect()
4894}
4895
4896/// One exact-sized buffer per worker. The span is the mapping that
4897/// worker would fill, and the bytes are formatted in place.
4898fn format_packed_buffers(
4899    frames: &[&ConFrame],
4900    lengths: &[usize],
4901    workers: usize,
4902    precision: Option<usize>,
4903    canonical: bool,
4904    bind: bool,
4905) -> Result<Vec<Vec<u8>>, WriteError> {
4906    let ranges = pack_frames_by_weight(lengths, workers);
4907    let mut prefix = vec![0usize; lengths.len() + 1];
4908    for (index, len) in lengths.iter().enumerate() {
4909        prefix[index + 1] = prefix[index] + len;
4910    }
4911    if cfg!(miri) {
4912        let mut parts = Vec::with_capacity(ranges.len());
4913        for &(start, end) in &ranges {
4914            let part = format_group_bytes(&frames[start..end], 1, precision, canonical, bind)?;
4915            if part.len() != prefix[end] - prefix[start] {
4916                return Err(packed_drift());
4917            }
4918            parts.push(part);
4919        }
4920        return Ok(parts);
4921    }
4922    let mut parts: Vec<Result<Vec<u8>, WriteError>> = Vec::with_capacity(ranges.len());
4923    std::thread::scope(|scope| {
4924        let mut guards = Vec::with_capacity(ranges.len());
4925        for (thread, &(start, end)) in ranges.iter().enumerate() {
4926            let span = prefix[end] - prefix[start];
4927            let piece = &frames[start..end];
4928            guards.push(scope.spawn(move || -> Result<Vec<u8>, WriteError> {
4929                pin_writer_worker(thread);
4930                if span == 0 {
4931                    return Ok(Vec::new());
4932                }
4933                let mut buf = vec![0u8; span];
4934                format_group_into(piece, &mut buf, precision, canonical, bind)?;
4935                Ok(buf)
4936            }));
4937        }
4938        for guard in guards {
4939            parts.push(match guard.join() {
4940                Ok(part) => part,
4941                Err(_) => Err(WriteError::Io(io::Error::other("frame formatter panicked"))),
4942            });
4943        }
4944    });
4945    parts.into_iter().collect()
4946}
4947
4948/// The pipeline's groups, formatted and not written.
4949fn format_pipeline_groups(
4950    frames: &[&ConFrame],
4951    workers: usize,
4952    precision: Option<usize>,
4953    canonical: bool,
4954    bind: bool,
4955) -> Result<Vec<Vec<u8>>, WriteError> {
4956    let groups = workers.saturating_mul(4).max(workers);
4957    let ranges = group_frame_ranges(frames, groups);
4958    let pieces: Vec<&[&ConFrame]> = ranges
4959        .iter()
4960        .map(|&(start, end)| &frames[start..end])
4961        .collect();
4962    let format_threads = pipeline_format_threads(workers).min(pieces.len().max(1));
4963    let next_job = std::sync::atomic::AtomicUsize::new(0);
4964    let mut slots: Vec<Option<Result<Vec<u8>, WriteError>>> =
4965        (0..pieces.len()).map(|_| None).collect();
4966    std::thread::scope(|scope| {
4967        let mut guards = Vec::with_capacity(format_threads);
4968        for _ in 0..format_threads {
4969            let pieces = &pieces;
4970            let next_job = &next_job;
4971            guards.push(scope.spawn(move || {
4972                let mut local = Vec::new();
4973                loop {
4974                    let index = next_job.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4975                    if index >= pieces.len() {
4976                        break;
4977                    }
4978                    local.push((
4979                        index,
4980                        format_group_bytes(pieces[index], 1, precision, canonical, bind),
4981                    ));
4982                }
4983                local
4984            }));
4985        }
4986        for guard in guards {
4987            let local = match guard.join() {
4988                Ok(local) => local,
4989                Err(_) => {
4990                    return;
4991                }
4992            };
4993            for (index, part) in local {
4994                slots[index] = Some(part);
4995            }
4996        }
4997    });
4998    let mut out = Vec::with_capacity(slots.len());
4999    for slot in slots {
5000        let Some(part) = slot else {
5001            return Err(WriteError::Io(io::Error::other("frame formatter panicked")));
5002        };
5003        out.push(part?);
5004    }
5005    Ok(out)
5006}
5007
5008/// Byte weight of one frame: atom lines, counting each extra section.
5009///
5010/// A velocity frame is about twice a coordinate frame of the same
5011/// atoms. Splitting on frame counts glues that heavy frame to a light
5012/// neighbour and leaves the other workers short.
5013pub(crate) fn frame_byte_weight(frame: &ConFrame) -> usize {
5014    let atoms = frame.atom_data.len().max(1);
5015    // Declared sections are the line blocks. Absent SoA columns are a
5016    // null check. Walking every atom for a coordinate-only frame was a
5017    // pointer chase per frame, about 5 ms on a 100 000-frame write.
5018    if !frame.header.sections.is_empty() {
5019        return atoms.saturating_mul(1 + frame.header.sections.len());
5020    }
5021    let mut blocks = 1usize;
5022    if frame.velocities.is_present() {
5023        blocks += 1;
5024    }
5025    if frame.forces.is_present() {
5026        blocks += 1;
5027    }
5028    if frame.atom_energies.is_present() {
5029        blocks += 1;
5030    }
5031    if frame.charges.is_present() {
5032        blocks += 1;
5033    }
5034    if frame.spins.is_present() {
5035        blocks += 1;
5036    }
5037    if frame.magmoms.is_present() {
5038        blocks += 1;
5039    }
5040    if frame.displacements.is_present() {
5041        blocks += 1;
5042    }
5043    if frame.spreads.is_present() {
5044        blocks += 1;
5045    }
5046    if blocks == 1
5047        && let Some(atom) = frame.atom_data.first()
5048    {
5049        if atom.has_velocity() {
5050            blocks += 1;
5051        }
5052        if atom.has_forces() {
5053            blocks += 1;
5054        }
5055        if atom.has_energy() {
5056            blocks += 1;
5057        }
5058        if atom.has_charge() {
5059            blocks += 1;
5060        }
5061        if atom.has_spin() {
5062            blocks += 1;
5063        }
5064        if atom.has_magmom() {
5065            blocks += 1;
5066        }
5067        if atom.has_displacement() {
5068            blocks += 1;
5069        }
5070        if atom.has_spread() {
5071            blocks += 1;
5072        }
5073    }
5074    atoms.saturating_mul(blocks)
5075}
5076
5077fn equal_frame_ranges(n: usize, groups: usize) -> Vec<(usize, usize)> {
5078    let groups = groups.max(1).min(n.max(1));
5079    let mut out = Vec::with_capacity(groups);
5080    if n == 0 {
5081        return out;
5082    }
5083    for group in 0..groups {
5084        let start = group * n / groups;
5085        let end = (group + 1) * n / groups;
5086        if start < end {
5087            out.push((start, end));
5088        }
5089    }
5090    out
5091}
5092
5093/// Equal slices when sampled frames share a weight. A mixed file is
5094/// packed from every frame's byte weight.
5095///
5096/// Walking every frame of a uniform 100 000-frame trajectory before
5097/// formatting it cost several milliseconds on the 8-thread write, and
5098/// the equal split is the same one the weights would have produced.
5099pub(crate) fn group_frame_ranges(frames: &[&ConFrame], groups: usize) -> Vec<(usize, usize)> {
5100    let n = frames.len();
5101    if n == 0 {
5102        return Vec::new();
5103    }
5104    let groups = groups.max(1).min(n);
5105    if n == 1 || !sampled_weights_vary(frames) {
5106        return equal_frame_ranges(n, groups);
5107    }
5108    let weights: Vec<usize> = frames
5109        .iter()
5110        .map(|frame| frame_byte_weight(frame))
5111        .collect();
5112    pack_frames_by_weight(&weights, groups)
5113}
5114
5115fn sampled_weights_vary(frames: &[&ConFrame]) -> bool {
5116    let anchor = frame_byte_weight(frames[0]);
5117    let last = frames.len() - 1;
5118    let samples = 16.min(frames.len());
5119    for i in 0..samples {
5120        let index = if samples == 1 {
5121            0
5122        } else {
5123            i * last / (samples - 1)
5124        };
5125        if frame_byte_weight(frames[index]) != anchor {
5126            return true;
5127        }
5128    }
5129    false
5130}
5131
5132/// Contiguous groups whose weights are as equal as a frame boundary allows.
5133///
5134/// `workers` groups when there are at least that many frames. A frame
5135/// heavier than the mean stands in its own group instead of sharing one
5136/// with the light frames an equal count would pair it with.
5137pub(crate) fn pack_frames_by_weight(weights: &[usize], workers: usize) -> Vec<(usize, usize)> {
5138    let n = weights.len();
5139    if n == 0 {
5140        return Vec::new();
5141    }
5142    let workers = workers.max(1).min(n);
5143    let mut prefix = vec![0u64; n + 1];
5144    for (i, weight) in weights.iter().enumerate() {
5145        prefix[i + 1] = prefix[i] + (*weight as u64).max(1);
5146    }
5147    let total = prefix[n];
5148    let mut out = Vec::with_capacity(workers);
5149    let mut start = 0usize;
5150    for worker in 0..workers {
5151        let end = if worker + 1 == workers {
5152            n
5153        } else {
5154            let target = ((worker as u64 + 1) * total) / workers as u64;
5155            let latest = n - (workers - worker - 1);
5156            let mut end = start + 1;
5157            while end < latest && prefix[end] < target {
5158                end += 1;
5159            }
5160            end
5161        };
5162        out.push((start, end));
5163        start = end;
5164    }
5165    out
5166}
5167
5168/// How many threads format frame groups.
5169///
5170/// Every worker formats. The bytes are placed afterwards, each at its
5171/// own offset, so the caller does not copy the file on one thread.
5172pub(crate) fn pipeline_format_threads(workers: usize) -> usize {
5173    workers.max(1)
5174}
5175
5176/// Eight workers on a long trajectory format into the file itself.
5177/// One writer stays on the serial formatter. Two and four keep the
5178/// overlapped copy, which is the faster of the two at those widths.
5179pub(crate) fn direct_slice_write(workers: usize, total_weight: usize) -> bool {
5180    workers >= 8 && total_weight >= 3_000_000
5181}
5182
5183/// Box numbers the writer emits. Lattice vectors are converted first.
5184fn written_box(frame: &ConFrame) -> ([f64; 3], [f64; 3]) {
5185    match frame.header.lattice_vectors() {
5186        Some(vecs) => crate::types::lengths_and_angles(vecs),
5187        None => (frame.header.boxl, frame.header.angles),
5188    }
5189}
5190
5191/// Refuses, before any byte is formatted or file created, a frame whose
5192/// written cell is NaN or infinite. The error names the frame by its index in
5193/// `frames`, which the formatting workers of a parallel write cannot know.
5194///
5195/// A frame with a finite header cell passes on six comparisons. Only a frame
5196/// without one reads its lattice vectors, which decide the written cell.
5197pub(crate) fn check_frames_cell_finite(frames: &[&ConFrame]) -> Result<(), WriteError> {
5198    for (index, frame) in frames.iter().enumerate() {
5199        if frame.header.check_cell_finite().is_ok() {
5200            continue;
5201        }
5202        let (boxl, angles) = written_box(frame);
5203        crate::types::check_cell_finite(&boxl, "boxl", &angles, "angles")
5204            .map_err(|error| WriteError::Format(error.in_frame(index as u64)))?;
5205    }
5206    Ok(())
5207}
5208
5209fn add_widths(sum: &mut usize, values: &[f64]) {
5210    *sum += sum_spelling_widths(values);
5211}
5212
5213/// Width of `n/10_000` for `n` in `0..=1_000_000` (magnitudes up to 100).
5214/// Built once; the timed samples do not pay for it.
5215fn milli_width_table() -> &'static [u8] {
5216    const N: usize = 1_000_001;
5217    static TABLE: std::sync::OnceLock<Box<[u8]>> = std::sync::OnceLock::new();
5218    TABLE.get_or_init(|| {
5219        let mut table = vec![0u8; N].into_boxed_slice();
5220        for n in 0..N {
5221            table[n] = spell_width((n as f64) / 10_000.0) as u8;
5222        }
5223        table
5224    })
5225}
5226
5227fn spell_width(value: f64) -> usize {
5228    if !value.is_finite() {
5229        return ryu::Buffer::new().format(value).len();
5230    }
5231    if let Some((_, n)) = encode_fixed_decimal_into(value) {
5232        return n;
5233    }
5234    let mut tmp = [0u8; 24];
5235    unsafe { ryu::raw::format64(value, tmp.as_mut_ptr()) }
5236}
5237
5238/// Sum of round-trip widths. Exact multiples of 1e-4 up to 100 use a table.
5239fn sum_spelling_widths(values: &[f64]) -> usize {
5240    let table = milli_width_table();
5241    let mut sum = 0usize;
5242    for &value in values {
5243        let bits = value.to_bits();
5244        let neg = bits >> 63 != 0;
5245        let mag = f64::from_bits(bits & !(1u64 << 63));
5246        let scaled = mag * 10_000.0;
5247        let nearest = scaled.round();
5248        if nearest <= 1_000_000.0 {
5249            let n = nearest as usize;
5250            if ((n as f64) / 10_000.0).to_bits() == mag.to_bits() {
5251                sum += table[n] as usize + usize::from(neg);
5252                continue;
5253            }
5254        }
5255        sum += spell_width(value);
5256    }
5257    sum
5258}
5259
5260/// Floats the writer emits for `frame`, excluding the header text around them.
5261///
5262/// `None` when the frame has no `(x, y, z)` row per atom, which the
5263/// buffered path reports as an error.
5264fn packed_float_widths(frame: &ConFrame) -> Option<usize> {
5265    let mut sum = 0usize;
5266    let (boxl, angles) = written_box(frame);
5267    add_widths(&mut sum, &boxl);
5268    add_widths(&mut sum, &angles);
5269    add_widths(&mut sum, &frame.header.masses_per_type);
5270    // The positions column may have been moved into a slab. `frame_coords`
5271    // borrows that row; `xyz_at` would only see the empty column.
5272    let coords = frame_coords(frame).ok()?;
5273    for index in 0..frame.atom_data.len() {
5274        let at = index * 3;
5275        sum += round_trip_width(coords[at]);
5276        sum += round_trip_width(coords[at + 1]);
5277        sum += round_trip_width(coords[at + 2]);
5278    }
5279    sum += optional_rows_width(frame.velocities.is_present().then(|| &*frame.velocities));
5280    sum += optional_rows_width(frame.forces.is_present().then(|| &*frame.forces));
5281    sum += optional_rows_width(frame.magmoms.is_present().then(|| &*frame.magmoms));
5282    sum += optional_rows_width(
5283        frame
5284            .displacements
5285            .is_present()
5286            .then(|| &*frame.displacements),
5287    );
5288    sum += optional_rows_width(frame.spreads.is_present().then(|| &*frame.spreads));
5289    sum += optional_column_width(
5290        frame
5291            .atom_energies
5292            .is_present()
5293            .then(|| &*frame.atom_energies),
5294    );
5295    sum += optional_column_width(frame.charges.is_present().then(|| &*frame.charges));
5296    sum += optional_column_width(frame.spins.is_present().then(|| &*frame.spins));
5297    // A section stored only on the atom tail is still emitted.
5298    if !frame.velocities.is_present() && frame.has_velocities() {
5299        for atom in &frame.atom_data {
5300            let [x, y, z] = atom.velocity().unwrap_or([0.0; 3]);
5301            sum += round_trip_width(x) + round_trip_width(y) + round_trip_width(z);
5302        }
5303    }
5304    if !frame.forces.is_present() && frame.has_forces() {
5305        for atom in &frame.atom_data {
5306            let [x, y, z] = atom.force().unwrap_or([0.0; 3]);
5307            sum += round_trip_width(x) + round_trip_width(y) + round_trip_width(z);
5308        }
5309    }
5310    Some(sum)
5311}
5312
5313fn optional_rows_width(storage: Option<&crate::storage_dtype::Array2Storage>) -> usize {
5314    let Some(storage) = storage else {
5315        return 0;
5316    };
5317    let Some(values) = storage.f64_slice() else {
5318        return 0;
5319    };
5320    let mut sum = 0usize;
5321    add_widths(&mut sum, values);
5322    sum
5323}
5324
5325fn optional_column_width(storage: Option<&crate::storage_dtype::Array1Storage>) -> usize {
5326    let Some(storage) = storage else {
5327        return 0;
5328    };
5329    let Some(values) = storage.f64_slice() else {
5330        return 0;
5331    };
5332    let mut sum = 0usize;
5333    add_widths(&mut sum, values);
5334    sum
5335}
5336
5337/// Non-float text matches `reference`, so one formatted frame prices it.
5338fn same_packed_shape(reference: &ConFrame, frame: &ConFrame) -> bool {
5339    if frame.atom_data.len() != reference.atom_data.len()
5340        || frame.atom_data.is_empty()
5341        || frame.header.spec_version != reference.header.spec_version
5342        || frame.header.natm_types != reference.header.natm_types
5343        || frame.header.natms_per_type != reference.header.natms_per_type
5344        || frame.header.masses_per_type.len() != reference.header.masses_per_type.len()
5345        || frame.header.prebox_header.user != reference.header.prebox_header.user
5346        || frame.header.prebox_header.metadata_line()
5347            != reference.header.prebox_header.metadata_line()
5348        || frame.header.postbox_header != reference.header.postbox_header
5349        || frame.has_velocities() != reference.has_velocities()
5350        || frame.has_forces() != reference.has_forces()
5351        || frame.has_energies() != reference.has_energies()
5352        || frame.has_charges() != reference.has_charges()
5353        || frame.has_spins() != reference.has_spins()
5354        || frame.has_magmoms() != reference.has_magmoms()
5355        || frame.has_displacements() != reference.has_displacements()
5356        || frame.has_spreads() != reference.has_spreads()
5357        || !ids_are_dense(&frame.atom_data, 1)
5358    {
5359        return false;
5360    }
5361    let mut offset = 0usize;
5362    for &count in &frame.header.natms_per_type {
5363        if frame.atom_data[offset].symbol != reference.atom_data[offset].symbol {
5364            return false;
5365        }
5366        offset += count;
5367    }
5368    true
5369}
5370
5371/// Exact byte length of every frame when they share one text skeleton.
5372///
5373/// The skeleton is priced by formatting the first frame. Every other
5374/// length is that price plus the change in float spellings. `None`
5375/// means the skeleton differs or a checked frame did not match, and the
5376/// caller formats into buffers instead.
5377fn packed_frame_lengths(
5378    frames: &[&ConFrame],
5379    workers: usize,
5380    precision: Option<usize>,
5381    canonical: bool,
5382    bind: bool,
5383) -> Option<Vec<usize>> {
5384    // Fixed decimals and a one-frame write keep the buffered path.
5385    if precision.is_some() || frames.len() < 2 {
5386        return None;
5387    }
5388    let reference = frames[0];
5389    if reference.atom_data.is_empty() || !ids_are_dense(&reference.atom_data, 1) {
5390        return None;
5391    }
5392    let workers = workers.max(1).min(frames.len());
5393    let shape_ok = std::thread::scope(|scope| {
5394        let mut guards = Vec::with_capacity(workers);
5395        for thread in 0..workers {
5396            let start = thread * frames.len() / workers;
5397            let end = (thread + 1) * frames.len() / workers;
5398            guards.push(scope.spawn(move || {
5399                frames[start..end]
5400                    .iter()
5401                    .all(|frame| same_packed_shape(reference, frame))
5402            }));
5403        }
5404        guards
5405            .into_iter()
5406            .all(|guard| guard.join().unwrap_or(false))
5407    });
5408    if !shape_ok {
5409        return None;
5410    }
5411    let widths = std::thread::scope(|scope| {
5412        let mut guards = Vec::with_capacity(workers);
5413        for thread in 0..workers {
5414            let start = thread * frames.len() / workers;
5415            let end = (thread + 1) * frames.len() / workers;
5416            guards.push(scope.spawn(move || {
5417                #[cfg(feature = "parallel")]
5418                crate::parser::pin_worker(thread);
5419                frames[start..end]
5420                    .iter()
5421                    .map(|frame| packed_float_widths(frame))
5422                    .collect::<Option<Vec<_>>>()
5423            }));
5424        }
5425        let mut widths = Vec::with_capacity(frames.len());
5426        for guard in guards {
5427            widths.extend(guard.join().ok().flatten()?);
5428        }
5429        Some(widths)
5430    })?;
5431    if widths.len() != frames.len() {
5432        return None;
5433    }
5434    let sample = format_group_bytes(
5435        std::slice::from_ref(&reference),
5436        1,
5437        precision,
5438        canonical,
5439        bind,
5440    )
5441    .ok()?;
5442    let overhead = sample.len().checked_sub(widths[0])?;
5443    let lengths: Vec<usize> = widths.iter().map(|width| overhead + width).collect();
5444    for &index in [0, frames.len() / 2, frames.len() - 1].iter() {
5445        let got = format_group_bytes(
5446            std::slice::from_ref(&frames[index]),
5447            1,
5448            precision,
5449            canonical,
5450            bind,
5451        )
5452        .ok()?
5453        .len();
5454        if got != lengths[index] {
5455            return None;
5456        }
5457    }
5458    Some(lengths)
5459}
5460
5461const PACKED_DRIFT: &str = "packed frame length drifted";
5462
5463fn packed_drift() -> WriteError {
5464    WriteError::Io(io::Error::other(PACKED_DRIFT))
5465}
5466
5467/// A priced length no longer matches the text. The price is keyed by frame
5468/// address, and a public field store or a move out of a slot does not
5469/// retire it.
5470fn is_packed_drift(err: &WriteError) -> bool {
5471    matches!(err, WriteError::Io(io) if io.kind() == io::ErrorKind::Other
5472        && io.get_ref().is_some_and(|inner| inner.to_string() == PACKED_DRIFT))
5473}
5474
5475/// Format `group` into `dest`, which must be exactly the length of the text.
5476///
5477/// `dest` is a bounded writer. Text longer than `dest` stops at its end and
5478/// shorter text leaves a tail; both are [`is_packed_drift`]. Nothing past
5479/// `dest` is written and its memory is never reallocated.
5480pub(crate) fn format_group_into(
5481    group: &[&ConFrame],
5482    dest: &mut [u8],
5483    precision: Option<usize>,
5484    canonical: bool,
5485    bind: bool,
5486) -> Result<(), WriteError> {
5487    if dest.is_empty() {
5488        return Ok(());
5489    }
5490    let mut rest: &mut [u8] = dest;
5491    {
5492        let mut writer = match precision {
5493            Some(precision) => ConFrameWriter::with_precision(&mut rest, precision),
5494            None => ConFrameWriter::new(&mut rest),
5495        }
5496        .canonical(canonical);
5497        let result = write_group(&mut writer, group, bind)
5498            .and_then(|()| writer.flush().map_err(WriteError::Io));
5499        match result {
5500            Err(WriteError::Io(err)) if err.kind() == io::ErrorKind::WriteZero => {
5501                return Err(packed_drift());
5502            }
5503            other => other?,
5504        }
5505    }
5506    if !rest.is_empty() {
5507        return Err(packed_drift());
5508    }
5509    Ok(())
5510}
5511
5512/// Format each group straight into its slice of `file`.
5513fn place_packed(
5514    file: &File,
5515    frames: &[&ConFrame],
5516    lengths: &[usize],
5517    workers: usize,
5518    precision: Option<usize>,
5519    canonical: bool,
5520    bind: bool,
5521) -> Result<(), WriteError> {
5522    let total: u64 = lengths.iter().map(|len| *len as u64).sum();
5523    allocate_len(file, total).map_err(WriteError::Io)?;
5524    if file.metadata().map_err(WriteError::Io)?.len() > total {
5525        file.set_len(total).map_err(WriteError::Io)?;
5526    }
5527    if total == 0 {
5528        return Ok(());
5529    }
5530    let ranges = pack_frames_by_weight(lengths, workers);
5531    let mut prefix = vec![0usize; lengths.len() + 1];
5532    for (index, len) in lengths.iter().enumerate() {
5533        prefix[index + 1] = prefix[index] + len;
5534    }
5535    // Miri writes through `pwrite`. A real file is one mapping, and each
5536    // worker fills its own range.
5537    if cfg!(miri) {
5538        let mut parts = Vec::with_capacity(ranges.len());
5539        for &(start, end) in &ranges {
5540            let part = format_group_bytes(&frames[start..end], 1, precision, canonical, bind)?;
5541            if part.len() != prefix[end] - prefix[start] {
5542                return Err(packed_drift());
5543            }
5544            parts.push(part);
5545        }
5546        return store_disjoint_parts(file, &parts).map_err(WriteError::Io);
5547    }
5548    // One mapping per worker, dropped on that worker. Tearing down a single
5549    // 184 MB map was a serial tail after the formatters had finished.
5550    std::thread::scope(|scope| {
5551        let mut guards = Vec::with_capacity(ranges.len());
5552        for (thread, &(start, end)) in ranges.iter().enumerate() {
5553            let offset = prefix[start];
5554            let span = prefix[end] - prefix[start];
5555            let piece = &frames[start..end];
5556            let cloned = file.try_clone().map_err(WriteError::Io)?;
5557            guards.push(scope.spawn(move || -> Result<(), WriteError> {
5558                pin_writer_worker(thread);
5559                if span == 0 {
5560                    return Ok(());
5561                }
5562                let page = 4096usize;
5563                let map_off = offset & !(page - 1);
5564                let delta = offset - map_off;
5565                let map_len = delta + span;
5566                let mut map = unsafe {
5567                    memmap2::MmapOptions::new()
5568                        .offset(map_off as u64)
5569                        .len(map_len)
5570                        .map_mut(&cloned)
5571                        .map_err(WriteError::Io)?
5572                };
5573                advise_shared_store(&cloned, map.as_mut_ptr(), map.len());
5574                let dest = &mut map[delta..delta + span];
5575                // A reused L2 buffer plus a plain or non-temporal copy was
5576                // slower here than spelling straight into the fresh pages.
5577                format_group_into(piece, dest, precision, canonical, bind)?;
5578                drop(map);
5579                Ok(())
5580            }));
5581        }
5582        for guard in guards {
5583            match guard.join() {
5584                Ok(result) => result?,
5585                Err(_) => {
5586                    return Err(WriteError::Io(io::Error::other("frame formatter panicked")));
5587                }
5588            }
5589        }
5590        Ok(())
5591    })
5592}
5593
5594/// Format frame groups on [`pipeline_format_threads`] threads, then
5595/// place each group at its file offset. There is no ordered `write_all`
5596/// of the whole text.
5597fn write_serial_frames(
5598    path: &std::path::Path,
5599    frames: &[&ConFrame],
5600    precision: Option<usize>,
5601    canonical: bool,
5602    bind: bool,
5603) -> Result<(), WriteError> {
5604    // A priced trajectory is spelled straight into the fresh file. The
5605    // copy onto a second buffer was the gap against a writer that filled
5606    // the inode itself. One frame has no group price; it streams.
5607    if frames.len() >= 2
5608        && let Some(lengths) = cached_packed_lengths(frames, 1, precision, canonical, bind)
5609    {
5610        let (staged, file) = begin_unpublished(path)?;
5611        let result = place_packed(&file, frames, &lengths, 1, precision, canonical, bind);
5612        match result {
5613            Err(err) if is_packed_drift(&err) => invalidate_packed_lengths(),
5614            result => return finish_unpublished(staged, path, result),
5615        }
5616    }
5617    let (staged, file) = begin_unpublished(path)?;
5618    let mut writer = match precision {
5619        Some(precision) => ConFrameWriter::with_precision(file, precision),
5620        None => ConFrameWriter::new(file),
5621    }
5622    .canonical(canonical);
5623    let result =
5624        write_group(&mut writer, frames, bind).and_then(|_| writer.flush().map_err(WriteError::Io));
5625    drop(writer);
5626    finish_unpublished(staged, path, result)
5627}
5628
5629fn pipeline_frame_groups(
5630    path: &std::path::Path,
5631    frames: &[&ConFrame],
5632    workers: usize,
5633    precision: Option<usize>,
5634    canonical: bool,
5635    bind: bool,
5636) -> Result<(), WriteError> {
5637    // One formatter per frame when there is a core for each. Reserving a
5638    // thread for the writer left two frames on two threads formatting
5639    // one after the other, so the pair took about twice one frame.
5640    if (2..=workers).contains(&frames.len()) {
5641        let mut parts: Vec<Result<Vec<u8>, WriteError>> = Vec::with_capacity(frames.len());
5642        std::thread::scope(|scope| {
5643            let mut guards = Vec::with_capacity(frames.len());
5644            for (index, frame) in frames.iter().enumerate() {
5645                guards.push(scope.spawn(move || {
5646                    pin_writer_worker(index);
5647                    format_group_bytes(std::slice::from_ref(frame), 1, precision, canonical, bind)
5648                }));
5649            }
5650            for guard in guards {
5651                parts.push(match guard.join() {
5652                    Ok(part) => part,
5653                    Err(_) => Err(WriteError::Io(io::Error::other("frame formatter panicked"))),
5654                });
5655            }
5656        });
5657        let mut formatted = Vec::with_capacity(parts.len());
5658        for part in parts {
5659            formatted.push(part?);
5660        }
5661        let (staged, file) = begin_unpublished(path)?;
5662        let result = store_disjoint_parts(&file, &formatted).map_err(WriteError::Io);
5663        return finish_unpublished(staged, path, result);
5664    }
5665    // Eight workers fill the machine, so a repeat write formats straight
5666    // into the file. Fewer workers keep the overlapped copy: pricing
5667    // and a direct store are slower there, and one worker never prices.
5668    let heavy = direct_slice_write(
5669        workers,
5670        frame_byte_weight(frames[0]).saturating_mul(frames.len()),
5671    );
5672    if heavy
5673        && let Some(lengths) = cached_packed_lengths(frames, workers, precision, canonical, bind)
5674    {
5675        let (staged, file) = begin_unpublished(path)?;
5676        let result = place_packed(&file, frames, &lengths, workers, precision, canonical, bind);
5677        match result {
5678            Err(err) if is_packed_drift(&err) => invalidate_packed_lengths(),
5679            result => return finish_unpublished(staged, path, result),
5680        }
5681    }
5682    // Several groups per worker so the first one finishes early and the
5683    // copy overlaps the rest. Uniform frames skip the weight scan;
5684    // a mixed trajectory is packed by byte weight.
5685    let groups = workers.saturating_mul(4).max(workers);
5686    let ranges = group_frame_ranges(frames, groups);
5687    let pieces: Vec<&[&ConFrame]> = ranges
5688        .iter()
5689        .map(|&(start, end)| &frames[start..end])
5690        .collect();
5691    let format_threads = pipeline_format_threads(workers).min(pieces.len().max(1));
5692    // Depth 2 keeps the copy on the caller's core. A deep queue lets
5693    // every group finish first and the copy becomes a second pass.
5694    let (tx, rx) = std::sync::mpsc::sync_channel::<(usize, Result<Vec<u8>, WriteError>)>(2);
5695    let next_job = std::sync::atomic::AtomicUsize::new(0);
5696    let (staged, file) = begin_unpublished(path)?;
5697    let result = std::thread::scope(|scope| {
5698        for _ in 0..format_threads {
5699            let tx = tx.clone();
5700            let pieces = &pieces;
5701            let next_job = &next_job;
5702            scope.spawn(move || {
5703                loop {
5704                    let index = next_job.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5705                    if index >= pieces.len() {
5706                        break;
5707                    }
5708                    let message = format_group_bytes(pieces[index], 1, precision, canonical, bind);
5709                    if tx.send((index, message)).is_err() {
5710                        break;
5711                    }
5712                }
5713            });
5714        }
5715        drop(tx);
5716        let mut file = file;
5717        let mut next = 0usize;
5718        let mut pending = BTreeMap::<usize, Vec<u8>>::new();
5719        while next < pieces.len() {
5720            let (index, part) = rx
5721                .recv()
5722                .map_err(|err| WriteError::Io(io::Error::other(err.to_string())))?;
5723            pending.insert(index, part?);
5724            while let Some(part) = pending.remove(&next) {
5725                file.write_all(&part).map_err(WriteError::Io)?;
5726                next += 1;
5727            }
5728        }
5729        file.flush().map_err(WriteError::Io)?;
5730        Ok(())
5731    });
5732    finish_unpublished(staged, path, result)
5733}
5734
5735struct PackedCache {
5736    identities: std::sync::Arc<[usize]>,
5737    /// Frame addresses whose retirement makes this entry stale.
5738    ///
5739    /// Snapshot entries are looked up and retired by source identities;
5740    /// ordinary entries use the view/frame identities for both.
5741    retire_identities: std::sync::Arc<[usize]>,
5742    count: usize,
5743    precision: Option<usize>,
5744    canonical: bool,
5745    bind: bool,
5746    generation: u64,
5747    lengths: Vec<usize>,
5748    /// Set when the lengths were priced from a coordinate snapshot.
5749    coords: Option<std::sync::Arc<Vec<f64>>>,
5750}
5751
5752/// One independently synchronized packed-length cache.
5753///
5754/// Production obtains one instance per process through [`packed_lengths`].
5755/// Keeping the state injectable also lets protocol tests exercise invalidation
5756/// without observing or perturbing unrelated tests.
5757struct PackedLengthsCache {
5758    entry: std::sync::Mutex<Option<PackedCache>>,
5759    generation: std::sync::atomic::AtomicU64,
5760}
5761
5762impl PackedLengthsCache {
5763    const fn new() -> Self {
5764        Self {
5765            entry: std::sync::Mutex::new(None),
5766            generation: std::sync::atomic::AtomicU64::new(1),
5767        }
5768    }
5769
5770    fn invalidate(&self) {
5771        self.generation
5772            .fetch_add(1, std::sync::atomic::Ordering::Release);
5773        self.entry
5774            .lock()
5775            .unwrap_or_else(|err| err.into_inner())
5776            .take();
5777    }
5778
5779    fn invalidate_if(&self, frame: usize) {
5780        self.invalidate_any(std::iter::once(frame));
5781    }
5782
5783    fn invalidate_any(&self, frames: impl IntoIterator<Item = usize>) {
5784        // Bump even while the slot is empty: a pricing operation may be in
5785        // flight and must not publish lengths for a frame that just died.
5786        self.generation
5787            .fetch_add(1, std::sync::atomic::Ordering::Release);
5788        let mut entry = self.entry.lock().unwrap_or_else(|err| err.into_inner());
5789        let retire = entry.as_ref().is_some_and(|cached| {
5790            frames
5791                .into_iter()
5792                .any(|frame| cached.retire_identities.contains(&frame))
5793        });
5794        if retire {
5795            entry.take();
5796        } else if let Some(cached) = entry.as_mut() {
5797            // Preserve an unrelated entry while bringing it forward to the
5798            // generation after this retirement. This is what lets a source-
5799            // keyed snapshot price survive destruction of its temporary view.
5800            cached.generation = self.generation.load(std::sync::atomic::Ordering::Acquire);
5801        }
5802    }
5803}
5804
5805fn packed_lengths() -> &'static PackedLengthsCache {
5806    static CACHE: crate::parser::PerProcess<PackedLengthsCache> = crate::parser::PerProcess::new();
5807    CACHE.get_or_init(PackedLengthsCache::new)
5808}
5809const MAX_PACKED_CACHE_BYTES: usize = 64 * 1024 * 1024;
5810
5811/// Names the frames a coordinate snapshot was taken from.
5812///
5813/// Each snapshot puts its views at new addresses, so the address key alone
5814/// would price every write again. Under this key a later snapshot of the
5815/// same source frames reuses the lengths when its coordinates match the
5816/// priced ones bit for bit; nothing else in a stored frame changes without
5817/// a setter that retires the price.
5818#[cfg(feature = "python")]
5819pub(crate) struct PriceKey {
5820    pub(crate) identities: std::sync::Arc<[usize]>,
5821    pub(crate) view_identities: std::sync::Arc<[usize]>,
5822    pub(crate) coords: std::sync::Arc<Vec<f64>>,
5823}
5824
5825#[cfg(feature = "python")]
5826thread_local! {
5827    static PRICE_KEY: std::cell::RefCell<Option<PriceKey>> =
5828        const { std::cell::RefCell::new(None) };
5829}
5830
5831/// Run `f` with `key` naming the snapshot frames it writes.
5832#[cfg(feature = "python")]
5833pub(crate) fn with_price_key<R>(key: Option<PriceKey>, f: impl FnOnce() -> R) -> R {
5834    struct Clear;
5835    impl Drop for Clear {
5836        fn drop(&mut self) {
5837            PRICE_KEY.with(|slot| slot.borrow_mut().take());
5838        }
5839    }
5840    PRICE_KEY.with(|slot| *slot.borrow_mut() = key);
5841    let _clear = Clear;
5842    f()
5843}
5844
5845fn frame_identities(frames: &[&ConFrame]) -> std::sync::Arc<[usize]> {
5846    frames
5847        .iter()
5848        .map(|frame| *frame as *const ConFrame as usize)
5849        .collect()
5850}
5851
5852/// The complete source identity and coordinates for `frames`, if they are the
5853/// snapshot the current thread-local key names.
5854type SnapshotKey = (std::sync::Arc<[usize]>, std::sync::Arc<Vec<f64>>);
5855
5856fn snapshot_key(frames: &[&ConFrame]) -> Option<SnapshotKey> {
5857    #[cfg(feature = "python")]
5858    {
5859        let views = frame_identities(frames);
5860        PRICE_KEY.with(|slot| {
5861            slot.borrow()
5862                .as_ref()
5863                .filter(|key| key.view_identities.as_ref() == views.as_ref())
5864                .map(|key| (key.identities.clone(), key.coords.clone()))
5865        })
5866    }
5867    #[cfg(not(feature = "python"))]
5868    {
5869        let _ = frames;
5870        None
5871    }
5872}
5873
5874/// The coordinates last priced for the exact source-frame sequence, if that
5875/// price still stands.
5876#[cfg(feature = "python")]
5877pub(crate) fn priced_coords(identities: &[usize]) -> Option<std::sync::Arc<Vec<f64>>> {
5878    let packed = packed_lengths();
5879    let cache = packed.entry.lock().unwrap_or_else(|err| err.into_inner());
5880    let generation = packed.generation.load(std::sync::atomic::Ordering::Acquire);
5881    cache
5882        .as_ref()
5883        .filter(|hit| hit.generation == generation && hit.identities.as_ref() == identities)
5884        .and_then(|hit| hit.coords.clone())
5885}
5886
5887fn same_bits(a: &[f64], b: &[f64]) -> bool {
5888    a.len() == b.len()
5889        && unsafe {
5890            std::slice::from_raw_parts(a.as_ptr().cast::<u8>(), std::mem::size_of_val(a))
5891                == std::slice::from_raw_parts(b.as_ptr().cast::<u8>(), std::mem::size_of_val(b))
5892        }
5893}
5894
5895/// A coordinate edit changes the spelled length. The next write prices again.
5896pub(crate) fn invalidate_packed_lengths() {
5897    packed_lengths().invalidate();
5898}
5899
5900/// Dropping any frame named by the full cache key retires that price.
5901/// A later allocation at the same address must not reuse it.
5902pub(crate) fn invalidate_packed_lengths_if(frame: usize) {
5903    packed_lengths().invalidate_if(frame);
5904}
5905
5906/// Retire temporary snapshot views with one generation change and one lock.
5907///
5908/// Source-keyed entries survive because their retirement identities differ
5909/// from every temporary view address.
5910#[cfg(feature = "python")]
5911pub(crate) fn invalidate_packed_lengths_if_any(frames: impl IntoIterator<Item = usize>) {
5912    packed_lengths().invalidate_any(frames);
5913}
5914
5915pub(crate) fn cached_packed_lengths(
5916    frames: &[&ConFrame],
5917    workers: usize,
5918    precision: Option<usize>,
5919    canonical: bool,
5920    bind: bool,
5921) -> Option<Vec<usize>> {
5922    cached_packed_lengths_in(
5923        packed_lengths(),
5924        frames,
5925        workers,
5926        precision,
5927        canonical,
5928        bind,
5929    )
5930}
5931
5932fn cached_packed_lengths_in(
5933    packed: &PackedLengthsCache,
5934    frames: &[&ConFrame],
5935    workers: usize,
5936    precision: Option<usize>,
5937    canonical: bool,
5938    bind: bool,
5939) -> Option<Vec<usize>> {
5940    let snapshot = snapshot_key(frames);
5941    let (identities, retire_identities, coords) = match snapshot {
5942        Some((identities, coords)) => (identities.clone(), identities, Some(coords)),
5943        None => {
5944            frames.last()?;
5945            let identities = frame_identities(frames);
5946            (identities.clone(), identities, None)
5947        }
5948    };
5949    let count = frames.len();
5950    let cache = packed.entry.lock().unwrap_or_else(|err| err.into_inner());
5951    let generation = packed.generation.load(std::sync::atomic::Ordering::Acquire);
5952    let hit = cache
5953        .as_ref()
5954        .filter(|hit| {
5955            hit.generation == generation
5956                && hit.identities.as_ref() == identities.as_ref()
5957                && hit.count == count
5958                && hit.precision == precision
5959                && hit.canonical == canonical
5960                && hit.bind == bind
5961                && hit.coords.is_some() == coords.is_some()
5962        })
5963        .map(|hit| (hit.lengths.clone(), hit.coords.clone()));
5964    drop(cache);
5965    if let Some((lengths, priced)) = hit {
5966        let same = match (&priced, &coords) {
5967            (Some(priced), Some(coords)) => {
5968                std::sync::Arc::ptr_eq(priced, coords) || same_bits(priced, coords)
5969            }
5970            _ => true,
5971        };
5972        if same {
5973            return Some(lengths);
5974        }
5975    }
5976    let generation_before = packed.generation.load(std::sync::atomic::Ordering::Acquire);
5977    let lengths = packed_frame_lengths(frames, workers, precision, canonical, bind)?;
5978    let coords_bytes = coords
5979        .as_ref()
5980        .map_or(0, |buf| std::mem::size_of_val(buf.as_slice()));
5981    let cache_bytes = coords_bytes
5982        .saturating_add(std::mem::size_of_val(lengths.as_slice()))
5983        .saturating_add(std::mem::size_of_val(identities.as_ref()))
5984        .saturating_add(if std::sync::Arc::ptr_eq(&identities, &retire_identities) {
5985            0
5986        } else {
5987            std::mem::size_of_val(retire_identities.as_ref())
5988        });
5989    let mut cache = packed.entry.lock().unwrap_or_else(|err| err.into_inner());
5990    let generation_after = packed.generation.load(std::sync::atomic::Ordering::Acquire);
5991    if generation_before == generation_after && cache_bytes <= MAX_PACKED_CACHE_BYTES {
5992        *cache = Some(PackedCache {
5993            identities,
5994            retire_identities,
5995            count,
5996            precision,
5997            canonical,
5998            bind,
5999            generation: generation_after,
6000            lengths: lengths.clone(),
6001            coords,
6002        });
6003    } else if generation_before == generation_after {
6004        cache.take();
6005    }
6006    Some(lengths)
6007}
6008
6009/// Place `parts` at their prefix-sum offsets. On tmpfs each part is
6010/// copied into one shared mapping. Elsewhere each part is a `pwrite`.
6011/// The ranges do not overlap, so the stores do not share a byte.
6012fn store_disjoint_parts(file: &File, parts: &[Vec<u8>]) -> io::Result<()> {
6013    let mut offsets = Vec::with_capacity(parts.len());
6014    let mut total = 0u64;
6015    for part in parts {
6016        offsets.push(total);
6017        total += part.len() as u64;
6018    }
6019    allocate_len(file, total)?;
6020    if file.metadata()?.len() > total {
6021        file.set_len(total)?;
6022    }
6023    if total == 0 {
6024        return Ok(());
6025    }
6026    if file_is_tmpfs(file) {
6027        store_mapped_parts(file, parts, &offsets)
6028    } else {
6029        std::thread::scope(|scope| {
6030            let mut guards = Vec::new();
6031            for (part, at) in parts.iter().zip(offsets) {
6032                let cloned = file.try_clone()?;
6033                guards.push(scope.spawn(move || pwrite_full(&cloned, part, at)));
6034            }
6035            for guard in guards {
6036                guard
6037                    .join()
6038                    .unwrap_or_else(|_| Err(io::Error::other("pwrite worker")))?;
6039            }
6040            Ok(())
6041        })
6042    }
6043}
6044
6045fn store_mapped_parts(file: &File, parts: &[Vec<u8>], offsets: &[u64]) -> io::Result<()> {
6046    let total = offsets
6047        .last()
6048        .copied()
6049        .unwrap_or(0)
6050        .saturating_add(parts.last().map(|part| part.len() as u64).unwrap_or(0));
6051    let mut map = unsafe {
6052        memmap2::MmapOptions::new()
6053            .len(total as usize)
6054            .map_mut(file)?
6055    };
6056    let base = map.as_mut_ptr() as usize;
6057    std::thread::scope(|scope| {
6058        for (part, at) in parts.iter().zip(offsets) {
6059            let src = part.as_ptr() as usize;
6060            let len = part.len();
6061            let dest = base + *at as usize;
6062            scope.spawn(move || {
6063                if len == 0 {
6064                    return;
6065                }
6066                // SAFETY: `dest` is inside `map`, the ranges do not
6067                // overlap, and `map` outlives this scope.
6068                unsafe {
6069                    std::ptr::copy_nonoverlapping(src as *const u8, dest as *mut u8, len);
6070                }
6071            });
6072        }
6073    });
6074    Ok(())
6075}
6076
6077fn write_group<W: Write>(
6078    writer: &mut ConFrameWriter<W>,
6079    group: &[&ConFrame],
6080    bind: bool,
6081) -> Result<(), WriteError> {
6082    if bind {
6083        for frame in group {
6084            writer.write_frame_bound(frame)?;
6085        }
6086        return Ok(());
6087    }
6088    writer.extend(group.iter().copied())
6089}
6090
6091fn loose_frame_bytes(frame: &ConFrame) -> usize {
6092    let mut blocks = 1usize;
6093    if frame.has_velocities() {
6094        blocks += 1;
6095    }
6096    if frame.has_forces() {
6097        blocks += 1;
6098    }
6099    if frame.has_energies() {
6100        blocks += 1;
6101    }
6102    if frame.has_charges() {
6103        blocks += 1;
6104    }
6105    if frame.has_spins() {
6106        blocks += 1;
6107    }
6108    if frame.has_magmoms() {
6109        blocks += 1;
6110    }
6111    if frame.has_displacements() {
6112        blocks += 1;
6113    }
6114    if frame.has_spreads() {
6115        blocks += 1;
6116    }
6117    256 + frame
6118        .atom_data
6119        .len()
6120        .saturating_mul(64)
6121        .saturating_mul(blocks)
6122}
6123
6124fn format_group_bytes(
6125    group: &[&ConFrame],
6126    workers: usize,
6127    precision: Option<usize>,
6128    canonical: bool,
6129    bind: bool,
6130) -> Result<Vec<u8>, WriteError> {
6131    let mut buffer = Vec::new();
6132    let mut writer = match precision {
6133        Some(precision) => ConFrameWriter::with_precision(&mut buffer, precision),
6134        None => ConFrameWriter::new(&mut buffer),
6135    }
6136    .canonical(canonical)
6137    .retain_scratch(true);
6138    if workers >= 2 {
6139        writer = writer.parallel_atoms(workers);
6140    }
6141    // One frame's reserve, repeated, copies the whole group each time it
6142    // doubles. Size the scratch for every frame before the first byte.
6143    let need: usize = group.iter().map(|frame| loose_frame_bytes(frame)).sum();
6144    writer.scratch.reserve(need);
6145    write_group(&mut writer, group, bind)?;
6146    Ok(std::mem::take(&mut writer.scratch))
6147}
6148
6149fn formatted_parts(
6150    frames: &[&ConFrame],
6151    workers: usize,
6152    precision: Option<usize>,
6153    canonical: bool,
6154    bind: bool,
6155) -> Result<Vec<Vec<u8>>, WriteError> {
6156    let wide = frames.len() == 1 && frames[0].atom_data.len() >= WIDE_ATOM_GRAIN;
6157    if workers < 2 || (frames.len() < 2 && !wide) {
6158        return Ok(vec![format_group_bytes(
6159            frames, 1, precision, canonical, bind,
6160        )?]);
6161    }
6162    if wide {
6163        return Ok(vec![format_group_bytes(
6164            frames, workers, precision, canonical, bind,
6165        )?]);
6166    }
6167    #[cfg(feature = "parallel")]
6168    {
6169        let chunk = frames.len().div_ceil(workers).max(1);
6170        crate::parser::on_pool(workers, || {
6171            use rayon::prelude::*;
6172            frames
6173                .par_chunks(chunk)
6174                .map(|group| format_group_bytes(group, 1, precision, canonical, bind))
6175                .collect()
6176        })
6177    }
6178    #[cfg(not(feature = "parallel"))]
6179    {
6180        let _ = workers;
6181        Ok(vec![format_group_bytes(
6182            frames, 1, precision, canonical, bind,
6183        )?])
6184    }
6185}
6186
6187fn pwrite_borrowed(file: &File, parts: &[&[u8]]) -> io::Result<()> {
6188    let mut offset = 0u64;
6189    let mut offsets = Vec::with_capacity(parts.len());
6190    for part in parts {
6191        offsets.push(offset);
6192        offset += part.len() as u64;
6193    }
6194    file.set_len(offset)?;
6195    std::thread::scope(|scope| {
6196        let mut handles = Vec::new();
6197        for (part, at) in parts.iter().zip(offsets) {
6198            let file = file.try_clone()?;
6199            handles.push(scope.spawn(move || pwrite_full(&file, part, at)));
6200        }
6201        for handle in handles {
6202            handle
6203                .join()
6204                .unwrap_or_else(|_| Err(io::Error::other("pwrite worker")))?;
6205        }
6206        Ok(())
6207    })
6208}
6209
6210fn pwrite_full(file: &File, buf: &[u8], mut offset: u64) -> io::Result<()> {
6211    if buf.is_empty() {
6212        return Ok(());
6213    }
6214    // Miri can seek and write. `pwrite` keeps the caller's offset on a
6215    // normal build; the clone does the same under Miri.
6216    #[cfg(miri)]
6217    {
6218        use std::io::{Seek, SeekFrom, Write};
6219        let mut out = file.try_clone()?;
6220        out.seek(SeekFrom::Start(offset))?;
6221        out.write_all(buf)?;
6222        return Ok(());
6223    }
6224    #[cfg(all(not(miri), unix))]
6225    {
6226        use std::os::unix::io::AsRawFd;
6227        let fd = file.as_raw_fd();
6228        let mut written = 0usize;
6229        while written < buf.len() {
6230            let n = unsafe {
6231                libc::pwrite(
6232                    fd,
6233                    buf[written..].as_ptr() as *const libc::c_void,
6234                    buf.len() - written,
6235                    offset as libc::off_t,
6236                )
6237            };
6238            if n < 0 {
6239                let err = io::Error::last_os_error();
6240                if err.kind() == io::ErrorKind::Interrupted {
6241                    continue;
6242                }
6243                return Err(err);
6244            }
6245            if n == 0 {
6246                return Err(io::Error::new(io::ErrorKind::WriteZero, "pwrite"));
6247            }
6248            written += n as usize;
6249            offset += n as u64;
6250        }
6251        Ok(())
6252    }
6253    #[cfg(all(not(miri), windows))]
6254    {
6255        use std::os::windows::fs::FileExt;
6256        file.seek_write(buf, offset)?;
6257        Ok(())
6258    }
6259}
6260
6261/// Serializes `frames` to a CON string. No file is created.
6262///
6263/// The bytes match [`ConFrameWriter::from_path`] writing the same frames.
6264pub fn write_frames_to_string(frames: &[ConFrame]) -> Result<String, WriteError> {
6265    let bytes = write_frames_to_vec(frames)?;
6266    String::from_utf8(bytes).map_err(|err| {
6267        WriteError::Io(io::Error::new(
6268            io::ErrorKind::InvalidData,
6269            err.utf8_error().to_string(),
6270        ))
6271    })
6272}
6273
6274// Gzip-compressed writer constructors.
6275impl ConFrameWriter<flate2::write::GzEncoder<File>> {
6276    /// Creates a gzip-compressed writer for the given path.
6277    pub fn from_path_gzip<P: AsRef<Path>>(path: P) -> io::Result<Self> {
6278        let encoder = crate::compression::gzip_writer(path.as_ref())?;
6279        Ok(Self::new(encoder))
6280    }
6281
6282    /// Creates a gzip-compressed writer with custom precision.
6283    pub fn from_path_gzip_with_precision<P: AsRef<Path>>(
6284        path: P,
6285        precision: usize,
6286    ) -> io::Result<Self> {
6287        let encoder = crate::compression::gzip_writer(path.as_ref())?;
6288        Ok(Self::with_precision(encoder, precision))
6289    }
6290}
6291
6292// Zstd-compressed writer constructors. Available only with the `zstd`
6293// Cargo feature.
6294#[cfg(feature = "zstd")]
6295impl ConFrameWriter<zstd::stream::write::AutoFinishEncoder<'static, File>> {
6296    /// Creates a zstd-compressed writer for the given path.
6297    pub fn from_path_zstd<P: AsRef<Path>>(path: P) -> io::Result<Self> {
6298        let encoder = crate::compression::zstd_writer(path.as_ref())?;
6299        Ok(Self::new(encoder))
6300    }
6301
6302    /// Creates a zstd-compressed writer with custom precision.
6303    pub fn from_path_zstd_with_precision<P: AsRef<Path>>(
6304        path: P,
6305        precision: usize,
6306    ) -> io::Result<Self> {
6307        let encoder = crate::compression::zstd_writer(path.as_ref())?;
6308        Ok(Self::with_precision(encoder, precision))
6309    }
6310}
6311
6312#[cfg(test)]
6313mod float_format_tests {
6314    use super::{encode_fixed_decimal_into, push_f64_prec, push_u64, write_finite};
6315
6316    fn formatted(v: f64, prec: usize) -> String {
6317        let mut buf = Vec::new();
6318        push_f64_prec(&mut buf, v, prec);
6319        String::from_utf8(buf).expect("utf8")
6320    }
6321
6322    #[test]
6323    fn matches_std_fixed_precision() {
6324        let vals = [
6325            0.0,
6326            -0.0,
6327            1.0,
6328            -1.0,
6329            0.9045,
6330            6.975_299_999_999_995,
6331            63.546,
6332            1.008,
6333            15.3456,
6334            90.0,
6335            218.0,
6336            1e-6,
6337            -1.23456789,
6338            10.0,
6339        ];
6340        for prec in [0usize, 6] {
6341            for v in vals {
6342                let got = formatted(v, prec);
6343                let exp = format!("{v:.prec$}");
6344                assert_eq!(got, exp, "v={v:?} prec={prec}");
6345            }
6346        }
6347    }
6348
6349    #[test]
6350    fn fixed6_matches_std_where_scaling_does_not() {
6351        let vals = [
6352            9.9999995,
6353            5e-7,
6354            999_999.999_999_5,
6355            1e20,
6356            -1e20,
6357            1e308,
6358            -1e308,
6359            f64::MAX,
6360            -f64::MAX,
6361            5.118_777_491_767_015e14,
6362        ];
6363        for v in vals {
6364            let got = formatted(v, 6);
6365            let exp = format!("{v:.6}");
6366            assert_eq!(got, exp, "v={v:?}");
6367        }
6368    }
6369
6370    #[test]
6371    fn fixed_decimal_matches_ryu_including_edges() {
6372        let mut ryu_buf = ryu::Buffer::new();
6373        let mut values = vec![
6374            0.0,
6375            -0.0,
6376            1.0,
6377            -1.0,
6378            10.0,
6379            97.0,
6380            -97.0,
6381            63.546,
6382            0.5,
6383            0.125,
6384            1.5,
6385            -0.1,
6386            0.1 + 0.2,
6387            1.0 / 3.0,
6388            -9088916957.866665,
6389            -9345863084.186747,
6390            9663676416.00047,
6391            1e15,
6392            -1e15,
6393            1e16,
6394            1e20,
6395            -1e20,
6396            1e-6,
6397            1e-10,
6398            f64::MIN_POSITIVE,
6399            f64::MAX,
6400            f64::MIN,
6401            f64::INFINITY,
6402            f64::NEG_INFINITY,
6403            f64::NAN,
6404        ];
6405        let mut state = 0x1234_5678_9abc_def0u64;
6406        for _ in 0..256 {
6407            state = state.wrapping_mul(0x5851_f42d_4c95_7f2d).wrapping_add(1);
6408            values.push(f64::from_bits(state));
6409        }
6410        for value in values {
6411            let mut got = Vec::new();
6412            let mut scratch = ryu::Buffer::new();
6413            super::push_round_trip(&mut got, &mut scratch, None, value);
6414            let expect = ryu_buf.format(value);
6415            if value.is_nan() {
6416                assert_eq!(std::str::from_utf8(&got).unwrap(), expect);
6417                continue;
6418            }
6419            assert_eq!(std::str::from_utf8(&got).unwrap(), expect, "{value:?}");
6420        }
6421    }
6422
6423    fn old_fixed(mag: f64) -> Option<(u64, u32)> {
6424        if mag <= 1e16 && mag.fract() == 0.0 {
6425            let n = mag as u64;
6426            if n < 10u64.pow(16) && n as f64 == mag {
6427                return Some((n, 0));
6428            }
6429        }
6430        let mut scale = 10.0f64;
6431        for d in 1u32..=6 {
6432            let scaled = mag * scale;
6433            if !scaled.is_finite() || scaled > 1e16 {
6434                break;
6435            }
6436            let nearest = scaled.round();
6437            let n = nearest as u64;
6438            if nearest == n as f64 && (n as f64) / scale == mag {
6439                let mut n = n;
6440                let mut places = d;
6441                while places > 0 && n.is_multiple_of(10) {
6442                    n /= 10;
6443                    places -= 1;
6444                }
6445                if places == 0 {
6446                    if n >= 10u64.pow(16) {
6447                        return None;
6448                    }
6449                    return Some((n, 0));
6450                }
6451                let digits = super::count_digits(n);
6452                let kk = digits as i32 - places as i32;
6453                if !(kk > -5 && kk <= 16) {
6454                    return None;
6455                }
6456                return Some((n, places));
6457            }
6458            scale *= 10.0;
6459        }
6460        None
6461    }
6462
6463    #[test]
6464    fn one_scale_matches_the_six_step_search() {
6465        let mut state = 0x1234_5678_9abc_def0u64;
6466        let mut values = vec![
6467            -9283744841.119225_f64,
6468            0.6394,
6469            -9088916957.866665,
6470            -9345863084.186747,
6471            9663676416.00047,
6472            -0.0001,
6473            1.25,
6474            97.0,
6475            -0.0,
6476            1.0e-7,
6477            -1.0e-7,
6478            1.0e20,
6479            -1.0e20,
6480            1.0e16,
6481            0.5,
6482            1.5,
6483            2.5,
6484            f64::MIN,
6485            f64::MAX,
6486        ];
6487        for _ in 0..50_000 {
6488            state = state.wrapping_mul(0x5851_f42d_4c95_7f2d).wrapping_add(1);
6489            values.push(f64::from_bits(state));
6490        }
6491        for value in values {
6492            if !value.is_finite() {
6493                continue;
6494            }
6495            let mag = value.abs();
6496            let old = old_fixed(mag);
6497            let new = super::fixed_decimal_parts(mag);
6498            if new != old {
6499                let mut got = Vec::new();
6500                let mut scratch = ryu::Buffer::new();
6501                super::push_round_trip(&mut got, &mut scratch, None, value);
6502                let mut ryu_buf = ryu::Buffer::new();
6503                let expect = ryu_buf.format(value);
6504                assert_eq!(
6505                    std::str::from_utf8(&got).unwrap(),
6506                    expect,
6507                    "{value:?} old={old:?} new={new:?}"
6508                );
6509                continue;
6510            }
6511            if let Some((n, places)) = new {
6512                let mut fast = [0u8; 32];
6513                let mut slow = [0u8; 32];
6514                let nfast =
6515                    super::write_fixed_digits(&mut fast, value.is_sign_negative(), n, places);
6516                let mut i = slow.len();
6517                let mut x = n;
6518                if x == 0 {
6519                    i -= 1;
6520                    slow[i] = b'0';
6521                } else {
6522                    while x > 0 {
6523                        i -= 1;
6524                        slow[i] = b'0' + (x % 10) as u8;
6525                        x /= 10;
6526                    }
6527                }
6528                let digs = &slow[i..];
6529                let mut expect = Vec::new();
6530                if value.is_sign_negative() {
6531                    expect.push(b'-');
6532                }
6533                if places == 0 {
6534                    expect.extend_from_slice(digs);
6535                    expect.extend_from_slice(b".0");
6536                } else {
6537                    let kk = digs.len() as i32 - places as i32;
6538                    if kk > 0 {
6539                        let cut = kk as usize;
6540                        expect.extend_from_slice(&digs[..cut]);
6541                        expect.push(b'.');
6542                        expect.extend_from_slice(&digs[cut..]);
6543                    } else {
6544                        expect.extend_from_slice(b"0.");
6545                        expect.extend(std::iter::repeat_n(b'0', (-kk) as usize));
6546                        expect.extend_from_slice(digs);
6547                    }
6548                }
6549                assert_eq!(&fast[..nfast], expect.as_slice(), "{value:?} {n} {places}");
6550            }
6551        }
6552    }
6553
6554    #[test]
6555    fn round_trip_spelling_matches_ryu_on_repeated_and_unique_rows() {
6556        use crate::iterators::ConFrameIterator;
6557        use crate::writer::ConFrameWriter;
6558        let mut text = String::from(
6559            "bench\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0 1\n1\n6\n12.0\nCu\nCoordinates of Component 1\n",
6560        );
6561        for i in 0..6 {
6562            let x = (i % 2) as f64 * 1.5 + 0.25;
6563            let y = 3.25;
6564            let z = if i == 3 {
6565                -0.0
6566            } else {
6567                (i as f64) * 0.0010000001
6568            };
6569            text.push_str(&format!("   {x:.17}    {y:.17}    {z:.17} 0 {i}\n"));
6570        }
6571        // Repeated velocities share the column cache with the coordinates.
6572        text.push_str("\nCu\nVelocities of Component 1\n");
6573        for i in 0..6 {
6574            let vx = 0.125;
6575            let vy = if i % 2 == 0 { 0.5 } else { -0.5 };
6576            let vz = (i as f64) * 1.0e-4;
6577            text.push_str(&format!("   {vx:.17}    {vy:.17}    {vz:.17} 0 {i}\n"));
6578        }
6579        let frames: Vec<_> = ConFrameIterator::new(&text)
6580            .map(|frame| frame.expect("parse"))
6581            .collect();
6582        let mut values = Vec::new();
6583        for index in 0..frames[0].atom_data.len() {
6584            values.extend(frames[0].xyz_at(index));
6585        }
6586        for atom in &frames[0].atom_data {
6587            if let Some(v) = atom.velocity() {
6588                values.extend(v);
6589            }
6590        }
6591        let mut buf = Vec::new();
6592        {
6593            let mut writer = ConFrameWriter::new(&mut buf);
6594            writer.extend(frames.iter()).unwrap();
6595        }
6596        let written = String::from_utf8(buf).unwrap();
6597        let mut ryu = ryu::Buffer::new();
6598        let mut spelled = Vec::new();
6599        for line in written.lines() {
6600            let toks: Vec<_> = line.split_whitespace().collect();
6601            if toks.len() >= 5
6602                && toks[0].contains('.')
6603                && toks[3].bytes().all(|b| b.is_ascii_digit())
6604            {
6605                spelled.extend(toks[..3].iter().map(|tok| (*tok).to_string()));
6606            }
6607        }
6608        assert_eq!(spelled.len(), values.len());
6609        for (got, value) in spelled.iter().zip(values) {
6610            let expect = if value.is_finite() {
6611                ryu.format_finite(value).to_string()
6612            } else {
6613                ryu.format(value).to_string()
6614            };
6615            assert_eq!(got, &expect, "value {value:?}");
6616        }
6617    }
6618
6619    #[test]
6620    fn fixed_decimal_matches_ryu_or_falls_back_to_it() {
6621        let mut values = vec![
6622            0.0,
6623            -0.0,
6624            1.0,
6625            -2.0,
6626            10.0,
6627            99.0,
6628            100.0,
6629            0.1,
6630            0.01,
6631            0.001,
6632            0.0001,
6633            0.0002,
6634            -0.0001,
6635            1.5,
6636            0.25,
6637            0.125,
6638            63.546,
6639            12.0,
6640            90.0,
6641            3.25,
6642            0.5,
6643            -0.5,
6644            1.0e-4,
6645            1.25,
6646            218.0,
6647            6.975_299_999_999_995,
6648            1.008,
6649            15.3456,
6650            -1.23456789,
6651            1e-6,
6652            1e16,
6653            1e20,
6654        ];
6655        for i in 0..200 {
6656            values.push(i as f64);
6657            values.push((i as f64) * 0.001);
6658            values.push((i as f64) * 0.0001);
6659            values.push(-(i as f64) * 0.001);
6660        }
6661        let mut ryu = ryu::Buffer::new();
6662        for value in values {
6663            let mut buf = Vec::new();
6664            write_finite(&mut buf, value);
6665            let expect = ryu.format_finite(value);
6666            assert_eq!(std::str::from_utf8(&buf).unwrap(), expect, "{value:?}");
6667            if encode_fixed_decimal_into(value).is_none() {
6668                continue;
6669            }
6670        }
6671    }
6672
6673    #[test]
6674    fn u64_matches_decimal_display() {
6675        let mut values = vec![0, 1, 9, 10, 11, 99, 100, 101, 999, 1000, 50000, u64::MAX];
6676        values.extend(0..200);
6677        for n in values {
6678            let mut buf = Vec::new();
6679            push_u64(&mut buf, n);
6680            assert_eq!(std::str::from_utf8(&buf).unwrap(), n.to_string());
6681        }
6682    }
6683}
6684
6685#[cfg(test)]
6686mod section_arity_tests {
6687    use super::require_unreserved_section_arity;
6688    use serde_json::json;
6689
6690    /// CON-section.16. Major 3 lists a new section from minor 2. Major 4 lists one from minor 1.
6691    #[test]
6692    fn minor2_lists_a_new_section_in_section_arity() {
6693        let widgets = vec![json!("widgets")];
6694        let err =
6695            require_unreserved_section_arity(3, 2, &widgets, &serde_json::Map::new()).unwrap_err();
6696        let msg = err.to_string();
6697        assert!(msg.contains("section_arity"), "{msg}");
6698
6699        let mut listed = serde_json::Map::new();
6700        listed.insert("section_arity".into(), json!({"widgets": 3}));
6701        require_unreserved_section_arity(3, 2, &widgets, &listed).unwrap();
6702
6703        let reserved = vec![json!("velocities"), json!("energies")];
6704        require_unreserved_section_arity(3, 2, &reserved, &serde_json::Map::new()).unwrap();
6705        require_unreserved_section_arity(3, 1, &widgets, &serde_json::Map::new()).unwrap();
6706        // Major 4 reserves the table at minor 0, so minor 1 must list the section.
6707        require_unreserved_section_arity(4, 1, &widgets, &serde_json::Map::new()).unwrap_err();
6708        require_unreserved_section_arity(4, 0, &widgets, &serde_json::Map::new()).unwrap();
6709    }
6710}
6711
6712#[cfg(test)]
6713mod allocate_len_tests {
6714    use super::allocate_len;
6715    use std::fs::File;
6716
6717    /// The scratch ends at the requested length on every host. macOS has no
6718    /// `posix_fallocate`, so this is the check that `F_PREALLOCATE` or
6719    /// `set_len` still leaves that length.
6720    #[test]
6721    fn temp_file_ends_at_the_requested_length() {
6722        let dir = tempfile::tempdir().unwrap();
6723        let file = File::create(dir.path().join("scratch")).unwrap();
6724        allocate_len(&file, 4096).unwrap();
6725        assert_eq!(file.metadata().unwrap().len(), 4096);
6726        allocate_len(&file, 100).unwrap();
6727        assert_eq!(file.metadata().unwrap().len(), 100);
6728    }
6729}
6730
6731#[cfg(test)]
6732mod publish_on_every_host {
6733    use super::publish_ranked_slices;
6734
6735    /// macOS renames a scratch reserved with `F_PREALLOCATE`. Windows
6736    /// renames a scratch extended with `set_len`. Linux may use an unnamed
6737    /// file. The published bytes and the absence of a scratch are the same.
6738    #[test]
6739    fn ranked_slices_replace_the_destination_and_leave_no_scratch() {
6740        let dir = tempfile::tempdir().unwrap();
6741        let path = dir.path().join("pieces.bin");
6742        std::fs::write(&path, b"previous").unwrap();
6743        publish_ranked_slices(&path, &[b"ab", &[], b"cde"], false, false).unwrap();
6744        assert_eq!(std::fs::read(&path).unwrap(), b"abcde");
6745        let names: Vec<_> = std::fs::read_dir(dir.path())
6746            .unwrap()
6747            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
6748            .filter(|name| name.starts_with(".readcon-write-") || name.ends_with(".rewrite"))
6749            .collect();
6750        assert!(names.is_empty(), "scratch left behind: {names:?}");
6751    }
6752}
6753
6754#[cfg(test)]
6755mod weight_partition {
6756    use super::pack_frames_by_weight;
6757    use proptest::prelude::*;
6758
6759    /// Groups are a half-open partition of `0..n` in file order.
6760    /// An empty range drops a frame; a step backwards repeats one.
6761    fn is_ordered_partition(n: usize, workers: usize, ranges: &[(usize, usize)]) -> bool {
6762        if n == 0 {
6763            return ranges.is_empty();
6764        }
6765        let workers = workers.max(1).min(n);
6766        if ranges.len() != workers {
6767            return false;
6768        }
6769        let mut cursor = 0usize;
6770        for &(start, end) in ranges {
6771            if start != cursor || end <= start || end > n {
6772                return false;
6773            }
6774            cursor = end;
6775        }
6776        cursor == n
6777    }
6778
6779    proptest! {
6780        #![proptest_config(ProptestConfig {
6781            cases: 64,
6782            failure_persistence: None,
6783            ..ProptestConfig::default()
6784        })]
6785        #[test]
6786        fn byte_weights_do_not_drop_or_reorder_frames(
6787            weights in prop::collection::vec(0usize..50_000, 0..48),
6788            workers in 1usize..17,
6789        ) {
6790            let ranges = pack_frames_by_weight(&weights, workers);
6791            prop_assert!(
6792                is_ordered_partition(weights.len(), workers, &ranges),
6793                "weights={weights:?} workers={workers} ranges={ranges:?}"
6794            );
6795        }
6796    }
6797}
6798
6799#[cfg(all(test, feature = "parallel"))]
6800mod parallel_write_tests {
6801    use super::{
6802        direct_slice_write, frame_byte_weight, pack_frames_by_weight, pipeline_format_threads,
6803    };
6804
6805    /// Two workers used to format on one thread. The caller only writes
6806    /// a group it has already received, so both workers have to format.
6807    #[test]
6808    fn two_workers_both_format_frame_groups() {
6809        assert_eq!(pipeline_format_threads(1), 1);
6810        assert_eq!(pipeline_format_threads(2), 2);
6811        assert_eq!(pipeline_format_threads(8), 8);
6812    }
6813
6814    /// One writer never prices the file. Two and four keep the overlapped
6815    /// copy. Only eight workers on a long trajectory format into the file.
6816    #[test]
6817    fn serial_and_narrow_writes_skip_the_direct_slice() {
6818        let long = 3_000_000;
6819        assert!(!direct_slice_write(1, long));
6820        assert!(!direct_slice_write(2, long));
6821        assert!(!direct_slice_write(4, long));
6822        assert!(direct_slice_write(8, long));
6823        assert!(!direct_slice_write(8, long - 1));
6824    }
6825
6826    /// Equal frame counts would split `[1, 1, 1, 100]` into two and two,
6827    /// gluing the heavy frame to a light one.
6828    #[test]
6829    fn a_heavy_frame_is_not_glued_to_a_light_one() {
6830        assert_eq!(
6831            pack_frames_by_weight(&[1, 1, 1, 100], 2),
6832            vec![(0, 3), (3, 4)]
6833        );
6834        assert_eq!(
6835            pack_frames_by_weight(&[100, 1, 1, 1], 2),
6836            vec![(0, 1), (1, 4)]
6837        );
6838        assert_eq!(
6839            pack_frames_by_weight(&[4, 4, 4, 4, 4, 4, 4, 4], 4),
6840            vec![(0, 2), (2, 4), (4, 6), (6, 8)]
6841        );
6842    }
6843
6844    #[test]
6845    fn velocity_lines_weigh_more_than_the_same_coordinates() {
6846        let con = std::fs::read_to_string(concat!(
6847            env!("CARGO_MANIFEST_DIR"),
6848            "/resources/test/tiny_cuh2.con"
6849        ))
6850        .unwrap();
6851        let vel = std::fs::read_to_string(concat!(
6852            env!("CARGO_MANIFEST_DIR"),
6853            "/resources/test/tiny_cuh2.convel"
6854        ))
6855        .unwrap();
6856        let plain = crate::iterators::frames_from_text(&con, Some(1)).unwrap();
6857        let moving = crate::iterators::frames_from_text(&vel, Some(1)).unwrap();
6858        assert!(frame_byte_weight(&moving[0]) > frame_byte_weight(&plain[0]));
6859        assert_eq!(
6860            frame_byte_weight(&moving[0]),
6861            plain[0].atom_data.len().max(1) * 2
6862        );
6863    }
6864
6865    /// Three frames, the last with velocities. Two workers must not
6866    /// scramble the file when the heavy frame sits in its own group.
6867    #[test]
6868    fn packed_groups_match_the_serial_bytes() {
6869        let _scratch = tempfile::tempdir().unwrap();
6870        let con = std::fs::read_to_string(concat!(
6871            env!("CARGO_MANIFEST_DIR"),
6872            "/resources/test/tiny_cuh2.con"
6873        ))
6874        .unwrap();
6875        let vel = std::fs::read_to_string(concat!(
6876            env!("CARGO_MANIFEST_DIR"),
6877            "/resources/test/tiny_cuh2.convel"
6878        ))
6879        .unwrap();
6880        let text = format!("{con}{con}{vel}");
6881        let frames = crate::iterators::frames_from_text(&text, Some(1)).unwrap();
6882        assert!(frames.len() > 2);
6883        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
6884        let mut serial = Vec::new();
6885        {
6886            let mut writer = super::ConFrameWriter::new(&mut serial);
6887            for frame in &frames {
6888                writer.write_frame_bound(frame).unwrap();
6889            }
6890            writer.flush().unwrap();
6891        }
6892        let path = _scratch
6893            .path()
6894            .join(format!("rc-pack-{}.con", std::process::id()));
6895        super::write_frame_refs_to_path(&path, &refs, 2, None, false, true).unwrap();
6896        let got = std::fs::read(&path).unwrap();
6897        assert_eq!(got, serial);
6898        let _ = std::fs::remove_file(&path);
6899    }
6900
6901    /// Light frames then velocity frames. Equal frame counts put the
6902    /// heavy half in its own groups, more than 10% above the mean.
6903    /// Byte weights keep the heaviest group within 10% of that mean,
6904    /// and the file is still the serial byte stream.
6905    #[test]
6906    fn mixed_con_and_convel_groups_stay_within_ten_percent() {
6907        let _scratch = tempfile::tempdir().unwrap();
6908        let con = std::fs::read_to_string(concat!(
6909            env!("CARGO_MANIFEST_DIR"),
6910            "/resources/test/tiny_cuh2.con"
6911        ))
6912        .unwrap();
6913        let vel = std::fs::read_to_string(concat!(
6914            env!("CARGO_MANIFEST_DIR"),
6915            "/resources/test/tiny_cuh2.convel"
6916        ))
6917        .unwrap();
6918        let text = format!("{}{}", con.repeat(24), vel.repeat(24));
6919        let frames = crate::iterators::frames_from_text(&text, Some(1)).unwrap();
6920        assert_eq!(frames.len(), 48);
6921        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
6922        let weights: Vec<usize> = refs.iter().map(|frame| frame_byte_weight(frame)).collect();
6923        let groups = 4usize;
6924        let ranges = super::group_frame_ranges(&refs, groups);
6925        let group_weight = |ranges: &[(usize, usize)]| -> Vec<u64> {
6926            ranges
6927                .iter()
6928                .map(|&(start, end)| weights[start..end].iter().map(|w| *w as u64).sum())
6929                .collect()
6930        };
6931        let weighted = group_weight(&ranges);
6932        let total: u64 = weighted.iter().sum();
6933        let mean = total as f64 / weighted.len() as f64;
6934        let max = *weighted.iter().max().unwrap() as f64;
6935        assert!(
6936            max <= mean * 1.10,
6937            "heaviest group {max} mean {mean} weights {weighted:?}"
6938        );
6939        let equal = group_weight(&super::equal_frame_ranges(frames.len(), groups));
6940        let equal_max = *equal.iter().max().unwrap() as f64;
6941        let equal_mean = total as f64 / equal.len() as f64;
6942        assert!(
6943            equal_max > equal_mean * 1.10,
6944            "equal frame counts should miss the 10% band: {equal:?}"
6945        );
6946
6947        let mut serial = Vec::new();
6948        {
6949            let mut writer = super::ConFrameWriter::new(&mut serial);
6950            for frame in &frames {
6951                writer.write_frame_bound(frame).unwrap();
6952            }
6953            writer.flush().unwrap();
6954        }
6955        let path = _scratch
6956            .path()
6957            .join(format!("rc-mix-{}.con", std::process::id()));
6958        super::write_frame_refs_to_path(&path, &refs, 4, None, false, true).unwrap();
6959        assert_eq!(std::fs::read(&path).unwrap(), serial);
6960        let _ = std::fs::remove_file(&path);
6961    }
6962
6963    /// Unequal slices land at their prefix-sum offsets. A serial
6964    /// `write_all` in the wrong order, or a store that ignores an
6965    /// empty slice's offset, would not rebuild the concatenation.
6966    #[test]
6967    fn disjoint_parts_rebuild_the_concatenation() {
6968        let _scratch = tempfile::tempdir().unwrap();
6969        let path = _scratch
6970            .path()
6971            .join(format!("rc-parts-{}.con", std::process::id()));
6972        let file = std::fs::OpenOptions::new()
6973            .read(true)
6974            .write(true)
6975            .create(true)
6976            .truncate(true)
6977            .open(&path)
6978            .unwrap();
6979        let parts = vec![
6980            b"aa".to_vec(),
6981            b"bbb".to_vec(),
6982            Vec::new(),
6983            b"cdef".to_vec(),
6984        ];
6985        super::store_disjoint_parts(&file, &parts).unwrap();
6986        drop(file);
6987        assert_eq!(std::fs::read(&path).unwrap(), b"aabbbcdef");
6988        let _ = std::fs::remove_file(&path);
6989    }
6990
6991    #[test]
6992    fn round_trip_width_matches_the_spelling() {
6993        let mut samples = vec![
6994            0.0,
6995            -0.0,
6996            1.0,
6997            -2.0,
6998            20.0,
6999            90.0,
7000            63.546,
7001            0.001,
7002            0.000001,
7003            1e-7,
7004            1e-20,
7005            1e22,
7006            -1.25,
7007            9.983,
7008            f64::MIN_POSITIVE,
7009            f64::MAX,
7010            f64::NAN,
7011            f64::INFINITY,
7012            f64::NEG_INFINITY,
7013        ];
7014        for i in 0..2000 {
7015            samples.push((i as f64) * 0.001);
7016            samples.push(-((i as f64) + 0.5) * 0.017);
7017        }
7018        let mut buf = Vec::new();
7019        let mut ryu = ryu::Buffer::new();
7020        for value in samples {
7021            buf.clear();
7022            super::push_round_trip(&mut buf, &mut ryu, None, value);
7023            assert_eq!(
7024                super::round_trip_width(value),
7025                buf.len(),
7026                "spelling {buf:?} of {value}"
7027            );
7028        }
7029    }
7030
7031    /// Float-width lengths match a real format, and the group is written
7032    /// into that exact slice. A short guess would reallocate the slice.
7033    #[test]
7034    fn packed_lengths_match_formatted_frames() {
7035        let _scratch = tempfile::tempdir().unwrap();
7036        use crate::types::ConFrameBuilder;
7037        let frame = |shift: f64, weird: f64| {
7038            let mut builder = ConFrameBuilder::new([20.0, 20.0, 20.0], [90.0, 90.0, 90.0]);
7039            builder
7040                .set_units(serde_json::json!({
7041                    "length": "angstrom",
7042                    "energy": "eV",
7043                    "mass": "amu",
7044                    "time": crate::units::NATURAL_TIME_UNIT,
7045                }))
7046                .unwrap();
7047            builder
7048                .add_atom("Cu", shift, shift + 0.001, weird, [false; 3], 0, 63.546)
7049                .with_velocity([shift * 0.1, -0.25, 0.0]);
7050            builder
7051                .add_atom("Cu", 1.5, -2.0, 0.0, [false; 3], 1, 63.546)
7052                .with_velocity([0.0, 1e-20, -0.0]);
7053            builder.build().unwrap()
7054        };
7055        let frames: Vec<_> = (0..6)
7056            .map(|i| {
7057                frame(
7058                    i as f64 * 0.017,
7059                    if i == 3 { 1.0e22 } else { 0.125 + i as f64 },
7060                )
7061            })
7062            .collect();
7063        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7064        let lengths = super::packed_frame_lengths(&refs, 4, None, false, true)
7065            .expect("uniform frames have exact lengths");
7066        for (frame, len) in refs.iter().zip(&lengths) {
7067            let formatted =
7068                super::format_group_bytes(std::slice::from_ref(frame), 1, None, false, true)
7069                    .unwrap();
7070            assert_eq!(formatted.len(), *len);
7071        }
7072        let mut dest = vec![0u8; lengths.iter().sum()];
7073        let ptr = dest.as_mut_ptr();
7074        super::format_group_into(&refs, &mut dest, None, false, true).unwrap();
7075        assert_eq!(dest.as_ptr(), ptr);
7076        let mut serial = Vec::new();
7077        {
7078            let mut writer = super::ConFrameWriter::new(&mut serial);
7079            for frame in &frames {
7080                writer.write_frame_bound(frame).unwrap();
7081            }
7082            writer.flush().unwrap();
7083        }
7084        assert_eq!(dest, serial);
7085        let path = _scratch
7086            .path()
7087            .join(format!("rc-packed-{}.con", std::process::id()));
7088        super::write_frame_refs_to_path(&path, &refs, 4, None, false, true).unwrap();
7089        assert_eq!(std::fs::read(&path).unwrap(), serial);
7090        let _ = std::fs::remove_file(&path);
7091
7092        let mut other = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7093        other
7094            .set_units(serde_json::json!({
7095                "length": "angstrom",
7096                "energy": "eV",
7097                "mass": "amu",
7098                "time": crate::units::NATURAL_TIME_UNIT,
7099            }))
7100            .unwrap();
7101        other
7102            .add_atom("H", 0.0, 0.0, 0.0, [false; 3], 0, 1.0)
7103            .with_velocity([0.0, 0.0, 0.0]);
7104        let odd = other.build().unwrap();
7105        let mixed = [refs[0], &odd];
7106        assert!(super::packed_frame_lengths(&mixed, 2, None, false, true).is_none());
7107        super::write_frame_refs_to_path(&path, &mixed, 2, None, false, true).unwrap();
7108        let mut serial = Vec::new();
7109        {
7110            let mut writer = super::ConFrameWriter::new(&mut serial);
7111            writer.write_frame_bound(mixed[0]).unwrap();
7112            writer.write_frame_bound(mixed[1]).unwrap();
7113            writer.flush().unwrap();
7114        }
7115        assert_eq!(std::fs::read(&path).unwrap(), serial);
7116        let _ = std::fs::remove_file(&path);
7117    }
7118
7119    /// Pricing is cached for a repeat write. Editing a coordinate, or
7120    /// dropping the frames, must not reuse that price.
7121    #[test]
7122    fn a_coordinate_edit_reprices_the_packed_lengths() {
7123        use crate::types::ConFrameBuilder;
7124        let mut frames = Vec::new();
7125        for i in 0..4 {
7126            let mut builder = ConFrameBuilder::new([20.0, 20.0, 20.0], [90.0, 90.0, 90.0]);
7127            builder
7128                .set_units(serde_json::json!({
7129                    "length": "angstrom",
7130                    "energy": "eV",
7131                    "mass": "amu",
7132                    "time": crate::units::NATURAL_TIME_UNIT,
7133                }))
7134                .unwrap();
7135            builder
7136                .add_atom("Cu", i as f64, 0.25, 0.5, [false; 3], 0, 63.546)
7137                .with_velocity([0.1, 0.0, 0.0]);
7138            builder
7139                .add_atom("Cu", 1.5, -2.0, 0.0, [false; 3], 1, 63.546)
7140                .with_velocity([0.0, 0.2, 0.0]);
7141            frames.push(builder.build().unwrap());
7142        }
7143        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7144        let before = super::cached_packed_lengths(&refs, 2, None, false, true).unwrap();
7145        let old = before[2];
7146        frames[2].set_x_at(0, 1.0e22);
7147        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7148        let after = super::cached_packed_lengths(&refs, 2, None, false, true).unwrap();
7149        let formatted =
7150            super::format_group_bytes(std::slice::from_ref(&refs[2]), 1, None, false, true)
7151                .unwrap();
7152        assert_ne!(old, formatted.len());
7153        assert_eq!(after[2], formatted.len());
7154    }
7155
7156    #[test]
7157    fn replacing_an_interior_frame_reprices_the_cache() {
7158        use crate::types::ConFrameBuilder;
7159        let mut frames = Vec::new();
7160        for i in 0..4 {
7161            let mut builder = ConFrameBuilder::new([20.0, 20.0, 20.0], [90.0, 90.0, 90.0]);
7162            builder
7163                .set_units(serde_json::json!({
7164                    "length": "angstrom",
7165                    "energy": "eV",
7166                    "mass": "amu",
7167                    "time": crate::units::NATURAL_TIME_UNIT,
7168                }))
7169                .unwrap();
7170            builder
7171                .add_atom("Cu", i as f64, 0.25, 0.5, [false; 3], 0, 63.546)
7172                .with_velocity([0.1, 0.0, 0.0]);
7173            builder
7174                .add_atom("Cu", 1.5, -2.0, 0.0, [false; 3], 1, 63.546)
7175                .with_velocity([0.0, 0.2, 0.0]);
7176            frames.push(builder.build().unwrap());
7177        }
7178        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7179        let before = super::cached_packed_lengths(&refs, 2, None, false, true).unwrap();
7180        let old = before[1];
7181        let mut replacement = ConFrameBuilder::new([20.0, 20.0, 20.0], [90.0, 90.0, 90.0]);
7182        replacement
7183            .set_units(serde_json::json!({
7184                "length": "angstrom",
7185                "energy": "eV",
7186                "mass": "amu",
7187                "time": crate::units::NATURAL_TIME_UNIT,
7188            }))
7189            .unwrap();
7190        replacement
7191            .add_atom("Cu", 1.0e22, 0.25, 0.5, [false; 3], 0, 63.546)
7192            .with_velocity([0.0, 0.0, 0.0]);
7193        replacement
7194            .add_atom("Cu", -1.0e-20, -2.0, 0.0, [false; 3], 1, 63.546)
7195            .with_velocity([0.0, 0.0, 0.0]);
7196        frames[1] = replacement.build().unwrap();
7197        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7198        let after = super::cached_packed_lengths(&refs, 2, None, false, true).unwrap();
7199        let formatted =
7200            super::format_group_bytes(std::slice::from_ref(&refs[1]), 1, None, false, true)
7201                .unwrap();
7202        assert_ne!(old, formatted.len());
7203        assert_eq!(after[1], formatted.len());
7204    }
7205
7206    #[test]
7207    fn invalidation_clears_the_cached_lengths_slot() {
7208        use crate::types::ConFrameBuilder;
7209        let packed = super::PackedLengthsCache::new();
7210        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7211        builder.add_atom("Cu", 0.0, 0.0, 0.0, [false; 3], 0, 63.546);
7212        let frame = builder.build().unwrap();
7213        let refs = vec![&frame, &frame];
7214        let _ = super::cached_packed_lengths_in(&packed, &refs, 1, None, false, true);
7215        assert!(
7216            packed
7217                .entry
7218                .lock()
7219                .unwrap_or_else(|err| err.into_inner())
7220                .is_some()
7221        );
7222        packed.invalidate();
7223        assert!(
7224            packed
7225                .entry
7226                .lock()
7227                .unwrap_or_else(|err| err.into_inner())
7228                .is_none()
7229        );
7230    }
7231
7232    #[test]
7233    fn format_group_into_detects_overrun_and_underrun_without_writing_past_slice() {
7234        use crate::types::ConFrameBuilder;
7235        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7236        builder.add_atom("Cu", 1.0, 2.0, 3.0, [false; 3], 0, 63.546);
7237        let frame = builder.build().unwrap();
7238        let refs = [&frame];
7239        let exact = super::format_group_bytes(&refs, 1, None, false, true).unwrap();
7240
7241        let mut larger = vec![0xAAu8; exact.len() + 8];
7242        let err = super::format_group_into(&refs, &mut larger, None, false, true).unwrap_err();
7243        assert!(super::is_packed_drift(&err));
7244
7245        let mut smaller = vec![0xAAu8; exact.len() + 4];
7246        let split = exact.len() - 3;
7247        let (dest, guard) = smaller.split_at_mut(split);
7248        let err = super::format_group_into(&refs, dest, None, false, true).unwrap_err();
7249        assert!(super::is_packed_drift(&err));
7250        assert!(guard.iter().all(|&b| b == 0xAA));
7251    }
7252
7253    #[test]
7254    fn format_packed_buffers_signals_drift_after_mutation() {
7255        use crate::types::ConFrameBuilder;
7256        let mut frames = Vec::new();
7257        for _ in 0..4 {
7258            let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7259            builder.add_atom("Cu", 1.0, 2.0, 3.0, [false; 3], 0, 63.546);
7260            frames.push(builder.build().unwrap());
7261        }
7262        let exact_len = super::format_group_bytes(&[&frames[0]], 1, None, false, false)
7263            .unwrap()
7264            .len();
7265        let lengths = vec![exact_len; 4];
7266        {
7267            let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7268            let parts =
7269                super::format_packed_buffers(&refs, &lengths, 2, None, false, false).unwrap();
7270            let combined: Vec<u8> = parts.into_iter().flatten().collect();
7271            assert_eq!(combined, super::write_frames_to_vec(&frames).unwrap());
7272        }
7273        frames[0].positions.f64_mut_slice().unwrap()[0] = 1.2345678901234567e22;
7274        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7275        let err = super::format_packed_buffers(&refs, &lengths, 2, None, false, false).unwrap_err();
7276        assert!(super::is_packed_drift(&err));
7277    }
7278}
7279
7280#[cfg(all(test, feature = "parallel"))]
7281mod parallel_write_bytes {
7282    use super::{write_frames_to_vec, write_frames_to_vec_with_threads};
7283    use crate::iterators::frames_from_text;
7284
7285    fn wide_text(n: usize) -> String {
7286        let mut text = String::new();
7287        text.push_str(
7288            "grid\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n1\n",
7289        );
7290        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
7291        for i in 0..n {
7292            text.push_str(&format!("{i}.125 0.25 0.5 0 {i}\n"));
7293        }
7294        text
7295    }
7296
7297    #[test]
7298    fn parallel_bytes_match_the_serial_writer() {
7299        let wide = frames_from_text(&wide_text(5000), Some(1)).unwrap();
7300        let serial = write_frames_to_vec(&wide).unwrap();
7301        let parallel = write_frames_to_vec_with_threads(&wide, 4, None, false).unwrap();
7302        assert_eq!(parallel, serial);
7303        let mut with_vel = wide_text(5000);
7304        with_vel.push_str("\nCu\nVelocities of Component 1\n");
7305        for i in 0..5000 {
7306            with_vel.push_str(&format!("{}.0001 0.0002 -0.0001 0 {i}\n", i % 7));
7307        }
7308        let moving = frames_from_text(&with_vel, Some(1)).unwrap();
7309        let serial = write_frames_to_vec(&moving).unwrap();
7310        let parallel = write_frames_to_vec_with_threads(&moving, 4, None, false).unwrap();
7311        assert_eq!(parallel, serial);
7312        let one = frames_from_text(
7313            &std::fs::read_to_string(concat!(
7314                env!("CARGO_MANIFEST_DIR"),
7315                "/resources/test/cuh2.con"
7316            ))
7317            .unwrap()
7318            .repeat(8),
7319            Some(1),
7320        )
7321        .unwrap();
7322        let serial = write_frames_to_vec(&one).unwrap();
7323        let parallel = write_frames_to_vec_with_threads(&one, 4, None, false).unwrap();
7324        assert_eq!(parallel, serial);
7325    }
7326
7327    #[test]
7328    fn pwrite_matches_the_concatenated_writer() {
7329        let _scratch = tempfile::tempdir().unwrap();
7330        let one = frames_from_text(
7331            &std::fs::read_to_string(concat!(
7332                env!("CARGO_MANIFEST_DIR"),
7333                "/resources/test/cuh2.con"
7334            ))
7335            .unwrap()
7336            .repeat(8),
7337            Some(1),
7338        )
7339        .unwrap();
7340        let serial = write_frames_to_vec(&one).unwrap();
7341        let refs: Vec<&crate::types::ConFrame> = one.iter().collect();
7342        let path = _scratch.path().join(format!(
7343            "readcon-pwrite-{}-{}.con",
7344            std::process::id(),
7345            one.len()
7346        ));
7347        super::write_frame_refs_to_path(&path, &refs, 4, None, false, false).unwrap();
7348        let got = std::fs::read(&path).unwrap();
7349        let _ = std::fs::remove_file(&path);
7350        assert_eq!(got, serial);
7351    }
7352
7353    #[test]
7354    fn stamped_pwrite_matches_the_binding_writer() {
7355        let _scratch = tempfile::tempdir().unwrap();
7356        let one = frames_from_text(
7357            &std::fs::read_to_string(concat!(
7358                env!("CARGO_MANIFEST_DIR"),
7359                "/resources/test/cuh2.con"
7360            ))
7361            .unwrap()
7362            .repeat(8),
7363            Some(1),
7364        )
7365        .unwrap();
7366        let mut serial = Vec::new();
7367        {
7368            let mut writer = super::ConFrameWriter::new(&mut serial);
7369            for frame in &one {
7370                let mut stamped = frame.clone();
7371                writer.write_frame_binding(&mut stamped).unwrap();
7372            }
7373        }
7374        let refs: Vec<&crate::types::ConFrame> = one.iter().collect();
7375        let path = _scratch.path().join(format!(
7376            "readcon-pwrite-bind-{}-{}.con",
7377            std::process::id(),
7378            one.len()
7379        ));
7380        super::write_frame_refs_to_path(&path, &refs, 4, None, false, true).unwrap();
7381        let got = std::fs::read(&path).unwrap();
7382        let _ = std::fs::remove_file(&path);
7383        assert_eq!(got, serial);
7384    }
7385
7386    /// A same-length rewrite matches a fresh write. The published path keeps
7387    /// the previous complete file until rename, and that inode becomes the
7388    /// spare the next rewrite fills.
7389    #[cfg(unix)]
7390    #[test]
7391    fn a_rewrite_matches_a_fresh_write_and_reuses_the_inode() {
7392        let _scratch = tempfile::tempdir().unwrap();
7393        use std::os::unix::fs::MetadataExt;
7394        let text = std::fs::read_to_string(concat!(
7395            env!("CARGO_MANIFEST_DIR"),
7396            "/resources/test/cuh2.con"
7397        ))
7398        .unwrap();
7399        let frames = frames_from_text(&text, Some(1)).unwrap();
7400        let refs: Vec<&crate::types::ConFrame> = vec![&frames[0]; 32];
7401        let path = _scratch
7402            .path()
7403            .join(format!("rc-rewrite-{}.con", std::process::id()));
7404        let fresh = _scratch
7405            .path()
7406            .join(format!("rc-rewrite-fresh-{}.con", std::process::id()));
7407        super::write_frame_refs_to_path(&fresh, &refs, 8, None, false, true).unwrap();
7408        let expect = std::fs::read(&fresh).unwrap();
7409        super::write_frame_refs_to_path(&path, &refs, 1, None, false, true).unwrap();
7410        let first_ino = std::fs::metadata(&path).unwrap().ino();
7411        super::rewrite_frame_refs_to_path(&path, &refs, 8, None, false, true, true).unwrap();
7412        assert_eq!(std::fs::read(&path).unwrap(), expect);
7413        let spare = path.with_file_name(format!(
7414            "{}.rewrite",
7415            path.file_name().unwrap().to_string_lossy()
7416        ));
7417        assert_eq!(
7418            std::fs::metadata(&spare).unwrap().ino(),
7419            first_ino,
7420            "the previous inode is the spare"
7421        );
7422        super::rewrite_frame_refs_to_path(&path, &refs, 1, None, false, true, true).unwrap();
7423        assert_eq!(std::fs::read(&path).unwrap(), expect);
7424        assert_eq!(
7425            std::fs::metadata(&path).unwrap().ino(),
7426            first_ino,
7427            "the second rewrite publishes the spare inode"
7428        );
7429        // The published name is still the previous bytes if the spare write
7430        // is what failed. An empty directory component cannot be created.
7431        let blocked = _scratch
7432            .path()
7433            .join(format!("rc-rewrite-missing-{}/out.con", std::process::id()));
7434        std::fs::write(&path, &expect).unwrap();
7435        let before = std::fs::read(&path).unwrap();
7436        let err = super::rewrite_frame_refs_to_path(&blocked, &refs, 1, None, false, true, true);
7437        assert!(err.is_err());
7438        assert_eq!(std::fs::read(&path).unwrap(), before);
7439        let _ = std::fs::remove_file(&path);
7440        let _ = std::fs::remove_file(&spare);
7441        let _ = std::fs::remove_file(&fresh);
7442    }
7443
7444    #[cfg(unix)]
7445    #[test]
7446    fn dropping_the_spare_leaves_one_file() {
7447        let _scratch = tempfile::tempdir().unwrap();
7448        let text = std::fs::read_to_string(concat!(
7449            env!("CARGO_MANIFEST_DIR"),
7450            "/resources/test/cuh2.con"
7451        ))
7452        .unwrap();
7453        let frames = frames_from_text(&text, Some(1)).unwrap();
7454        let refs: Vec<&crate::types::ConFrame> = vec![&frames[0]; 4];
7455        let path = _scratch
7456            .path()
7457            .join(format!("rc-rewrite-drop-{}.con", std::process::id()));
7458        let fresh = _scratch
7459            .path()
7460            .join(format!("rc-rewrite-drop-fresh-{}.con", std::process::id()));
7461        super::write_frame_refs_to_path(&fresh, &refs, 1, None, false, true).unwrap();
7462        let expect = std::fs::read(&fresh).unwrap();
7463        super::write_frame_refs_to_path(&path, &refs, 1, None, false, true).unwrap();
7464        super::rewrite_frame_refs_to_path(&path, &refs, 1, None, false, true, false).unwrap();
7465        assert_eq!(std::fs::read(&path).unwrap(), expect);
7466        let spare = path.with_file_name(format!(
7467            "{}.rewrite",
7468            path.file_name().unwrap().to_string_lossy()
7469        ));
7470        assert!(!spare.exists(), "keep_spare false removes the second inode");
7471        let _ = std::fs::remove_file(&path);
7472        let _ = std::fs::remove_file(&fresh);
7473    }
7474
7475    /// Kill the process while the spare is being written. The published
7476    /// path must still be the previous complete file, not a mix.
7477    #[cfg(unix)]
7478    #[test]
7479    fn a_killed_rewrite_leaves_the_published_file_whole() {
7480        let _scratch = tempfile::tempdir().unwrap();
7481        let text = std::fs::read_to_string(concat!(
7482            env!("CARGO_MANIFEST_DIR"),
7483            "/resources/test/cuh2.con"
7484        ))
7485        .unwrap();
7486        let frames = frames_from_text(&text, Some(1)).unwrap();
7487        let n = 8_000usize;
7488        let refs: Vec<&crate::types::ConFrame> = vec![&frames[0]; n];
7489        let path = _scratch
7490            .path()
7491            .join(format!("rc-rewrite-kill-{}.con", std::process::id()));
7492        super::write_frame_refs_to_path(&path, &refs, 1, None, false, true).unwrap();
7493        let original = std::fs::read(&path).unwrap();
7494        let mut changed = frames[0].clone();
7495        let x = changed.x_at(0);
7496        changed.set_x_at(0, x + 0.0001);
7497        let changed_refs: Vec<&crate::types::ConFrame> = vec![&changed; n];
7498        let spare = path.with_file_name(format!(
7499            "{}.rewrite",
7500            path.file_name().unwrap().to_string_lossy()
7501        ));
7502        let _ = std::fs::remove_file(&spare);
7503        let pid = unsafe { libc::fork() };
7504        assert!(pid >= 0, "fork");
7505        if pid == 0 {
7506            let _ =
7507                super::rewrite_frame_refs_to_path(&path, &changed_refs, 1, None, false, true, true);
7508            std::process::exit(0);
7509        }
7510        let started = std::time::Instant::now();
7511        while started.elapsed() < std::time::Duration::from_secs(30) {
7512            if spare.exists()
7513                && std::fs::metadata(&spare)
7514                    .map(|meta| meta.len() > 65_536)
7515                    .unwrap_or(false)
7516            {
7517                break;
7518            }
7519            std::thread::sleep(std::time::Duration::from_millis(5));
7520        }
7521        unsafe { libc::kill(pid, libc::SIGKILL) };
7522        let mut status = 0i32;
7523        unsafe { libc::waitpid(pid, &mut status, 0) };
7524        assert!(
7525            libc::WIFSIGNALED(status),
7526            "the rewrite finished before the kill; status {status}"
7527        );
7528        assert_eq!(std::fs::read(&path).unwrap(), original);
7529        let _ = std::fs::remove_file(&path);
7530        let _ = std::fs::remove_file(&spare);
7531        let hold = path.with_file_name(format!(
7532            "{}.rewrite-hold",
7533            path.file_name().unwrap().to_string_lossy()
7534        ));
7535        let _ = std::fs::remove_file(&hold);
7536    }
7537
7538    #[test]
7539    fn a_wide_file_write_matches_the_serial_bytes_when_ids_are_not_dense() {
7540        let _scratch = tempfile::tempdir().unwrap();
7541        let n = 4096usize;
7542        let mut text = String::from(
7543            "grid\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n1\n",
7544        );
7545        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
7546        for i in 0..n {
7547            text.push_str(&format!("{i}.125 0.25 0.5 0 {}\n", i + 10));
7548        }
7549        text.push_str("\nCu\nVelocities of Component 1\n");
7550        for i in 0..n {
7551            text.push_str(&format!("{}.0001 0.0002 -0.0001 0 {}\n", i % 7, i + 10));
7552        }
7553        let frames = frames_from_text(&text, Some(1)).unwrap();
7554        let serial = write_frames_to_vec(&frames).unwrap();
7555        let parallel = write_frames_to_vec_with_threads(&frames, 8, None, false).unwrap();
7556        assert_eq!(parallel, serial);
7557        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7558        let path = _scratch.path().join(format!(
7559            "readcon-wide-stream-{}-{n}.con",
7560            std::process::id()
7561        ));
7562        super::write_frame_refs_to_path(&path, &refs, 8, None, false, false).unwrap();
7563        let got = std::fs::read(&path).unwrap();
7564        let _ = std::fs::remove_file(&path);
7565        assert_eq!(got, serial);
7566    }
7567
7568    #[test]
7569    fn a_mixed_wide_frame_matches_the_serial_parse() {
7570        let n = 7000usize;
7571        let mut text = String::from(
7572            "grid\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n2\n",
7573        );
7574        text.push_str(&format!("{n} {n}\n63.546 1.008\n"));
7575        text.push_str("Cu\nCoordinates of Component 1\n");
7576        for i in 0..n {
7577            text.push_str(&format!("{i}.125 0.25 0.5 0 {i}\n"));
7578        }
7579        text.push_str("H\nCoordinates of Component 2\n");
7580        for i in 0..n {
7581            let id = n + i;
7582            text.push_str(&format!("1.5 2.25 {i}.5 0 {id}\n"));
7583        }
7584        assert!(text.len() >= (256 << 10), "frame is {} bytes", text.len());
7585        let serial = frames_from_text(&text, Some(1)).unwrap();
7586        let parallel = frames_from_text(&text, Some(8)).unwrap();
7587        assert_eq!(parallel.len(), 1);
7588        assert_eq!(parallel[0].atom_data.len(), n * 2);
7589        assert_eq!(parallel[0].atom_data[0].symbol.as_ref(), "Cu");
7590        assert_eq!(parallel[0].atom_data[n].symbol.as_ref(), "H");
7591        assert_eq!(
7592            parallel[0].atom_data[n].atom_id,
7593            serial[0].atom_data[n].atom_id
7594        );
7595        assert_eq!(parallel, serial);
7596    }
7597
7598    #[test]
7599    fn coordinate_lines_match_the_serial_frame_body() {
7600        let frames = frames_from_text(&wide_text(32), Some(1)).unwrap();
7601        let rows = super::frame_coords(&frames[0]).unwrap();
7602        let lines = super::format_coordinate_lines(&frames[0].atom_data, &rows).unwrap();
7603        let serial = write_frames_to_vec(&frames).unwrap();
7604        let text = std::str::from_utf8(&serial).unwrap();
7605        let marker = "Coordinates of Component 1\n";
7606        let start = text.find(marker).unwrap() + marker.len();
7607        assert_eq!(lines, text.as_bytes()[start..]);
7608    }
7609
7610    #[test]
7611    fn pwrite_offsets_follow_an_exclusive_scan() {
7612        let _scratch = tempfile::tempdir().unwrap();
7613        let path = _scratch
7614            .path()
7615            .join(format!("readcon-pwrite-scan-{}.bin", std::process::id()));
7616        let parts: [&[u8]; 4] = [b"abc", b"", b"def\n", b"g"];
7617        super::publish_new(
7618            &path,
7619            |err| err,
7620            |file| super::pwrite_borrowed(file, &parts),
7621        )
7622        .unwrap();
7623        let got = std::fs::read(&path).unwrap();
7624        let _ = std::fs::remove_file(&path);
7625        assert_eq!(got, b"abcdef\ng");
7626    }
7627
7628    #[test]
7629    fn mapped_write_matches_the_serial_write() {
7630        let _scratch = tempfile::tempdir().unwrap();
7631        use crate::types::ConFrameBuilder;
7632        for n in [1usize, 3, 7, 4097, 8191] {
7633            let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7634            for i in 0..n {
7635                let x = (i % 97) as f64 * 0.125;
7636                let y = (i % 13) as f64;
7637                let z = if i % 2 == 0 { i as f64 * 0.001 } else { -0.5 };
7638                builder.add_atom("Cu", x, y, z, [false, i % 5 == 0, false], i as u64, 63.546);
7639            }
7640            let frame = builder.build().expect("frame");
7641            let serial = super::write_frames_to_vec(std::slice::from_ref(&frame)).expect("serial");
7642            for workers in [1usize, 2, 3, 8] {
7643                let path = _scratch.path().join(format!(
7644                    "readcon-map-{n}-{workers}-{}.con",
7645                    std::process::id()
7646                ));
7647                let mut writer = super::ConFrameWriter::new(Vec::<u8>::new())
7648                    .parallel_atoms(workers)
7649                    .map_rows(true);
7650                writer.stream_file = Some(
7651                    std::fs::OpenOptions::new()
7652                        .read(true)
7653                        .write(true)
7654                        .create(true)
7655                        .truncate(true)
7656                        .open(&path)
7657                        .expect("create"),
7658                );
7659                writer.write_frame(&frame).expect("mapped");
7660                drop(writer);
7661                let got = std::fs::read(&path).expect("read");
7662                let _ = std::fs::remove_file(&path);
7663                assert_eq!(got, serial, "n={n} workers={workers}");
7664            }
7665        }
7666    }
7667
7668    fn copper_frame(
7669        n: usize,
7670        symbol: &str,
7671        mass: f64,
7672        id_at: impl Fn(usize) -> u64,
7673    ) -> crate::types::ConFrame {
7674        use crate::types::ConFrameBuilder;
7675        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7676        for i in 0..n {
7677            builder.add_atom(
7678                symbol,
7679                i as f64 * 0.125,
7680                0.25,
7681                0.5,
7682                [false, false, false],
7683                id_at(i),
7684                mass,
7685            );
7686        }
7687        builder.build().expect("frame")
7688    }
7689
7690    #[test]
7691    fn a_binding_header_plus_coordinate_lines_match_the_bound_writer() {
7692        let frame = copper_frame(4, "Cu", 63.546, |i| i as u64);
7693        let header = super::wide_frame_header(&frame).expect("header");
7694        let rows = super::frame_coords(&frame).expect("coords");
7695        let coords = super::format_coordinate_lines(&frame.atom_data, &rows).expect("coords");
7696        let mut full = Vec::new();
7697        {
7698            let mut writer = super::ConFrameWriter::new(&mut full);
7699            writer.write_frame_bound(&frame).expect("bound");
7700            writer.flush().expect("flush");
7701        }
7702        let mut got = header.clone();
7703        got.extend(coords);
7704        assert_eq!(got, full);
7705        // The wide-frame harness puts this header on rank 0 and lets every
7706        // rank format its own atom slice. One, two, four and eight ranks
7707        // write the same bytes as the one-rank binding writer.
7708        let frame = copper_frame(8, "Cu", 63.546, |i| i as u64);
7709        let header = super::wide_frame_header(&frame).expect("header");
7710        let mut full = Vec::new();
7711        {
7712            let mut writer = super::ConFrameWriter::new(&mut full);
7713            writer.write_frame_bound(&frame).expect("bound");
7714            writer.flush().expect("flush");
7715        }
7716        for ranks in [1usize, 2, 4, 8] {
7717            let share = frame.atom_data.len() / ranks;
7718            let mut split = header.clone();
7719            for rank in 0..ranks {
7720                let slice = &frame.atom_data[rank * share..(rank + 1) * share];
7721                let rows = super::frame_coords(&frame).expect("coords");
7722                split.extend(
7723                    super::format_coordinate_lines(
7724                        slice,
7725                        &rows[rank * share * 3..(rank + 1) * share * 3],
7726                    )
7727                    .expect("slice"),
7728                );
7729            }
7730            assert_eq!(split, full, "ranks {ranks}");
7731        }
7732    }
7733
7734    #[test]
7735    fn two_wide_frames_on_two_threads_keep_up_with_one_frame() {
7736        let _scratch = tempfile::tempdir().unwrap();
7737        let n = 200_000usize;
7738        let one = copper_frame(n, "Cu", 63.546, |i| i as u64);
7739        let frames = [one.clone(), one.clone()];
7740        let refs: Vec<&crate::types::ConFrame> = frames.iter().collect();
7741        let serial = super::write_frames_to_vec(&frames).expect("serial");
7742        let path = _scratch
7743            .path()
7744            .join(format!("readcon-weak-write-{}.con", std::process::id()));
7745        super::write_frame_refs_to_path(&path, &refs, 2, None, false, false).expect("parallel");
7746        let got = std::fs::read(&path).expect("read");
7747        let _ = std::fs::remove_file(&path);
7748        assert_eq!(got, serial);
7749    }
7750
7751    #[test]
7752    fn parallel_write_rejects_an_id_repeated_in_another_type() {
7753        let _scratch = tempfile::tempdir().unwrap();
7754        use crate::types::ConFrameBuilder;
7755        let n = 4096usize;
7756        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7757        for i in 0..n {
7758            builder.add_atom(
7759                "Cu",
7760                i as f64 * 0.125,
7761                0.25,
7762                0.5,
7763                [false, false, false],
7764                i as u64,
7765                63.546,
7766            );
7767        }
7768        for i in 0..n {
7769            builder.add_atom(
7770                "H",
7771                i as f64 * 0.125,
7772                1.5,
7773                0.5,
7774                [false, false, false],
7775                i as u64,
7776                1.008,
7777            );
7778        }
7779        let frame = builder.build().expect("frame");
7780        let serial = write_frames_to_vec(std::slice::from_ref(&frame));
7781        let parallel =
7782            write_frames_to_vec_with_threads(std::slice::from_ref(&frame), 4, None, false);
7783        assert!(serial.is_err(), "serial writer accepted a repeated id");
7784        assert!(parallel.is_err(), "parallel writer accepted a repeated id");
7785        let path = _scratch
7786            .path()
7787            .join(format!("readcon-repeat-id-{}.con", std::process::id()));
7788        std::fs::write(&path, b"keep").unwrap();
7789        let refs = [&frame];
7790        let err = super::write_frame_refs_to_path(&path, &refs, 4, None, false, false);
7791        assert!(err.is_err(), "path write accepted a repeated id");
7792        assert_eq!(std::fs::read(&path).unwrap(), b"keep");
7793        let _ = std::fs::remove_file(&path);
7794    }
7795
7796    #[test]
7797    fn a_failed_later_group_leaves_the_previous_file() {
7798        let _scratch = tempfile::tempdir().unwrap();
7799        let good = copper_frame(2, "Cu", 63.546, |i| i as u64);
7800        let bad = copper_frame(2, "Cu", 63.546, |_| 0);
7801        let path = _scratch
7802            .path()
7803            .join(format!("readcon-group-fail-{}.con", std::process::id()));
7804        std::fs::write(&path, b"keep").unwrap();
7805        let refs = [&good, &bad];
7806        let err = super::write_frame_refs_to_path(&path, &refs, 4, None, false, false);
7807        assert!(err.is_err());
7808        assert_eq!(std::fs::read(&path).unwrap(), b"keep");
7809        let _ = std::fs::remove_file(&path);
7810    }
7811
7812    #[test]
7813    fn mapped_decimal_lines_match_the_serial_writer() {
7814        let _scratch = tempfile::tempdir().unwrap();
7815        let frame = copper_frame(64, "Cu", 63.546, |i| i as u64);
7816        let frames = [frame];
7817        let serial = write_frames_to_vec_with_threads(&frames, 1, Some(40), false).unwrap();
7818        let path = _scratch
7819            .path()
7820            .join(format!("readcon-long-line-{}.con", std::process::id()));
7821        let mut writer = super::ConFrameWriter::with_precision(Vec::<u8>::new(), 40)
7822            .parallel_atoms(4)
7823            .map_rows(true);
7824        writer.stream_file = Some(
7825            std::fs::OpenOptions::new()
7826                .read(true)
7827                .write(true)
7828                .create(true)
7829                .truncate(true)
7830                .open(&path)
7831                .unwrap(),
7832        );
7833        writer.write_frame(&frames[0]).unwrap();
7834        drop(writer);
7835        let got = std::fs::read(&path).unwrap();
7836        let _ = std::fs::remove_file(&path);
7837        assert_eq!(got, serial);
7838    }
7839
7840    #[test]
7841    fn a_rejected_spread_does_not_keep_the_reserved_file() {
7842        let _scratch = tempfile::tempdir().unwrap();
7843        use crate::types::ConFrameBuilder;
7844        let n = 4096usize;
7845        let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
7846        for i in 0..n {
7847            builder.add_atom(
7848                "Cu",
7849                i as f64 * 0.125,
7850                0.25,
7851                0.5,
7852                [false, false, false],
7853                i as u64,
7854                63.546,
7855            );
7856        }
7857        builder.with_spread([0.0, 0.0, 0.0]);
7858        let mut frame = builder.build().expect("frame");
7859        frame.atom_data[0].set_spread(Some([-1.0, 0.0, 0.0]));
7860        let path = _scratch
7861            .path()
7862            .join(format!("readcon-spread-fail-{}.con", std::process::id()));
7863        let file = std::fs::OpenOptions::new()
7864            .read(true)
7865            .write(true)
7866            .create(true)
7867            .truncate(true)
7868            .open(&path)
7869            .unwrap();
7870        let mut writer = super::ConFrameWriter::new(Vec::<u8>::new())
7871            .parallel_atoms(4)
7872            .map_rows(true)
7873            .mapped_file(file);
7874        let err = writer.write_frame(&frame);
7875        drop(writer);
7876        assert!(err.is_err());
7877        assert_eq!(std::fs::metadata(&path).unwrap().len(), 0);
7878        let _ = std::fs::remove_file(&path);
7879    }
7880
7881    #[test]
7882    fn overlapped_pwrite_does_not_keep_bytes_past_the_frame() {
7883        use std::io::{Seek, Write};
7884        let frame = copper_frame(4096, "Cu", 63.546, |i| i as u64);
7885        let serial = write_frames_to_vec(std::slice::from_ref(&frame)).unwrap();
7886        let path = std::env::current_dir()
7887            .unwrap()
7888            .join(format!("readcon-pwrite-tail-{}.con", std::process::id()));
7889        let mut file = std::fs::OpenOptions::new()
7890            .read(true)
7891            .write(true)
7892            .create(true)
7893            .truncate(true)
7894            .open(&path)
7895            .unwrap();
7896        file.write_all(&vec![b'Z'; serial.len() + 64]).unwrap();
7897        file.seek(std::io::SeekFrom::Start(0)).unwrap();
7898        let workers = super::physical_cores().max(2);
7899        let mut writer = super::ConFrameWriter::new(Vec::<u8>::new())
7900            .parallel_atoms(workers)
7901            .mapped_file(file);
7902        writer.write_frame(&frame).unwrap();
7903        drop(writer);
7904        let got = std::fs::read(&path).unwrap();
7905        let _ = std::fs::remove_file(&path);
7906        assert_eq!(got, serial);
7907    }
7908}
7909
7910#[cfg(test)]
7911mod gzip_stream_memory {
7912    use super::ConFrameWriter;
7913    use crate::iterators::{frames_from_text, read_all_frames};
7914
7915    fn parsed_frame() -> crate::types::ConFrame {
7916        let mut text = String::from(
7917            "grid\n{\"con_spec_version\":2,\"units\":{\"length\":\"angstrom\",\"energy\":\"eV\"}}\n20 20 20\n90 90 90\n0 0\n0 0\n1\n48\n63.546\nCu\nCoordinates of Component 1\n",
7918        );
7919        for i in 0..48 {
7920            text.push_str(&format!("0.{i} 1 2 0 {i}\n"));
7921        }
7922        frames_from_text(&text, Some(1)).unwrap().remove(0)
7923    }
7924
7925    /// A streaming gzip rewrite must not pin a metadata map on every frame.
7926    ///
7927    /// The map is about a kilobyte and stays reachable on the frame. Four
7928    /// thousand frames keep several megabytes after the writer is gone, which
7929    /// is what pushed a 20k-frame rewrite past the 8 MiB high-water budget.
7930    /// Isolated measurements of that rewrite: 26 MiB high-water and 30 MB
7931    /// committed before, 4 MiB high-water and 5.5 MB committed after (the
7932    /// deflate arena, flat in the frame count).
7933    #[cfg_attr(miri, ignore = "slow under Miri: superlinear in frame count")]
7934    #[test]
7935    fn parsed_frames_gzip_write_drops_the_metadata_maps() {
7936        let _scratch = tempfile::tempdir().unwrap();
7937        let frames = vec![parsed_frame(); 4000];
7938        assert!(
7939            frames
7940                .iter()
7941                .all(|frame| !frame.header.metadata.has_cached_map())
7942        );
7943        let path = _scratch.path().join(format!(
7944            "readcon-gzip-peak-{}-{}.con.gz",
7945            std::process::id(),
7946            std::time::SystemTime::now()
7947                .duration_since(std::time::UNIX_EPOCH)
7948                .unwrap()
7949                .as_nanos()
7950        ));
7951        {
7952            let mut writer = ConFrameWriter::from_path_gzip(&path).unwrap();
7953            for frame in &frames {
7954                writer.write_frame(frame).unwrap();
7955            }
7956            writer.flush().unwrap();
7957        }
7958        let cached = frames
7959            .iter()
7960            .filter(|frame| frame.header.metadata.has_cached_map())
7961            .count();
7962        assert_eq!(
7963            cached, 0,
7964            "the write retained {cached} metadata maps; each is about a kilobyte"
7965        );
7966        let back = read_all_frames(&path).unwrap();
7967        assert_eq!(back.len(), frames.len());
7968        assert_eq!(back[0].atom_data.len(), 48);
7969        assert_eq!(back[0].atom_data[3].atom_id, 3);
7970        assert_eq!(back[17].atom_data[0].symbol.as_ref(), "Cu");
7971        let _ = std::fs::remove_file(&path);
7972    }
7973
7974    /// Lattice vectors live on the metadata line. Reading them must not pin
7975    /// the parsed map, and a later keyed lookup still sees the same matrix.
7976    #[test]
7977    fn lattice_line_overrides_box_lengths_and_can_be_reread_from_the_cache() {
7978        let _scratch = tempfile::tempdir().unwrap();
7979        let text = "\
7980grid
7981{\"con_spec_version\":2,\"lattice_vectors\":[[10,0,0],[0,20,0],[0,0,30]]}
79825 5 5
798390 90 90
79840 0
79850 0
79861
79871
79881.0
7989Cu
7990Coordinates of Component 1
79910 0 0 0 1
7992";
7993        let frame = frames_from_text(text, Some(1)).unwrap().remove(0);
7994        assert!(!frame.header.metadata.has_cached_map());
7995        let vecs = frame.header.lattice_vectors().unwrap();
7996        assert_eq!(vecs, [[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]]);
7997        assert!(
7998            !frame.header.metadata.has_cached_map(),
7999            "reading lattice vectors cached the whole metadata map"
8000        );
8001        let path = _scratch
8002            .path()
8003            .join(format!("readcon-lattice-line-{}.con", std::process::id()));
8004        {
8005            let mut writer = ConFrameWriter::from_path(&path).unwrap();
8006            writer.write_frame(&frame).unwrap();
8007            writer.flush().unwrap();
8008        }
8009        let back = read_all_frames(&path).unwrap();
8010        let _ = std::fs::remove_file(&path);
8011        assert_eq!(back[0].header.boxl, [10.0, 20.0, 30.0]);
8012        assert!(frame.header.metadata.get("lattice_vectors").is_some());
8013        assert!(frame.header.metadata.has_cached_map());
8014        assert_eq!(frame.header.lattice_vectors().unwrap()[1][1], 20.0);
8015    }
8016
8017    /// Five different lines share one small cache. Each lookup still answers
8018    /// that line, and none of the frames grows its own map.
8019    #[test]
8020    fn repeated_lattice_lookups_share_a_bounded_cache() {
8021        let mut frames = Vec::new();
8022        for side in [10.0, 11.0, 12.0, 13.0, 14.0] {
8023            let text = format!(
8024                "grid\n{{\"con_spec_version\":2,\"lattice_vectors\":[[{side},0,0],[0,{side},0],[0,0,{side}]]}}\n5 5 5\n90 90 90\n0 0\n0 0\n1\n1\n1.0\nCu\nCoordinates of Component 1\n0 0 0 0 1\n"
8025            );
8026            frames.push(frames_from_text(&text, Some(1)).unwrap().remove(0));
8027        }
8028        for _ in 0..2 {
8029            for (index, frame) in frames.iter().enumerate() {
8030                let side = 10.0 + index as f64;
8031                let vecs = frame.header.lattice_vectors().unwrap();
8032                assert_eq!(vecs[0][0], side);
8033                assert_eq!(vecs[2][2], side);
8034                assert!(!frame.header.metadata.has_cached_map());
8035            }
8036        }
8037        // The last line is at the front. An older line is still cached
8038        // behind it, and a freshly parsed copy of the front line is a
8039        // content hit rather than a shared allocation.
8040        let older = frames[1].header.lattice_vectors().unwrap();
8041        assert_eq!(older[0][0], 11.0);
8042        let text = "\
8043grid
8044{\"con_spec_version\":2,\"lattice_vectors\":[[14,0,0],[0,14,0],[0,0,14]]}
80455 5 5
804690 90 90
80470 0
80480 0
80491
80501
80511.0
8052Cu
8053Coordinates of Component 1
80540 0 0 0 1
8055";
8056        let twin = frames_from_text(text, Some(1)).unwrap().remove(0);
8057        assert_eq!(twin.header.lattice_vectors().unwrap()[0][0], 14.0);
8058        assert!(!twin.header.metadata.has_cached_map());
8059    }
8060
8061    /// Each thread keeps its own metadata-line cache. Concurrent lookups of
8062    /// different lines must not observe another thread's lattice.
8063    #[test]
8064    fn lattice_lookups_from_several_threads_keep_their_own_lines() {
8065        let frames: Vec<_> = (1..17)
8066            .map(|side| {
8067                let text = format!(
8068                    "grid\n{{\"con_spec_version\":2,\"lattice_vectors\":[[{side},0,0],[0,{side},0],[0,0,{side}]]}}\n5 5 5\n90 90 90\n0 0\n0 0\n1\n1\n1.0\nCu\nCoordinates of Component 1\n0 0 0 0 1\n"
8069                );
8070                frames_from_text(&text, Some(1)).unwrap().remove(0)
8071            })
8072            .collect();
8073        std::thread::scope(|scope| {
8074            for _ in 0..4 {
8075                scope.spawn(|| {
8076                    for _ in 0..8 {
8077                        for (index, frame) in frames.iter().enumerate() {
8078                            let side = 1.0 + index as f64;
8079                            let vecs = frame.header.lattice_vectors().unwrap();
8080                            assert_eq!(vecs[0][0], side);
8081                            assert_eq!(vecs[1][1], side);
8082                            assert_eq!(vecs[2][2], side);
8083                        }
8084                    }
8085                });
8086            }
8087        });
8088    }
8089}
8090
8091/// A version 2 file that names only units.time still rewrites.
8092#[cfg(test)]
8093mod binding_units {
8094    use crate::iterators::frames_from_text;
8095
8096    #[test]
8097    fn version_2_time_label_rewrites_at_major_4() {
8098        let text = "\
8099title
8100{\"con_spec_version\":2,\"units\":{\"time\":\"fs\"},\"sections\":[\"velocities\"]}
810110 10 10
810290 90 90
81030 0
81040 0 0
81051
81061
81071.0
8108H
8109Coordinates of Component 1
81101 2 3 0 0
8111
8112H
8113Velocities of Component 1
81140.1 0.2 0.3 0 0
8115";
8116        let read = frames_from_text(text, Some(1)).unwrap();
8117        let mut bytes = Vec::new();
8118        {
8119            let mut writer = super::ConFrameWriter::new(&mut bytes);
8120            writer.write_frame_bound(&read[0]).unwrap();
8121            writer.flush().unwrap();
8122        }
8123        let written = String::from_utf8(bytes).unwrap();
8124        let again = frames_from_text(&written, Some(1)).unwrap();
8125        assert_eq!(again[0].header.spec_version, crate::CON_SPEC_VERSION);
8126        assert_eq!(again[0].header.length_unit(), Some("angstrom"));
8127        assert_eq!(again[0].header.unit_for("energy"), Some("eV"));
8128        assert_eq!(
8129            again[0].header.unit_for("time"),
8130            Some(crate::units::NATURAL_TIME_UNIT)
8131        );
8132        assert_eq!(
8133            again[0].atom_data[0].velocity(),
8134            read[0].atom_data[0].velocity()
8135        );
8136    }
8137}