1use std::io::Read;
4use std::path::Path;
5
6use crate::error::{Error, Result};
7use crate::model::{
8 AttachmentInfo, CheckReport, DetectConfidence, FileInfo, FormatDescriptor, LsEntry, Spectrum,
9 Table, Trace,
10};
11use crate::pixel::Plane;
12use crate::provenance::ProvenanceMap;
13use crate::source::Input;
14
15#[derive(Debug, Clone)]
17pub struct Detection {
18 pub format_id: &'static str,
20 pub confidence: DetectConfidence,
22 pub note: Option<String>,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
29#[non_exhaustive]
30pub enum SpectrumView {
31 #[default]
33 Primary,
34 Centroid,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
41pub struct PlaneIndex {
42 pub c: u32,
44 pub z: u32,
46 pub t: u32,
48}
49
50pub trait Dataset: Send {
52 fn info(&self) -> Result<FileInfo>;
54 fn vendor_metadata(&self) -> Result<serde_json::Value>;
56 fn provenance(&self) -> ProvenanceMap;
58 fn entries(&self) -> Result<Vec<LsEntry>>;
60 fn read_plane(&mut self, image: u32, index: PlaneIndex) -> Result<Plane>;
62 fn check(&mut self) -> Result<CheckReport>;
64 fn check_headers(&mut self) -> Result<CheckReport> {
70 self.check()
71 }
72 fn member_files(&self) -> Vec<std::path::PathBuf> {
79 Vec::new()
80 }
81 fn write_state(&self) -> Option<crate::live::WriteState> {
86 None
87 }
88 fn read_table(&mut self, index: u32, first_row: u64, max_rows: u64) -> Result<Table> {
90 let _ = (index, first_row, max_rows);
91 Err(Error::unsupported(
92 "core",
93 "tabular data",
94 "This format exposes images, not tables.",
95 ))
96 }
97 fn read_trace(
99 &mut self,
100 index: u32,
101 sweep: u32,
102 first_sample: u64,
103 max_samples: u64,
104 ) -> Result<Trace> {
105 let _ = (index, sweep, first_sample, max_samples);
106 Err(Error::unsupported(
107 "core",
108 "sampled signals",
109 "This format does not expose traces.",
110 ))
111 }
112 fn read_spectrum(&mut self, index: u32, spectrum: u64) -> Result<Spectrum> {
114 let _ = (index, spectrum);
115 Err(Error::unsupported(
116 "core",
117 "mass spectra",
118 "This format exposes images, not spectra.",
119 ))
120 }
121 fn spectrum_ms_levels(&mut self, run: u32) -> Result<Option<Vec<u32>>> {
125 let _ = run;
126 Ok(None)
127 }
128 fn find_spectrum(&mut self, run: u32, scan_number: u64) -> Result<Option<u64>> {
132 let _ = (run, scan_number);
133 Ok(None)
134 }
135 fn visit_scan_headers(
141 &mut self,
142 run: u32,
143 first: u64,
144 visit: &mut dyn FnMut(crate::scans::ScanHeader) -> bool,
145 ) -> Result<bool> {
146 let _ = (run, first, visit);
147 Ok(false)
148 }
149 fn read_spectrum_view(
152 &mut self,
153 index: u32,
154 spectrum: u64,
155 view: SpectrumView,
156 ) -> Result<Spectrum> {
157 let _ = view;
158 self.read_spectrum(index, spectrum)
159 }
160 fn read_plane_level(&mut self, image: u32, index: PlaneIndex, level: u32) -> Result<Plane> {
164 if level == 0 {
165 return self.read_plane(image, index);
166 }
167 Err(Error::unsupported(
168 "core",
169 "pyramid level reads",
170 "This format does not expose downsampled pyramid levels; read level 0.",
171 ))
172 }
173 fn read_region(
180 &mut self,
181 image: u32,
182 index: PlaneIndex,
183 level: u32,
184 region: crate::region::Region,
185 ) -> Result<Plane> {
186 let plane = self.read_plane_level(image, index, level)?;
187 crate::region::crop(plane, region, &format!("image {image} level {level}"))
188 }
189 fn stored_areas(
196 &mut self,
197 image: u32,
198 index: PlaneIndex,
199 level: u32,
200 region: Option<crate::region::Region>,
201 ) -> Result<Option<Vec<crate::region::Region>>> {
202 let _ = (image, index, level, region);
203 Ok(None)
204 }
205 fn reads_strips(&self, image: u32, level: u32) -> bool {
211 let _ = (image, level);
212 false
213 }
214 fn read_strips(
218 &mut self,
219 image: u32,
220 index: PlaneIndex,
221 level: u32,
222 strips: &[crate::region::Region],
223 sink: &mut dyn FnMut(Plane) -> Result<()>,
224 ) -> Result<()> {
225 for &r in strips {
226 let p = self.read_region(image, index, level, r)?;
227 sink(p)?;
228 }
229 Ok(())
230 }
231 fn z_planes_per_chunk(&self, image: u32, level: u32) -> u32 {
236 let _ = (image, level);
237 1
238 }
239 fn pixels_refused(&self, image: u32) -> Option<String> {
245 let _ = image;
246 None
247 }
248 fn attachments(&self) -> Result<Vec<AttachmentInfo>> {
250 Ok(Vec::new())
251 }
252 fn read_attachment(&mut self, index: u32) -> Result<Vec<u8>> {
254 let _ = index;
255 Err(Error::unsupported(
256 "core",
257 "attachments",
258 "This format has no embedded attachments; `info --view structure` lists what the file contains.",
259 ))
260 }
261 fn sum_planes(&mut self, image: u32, c: u32, z: u32, ts: &[u32]) -> Result<Plane> {
266 sum_planes_by_reading(self, image, c, z, ts)
267 }
268 fn frames(&self, image: u32, limit: Option<usize>) -> Result<(u64, Vec<serde_json::Value>)> {
275 let _ = (image, limit);
276 Ok((0, Vec::new()))
277 }
278 fn experiment(&self) -> Option<crate::experiment::Experiment> {
283 None
284 }
285 fn plate(&self) -> Option<crate::plate::PlateSummary> {
289 None
290 }
291 fn assurance_observations(&self) -> crate::assurance::Observations {
296 crate::assurance::Observations::default()
297 }
298 fn file_assurance(&self) -> Option<crate::assurance::Assurance> {
302 let info = self.info().ok()?;
303 Some(crate::assurance::assess(
304 &info,
305 self.assurance_observations(),
306 &self.provenance(),
307 ))
308 }
309 fn exclude_flagged_peaks(&mut self, exclude: bool) -> bool {
313 let _ = exclude;
314 false
315 }
316 fn set_lock_mass(&mut self, reference_mz: Option<f64>) -> crate::Result<bool> {
322 let _ = reference_mz;
323 Ok(false)
324 }
325 fn is_strict(&self) -> bool {
328 false
329 }
330}
331
332pub fn sum_planes_by_reading<D: Dataset + ?Sized>(
334 ds: &mut D,
335 image: u32,
336 channel: u32,
337 plane_z: u32,
338 ts: &[u32],
339) -> Result<Plane> {
340 let mut acc: Vec<f32> = Vec::new();
341 let (mut width, mut height) = (0u32, 0u32);
342 for &t in ts {
343 let p = ds.read_plane(
344 image,
345 PlaneIndex {
346 c: channel,
347 z: plane_z,
348 t,
349 },
350 )?;
351 if p.samples_per_pixel != 1 {
352 return Err(Error::Usage(
353 "frames with several samples per pixel (RGB) are not summed".into(),
354 ));
355 }
356 let bps = p.pixel_type.bytes_per_sample();
357 let n = p.width as usize * p.height as usize;
358 if acc.is_empty() {
359 (width, height) = (p.width, p.height);
360 acc = vec![0f32; n];
361 } else if (p.width, p.height) != (width, height) {
362 return Err(Error::Other(format!(
363 "frame t={t} is {}x{}, the first {width}x{height}: frames of different sizes are not summed",
364 p.width, p.height
365 )));
366 }
367 for (a, sample) in acc.iter_mut().zip(p.data.chunks_exact(bps)) {
368 *a += p.pixel_type.sample_f64(sample) as f32;
369 }
370 }
371 if ts.is_empty() {
372 return Err(Error::Usage("no frames to sum".into()));
373 }
374 Ok(Plane {
375 width,
376 height,
377 pixel_type: crate::PixelType::Float,
378 samples_per_pixel: 1,
379 data: acc.iter().flat_map(|v| v.to_le_bytes()).collect(),
380 })
381}
382
383pub fn spectrum_by_scan(
387 ds: &mut dyn Dataset,
388 run: u32,
389 scan: u64,
390 view: SpectrumView,
391) -> Result<Spectrum> {
392 if let Some(i) = ds.find_spectrum(run, scan)? {
393 return ds.read_spectrum_view(run, i, view);
394 }
395 let first = ds.read_spectrum_view(run, 0, view)?;
396 let i = scan.checked_sub(first.scan_number).ok_or_else(|| {
397 Error::Usage(format!(
398 "scan {scan} precedes the first scan ({})",
399 first.scan_number
400 ))
401 })?;
402 let sp = if i == 0 {
403 first
404 } else {
405 ds.read_spectrum_view(run, i, view)?
406 };
407 if sp.scan_number != scan {
408 return Err(Error::Usage(format!(
409 "scan numbers are not contiguous; spectrum {i} is scan {}. Use --spectrum (the zero-based index)",
410 sp.scan_number
411 )));
412 }
413 Ok(sp)
414}
415
416pub fn spectrum_by_level(
423 ds: &mut dyn Dataset,
424 run: u32,
425 ms_level: u32,
426 index: u64,
427 scan_count: u64,
428 view: SpectrumView,
429) -> Result<Spectrum> {
430 let mut seen = 0u64;
431 let too_few = |seen: u64| {
432 Error::Usage(format!(
433 "run {run} has {seen} MS{ms_level} spectra, so the zero-based index {index} is out of range; `info` → spectra[].extra.ms_level_counts lists the counts"
434 ))
435 };
436 if let Some(levels) = ds.spectrum_ms_levels(run)? {
437 for (i, l) in levels.iter().enumerate() {
438 if *l == ms_level {
439 if seen == index {
440 return ds.read_spectrum_view(run, i as u64, view);
441 }
442 seen += 1;
443 }
444 }
445 return Err(too_few(seen));
446 }
447 for i in 0..scan_count {
448 let sp = ds.read_spectrum_view(run, i, view)?;
449 if sp.ms_level == ms_level {
450 if seen == index {
451 return Ok(sp);
452 }
453 seen += 1;
454 }
455 }
456 Err(too_few(seen))
457}
458
459pub const DEFAULT_FRAME_RECORDS: usize = 100;
462
463pub fn attach_frames(ds: &dyn Dataset, info: &mut FileInfo, limit: Option<usize>) -> Result<()> {
466 for img in &mut info.images {
467 let (total, records) = ds.frames(img.index, limit)?;
468 if records.is_empty() {
469 continue;
470 }
471 let truncated = (records.len() as u64) < total;
472 img.extra
473 .insert("frames".into(), serde_json::Value::Array(records));
474 img.extra
475 .insert("frame_records_total".into(), serde_json::Value::from(total));
476 if truncated {
477 img.extra
478 .insert("frames_truncated".into(), serde_json::Value::Bool(true));
479 }
480 }
481 Ok(())
482}
483
484pub trait FormatReader: Send + Sync {
486 fn descriptor(&self) -> FormatDescriptor;
488 fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection>;
490 fn open(&self, path: &Path) -> Result<Box<dyn Dataset>>;
492 fn sniff_input(&self, head: &[u8], input: &Input) -> Option<Detection> {
497 self.sniff(head, input.path())
498 }
499 fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
505 if input.is_local() {
506 return self.open(input.path());
507 }
508 let d = self.descriptor();
509 Err(Error::Unsupported {
510 format: "input",
511 feature: format!(
512 "reading {} ({}) from an in-memory or host-provided source",
513 d.name, d.id
514 ),
515 hint: Some(
516 "This reader opens local files only so far: save the data to a file and open its path."
517 .into(),
518 ),
519 })
520 }
521 fn reads_any_source(&self) -> bool {
524 false
525 }
526 fn assurance(&self) -> Option<&'static crate::assurance::AssuranceProfile> {
530 None
531 }
532}
533
534pub const SNIFF_LEN: usize = 64 * 1024;
536
537pub struct Registry {
539 readers: Vec<Box<dyn FormatReader>>,
540 strict: bool,
543}
544
545impl std::fmt::Debug for Registry {
546 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
547 let ids: Vec<String> = self.readers.iter().map(|r| r.descriptor().id).collect();
548 f.debug_struct("Registry")
549 .field("readers", &ids)
550 .field("strict", &self.strict)
551 .finish()
552 }
553}
554
555impl Default for Registry {
556 fn default() -> Self {
559 Registry {
560 readers: Vec::new(),
561 strict: crate::assurance::default_strict(),
562 }
563 }
564}
565
566impl Registry {
567 pub fn new() -> Self {
569 Self::default()
570 }
571
572 pub fn register(&mut self, reader: Box<dyn FormatReader>) {
574 if let Some(p) = reader.assurance() {
575 crate::assurance::register_profile(p);
576 }
577 self.readers.push(reader);
578 }
579
580 #[must_use]
585 pub fn strict(mut self, on: bool) -> Self {
586 self.strict = on;
587 self
588 }
589
590 pub fn is_strict(&self) -> bool {
592 self.strict
593 }
594
595 pub fn with(mut self, reader: Box<dyn FormatReader>) -> Self {
597 self.register(reader);
598 self
599 }
600
601 pub fn descriptors(&self) -> Vec<FormatDescriptor> {
603 self.readers.iter().map(|r| r.descriptor()).collect()
604 }
605
606 pub fn by_id(&self, id: &str) -> Option<&dyn FormatReader> {
608 self.readers
609 .iter()
610 .find(|r| r.descriptor().id == id)
611 .map(AsRef::as_ref)
612 }
613
614 pub fn detect(&self, path: &Path) -> Result<(&dyn FormatReader, Detection)> {
618 self.detect_input(&Input::local(path))
619 }
620
621 pub fn detect_input(&self, input: &Input) -> Result<(&dyn FormatReader, Detection)> {
624 let path = input.path();
625 let meta = input.metadata()?;
626 let mut head = Vec::new();
627 if !meta.is_dir() {
628 let mut file = input.open()?;
629 head = vec![0u8; SNIFF_LEN];
630 let mut filled = 0;
631 while filled < head.len() {
632 let n = file
633 .read(&mut head[filled..])
634 .map_err(|e| Error::io(path, e))?;
635 if n == 0 {
636 break;
637 }
638 filled += n;
639 }
640 head.truncate(filled);
641 if filled == 0 {
642 return Err(Error::Corrupt {
645 format: "input",
646 detail: "the file is empty (0 bytes)".into(),
647 offset: Some(0),
648 });
649 }
650 }
651 if is_apple_double(&head) {
652 return Err(Error::UnknownFormat {
653 path: path.to_path_buf(),
654 });
655 }
656 let mut best: Option<(&dyn FormatReader, Detection)> = None;
657 for r in &self.readers {
658 if let Some(d) = r.sniff_input(&head, input) {
659 let better = match &best {
660 None => true,
661 Some((_, b)) => rank(d.confidence) > rank(b.confidence),
662 };
663 if better {
664 let definite = d.confidence == DetectConfidence::Definite;
665 best = Some((r.as_ref(), d));
666 if definite {
667 break;
668 }
669 }
670 }
671 }
672 best.ok_or_else(|| Error::UnknownFormat {
673 path: path.to_path_buf(),
674 })
675 }
676
677 pub fn open(&self, path: &Path) -> Result<(Detection, Box<dyn Dataset>)> {
679 let (reader, det) = self.detect(path)?;
680 let ds = reader
681 .open(path)
682 .map_err(|e| extension_only_context(e, &det))?;
683 Ok((det, self.guard(ds)?))
684 }
685
686 pub fn guard(&self, ds: Box<dyn Dataset>) -> Result<Box<dyn Dataset>> {
688 if self.strict {
689 crate::strict::StrictDataset::wrap(ds)
690 } else {
691 Ok(ds)
692 }
693 }
694
695 pub fn open_input(&self, input: &Input) -> Result<(Detection, Box<dyn Dataset>)> {
698 let (reader, det) = self.detect_input(input)?;
699 let ds = reader
700 .open_input(input)
701 .map_err(|e| extension_only_context(e, &det))?;
702 Ok((det, self.guard(ds)?))
703 }
704
705 pub fn detect_bytes(&self, head: &[u8], name: &Path) -> Result<(&dyn FormatReader, Detection)> {
708 let head = &head[..head.len().min(SNIFF_LEN)];
709 if is_apple_double(head) {
710 return Err(Error::UnknownFormat {
711 path: name.to_path_buf(),
712 });
713 }
714 let mut best: Option<(&dyn FormatReader, Detection)> = None;
715 for r in &self.readers {
716 if let Some(d) = r.sniff(head, name)
717 && best
718 .as_ref()
719 .is_none_or(|(_, b)| rank(d.confidence) > rank(b.confidence))
720 {
721 let definite = d.confidence == DetectConfidence::Definite;
722 best = Some((r.as_ref(), d));
723 if definite {
724 break;
725 }
726 }
727 }
728 best.ok_or_else(|| Error::UnknownFormat {
729 path: name.to_path_buf(),
730 })
731 }
732}
733
734fn extension_only_context(e: Error, det: &Detection) -> Error {
738 if det.confidence != DetectConfidence::ExtensionOnly {
739 return e;
740 }
741 match e {
742 Error::Corrupt {
743 format,
744 detail,
745 offset,
746 } => Error::Corrupt {
747 format,
748 detail: format!("{detail} ({})", crate::error::EXTENSION_ONLY),
749 offset,
750 },
751 Error::Unsupported {
752 format,
753 feature,
754 hint,
755 } => Error::Unsupported {
756 format,
757 feature: format!("{feature} ({})", crate::error::EXTENSION_ONLY),
758 hint: Some(match hint {
759 Some(h) => format!("{} {h}", crate::error::EXTENSION_ONLY_HINT),
760 None => crate::error::EXTENSION_ONLY_HINT.into(),
761 }),
762 },
763 other => other,
764 }
765}
766
767fn is_apple_double(head: &[u8]) -> bool {
771 head.starts_with(&[0x00, 0x05, 0x16, 0x07]) || head.starts_with(&[0x00, 0x05, 0x16, 0x00])
772}
773
774fn rank(c: DetectConfidence) -> u8 {
775 match c {
776 DetectConfidence::Definite => 3,
777 DetectConfidence::Likely => 2,
778 DetectConfidence::ExtensionOnly => 1,
779 }
780}
781
782pub fn has_extension(path: &Path, exts: &[&str]) -> bool {
784 path.extension()
785 .and_then(|e| e.to_str())
786 .is_some_and(|e| exts.iter().any(|x| x.eq_ignore_ascii_case(e)))
787}
788
789#[cfg(test)]
790mod tests {
791 use super::*;
792 use crate::provenance::Confidence;
793
794 #[derive(Debug)]
795 struct PathOnly;
796
797 impl FormatReader for PathOnly {
798 fn descriptor(&self) -> FormatDescriptor {
799 FormatDescriptor {
800 id: "path-only".into(),
801 name: "Path-only test format".into(),
802 vendor: String::new(),
803 extensions: vec!["po".into()],
804 family: "test".into(),
805 can_read: true,
806 can_write: false,
807 confidence: Confidence::Low,
808 known_gaps: Vec::new(),
809 }
810 }
811 fn sniff(&self, head: &[u8], _path: &Path) -> Option<Detection> {
812 head.starts_with(b"PO").then_some(Detection {
813 format_id: "path-only",
814 confidence: DetectConfidence::Definite,
815 note: None,
816 })
817 }
818 fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
819 Err(Error::Other(format!("opened {}", path.display())))
820 }
821 }
822
823 #[test]
824 fn unmigrated_readers_refuse_non_file_inputs() {
825 let reg = Registry::new().with(Box::new(PathOnly));
826 let input = Input::from_bytes("x.po", b"PO data".to_vec());
827 let (r, det) = reg.detect_input(&input).unwrap();
828 assert_eq!(det.format_id, "path-only");
829 assert!(!r.reads_any_source());
830 let err = reg.open_input(&input).map(|_| ()).unwrap_err();
831 assert_eq!(err.exit_code(), 6, "{err}");
832 assert!(err.hint().is_some());
833 let dir = tempfile::tempdir().unwrap();
835 let path = dir.path().join("x.po");
836 std::fs::write(&path, b"PO data").unwrap();
837 let err = reg
838 .open_input(&Input::local(&path))
839 .map(|_| ())
840 .unwrap_err();
841 assert!(err.to_string().starts_with("opened "), "{err}");
842 let empty = Input::from_bytes("e.po", Vec::new());
844 let code = |i: &Input| reg.detect_input(i).map(|_| ()).unwrap_err().exit_code();
845 assert_eq!(code(&empty), 4);
846 assert_eq!(code(&empty.with_path("other.po")), 5);
847 }
848
849 #[derive(Debug)]
851 struct ByName;
852
853 impl FormatReader for ByName {
854 fn descriptor(&self) -> FormatDescriptor {
855 FormatDescriptor {
856 extensions: vec!["ext".into()],
857 ..PathOnly.descriptor()
858 }
859 }
860 fn sniff(&self, _head: &[u8], path: &Path) -> Option<Detection> {
861 (path.extension()? == "ext").then_some(Detection {
862 format_id: "by-name",
863 confidence: DetectConfidence::ExtensionOnly,
864 note: None,
865 })
866 }
867 fn open(&self, _path: &Path) -> Result<Box<dyn Dataset>> {
868 Err(Error::corrupt("by-name", "no signature"))
869 }
870 }
871
872 #[test]
873 fn apple_double_files_are_not_data() {
874 let reg = Registry::new().with(Box::new(ByName));
875 let dir = tempfile::tempdir().unwrap();
876 let path = dir.path().join("._spectrum.ext");
877 let mut b = vec![0x00, 0x05, 0x16, 0x07, 0x00, 0x02, 0x00, 0x00];
878 b.extend_from_slice(b"Mac OS X ");
879 std::fs::write(&path, &b).unwrap();
880 let err = reg.open(&path).map(|_| ()).unwrap_err();
881 assert_eq!(err.exit_code(), 3, "{err}");
882 assert!(err.hint().unwrap().contains("AppleDouble"));
883 let err = reg.detect_bytes(&b, &path).map(|_| ()).unwrap_err();
884 assert_eq!(err.exit_code(), 3, "{err}");
885 }
886
887 #[test]
888 fn extension_only_failures_say_only_the_extension_matched() {
889 let reg = Registry::new().with(Box::new(ByName));
890 let dir = tempfile::tempdir().unwrap();
891 let path = dir.path().join("model.ext");
892 std::fs::write(&path, b"{\"json\": true}").unwrap();
893 let err = reg.open(&path).map(|_| ()).unwrap_err();
894 assert_eq!(err.exit_code(), 4);
895 assert!(
896 err.to_string().contains("only the file extension matched"),
897 "{err}"
898 );
899 assert!(err.hint().unwrap().contains("another kind of file"));
900 }
901}
902
903#[cfg(test)]
904mod level_tests {
905 use super::*;
906 use crate::model::{CheckReport, FileInfo, LsEntry, Spectrum};
907
908 struct Run {
910 levels: Vec<u32>,
911 indexed: bool,
912 reads: u64,
913 }
914 impl Dataset for Run {
915 fn info(&self) -> Result<FileInfo> {
916 Err(Error::Other("unused".into()))
917 }
918 fn vendor_metadata(&self) -> Result<serde_json::Value> {
919 Ok(serde_json::Value::Null)
920 }
921 fn provenance(&self) -> ProvenanceMap {
922 ProvenanceMap::new()
923 }
924 fn entries(&self) -> Result<Vec<LsEntry>> {
925 Ok(vec![])
926 }
927 fn read_plane(&mut self, _: u32, _: PlaneIndex) -> Result<Plane> {
928 Err(Error::Other("unused".into()))
929 }
930 fn check(&mut self) -> Result<CheckReport> {
931 Ok(CheckReport::new("fake", "fake"))
932 }
933 fn read_spectrum(&mut self, _: u32, i: u64) -> Result<Spectrum> {
934 self.reads += 1;
935 Ok(Spectrum {
936 index: i,
937 ms_level: self.levels[i as usize],
938 ..Spectrum::default()
939 })
940 }
941 fn spectrum_ms_levels(&mut self, _: u32) -> Result<Option<Vec<u32>>> {
942 Ok(self.indexed.then(|| self.levels.clone()))
943 }
944 }
945
946 #[test]
947 fn spectrum_of_level_uses_the_index_when_there_is_one() {
948 for indexed in [true, false] {
949 let mut r = Run {
950 levels: vec![1, 2, 2, 1, 2],
951 indexed,
952 reads: 0,
953 };
954 let sp = spectrum_by_level(&mut r, 0, 2, 2, 5, SpectrumView::Primary).unwrap();
955 assert_eq!(sp.index, 4);
956 assert_eq!(r.reads, if indexed { 1 } else { 5 });
957 let err = spectrum_by_level(&mut r, 0, 2, 3, 5, SpectrumView::Primary).unwrap_err();
958 assert!(err.to_string().contains("has 3 MS2 spectra"), "{err}");
959 }
960 }
961}