ionic/ion/decoder/decode/
spectra.rs1use super::*;
2
3#[inline]
4pub(crate) fn slice_summary(
5 bytes: &[u8],
6 off: u64,
7 index: usize,
8 size: usize,
9 count: u64,
10) -> Option<&[u8]> {
11 if index >= count as usize {
12 return None;
13 }
14 let base = usize::try_from(off)
15 .ok()
16 .and_then(|o| index.checked_mul(size).and_then(|d| o.checked_add(d)))?;
17 bytes.get(base..base.checked_add(size)?)
18}
19
20#[inline]
21pub(crate) fn parse_spec_summary(bytes: &[u8]) -> SpectrumSummary {
22 SpectrumSummary {
23 rt: f64::from_le_bytes(bytes[0..8].try_into().unwrap()),
24 rt_unit: bytes[54],
25 base_peak_mz: f64::from_le_bytes(bytes[8..16].try_into().unwrap()),
26 selected_ion_mz: f64::from_le_bytes(bytes[16..24].try_into().unwrap()),
27 base_peak_int: f64::from_le_bytes(bytes[24..32].try_into().unwrap()),
28 total_ion_current: f64::from_le_bytes(bytes[32..40].try_into().unwrap()),
29 ms_level: bytes[40],
30 polarity: bytes[41],
31 position_x: u32::from_le_bytes(bytes[42..46].try_into().unwrap()),
32 position_y: u32::from_le_bytes(bytes[46..50].try_into().unwrap()),
33 position_z: u32::from_le_bytes(bytes[50..54].try_into().unwrap()),
34 }
35}
36
37pub(crate) fn parse_chrom_summary(bytes: &[u8]) -> ChromatogramSummary {
38 ChromatogramSummary {
39 lowest_mz: f64::from_le_bytes(bytes[0..8].try_into().unwrap()),
40 highest_mz: f64::from_le_bytes(bytes[8..16].try_into().unwrap()),
41 lowest_wavelength: f64::from_le_bytes(bytes[16..24].try_into().unwrap()),
42 highest_wavelength: f64::from_le_bytes(bytes[24..32].try_into().unwrap()),
43 lowest_ion_mobility: f64::from_le_bytes(bytes[32..40].try_into().unwrap()),
44 highest_ion_mobility: f64::from_le_bytes(bytes[40..48].try_into().unwrap()),
45 polarity: bytes[48],
46 }
47}
48
49pub(crate) fn build_one_spectrum(rows: &[Metadatum], fallback_index: usize) -> Option<Spectrum> {
50 let children_lookup = ChildrenLookup::new(rows);
51 let spectrum_id = children_lookup.all_ids(TagId::Spectrum).first().copied()?;
52 let mut owner_rows = OwnerRows::with_capacity(rows.len());
53 for row in rows {
54 owner_rows.insert(row.id, row);
55 }
56 let policy = DefaultMetadataPolicy;
57 let mut param_buffer = Vec::new();
58 Some(parse_spectrum(
59 &owner_rows,
60 &children_lookup,
61 spectrum_id,
62 fallback_index as u32,
63 &policy,
64 &mut param_buffer,
65 ))
66}
67
68pub(crate) fn build_one_chromatogram(
69 rows: &[Metadatum],
70 fallback_index: usize,
71) -> Option<Chromatogram> {
72 let children_lookup = ChildrenLookup::new(rows);
73 let chromatogram_id = children_lookup
74 .all_ids(TagId::Chromatogram)
75 .first()
76 .copied()?;
77 let mut owner_rows = OwnerRows::with_capacity(rows.len());
78 for row in rows {
79 owner_rows.insert(row.id, row);
80 }
81 let policy = DefaultMetadataPolicy;
82 let mut param_buffer = Vec::new();
83 Some(parse_chromatogram(
84 &owner_rows,
85 &children_lookup,
86 chromatogram_id,
87 fallback_index as u32,
88 &policy,
89 &mut param_buffer,
90 ))
91}
92
93impl IonReader {
94 pub fn spectrum_summary(&self, index: usize) -> Option<SpectrumSummary> {
95 let b = slice_summary(
96 &self.spec_summary_buf,
97 0,
98 index,
99 SPEC_SUMMARY_SIZE,
100 self.header.spectrum_count,
101 )?;
102 Some(parse_spec_summary(b))
103 }
104
105 pub(crate) fn spectrum_rt(&self, index: usize) -> f64 {
106 let start = index * SPEC_SUMMARY_SIZE;
107 let Some(bytes) = self.spec_summary_buf.get(start..start + 8) else {
108 return f64::NAN;
109 };
110 let mut rt = [0u8; 8];
111 rt.copy_from_slice(bytes);
112 f64::from_le_bytes(rt)
113 }
114
115 pub(crate) fn spec_rt_is_finite_ascending(&self) -> bool {
116 if let Some(known) = self.spec_rt_finite_ascending.get() {
117 return known;
118 }
119 let mut previous = f64::NEG_INFINITY;
120 let mut ascending = true;
121 for index in 0..self.header.spectrum_count as usize {
122 let rt = self.spectrum_rt(index);
123 if !rt.is_finite() || rt < previous {
124 ascending = false;
125 break;
126 }
127 previous = rt;
128 }
129 self.spec_rt_finite_ascending.set(Some(ascending));
130 ascending
131 }
132
133 pub fn spectrum_summaries(&self) -> IonResult<Vec<SpectrumSummary>> {
134 let count = usize::try_from(self.header.spectrum_count)
135 .map_err(|_| IonError::from("spec summary: out of bounds"))?;
136 let len = self.spec_summary_buf.len();
137 if len != count * SPEC_SUMMARY_SIZE {
138 return Err(
139 format!("spec summary: len={len} != count={count} × {SPEC_SUMMARY_SIZE}").into(),
140 );
141 }
142 Ok(self
143 .spec_summary_buf
144 .as_chunks::<SPEC_SUMMARY_SIZE>()
145 .0
146 .iter()
147 .map(|c| parse_spec_summary(c))
148 .collect())
149 }
150
151 pub fn chromatogram_summaries(&self) -> IonResult<Vec<ChromatogramSummary>> {
152 let count = usize::try_from(self.header.chrom_count)
153 .map_err(|_| IonError::from("chrom summary: out of bounds"))?;
154 let len = self.chrom_summary_buf.len();
155 if len != count * CHROM_SUMMARY_SIZE {
156 return Err(format!(
157 "chrom summary: len={len} != count={count} × {CHROM_SUMMARY_SIZE}"
158 )
159 .into());
160 }
161 Ok(self
162 .chrom_summary_buf
163 .as_chunks::<CHROM_SUMMARY_SIZE>()
164 .0
165 .iter()
166 .map(|c| parse_chrom_summary(c))
167 .collect())
168 }
169
170 fn global_meta_bytes(&self) -> IonResult<&[u8]> {
171 if let Some(bytes) = self.global_meta.get() {
172 return Ok(bytes);
173 }
174 let bytes = self.source.read(ByteRange {
175 offset: self.header.off_global_meta,
176 length: self.header.len_global_meta,
177 })?;
178 if self.options.verify_checksums {
179 check_crc(&bytes, self.header.global_meta_crc32, "global_meta")?;
180 }
181 Ok(self.global_meta.get_or_init(|| bytes))
182 }
183
184 pub(crate) fn global_metadata_rows(&self) -> IonResult<Vec<Metadatum>> {
185 parse_global_metadata(
186 self.global_meta_bytes()?,
187 0,
188 self.header.global_meta_count,
189 self.header.global_meta_numeric_count,
190 self.header.global_meta_string_count,
191 self.header.compression_codec,
192 self.header.global_meta_uncompressed_bytes,
193 self.options.decompression_limit,
194 MetaColumnLayout::new().without_ids_reset(),
195 )
196 }
197
198 pub(crate) fn spectrum_metadata_grouped(&self) -> IonResult<Vec<Vec<Metadatum>>> {
199 self.spec_meta.read_all_grouped()
200 }
201
202 pub(crate) fn chromatogram_metadata_grouped(&self) -> IonResult<Vec<Vec<Metadatum>>> {
203 self.chrom_meta.read_all_grouped()
204 }
205
206 pub(crate) fn spectrum_metadata_rows_at(&mut self, index: usize) -> IonResult<Vec<Metadatum>> {
207 self.spec_meta.read_item(index as u64)
208 }
209
210 pub(crate) fn chromatogram_metadata_rows_at(
211 &mut self,
212 index: usize,
213 ) -> IonResult<Vec<Metadatum>> {
214 self.chrom_meta.read_item(index as u64)
215 }
216
217 pub fn spectrum_metadata_at(&mut self, index: usize) -> IonResult<Spectrum> {
218 self.check_spectrum_index(index)?;
219 let rows = self.spectrum_metadata_rows_at(index)?;
220 build_one_spectrum(&rows, index).ok_or_else(|| {
221 IonError::from(format!(
222 "spectrum {index}: metadata is missing the spectrum tag"
223 ))
224 })
225 }
226
227 pub fn spectrum_metadata_byte_ranges(&self, index: usize) -> IonResult<Vec<ByteRange>> {
228 self.check_spectrum_index(index)?;
229 Ok(vec![self.spec_meta.item_byte_range(index as u64)?])
230 }
231
232 fn check_spectrum_index(&self, index: usize) -> IonResult<()> {
233 if index >= self.header.spectrum_count as usize {
234 return Err(IonError::OutOfRange {
235 index,
236 count: self.header.spectrum_count,
237 });
238 }
239 Ok(())
240 }
241
242 pub fn chromatogram_metadata_at(&mut self, index: usize) -> IonResult<Chromatogram> {
243 if index >= self.header.chrom_count as usize {
244 return Err(IonError::OutOfRange {
245 index,
246 count: self.header.chrom_count,
247 });
248 }
249 let rows = self.chromatogram_metadata_rows_at(index)?;
250 build_one_chromatogram(&rows, index).ok_or_else(|| {
251 IonError::from(format!(
252 "chromatogram {index}: metadata is missing the chromatogram tag"
253 ))
254 })
255 }
256}
257
258#[cfg(test)]
259impl IonReader {
260 pub(crate) fn spectrum_metadata(&self) -> IonResult<Vec<Metadatum>> {
261 self.spec_meta.read_all()
262 }
263
264 pub(crate) fn chromatogram_metadata(&self) -> IonResult<Vec<Metadatum>> {
265 self.chrom_meta.read_all()
266 }
267}