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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
55pub enum FloatFormat {
56 DecimalPlaces(usize),
58 #[default]
62 RoundTrip,
63}
64
65pub struct ConFrameWriter<W: Write> {
80 writer: BufWriter<W>,
81 float_format: FloatFormat,
82 canonical: bool,
86 metadata_cache: Option<MetadataCacheEntry>,
93 scratch: Vec<u8>,
96 ryu: ryu::Buffer,
98 fmt_slot: [FmtSlot; 3],
101}
102
103#[derive(Clone, Copy)]
105struct FmtSlot {
106 bits: u64,
107 text: [u8; 24],
108 len: u8,
109 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 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 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
178fn 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
198fn 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
229impl<W: Write> ConFrameWriter<W> {
231 pub fn new(writer: W) -> Self {
237 Self::with_float_format(writer, FloatFormat::default())
238 }
239
240 pub fn with_precision(writer: W, precision: usize) -> Self {
247 Self::with_float_format(writer, FloatFormat::DecimalPlaces(precision))
248 }
249
250 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 pub fn canonical(mut self, on: bool) -> Self {
271 self.set_canonical(on);
272 self
273 }
274
275 pub fn set_canonical(&mut self, on: bool) {
277 self.canonical = on;
278 if on {
279 self.metadata_cache = None;
280 }
281 }
282
283 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 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 require_minor2_section_arity(minor, §ions, &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 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 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 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 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 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 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 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 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 pub fn flush(&mut self) -> io::Result<()> {
798 self.writer.flush()
799 }
800
801 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 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 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
911fn 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 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
957fn push_f64_prec(buf: &mut Vec<u8>, v: f64, prec: usize) {
960 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 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
1045pub(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 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 if meta.contains_key(meta::CON_SPEC_MINOR) {
1084 meta.insert(meta::CON_SPEC_MINOR.to_string(), Value::from(1u64));
1085 }
1086 }
1087}
1088
1089pub 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 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
1114pub 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 if out.header.spec_version < crate::CON_SPEC_VERSION {
1121 out.header.spec_version = crate::CON_SPEC_VERSION;
1122 }
1123 Ok(out)
1124}
1125
1126impl ConFrameWriter<File> {
1128 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 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 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 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
1194pub(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
1221pub 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
1233pub 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
1246impl ConFrameWriter<flate2::write::GzEncoder<File>> {
1248 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 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#[cfg(feature = "zstd")]
1267impl ConFrameWriter<zstd::stream::write::AutoFinishEncoder<'static, File>> {
1268 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 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 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}