Skip to main content

readcon_core/
writer.rs

1use crate::types::{
2    ConFrame, SECTION_CHARGES, SECTION_DISPLACEMENTS, SECTION_ENERGIES, SECTION_FORCES,
3    SECTION_MAGMOMS, SECTION_SPINS, SECTION_SPREADS, SECTION_VELOCITIES, encode_fixed_bitmask,
4    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
20impl std::fmt::Display for WriteError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            WriteError::Io(e) => write!(f, "{e}"),
24            WriteError::Format(e) => write!(f, "{e}"),
25        }
26    }
27}
28
29impl std::error::Error for WriteError {
30    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
31        match self {
32            WriteError::Io(e) => Some(e),
33            WriteError::Format(e) => Some(e),
34        }
35    }
36}
37
38impl From<io::Error> for WriteError {
39    fn from(e: io::Error) -> Self {
40        WriteError::Io(e)
41    }
42}
43
44impl From<WriteError> for io::Error {
45    fn from(e: WriteError) -> Self {
46        match e {
47            WriteError::Io(e) => e,
48            WriteError::Format(err) => io::Error::new(io::ErrorKind::InvalidData, err.to_string()),
49        }
50    }
51}
52
53/// Numeric text representation for CON frame fields.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
55pub enum FloatFormat {
56    /// A fixed number of digits after the decimal point.
57    DecimalPlaces(usize),
58    /// The shortest scientific representation preserving each finite f64.
59    /// Signed zero is preserved; decimal precision does not limit this mode.
60    /// CON-num.6 (D13): the default writer round-trips binary64.
61    #[default]
62    RoundTrip,
63}
64
65/// A writer that can serialize and write `ConFrame` objects to any output stream.
66///
67/// This struct encapsulates a writer (like a file) and provides a high-level API
68/// for writing simulation frames in the `.con` format.
69///
70/// # Example
71/// ```no_run
72/// # use std::fs::File;
73/// # use readcon_core::types::ConFrame;
74/// # use readcon_core::writer::ConFrameWriter;
75/// # let frames: Vec<ConFrame> = Vec::new();
76/// let mut writer = ConFrameWriter::from_path("output.con").unwrap();
77/// writer.extend(frames.iter()).unwrap();
78/// ```
79pub struct ConFrameWriter<W: Write> {
80    writer: BufWriter<W>,
81    float_format: FloatFormat,
82    /// When true: sort metadata keys in JSON and emit sections in canonical
83    /// order (velocities, forces, energies). Opt-in. Float text follows
84    /// `float_format` (round-trip unless the caller asked for decimals).
85    canonical: bool,
86    /// Cache for the JSON metadata line: when consecutive frames share
87    /// the same (spec_version, sections-set, metadata) triple the
88    /// serialized JSON object is identical, so reusing the cached
89    /// string skips the per-frame `serde_json::Map::insert` rebuild
90    /// and re-serialisation. Hot for trajectory writes where every
91    /// frame has the same `units` / `potential` / `validate` keys.
92    metadata_cache: Option<MetadataCacheEntry>,
93    /// One frame of CON text. Filled then flushed with a single `write_all`
94    /// so the sink is not entered once per atom line.
95    scratch: Vec<u8>,
96    /// Reused shortest-round-trip buffer (ryu). One per writer, not per float.
97    ryu: ryu::Buffer,
98    /// Last x/y/z spellings. A value is formatted on the second sight and
99    /// copied after that, which is the common lattice column.
100    fmt_slot: [FmtSlot; 3],
101}
102
103/// One column of the round-trip float cache.
104#[derive(Clone, Copy)]
105struct FmtSlot {
106    bits: u64,
107    text: [u8; 24],
108    len: u8,
109    /// 0 empty, 1 seen once, 2 `text` holds the spelling.
110    state: u8,
111}
112
113impl FmtSlot {
114    const fn new() -> Self {
115        Self {
116            bits: 0,
117            text: [0; 24],
118            len: 0,
119            state: 0,
120        }
121    }
122}
123
124#[derive(Debug)]
125struct MetadataCacheEntry {
126    /// Snapshot of the inputs that fully determine the serialized JSON
127    /// metadata line. Cheap to clone; cheaper than re-serialising the
128    /// whole map on every frame.
129    spec_version: u32,
130    has_velocities: bool,
131    has_forces: bool,
132    has_energies: bool,
133    has_charges: bool,
134    has_spins: bool,
135    has_magmoms: bool,
136    has_displacements: bool,
137    has_spreads: bool,
138    metadata: std::collections::BTreeMap<String, serde_json::Value>,
139    /// Cached serialised metadata line (without trailing newline).
140    serialized: String,
141}
142
143impl MetadataCacheEntry {
144    fn matches(
145        &self,
146        spec_version: u32,
147        sections: [bool; 8],
148        metadata: &std::collections::BTreeMap<String, serde_json::Value>,
149    ) -> bool {
150        let [
151            has_velocities,
152            has_forces,
153            has_energies,
154            has_charges,
155            has_spins,
156            has_magmoms,
157            has_displacements,
158            has_spreads,
159        ] = sections;
160        self.spec_version == spec_version
161            && self.has_velocities == has_velocities
162            && self.has_forces == has_forces
163            && self.has_energies == has_energies
164            && self.has_charges == has_charges
165            && self.has_spins == has_spins
166            && self.has_magmoms == has_magmoms
167            && self.has_displacements == has_displacements
168            && self.has_spreads == has_spreads
169            && self.metadata.len() == metadata.len()
170            && self
171                .metadata
172                .iter()
173                .zip(metadata)
174                .all(|((ka, a), (kb, b))| ka == kb && metadata_value_eq(a, b))
175    }
176}
177
178// Cache equality preserves the numeric representation, including signed zero,
179// throughout nested JSON values.
180fn metadata_value_eq(a: &serde_json::Value, b: &serde_json::Value) -> bool {
181    use serde_json::Value;
182    match (a, b) {
183        (Value::Number(a), Value::Number(b)) if a.is_f64() && b.is_f64() => {
184            a.as_f64().map(f64::to_bits) == b.as_f64().map(f64::to_bits)
185        }
186        (Value::Array(a), Value::Array(b)) => {
187            a.len() == b.len() && a.iter().zip(b).all(|(a, b)| metadata_value_eq(a, b))
188        }
189        (Value::Object(a), Value::Object(b)) => {
190            a.len() == b.len()
191                && a.iter()
192                    .all(|(key, a)| b.get(key).is_some_and(|b| metadata_value_eq(a, b)))
193        }
194        _ => a == b,
195    }
196}
197
198/// CON-section.16. Minor 2 and later must list, in `section_arity`, every
199/// emitted section that minor 1 does not reserve.
200fn require_minor2_section_arity(
201    minor: u64,
202    sections: &[serde_json::Value],
203    metadata: &serde_json::Map<String, serde_json::Value>,
204) -> Result<(), WriteError> {
205    if minor < 2 {
206        return Ok(());
207    }
208    for name in sections.iter().filter_map(|value| value.as_str()) {
209        if crate::types::reserved_section_value_arity(name).is_some() {
210            continue;
211        }
212        let listed = metadata
213            .get(meta::SECTION_ARITY)
214            .and_then(|value| value.as_object())
215            .and_then(|obj| obj.get(name))
216            .and_then(|value| value.as_u64())
217            .is_some_and(|n| n >= 1);
218        if !listed {
219            return Err(WriteError::Format(
220                crate::error::ParseError::ValidationError(format!(
221                    "minor >= 2 must list {name} in section_arity"
222                )),
223            ));
224        }
225    }
226    Ok(())
227}
228
229// General implementation for any type that implements `Write`.
230impl<W: Write> ConFrameWriter<W> {
231    /// Creates a new `ConFrameWriter` that wraps a given writer.
232    ///
233    /// # Arguments
234    ///
235    /// * `writer` - Any type that implements `std::io::Write`, e.g., a `File`.
236    pub fn new(writer: W) -> Self {
237        Self::with_float_format(writer, FloatFormat::default())
238    }
239
240    /// Creates a new `ConFrameWriter` with a custom floating-point precision.
241    ///
242    /// # Arguments
243    ///
244    /// * `writer` - Any type that implements `std::io::Write`.
245    /// * `precision` - Number of decimal places for floating-point output.
246    pub fn with_precision(writer: W, precision: usize) -> Self {
247        Self::with_float_format(writer, FloatFormat::DecimalPlaces(precision))
248    }
249
250    /// Creates a writer with an explicit numeric text representation.
251    ///
252    /// `FloatFormat::RoundTrip` retains small forces and coordinates exactly.
253    /// Metadata floats use the JSON serializer independently of this setting.
254    pub fn with_float_format(writer: W, float_format: FloatFormat) -> Self {
255        Self {
256            writer: BufWriter::new(writer),
257            float_format,
258            canonical: false,
259            metadata_cache: None,
260            scratch: Vec::with_capacity(16 * 1024),
261            ryu: ryu::Buffer::new(),
262            fmt_slot: [FmtSlot::new(); 3],
263        }
264    }
265
266    /// Opt-in **canonical** serialization: BTree-ordered metadata keys in JSON,
267    /// fixed section order. Use for corpus
268    /// materialization and content-stable hashes; not required for on-disk fidelity
269    /// of spans preserved from `next_with_raw_span`.
270    pub fn canonical(mut self, on: bool) -> Self {
271        self.set_canonical(on);
272        self
273    }
274
275    /// Set or clear canonical mode on an existing writer (C ABI / FFI).
276    pub fn set_canonical(&mut self, on: bool) {
277        self.canonical = on;
278        if on {
279            self.metadata_cache = None;
280        }
281    }
282
283    /// Whether canonical serialization is enabled.
284    pub fn is_canonical(&self) -> bool {
285        self.canonical
286    }
287
288    fn refresh_metadata_cache(&mut self, frame: &ConFrame) -> Result<(), WriteError> {
289        let spec_version = frame.header.spec_version;
290        let has_vel = frame.has_velocities();
291        let has_frc = frame.has_forces();
292        let has_eng = frame.has_energies();
293        let has_chg = frame.has_charges();
294        let has_spn = frame.has_spins();
295        let has_mm = frame.has_magmoms();
296        let has_dsp = frame.has_displacements();
297        let has_spr = frame.has_spreads();
298
299        let cache_hit = !self.canonical
300            && self.metadata_cache.as_ref().is_some_and(|c| {
301                c.matches(
302                    spec_version,
303                    [
304                        has_vel, has_frc, has_eng, has_chg, has_spn, has_mm, has_dsp, has_spr,
305                    ],
306                    &frame.header.metadata,
307                )
308            });
309        if cache_hit {
310            return Ok(());
311        }
312
313        let mut meta_obj = serde_json::Map::new();
314        meta_obj.insert(meta::CON_SPEC_VERSION.into(), json!(spec_version));
315        let mut sections = Vec::new();
316        if has_vel {
317            sections.push(json!(SECTION_VELOCITIES));
318        }
319        if has_frc {
320            sections.push(json!(SECTION_FORCES));
321        }
322        if has_eng {
323            sections.push(json!(SECTION_ENERGIES));
324        }
325        if has_chg {
326            sections.push(json!(SECTION_CHARGES));
327        }
328        if has_spn {
329            sections.push(json!(SECTION_SPINS));
330        }
331        if has_mm {
332            sections.push(json!(SECTION_MAGMOMS));
333        }
334        if has_dsp {
335            sections.push(json!(SECTION_DISPLACEMENTS));
336        }
337        if has_spr {
338            sections.push(json!(SECTION_SPREADS));
339        }
340        let validate = frame
341            .header
342            .metadata
343            .get(meta::VALIDATE)
344            .and_then(|value| value.as_bool())
345            .unwrap_or(false);
346        if !sections.is_empty() || validate {
347            meta_obj.insert(meta::SECTIONS.into(), json!(sections));
348        }
349        for (k, v) in &frame.header.metadata {
350            if k == meta::CON_SPEC_VERSION || k == meta::SECTIONS {
351                continue;
352            }
353            meta_obj.insert(k.clone(), v.clone());
354        }
355        if let Some(u) = meta_obj.get(meta::UNITS).cloned() {
356            // D11: an invalid unit fails the write. Do not substitute a default.
357            let c = crate::units::canonicalize_units_object(&u).map_err(|e| {
358                WriteError::Format(crate::error::ParseError::InvalidUnits(e.to_string()))
359            })?;
360            meta_obj.insert(meta::UNITS.into(), c);
361        }
362        if spec_version >= 3 {
363            match meta_obj.get(meta::UNITS) {
364                None => {
365                    return Err(WriteError::Format(crate::error::ParseError::InvalidUnits(
366                        "con_spec_version >= 3 requires units.length and units.energy".into(),
367                    )));
368                }
369                Some(u) => {
370                    crate::units::validate_v3_units_metadata(u).map_err(|e| {
371                        WriteError::Format(crate::error::ParseError::InvalidUnits(e.to_string()))
372                    })?;
373                }
374            }
375        }
376        let minor = frame
377            .header
378            .metadata
379            .get(meta::CON_SPEC_MINOR)
380            .and_then(|v| v.as_u64())
381            .unwrap_or(0);
382        if spec_version >= 3 && minor >= 1 && has_vel {
383            let time_ok = meta_obj
384                .get(meta::UNITS)
385                .and_then(|u| u.get("time"))
386                .and_then(|v| v.as_str())
387                .is_some_and(|s| !s.trim().is_empty());
388            if !time_ok {
389                return Err(WriteError::Format(crate::error::ParseError::InvalidUnits(
390                    "minor >= 1 requires units.time when a velocities section is present".into(),
391                )));
392            }
393        }
394        // A minor of 2 or later lists every section minor 1 does not reserve
395        // (CON-section.16). Reserved names need no entry.
396        require_minor2_section_arity(minor, &sections, &meta_obj)?;
397        let serialized = serde_json::Value::Object(meta_obj).to_string();
398        self.metadata_cache = Some(MetadataCacheEntry {
399            spec_version,
400            has_velocities: has_vel,
401            has_forces: has_frc,
402            has_energies: has_eng,
403            has_charges: has_chg,
404            has_spins: has_spn,
405            has_magmoms: has_mm,
406            has_displacements: has_dsp,
407            has_spreads: has_spr,
408            metadata: frame.header.metadata.clone(),
409            serialized,
410        });
411        Ok(())
412    }
413
414    /// Writes `frame` with the binding metadata stamp and the original atoms.
415    ///
416    /// The stamp is installed for the duration of the write and then put back.
417    /// Atoms are not rebuilt.
418    pub fn write_frame_binding(&mut self, frame: &mut ConFrame) -> Result<(), WriteError> {
419        let stamped = binding_metadata(frame);
420        let saved_meta = std::mem::replace(&mut frame.header.metadata, stamped);
421        let saved_spec = frame.header.spec_version;
422        if frame.header.spec_version < crate::CON_SPEC_VERSION {
423            frame.header.spec_version = crate::CON_SPEC_VERSION;
424        }
425        let result = self.write_frame(frame);
426        frame.header.metadata = saved_meta;
427        frame.header.spec_version = saved_spec;
428        result
429    }
430
431    /// Writes a single `ConFrame` to the output stream.
432    pub fn write_frame(&mut self, frame: &ConFrame) -> Result<(), WriteError> {
433        let zero_frame = frame.header.natm_types == 0
434            && frame.atom_data.is_empty()
435            && frame.header.natms_per_type.is_empty()
436            && frame.header.masses_per_type.is_empty();
437        if zero_frame && !frame.header.sections.is_empty() {
438            return Err(WriteError::Format(crate::error::ParseError::InvalidCount(
439                "a zero-atom frame cannot declare sections".into(),
440            )));
441        }
442        if !zero_frame
443            && (frame.header.natm_types == 0
444                || frame.atom_data.is_empty()
445                || frame.header.natms_per_type.contains(&0))
446        {
447            return Err(WriteError::Format(crate::error::ParseError::InvalidCount(
448                "each per-type count must be >= 1".into(),
449            )));
450        }
451        ensure_unique_ids(&frame.atom_data)?;
452        let prec = self.float_format;
453        if frame.header.spec_version >= 2 {
454            self.refresh_metadata_cache(frame)?;
455        }
456        let (boxl, angles) = match frame.header.lattice_vectors() {
457            Some(vecs) => crate::types::lengths_and_angles(vecs),
458            None => (frame.header.boxl, frame.header.angles),
459        };
460        let atoms = frame.atom_data.len();
461        let mut blocks = 1usize;
462        if frame.has_velocities() {
463            blocks += 1;
464        }
465        if frame.has_forces() {
466            blocks += 1;
467        }
468        if frame.has_energies() {
469            blocks += 1;
470        }
471        if frame.has_charges() {
472            blocks += 1;
473        }
474        if frame.has_spins() {
475            blocks += 1;
476        }
477        if frame.has_magmoms() {
478            blocks += 1;
479        }
480        if frame.has_displacements() {
481            blocks += 1;
482        }
483        if frame.has_spreads() {
484            blocks += 1;
485        }
486        self.scratch
487            .reserve(256 + atoms.saturating_mul(64).saturating_mul(blocks));
488        self.scratch.clear();
489        push_str_line(&mut self.scratch, &frame.header.prebox_header.user);
490        if frame.header.spec_version < 2 {
491            // Spec 1 line 2 is free text. Do not re-emit JSON major 0 or 1 (D15).
492            push_str_line(
493                &mut self.scratch,
494                frame.header.prebox_header.metadata_line(),
495            );
496        } else {
497            let line = self
498                .metadata_cache
499                .as_ref()
500                .expect("metadata_cache populated above")
501                .serialized
502                .as_bytes();
503            self.scratch.extend_from_slice(line);
504            self.scratch.push(b'\n');
505        }
506        {
507            let buf = &mut self.scratch;
508            let ryu = &mut self.ryu;
509            let slots = &mut self.fmt_slot;
510
511            // --- Write the 9-line Header ---
512            push_f64(buf, ryu, boxl[0], prec);
513            buf.push(b' ');
514            push_f64(buf, ryu, boxl[1], prec);
515            buf.push(b' ');
516            push_f64(buf, ryu, boxl[2], prec);
517            buf.push(b'\n');
518            push_f64(buf, ryu, angles[0], prec);
519            buf.push(b' ');
520            push_f64(buf, ryu, angles[1], prec);
521            buf.push(b' ');
522            push_f64(buf, ryu, angles[2], prec);
523            buf.push(b'\n');
524            push_str_line(buf, &frame.header.postbox_header[0]);
525            push_str_line(buf, &frame.header.postbox_header[1]);
526            push_u64(buf, frame.header.natm_types as u64);
527            buf.push(b'\n');
528
529            for (i, n) in frame.header.natms_per_type.iter().enumerate() {
530                if i > 0 {
531                    buf.push(b' ');
532                }
533                push_u64(buf, *n as u64);
534            }
535            buf.push(b'\n');
536
537            for (i, m) in frame.header.masses_per_type.iter().enumerate() {
538                if i > 0 {
539                    buf.push(b' ');
540                }
541                push_f64(buf, ryu, *m, prec);
542            }
543            buf.push(b'\n');
544
545            // --- Write the Atom Data ---
546            let mut atom_idx_offset = 0;
547            for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate() {
548                let symbol = &frame.atom_data[atom_idx_offset].symbol;
549                push_str_line(buf, symbol);
550                push_component_line(buf, "Coordinates of Component", type_idx);
551
552                for i in 0..num_atoms_in_type {
553                    let atom = &frame.atom_data[atom_idx_offset + i];
554                    push_xyz_line(
555                        buf,
556                        ryu,
557                        slots,
558                        [atom.x, atom.y, atom.z],
559                        prec,
560                        written_fixed_flag(atom.fixed, frame.header.spec_version),
561                        atom.atom_id,
562                    );
563                }
564                atom_idx_offset += num_atoms_in_type;
565            }
566
567            // --- Write optional velocity section ---
568            if frame.has_velocities() {
569                buf.push(b'\n');
570
571                let mut vel_idx_offset = 0;
572                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
573                {
574                    let symbol = &frame.atom_data[vel_idx_offset].symbol;
575                    push_str_line(buf, symbol);
576                    push_component_line(buf, "Velocities of Component", type_idx);
577
578                    for i in 0..num_atoms_in_type {
579                        let atom = &frame.atom_data[vel_idx_offset + i];
580                        let [vx, vy, vz] = atom.velocity().unwrap_or([0.0; 3]);
581                        push_xyz_line(
582                            buf,
583                            ryu,
584                            slots,
585                            [vx, vy, vz],
586                            prec,
587                            written_fixed_flag(atom.fixed, frame.header.spec_version),
588                            atom.atom_id,
589                        );
590                    }
591                    vel_idx_offset += num_atoms_in_type;
592                }
593            }
594
595            // --- Write optional force section ---
596            if frame.has_forces() {
597                buf.push(b'\n');
598
599                let mut force_idx_offset = 0;
600                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
601                {
602                    let symbol = &frame.atom_data[force_idx_offset].symbol;
603                    push_str_line(buf, symbol);
604                    push_component_line(buf, "Forces of Component", type_idx);
605
606                    for i in 0..num_atoms_in_type {
607                        let atom = &frame.atom_data[force_idx_offset + i];
608                        let [fx, fy, fz] = atom.force().unwrap_or([0.0; 3]);
609                        push_xyz_line(
610                            buf,
611                            ryu,
612                            slots,
613                            [fx, fy, fz],
614                            prec,
615                            written_fixed_flag(atom.fixed, frame.header.spec_version),
616                            atom.atom_id,
617                        );
618                    }
619                    force_idx_offset += num_atoms_in_type;
620                }
621            }
622
623            // --- Write optional energies section ---
624            if frame.has_energies() {
625                buf.push(b'\n');
626
627                let mut energy_idx_offset = 0;
628                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
629                {
630                    let symbol = &frame.atom_data[energy_idx_offset].symbol;
631                    push_str_line(buf, symbol);
632                    push_component_line(buf, "Energies of Component", type_idx);
633
634                    for i in 0..num_atoms_in_type {
635                        let atom = &frame.atom_data[energy_idx_offset + i];
636                        let e = atom.energy().unwrap_or(0.0);
637                        push_scalar_line(
638                            buf,
639                            ryu,
640                            slots,
641                            e,
642                            prec,
643                            written_fixed_flag(atom.fixed, frame.header.spec_version),
644                            atom.atom_id,
645                        );
646                    }
647                    energy_idx_offset += num_atoms_in_type;
648                }
649            }
650
651            if frame.has_charges() {
652                buf.push(b'\n');
653                let mut off = 0;
654                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
655                {
656                    let symbol = &frame.atom_data[off].symbol;
657                    push_str_line(buf, symbol);
658                    push_component_line(buf, "Charges of Component", type_idx);
659                    for i in 0..num_atoms_in_type {
660                        let atom = &frame.atom_data[off + i];
661                        let q = atom.charge().unwrap_or(0.0);
662                        push_scalar_line(
663                            buf,
664                            ryu,
665                            slots,
666                            q,
667                            prec,
668                            written_fixed_flag(atom.fixed, frame.header.spec_version),
669                            atom.atom_id,
670                        );
671                    }
672                    off += num_atoms_in_type;
673                }
674            }
675
676            if frame.has_spins() {
677                buf.push(b'\n');
678                let mut off = 0;
679                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
680                {
681                    let symbol = &frame.atom_data[off].symbol;
682                    push_str_line(buf, symbol);
683                    push_component_line(buf, "Spins of Component", type_idx);
684                    for i in 0..num_atoms_in_type {
685                        let atom = &frame.atom_data[off + i];
686                        let s = atom.spin().unwrap_or(0.0);
687                        push_scalar_line(
688                            buf,
689                            ryu,
690                            slots,
691                            s,
692                            prec,
693                            written_fixed_flag(atom.fixed, frame.header.spec_version),
694                            atom.atom_id,
695                        );
696                    }
697                    off += num_atoms_in_type;
698                }
699            }
700
701            if frame.has_magmoms() {
702                buf.push(b'\n');
703                let mut off = 0;
704                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
705                {
706                    let symbol = &frame.atom_data[off].symbol;
707                    push_str_line(buf, symbol);
708                    push_component_line(buf, "Magmoms of Component", type_idx);
709                    for i in 0..num_atoms_in_type {
710                        let atom = &frame.atom_data[off + i];
711                        let [mx, my, mz] = atom.magmom().unwrap_or([0.0; 3]);
712                        push_xyz_line(
713                            buf,
714                            ryu,
715                            slots,
716                            [mx, my, mz],
717                            prec,
718                            written_fixed_flag(atom.fixed, frame.header.spec_version),
719                            atom.atom_id,
720                        );
721                    }
722                    off += num_atoms_in_type;
723                }
724            }
725
726            if frame.has_displacements() {
727                buf.push(b'\n');
728                let mut off = 0;
729                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
730                {
731                    let symbol = &frame.atom_data[off].symbol;
732                    push_str_line(buf, symbol);
733                    push_component_line(buf, "Displacements of Component", type_idx);
734                    for i in 0..num_atoms_in_type {
735                        let atom = &frame.atom_data[off + i];
736                        let [dx, dy, dz] = atom.displacement().unwrap_or([0.0; 3]);
737                        push_xyz_line(
738                            buf,
739                            ryu,
740                            slots,
741                            [dx, dy, dz],
742                            prec,
743                            written_fixed_flag(atom.fixed, frame.header.spec_version),
744                            atom.atom_id,
745                        );
746                    }
747                    off += num_atoms_in_type;
748                }
749            }
750
751            if frame.has_spreads() {
752                buf.push(b'\n');
753                let mut off = 0;
754                for (type_idx, &num_atoms_in_type) in frame.header.natms_per_type.iter().enumerate()
755                {
756                    let symbol = &frame.atom_data[off].symbol;
757                    push_str_line(buf, symbol);
758                    push_component_line(buf, "Spreads of Component", type_idx);
759                    for i in 0..num_atoms_in_type {
760                        let atom = &frame.atom_data[off + i];
761                        let [sx, sy, sz] = atom.spread().unwrap_or([0.0; 3]);
762                        if !crate::types::spread_row_ok([sx, sy, sz]) {
763                            let err = if sx.is_finite() && sy.is_finite() && sz.is_finite() {
764                                crate::types::invalid_spread(off + i)
765                            } else {
766                                crate::error::ParseError::NonFiniteValue(format!(
767                                    "spreads atom {}",
768                                    off + i
769                                ))
770                            };
771                            return Err(WriteError::Format(err));
772                        }
773                        push_xyz_line(
774                            buf,
775                            ryu,
776                            slots,
777                            [sx, sy, sz],
778                            prec,
779                            written_fixed_flag(atom.fixed, frame.header.spec_version),
780                            atom.atom_id,
781                        );
782                    }
783                    off += num_atoms_in_type;
784                }
785            }
786        }
787
788        self.writer.write_all(&self.scratch)?;
789        Ok(())
790    }
791
792    /// Flushes buffered frames to the underlying writer.
793    ///
794    /// `write_frame` fills a buffer and does not always reach the sink.
795    /// After `flush` returns, a reader sees a complete, parseable prefix.
796    /// Dropping the writer flushes as well.
797    pub fn flush(&mut self) -> io::Result<()> {
798        self.writer.flush()
799    }
800
801    /// Writes all frames from an iterator to the output stream.
802    ///
803    /// This is the most convenient way to write a multi-frame file.
804    pub fn extend<'a>(
805        &mut self,
806        frames: impl Iterator<Item = &'a ConFrame>,
807    ) -> Result<(), WriteError> {
808        for frame in frames {
809            self.write_frame(frame)?;
810        }
811        Ok(())
812    }
813}
814
815fn ensure_unique_ids(atoms: &[crate::types::AtomDatum]) -> Result<(), WriteError> {
816    let n = atoms.len();
817    if n == 0 {
818        return Ok(());
819    }
820    // Trajectory frames usually number atoms 0..n-1. That needs no set.
821    if atoms
822        .iter()
823        .enumerate()
824        .all(|(i, atom)| atom.atom_id == i as u64)
825    {
826        return Ok(());
827    }
828    let mut seen_ids = std::collections::HashSet::with_capacity(n);
829    for atom in atoms {
830        if !seen_ids.insert(atom.atom_id) {
831            return Err(WriteError::Format(
832                crate::error::ParseError::ValidationError(format!(
833                    "atom id {} is repeated in the frame",
834                    atom.atom_id
835                )),
836            ));
837        }
838    }
839    Ok(())
840}
841
842fn written_fixed_flag(fixed: [bool; 3], spec_version: u32) -> u8 {
843    if spec_version < 2 {
844        if fixed.iter().any(|axis| *axis) { 1 } else { 0 }
845    } else {
846        encode_fixed_bitmask(fixed)
847    }
848}
849
850fn push_u64(buf: &mut Vec<u8>, n: u64) {
851    // Two digits per division. u64 stays in a hardware remainder; the old
852    // path widened every atom id to u128 and called the software divider.
853    const DIGITS: &[u8; 200] = b"00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";
854    let mut tmp = [0u8; 20];
855    let mut i = 20;
856    let mut n = n;
857    while n >= 100 {
858        let q = n / 100;
859        let r = (n % 100) as usize;
860        i -= 2;
861        tmp[i] = DIGITS[r * 2];
862        tmp[i + 1] = DIGITS[r * 2 + 1];
863        n = q;
864    }
865    if n < 10 {
866        i -= 1;
867        tmp[i] = b'0' + n as u8;
868    } else {
869        let r = n as usize;
870        i -= 2;
871        tmp[i] = DIGITS[r * 2];
872        tmp[i + 1] = DIGITS[r * 2 + 1];
873    }
874    buf.extend_from_slice(&tmp[i..]);
875}
876
877fn push_u128(buf: &mut Vec<u8>, mut n: u128) {
878    if n <= u128::from(u64::MAX) {
879        push_u64(buf, n as u64);
880        return;
881    }
882    let mut tmp = [0u8; 40];
883    let mut i = 40;
884    while n > 0 {
885        i -= 1;
886        tmp[i] = b'0' + (n % 10) as u8;
887        n /= 10;
888    }
889    buf.extend_from_slice(&tmp[i..]);
890}
891
892fn push_str_line(buf: &mut Vec<u8>, text: &str) {
893    buf.extend_from_slice(text.as_bytes());
894    buf.push(b'\n');
895}
896
897fn push_component_line(buf: &mut Vec<u8>, label: &str, index: usize) {
898    buf.extend_from_slice(label.as_bytes());
899    buf.push(b' ');
900    push_u64(buf, (index + 1) as u64);
901    buf.push(b'\n');
902}
903
904fn push_f64(buf: &mut Vec<u8>, ryu: &mut ryu::Buffer, value: f64, format: FloatFormat) {
905    match format {
906        FloatFormat::DecimalPlaces(precision) => push_f64_prec(buf, value, precision),
907        FloatFormat::RoundTrip => push_round_trip(buf, ryu, None, value),
908    }
909}
910
911/// Shortest round-trip spelling. Finite values are written with `ryu::raw`
912/// straight into `buf`. `slot` remembers a column so a repeated lattice
913/// value is copied instead of formatted again.
914fn push_round_trip(
915    buf: &mut Vec<u8>,
916    ryu: &mut ryu::Buffer,
917    slot: Option<&mut FmtSlot>,
918    value: f64,
919) {
920    if !value.is_finite() {
921        let text = ryu.format(value);
922        buf.extend_from_slice(text.as_bytes());
923        return;
924    }
925    if let Some(slot) = slot {
926        let bits = value.to_bits();
927        if slot.bits == bits {
928            if slot.state == 2 {
929                buf.extend_from_slice(&slot.text[..slot.len as usize]);
930                return;
931            }
932            if slot.state == 1 {
933                let n = unsafe { ryu::raw::format64(value, slot.text.as_mut_ptr()) };
934                debug_assert!(n <= 24);
935                slot.len = n as u8;
936                slot.state = 2;
937                buf.extend_from_slice(&slot.text[..n]);
938                return;
939            }
940        }
941        write_finite(buf, value);
942        slot.bits = bits;
943        slot.state = 1;
944        return;
945    }
946    write_finite(buf, value);
947}
948
949fn write_finite(buf: &mut Vec<u8>, value: f64) {
950    buf.reserve(24);
951    // `format64` writes at most 24 bytes and does not handle non-finite values.
952    let n = unsafe { ryu::raw::format64(value, buf.as_mut_ptr().add(buf.len())) };
953    debug_assert!(n <= 24);
954    unsafe { buf.set_len(buf.len() + n) };
955}
956
957/// Fixed-point `f64` with `prec` digits after the decimal, matching `{:.prec$}`.
958/// Non-finite values and `prec > 17` fall back to `std::fmt`.
959fn push_f64_prec(buf: &mut Vec<u8>, v: f64, prec: usize) {
960    // The six-decimal path uses fixed-point arithmetic; other precisions
961    // use the standard formatter.
962    if !v.is_finite() || prec != 6 {
963        let _ = write!(buf, "{v:.prec$}");
964        return;
965    }
966    if v.is_sign_negative() {
967        buf.push(b'-');
968    }
969    let ax = v.abs();
970    if prec == 0 {
971        push_u128(buf, ax.round() as u128);
972        return;
973    }
974    let scale = 10u128.pow(prec as u32);
975    let n = (ax * scale as f64).round() as u128;
976    let int_part = n / scale;
977    let frac = n % scale;
978    push_u128(buf, int_part);
979    buf.push(b'.');
980    let mut tmp = [b'0'; 20];
981    let mut x = frac;
982    let mut i = prec;
983    while i > 0 {
984        i -= 1;
985        tmp[i] = b'0' + (x % 10) as u8;
986        x /= 10;
987    }
988    buf.extend_from_slice(&tmp[..prec]);
989}
990
991fn push_xyz_line(
992    buf: &mut Vec<u8>,
993    ryu: &mut ryu::Buffer,
994    slots: &mut [FmtSlot; 3],
995    xyz: [f64; 3],
996    prec: FloatFormat,
997    fixed: u8,
998    atom_id: u64,
999) {
1000    let [x, y, z] = xyz;
1001    match prec {
1002        FloatFormat::RoundTrip => {
1003            push_round_trip(buf, ryu, Some(&mut slots[0]), x);
1004            buf.push(b' ');
1005            push_round_trip(buf, ryu, Some(&mut slots[1]), y);
1006            buf.push(b' ');
1007            push_round_trip(buf, ryu, Some(&mut slots[2]), z);
1008        }
1009        FloatFormat::DecimalPlaces(_) => {
1010            push_f64(buf, ryu, x, prec);
1011            buf.push(b' ');
1012            push_f64(buf, ryu, y, prec);
1013            buf.push(b' ');
1014            push_f64(buf, ryu, z, prec);
1015        }
1016    }
1017    buf.push(b' ');
1018    // Column 4 is a mask in 0..=7, one digit.
1019    buf.push(b'0' + fixed);
1020    buf.push(b' ');
1021    push_u64(buf, atom_id);
1022    buf.push(b'\n');
1023}
1024
1025fn push_scalar_line(
1026    buf: &mut Vec<u8>,
1027    ryu: &mut ryu::Buffer,
1028    slots: &mut [FmtSlot; 3],
1029    v: f64,
1030    prec: FloatFormat,
1031    fixed: u8,
1032    atom_id: u64,
1033) {
1034    match prec {
1035        FloatFormat::RoundTrip => push_round_trip(buf, ryu, Some(&mut slots[0]), v),
1036        FloatFormat::DecimalPlaces(_) => push_f64(buf, ryu, v, prec),
1037    }
1038    buf.push(b' ');
1039    push_u64(buf, u64::from(fixed));
1040    buf.push(b' ');
1041    push_u64(buf, atom_id);
1042    buf.push(b'\n');
1043}
1044
1045/// Record `units.time` for a v1 or v2 frame that carries velocities.
1046///
1047/// Those velocities are already in [`crate::units::NATURAL_TIME_UNIT`]
1048/// (CON-units.8). [`ConFrameBuilder::build`] stamps minor 1, and a minor
1049/// of 1 or later rejects velocities with no `units.time` (CON-units.11).
1050/// A 3.0 frame is treated the same way, overwriting any `units.time`
1051/// label. A 3.1 frame is left alone so a caller who omitted time still fails.
1052pub(crate) fn stamp_legacy_velocity_time(
1053    meta: &mut BTreeMap<String, Value>,
1054    spec_version: u32,
1055    has_velocity: bool,
1056) {
1057    if !has_velocity {
1058        return;
1059    }
1060    let minor = meta
1061        .get(meta::CON_SPEC_MINOR)
1062        .and_then(Value::as_u64)
1063        .unwrap_or(0);
1064    if spec_version >= 3 && minor >= 1 {
1065        return;
1066    }
1067    // Versions 1, 2 and 3.0 store velocities in the natural unit whatever
1068    // `units.time` says (CON-units.8, CON-units.9). Writing minor 1 makes
1069    // the label authoritative (CON-units.10), so replace any label rather
1070    // than keep one the old file never honoured.
1071    let mut units = match meta.get(meta::UNITS).cloned() {
1072        Some(Value::Object(map)) => Value::Object(map),
1073        Some(_) => return,
1074        None => crate::units::default_v3_units_json(),
1075    };
1076    if let Some(object) = units.as_object_mut() {
1077        object.insert(
1078            "time".to_string(),
1079            Value::String(crate::units::NATURAL_TIME_UNIT.to_string()),
1080        );
1081        meta.insert(meta::UNITS.to_string(), units);
1082        // The label now holds, so the frame is written as minor 1.
1083        if meta.contains_key(meta::CON_SPEC_MINOR) {
1084            meta.insert(meta::CON_SPEC_MINOR.to_string(), Value::from(1u64));
1085        }
1086    }
1087}
1088
1089/// Metadata a language binding emits for `frame`, without copying atoms.
1090///
1091/// [`ConFrameBuilder::build`] stamps `con_spec_minor` 1 when the key is
1092/// absent. A parsed frame does not carry that key unless the file did.
1093/// The stamp lives on the header. The atoms stay where the parser put them.
1094pub fn binding_metadata(frame: &ConFrame) -> BTreeMap<String, Value> {
1095    let mut meta = frame.header.metadata.clone();
1096    meta.remove(meta::CON_SPEC_VERSION);
1097    meta.remove(meta::SECTIONS);
1098    let has_velocity = frame.atom_data.iter().any(|atom| atom.has_velocity());
1099    stamp_legacy_velocity_time(&mut meta, frame.header.spec_version, has_velocity);
1100    // The builder writes the current spec and fills units when the file
1101    // omitted them. A binding rewrite has to emit that same header.
1102    if !meta.contains_key(meta::UNITS) {
1103        meta.insert(
1104            meta::UNITS.to_string(),
1105            crate::units::default_v3_units_json(),
1106        );
1107    }
1108    if !meta.contains_key(meta::CON_SPEC_MINOR) {
1109        meta.insert(meta::CON_SPEC_MINOR.to_string(), Value::from(1u64));
1110    }
1111    meta
1112}
1113
1114/// Same bytes as a binding rewrite, without rebuilding each atom.
1115pub fn binding_rewrite_frame(frame: &ConFrame) -> Result<ConFrame, crate::error::ParseError> {
1116    let mut out = frame.clone();
1117    out.header.metadata = binding_metadata(frame);
1118    // A parsed spec 1 frame keeps line 2 as free text. The builder emits
1119    // the current spec as JSON, so the rewrite does too.
1120    if out.header.spec_version < crate::CON_SPEC_VERSION {
1121        out.header.spec_version = crate::CON_SPEC_VERSION;
1122    }
1123    Ok(out)
1124}
1125
1126// Implementation block specifically for when the writer is a `File`.
1127impl ConFrameWriter<File> {
1128    /// Creates a new `ConFrameWriter` that writes to a file at the given path.
1129    ///
1130    /// This is a convenience function that creates the file and wraps it.
1131    pub fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Self> {
1132        let file = File::create(path)?;
1133        Ok(Self::new(file))
1134    }
1135
1136    /// Creates a new `ConFrameWriter` that writes to a file with a custom precision.
1137    pub fn from_path_with_precision<P: AsRef<Path>>(path: P, precision: usize) -> io::Result<Self> {
1138        let file = File::create(path)?;
1139        Ok(Self::with_precision(file, precision))
1140    }
1141
1142    /// Opens an uncompressed file for appending.
1143    ///
1144    /// The file is created when it does not exist. A non-empty file that does
1145    /// not end in a newline receives one, so the next frame header starts on
1146    /// its own line. A file this writer produced already ends in a newline,
1147    /// and appending the remaining frames reproduces one whole-file write.
1148    /// Gzip and zstd paths are refused: a compressed member cannot be extended.
1149    ///
1150    /// `write_frame` fills a one-frame scratch buffer and a [`std::io::BufWriter`].
1151    /// [`Self::flush`] pushes that buffer to the file before the writer is dropped.
1152    ///
1153    /// ```
1154    /// use readcon_core::iterators::read_all_frames;
1155    /// use readcon_core::types::ConFrameBuilder;
1156    /// use readcon_core::writer::ConFrameWriter;
1157    /// let path = std::env::temp_dir().join(format!(
1158    ///     "readcon-append-doc-{}",
1159    ///     std::process::id()
1160    /// ));
1161    /// let mut builder = ConFrameBuilder::new([10.0, 10.0, 10.0], [90.0, 90.0, 90.0]);
1162    /// builder.add_atom("H", 0.0, 0.0, 0.0, [false; 3], 1, 1.0);
1163    /// let frame = builder.build().unwrap();
1164    /// {
1165    ///     let mut writer = ConFrameWriter::from_path(&path).unwrap();
1166    ///     writer.write_frame(&frame).unwrap();
1167    ///     writer.flush().unwrap();
1168    /// }
1169    /// {
1170    ///     let mut writer = ConFrameWriter::from_path_append(&path).unwrap();
1171    ///     writer.write_frame(&frame).unwrap();
1172    ///     writer.flush().unwrap();
1173    /// }
1174    /// let frames = read_all_frames(&path).unwrap();
1175    /// assert_eq!(frames.len(), 2);
1176    /// let _ = std::fs::remove_file(&path);
1177    /// ```
1178    pub fn from_path_append<P: AsRef<Path>>(path: P) -> io::Result<Self> {
1179        Ok(Self::new(open_uncompressed_append(path.as_ref())?))
1180    }
1181
1182    /// Opens an uncompressed file for appending with a fixed decimal precision.
1183    pub fn from_path_append_with_precision<P: AsRef<Path>>(
1184        path: P,
1185        precision: usize,
1186    ) -> io::Result<Self> {
1187        Ok(Self::with_precision(
1188            open_uncompressed_append(path.as_ref())?,
1189            precision,
1190        ))
1191    }
1192}
1193
1194/// Opens `path` at the end. See [`ConFrameWriter::from_path_append`].
1195pub(crate) fn open_uncompressed_append(path: &Path) -> io::Result<File> {
1196    if let Some(ext) = path.extension().and_then(|ext| ext.to_str())
1197        && (ext == "gz" || ext == "zst")
1198    {
1199        return Err(io::Error::new(
1200            io::ErrorKind::InvalidInput,
1201            "append is only supported for an uncompressed file",
1202        ));
1203    }
1204    let mut file = OpenOptions::new()
1205        .create(true)
1206        .read(true)
1207        .append(true)
1208        .open(path)?;
1209    let len = file.seek(SeekFrom::End(0))?;
1210    if len > 0 {
1211        file.seek(SeekFrom::End(-1))?;
1212        let mut last = [0u8; 1];
1213        file.read_exact(&mut last)?;
1214        if last[0] != b'\n' {
1215            file.write_all(b"\n")?;
1216        }
1217    }
1218    Ok(file)
1219}
1220
1221/// Serializes `frames` to CON bytes. No file is created.
1222///
1223/// The bytes match [`ConFrameWriter::from_path`] writing the same frames.
1224pub fn write_frames_to_vec(frames: &[ConFrame]) -> Result<Vec<u8>, WriteError> {
1225    let mut buffer = Vec::new();
1226    {
1227        let mut writer = ConFrameWriter::new(&mut buffer);
1228        writer.extend(frames.iter())?;
1229    }
1230    Ok(buffer)
1231}
1232
1233/// Serializes `frames` to a CON string. No file is created.
1234///
1235/// The bytes match [`ConFrameWriter::from_path`] writing the same frames.
1236pub fn write_frames_to_string(frames: &[ConFrame]) -> Result<String, WriteError> {
1237    let bytes = write_frames_to_vec(frames)?;
1238    String::from_utf8(bytes).map_err(|err| {
1239        WriteError::Io(io::Error::new(
1240            io::ErrorKind::InvalidData,
1241            err.utf8_error().to_string(),
1242        ))
1243    })
1244}
1245
1246// Gzip-compressed writer constructors.
1247impl ConFrameWriter<flate2::write::GzEncoder<File>> {
1248    /// Creates a gzip-compressed writer for the given path.
1249    pub fn from_path_gzip<P: AsRef<Path>>(path: P) -> io::Result<Self> {
1250        let encoder = crate::compression::gzip_writer(path.as_ref())?;
1251        Ok(Self::new(encoder))
1252    }
1253
1254    /// Creates a gzip-compressed writer with custom precision.
1255    pub fn from_path_gzip_with_precision<P: AsRef<Path>>(
1256        path: P,
1257        precision: usize,
1258    ) -> io::Result<Self> {
1259        let encoder = crate::compression::gzip_writer(path.as_ref())?;
1260        Ok(Self::with_precision(encoder, precision))
1261    }
1262}
1263
1264// Zstd-compressed writer constructors. Available only with the `zstd`
1265// Cargo feature.
1266#[cfg(feature = "zstd")]
1267impl ConFrameWriter<zstd::stream::write::AutoFinishEncoder<'static, File>> {
1268    /// Creates a zstd-compressed writer for the given path.
1269    pub fn from_path_zstd<P: AsRef<Path>>(path: P) -> io::Result<Self> {
1270        let encoder = crate::compression::zstd_writer(path.as_ref())?;
1271        Ok(Self::new(encoder))
1272    }
1273
1274    /// Creates a zstd-compressed writer with custom precision.
1275    pub fn from_path_zstd_with_precision<P: AsRef<Path>>(
1276        path: P,
1277        precision: usize,
1278    ) -> io::Result<Self> {
1279        let encoder = crate::compression::zstd_writer(path.as_ref())?;
1280        Ok(Self::with_precision(encoder, precision))
1281    }
1282}
1283
1284#[cfg(test)]
1285mod float_format_tests {
1286    use super::{push_f64_prec, push_u64};
1287
1288    fn formatted(v: f64, prec: usize) -> String {
1289        let mut buf = Vec::new();
1290        push_f64_prec(&mut buf, v, prec);
1291        String::from_utf8(buf).expect("utf8")
1292    }
1293
1294    #[test]
1295    fn matches_std_fixed_precision() {
1296        let vals = [
1297            0.0,
1298            -0.0,
1299            1.0,
1300            -1.0,
1301            0.9045,
1302            6.975_299_999_999_995,
1303            63.546,
1304            1.008,
1305            15.3456,
1306            90.0,
1307            218.0,
1308            1e-6,
1309            -1.23456789,
1310            10.0,
1311        ];
1312        for prec in [0usize, 6] {
1313            for v in vals {
1314                let got = formatted(v, prec);
1315                let exp = format!("{v:.prec$}");
1316                assert_eq!(got, exp, "v={v:?} prec={prec}");
1317            }
1318        }
1319    }
1320
1321    #[test]
1322    fn round_trip_spelling_matches_ryu_on_repeated_and_unique_rows() {
1323        use crate::iterators::ConFrameIterator;
1324        use crate::writer::ConFrameWriter;
1325        let mut text = String::from(
1326            "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",
1327        );
1328        for i in 0..6 {
1329            let x = (i % 2) as f64 * 1.5 + 0.25;
1330            let y = 3.25;
1331            let z = if i == 3 {
1332                -0.0
1333            } else {
1334                (i as f64) * 0.0010000001
1335            };
1336            text.push_str(&format!("   {x:.17}    {y:.17}    {z:.17} 0 {i}\n"));
1337        }
1338        // Repeated velocities share the column cache with the coordinates.
1339        text.push_str("\nCu\nVelocities of Component 1\n");
1340        for i in 0..6 {
1341            let vx = 0.125;
1342            let vy = if i % 2 == 0 { 0.5 } else { -0.5 };
1343            let vz = (i as f64) * 1.0e-4;
1344            text.push_str(&format!("   {vx:.17}    {vy:.17}    {vz:.17} 0 {i}\n"));
1345        }
1346        let frames: Vec<_> = ConFrameIterator::new(&text)
1347            .map(|frame| frame.expect("parse"))
1348            .collect();
1349        let mut values = Vec::new();
1350        for atom in &frames[0].atom_data {
1351            values.extend([atom.x, atom.y, atom.z]);
1352        }
1353        for atom in &frames[0].atom_data {
1354            if let Some(v) = atom.velocity() {
1355                values.extend(v);
1356            }
1357        }
1358        let mut buf = Vec::new();
1359        {
1360            let mut writer = ConFrameWriter::new(&mut buf);
1361            writer.extend(frames.iter()).unwrap();
1362        }
1363        let written = String::from_utf8(buf).unwrap();
1364        let mut ryu = ryu::Buffer::new();
1365        let mut spelled = Vec::new();
1366        for line in written.lines() {
1367            let toks: Vec<_> = line.split_whitespace().collect();
1368            if toks.len() >= 5
1369                && toks[0].contains('.')
1370                && toks[3].bytes().all(|b| b.is_ascii_digit())
1371            {
1372                spelled.extend(toks[..3].iter().map(|tok| (*tok).to_string()));
1373            }
1374        }
1375        assert_eq!(spelled.len(), values.len());
1376        for (got, value) in spelled.iter().zip(values) {
1377            let expect = if value.is_finite() {
1378                ryu.format_finite(value).to_string()
1379            } else {
1380                ryu.format(value).to_string()
1381            };
1382            assert_eq!(got, &expect, "value {value:?}");
1383        }
1384    }
1385
1386    #[test]
1387    fn u64_matches_decimal_display() {
1388        let mut values = vec![0, 1, 9, 10, 11, 99, 100, 101, 999, 1000, 50000, u64::MAX];
1389        values.extend(0..200);
1390        for n in values {
1391            let mut buf = Vec::new();
1392            push_u64(&mut buf, n);
1393            assert_eq!(std::str::from_utf8(&buf).unwrap(), n.to_string());
1394        }
1395    }
1396}
1397
1398#[cfg(test)]
1399mod section_arity_tests {
1400    use super::require_minor2_section_arity;
1401    use serde_json::json;
1402
1403    #[test]
1404    fn minor2_lists_a_new_section_in_section_arity() {
1405        let widgets = vec![json!("widgets")];
1406        let err = require_minor2_section_arity(2, &widgets, &serde_json::Map::new()).unwrap_err();
1407        let msg = err.to_string();
1408        assert!(msg.contains("section_arity"), "{msg}");
1409
1410        let mut listed = serde_json::Map::new();
1411        listed.insert("section_arity".into(), json!({"widgets": 3}));
1412        require_minor2_section_arity(2, &widgets, &listed).unwrap();
1413
1414        let reserved = vec![json!("velocities"), json!("energies")];
1415        require_minor2_section_arity(2, &reserved, &serde_json::Map::new()).unwrap();
1416        require_minor2_section_arity(1, &widgets, &serde_json::Map::new()).unwrap();
1417    }
1418}