Skip to main content

ionic/
convert.rs

1use std::{fs, path::PathBuf};
2#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
3use std::{fs::File, io::Read, path::Path};
4
5use crate::{
6    ion::{
7        FILE_SIGNATURE, IonError, IonReader, IonResult, ReadOptions, WriteBytes, WriteOptions,
8        write_mzml_to_ion,
9    },
10    mzml::{bin_to_mzml, parse_mzml},
11};
12#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
13use crate::{
14    ion::{FileWriter, IonWriter},
15    mzml::MzmlReader,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19pub enum ConvertKind {
20    #[default]
21    Auto,
22    MzmlToIon,
23    IonToMzml,
24}
25
26pub enum Input<'a> {
27    Bytes(&'a [u8]),
28    #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
29    Path(PathBuf),
30}
31
32#[derive(Debug, Clone, Default)]
33pub struct ConvertOptions {
34    pub output: Option<PathBuf>,
35    pub kind: ConvertKind,
36    pub read: ReadOptions,
37    pub write: WriteOptions,
38}
39
40impl<'a> From<&'a [u8]> for Input<'a> {
41    fn from(bytes: &'a [u8]) -> Self {
42        Self::Bytes(bytes)
43    }
44}
45
46impl<'a> From<&'a Vec<u8>> for Input<'a> {
47    fn from(bytes: &'a Vec<u8>) -> Self {
48        Self::Bytes(bytes)
49    }
50}
51
52#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
53impl From<&Path> for Input<'_> {
54    fn from(path: &Path) -> Self {
55        Self::Path(path.to_path_buf())
56    }
57}
58
59#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
60impl From<PathBuf> for Input<'_> {
61    fn from(path: PathBuf) -> Self {
62        Self::Path(path)
63    }
64}
65
66#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
67impl From<&PathBuf> for Input<'_> {
68    fn from(path: &PathBuf) -> Self {
69        Self::Path(path.clone())
70    }
71}
72
73pub fn convert<'a>(
74    input: impl Into<Input<'a>>,
75    options: ConvertOptions,
76) -> IonResult<Option<Vec<u8>>> {
77    let input = input.into();
78    if get_kind(&input, options.kind)? == ConvertKind::IonToMzml {
79        return ion_to_mzml(&input, options);
80    }
81    mzml_to_ion(&input, options)
82}
83
84fn get_kind(input: &Input<'_>, kind: ConvertKind) -> IonResult<ConvertKind> {
85    if kind != ConvertKind::Auto {
86        return Ok(kind);
87    }
88    #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
89    if let Input::Path(path) = input
90        && let Some(kind) = kind_from_extension(path)
91    {
92        return Ok(kind);
93    }
94    Ok(if input_is_ion(input)? {
95        ConvertKind::IonToMzml
96    } else {
97        ConvertKind::MzmlToIon
98    })
99}
100
101#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
102fn kind_from_extension(path: &Path) -> Option<ConvertKind> {
103    let extension = path.extension()?.to_str()?.to_ascii_lowercase();
104    match extension.as_str() {
105        "mzml" => Some(ConvertKind::MzmlToIon),
106        "ion" => Some(ConvertKind::IonToMzml),
107        _ => None,
108    }
109}
110
111fn input_is_ion(input: &Input<'_>) -> IonResult<bool> {
112    match input {
113        Input::Bytes(bytes) => Ok(bytes.starts_with(&FILE_SIGNATURE)),
114        #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
115        Input::Path(path) => Ok(read_file_start(path)?.starts_with(&FILE_SIGNATURE)),
116    }
117}
118
119#[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
120fn read_file_start(path: &Path) -> IonResult<Vec<u8>> {
121    let file = File::open(path).map_err(|error| {
122        IonError::from(format!(
123            "cannot open input file '{}': {error}",
124            path.display()
125        ))
126    })?;
127    let mut start = Vec::with_capacity(FILE_SIGNATURE.len());
128    file.take(FILE_SIGNATURE.len() as u64)
129        .read_to_end(&mut start)?;
130    Ok(start)
131}
132
133fn mzml_to_ion(input: &Input<'_>, options: ConvertOptions) -> IonResult<Option<Vec<u8>>> {
134    if input_is_ion(input)? {
135        return Err(IonError::from("input is already an ion file"));
136    }
137    #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
138    let write = options.write;
139    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
140    let write = WriteOptions {
141        compression_level: 1,
142        ..options.write
143    };
144    match options.output {
145        None => {
146            let mut bytes = Vec::new();
147            write_ion(input, write, &mut bytes)?;
148            Ok(Some(bytes))
149        }
150        #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
151        Some(path) => {
152            let mut file = FileWriter::open_path(&path)?;
153            write_ion(input, write, &mut file)?;
154            file.flush()?;
155            Ok(None)
156        }
157        #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
158        Some(_) => Err(IonError::from(
159            "file output is not available in browser wasm",
160        )),
161    }
162}
163
164fn write_ion(input: &Input<'_>, write: WriteOptions, output: &mut dyn WriteBytes) -> IonResult<()> {
165    match input {
166        Input::Bytes(bytes) => write_mzml_to_ion(&parse_mzml(bytes)?, write, output),
167        #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
168        Input::Path(path) => {
169            IonWriter::create(output, write)?.write_stream(&mut MzmlReader::open(path)?)
170        }
171    }
172}
173
174fn ion_to_mzml(input: &Input<'_>, options: ConvertOptions) -> IonResult<Option<Vec<u8>>> {
175    let mzml = open_ion(input, options.read)?.to_mzml()?;
176    let xml = bin_to_mzml(&mzml)?;
177    drop(mzml);
178    let Some(path) = options.output else {
179        return Ok(Some(xml));
180    };
181    fs::write(path, &xml)?;
182    Ok(None)
183}
184
185fn open_ion(input: &Input<'_>, read: ReadOptions) -> IonResult<IonReader> {
186    match input {
187        Input::Bytes(bytes) => IonReader::open(bytes, read),
188        #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
189        Input::Path(path) => IonReader::open_file(path, read),
190    }
191}