1use std::fmt;
8use std::io;
9use std::path::Path;
10
11use crate::chemfiles_import::{self, ChemfilesImportError};
12use crate::compression;
13use crate::iterators::ConFrameIterator;
14use crate::types::ConFrame;
15use crate::writer::ConFrameWriter;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ConvertReport {
20 pub n_frames: usize,
22 pub n_atoms_last: usize,
24 pub native_con: bool,
26}
27
28#[derive(Debug)]
30pub enum ConvertError {
31 InputMissing(String),
33 Empty,
35 Io(io::Error),
37 Parse(String),
39 Chemfiles(ChemfilesImportError),
41}
42
43impl fmt::Display for ConvertError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 ConvertError::InputMissing(p) => write!(f, "input not found: {p}"),
47 ConvertError::Empty => write!(f, "no frames produced from input"),
48 ConvertError::Io(e) => write!(f, "I/O error: {e}"),
49 ConvertError::Parse(msg) => write!(f, "parse error: {msg}"),
50 ConvertError::Chemfiles(e) => write!(f, "{e}"),
51 }
52 }
53}
54
55impl std::error::Error for ConvertError {
56 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
57 match self {
58 ConvertError::Io(e) => Some(e),
59 ConvertError::Chemfiles(e) => Some(e),
60 _ => None,
61 }
62 }
63}
64
65impl From<io::Error> for ConvertError {
66 fn from(e: io::Error) -> Self {
67 ConvertError::Io(e)
68 }
69}
70
71impl From<ChemfilesImportError> for ConvertError {
72 fn from(e: ChemfilesImportError) -> Self {
73 ConvertError::Chemfiles(e)
74 }
75}
76
77pub fn path_looks_like_con(path: &Path) -> bool {
79 let name = path
80 .file_name()
81 .and_then(|s| s.to_str())
82 .unwrap_or("")
83 .to_ascii_lowercase();
84 let base = name
86 .strip_suffix(".gz")
87 .or_else(|| name.strip_suffix(".zst"))
88 .unwrap_or(&name);
89 base.ends_with(".con") || base.ends_with(".convel")
90}
91
92pub fn read_frames_for_convert(input: &Path) -> Result<(Vec<ConFrame>, bool), ConvertError> {
94 if !input.is_file() {
95 return Err(ConvertError::InputMissing(input.display().to_string()));
96 }
97 if path_looks_like_con(input) {
98 let contents = compression::read_file_contents(input)
100 .map_err(|e| ConvertError::Io(io::Error::other(e.to_string())))?;
101 let text = contents
102 .as_str()
103 .map_err(|e| ConvertError::Parse(format!("input is not valid UTF-8: {e}")))?;
104 let mut frames = Vec::new();
105 for item in ConFrameIterator::new(text) {
106 match item {
107 Ok(f) => frames.push(f),
108 Err(e) => {
109 return Err(ConvertError::Parse(e.to_string()));
110 }
111 }
112 }
113 if frames.is_empty() {
114 return Err(ConvertError::Empty);
115 }
116 Ok((frames, true))
117 } else {
118 if !chemfiles_import::chemfiles_enabled() {
119 return Err(ConvertError::Chemfiles(
120 ChemfilesImportError::FeatureDisabled,
121 ));
122 }
123 let frames = chemfiles_import::con_frames_from_trajectory_path(input)?;
124 if frames.is_empty() {
125 return Err(ConvertError::Empty);
126 }
127 Ok((frames, false))
128 }
129}
130
131pub fn convert_path_to_con(input: &Path, output: &Path) -> Result<ConvertReport, ConvertError> {
155 let (frames, native_con) = read_frames_for_convert(input)?;
156 let n_frames = frames.len();
157 let n_atoms_last = frames.last().map(|f| f.atom_data.len()).unwrap_or(0);
158 let mut writer = ConFrameWriter::from_path(output)?;
159 writer
160 .extend(frames.iter())
161 .map_err(|e| ConvertError::Io(io::Error::other(e.to_string())))?;
162 Ok(ConvertReport {
163 n_frames,
164 n_atoms_last,
165 native_con,
166 })
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use std::fs;
173 use std::path::PathBuf;
174
175 fn fixture(name: &str) -> PathBuf {
176 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
177 .join("resources/test")
178 .join(name)
179 }
180
181 #[test]
182 fn path_looks_like_con_suffixes() {
183 assert!(path_looks_like_con(Path::new("a.con")));
184 assert!(path_looks_like_con(Path::new("a.convel")));
185 assert!(path_looks_like_con(Path::new("a.con.gz")));
186 assert!(!path_looks_like_con(Path::new("a.xyz")));
187 assert!(!path_looks_like_con(Path::new("a.pdb")));
188 }
189
190 #[test]
191 fn convert_native_con_roundtrip() {
192 let dir = scratch_dir();
193 let out = dir.path().join("out.con");
194 let report = convert_path_to_con(&fixture("tiny_multi_cuh2.con"), &out).unwrap();
195 assert!(report.native_con);
196 assert_eq!(report.n_frames, 2);
197 assert_eq!(report.n_atoms_last, 4);
198 let (back, native) = read_frames_for_convert(&out).unwrap();
199 assert!(native);
200 assert_eq!(back.len(), 2);
201 assert_eq!(back[0].atom_data.len(), 4);
202 assert_eq!(back[0].atom_data[0].atom_id, 0);
203 }
204
205 #[test]
206 #[cfg(feature = "chemfiles")]
207 fn convert_xyz_via_chemfiles() {
208 let dir = scratch_dir();
209 let xyz = dir.path().join("water.xyz");
210 fs::write(
211 &xyz,
212 "3\nwater migrate\nO 0 0 0\nH 0.96 0 0\nH -0.24 0.93 0\n",
213 )
214 .unwrap();
215 let out = dir.path().join("water.con");
216 let report = convert_path_to_con(&xyz, &out).unwrap();
217 assert!(!report.native_con);
218 assert_eq!(report.n_frames, 1);
219 assert_eq!(report.n_atoms_last, 3);
220 let (back, _) = read_frames_for_convert(&out).unwrap();
221 assert_eq!(back[0].atom_data.len(), 3);
222 let symbols: Vec<_> = back[0]
223 .atom_data
224 .iter()
225 .map(|a| a.symbol.as_ref())
226 .collect();
227 assert!(symbols.contains(&"O"));
228 assert_eq!(symbols.iter().filter(|s| **s == "H").count(), 2);
229 }
230
231 #[test]
232 #[cfg(not(feature = "chemfiles"))]
233 fn convert_xyz_fails_without_chemfiles() {
234 let dir = scratch_dir();
235 let xyz = dir.path().join("water.xyz");
236 fs::write(&xyz, "3\nx\nO 0 0 0\nH 1 0 0\nH 0 1 0\n").unwrap();
237 let out = dir.path().join("water.con");
238 let err = convert_path_to_con(&xyz, &out).unwrap_err();
239 assert!(matches!(
240 err,
241 ConvertError::Chemfiles(ChemfilesImportError::FeatureDisabled)
242 ));
243 }
244
245 fn scratch_dir() -> tempfile::TempDir {
246 let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("build");
247 fs::create_dir_all(&base).unwrap();
248 tempfile::Builder::new()
249 .prefix("readcon-convert-")
250 .tempdir_in(&base)
251 .unwrap()
252 }
253
254 fn convert_names(dir: &std::path::Path) -> Vec<std::ffi::OsString> {
255 let mut names = Vec::new();
256 let Ok(entries) = fs::read_dir(dir) else {
257 return names;
258 };
259 for entry in entries.flatten() {
260 let name = entry.file_name();
261 let text = name.to_string_lossy();
262 if text.starts_with("readcon-convert-") || text == "water.xyz" {
263 names.push(name);
264 }
265 }
266 names.sort();
267 names
268 }
269
270 #[test]
271 fn convert_scratch_leaves_the_system_tempdir_clean() {
272 let system = std::env::temp_dir();
273 let before = convert_names(&system);
274 let dir = scratch_dir();
275 let xyz = dir.path().join("water.xyz");
276 fs::write(&xyz, b"3\nx\nO 0 0 0\nH 1 0 0\nH 0 1 0\n").unwrap();
277 let build = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("build");
278 assert!(
279 dir.path().starts_with(&build),
280 "convert scratch {} is outside build/",
281 dir.path().display()
282 );
283 assert!(
284 !dir.path().starts_with(&system),
285 "convert scratch {} is in the system tempdir",
286 dir.path().display()
287 );
288 assert!(xyz.is_file());
289 drop(dir);
290 assert_eq!(convert_names(&system), before);
291 }
292}