sfs_core/spectrum/io/
write.rs1use std::{fs, io, path::Path};
4
5use crate::{spectrum::State, Spectrum};
6
7use super::{text, Format};
8
9#[derive(Debug)]
11pub struct Builder {
12 format: Format,
13 precision: usize,
14}
15
16impl Builder {
17 pub fn set_format(mut self, format: Format) -> Self {
21 self.format = format;
22 self
23 }
24
25 pub fn set_precision(mut self, precision: usize) -> Self {
30 self.precision = precision;
31 self
32 }
33
34 pub fn write<W, S: State>(self, writer: &mut W, spectrum: &Spectrum<S>) -> io::Result<()>
36 where
37 W: io::Write,
38 {
39 match self.format {
40 Format::Text => text::write_spectrum(writer, spectrum, self.precision),
41 Format::Npy => spectrum.array.write_npy(writer),
42 }
43 }
44
45 pub fn write_to_stdout<S: State>(self, spectrum: &Spectrum<S>) -> io::Result<()> {
47 self.write(&mut io::stdout().lock(), spectrum)
48 }
49
50 pub fn write_to_path<P, S: State>(self, path: P, spectrum: &Spectrum<S>) -> io::Result<()>
54 where
55 P: AsRef<Path>,
56 {
57 self.write(&mut fs::File::create(path)?, spectrum)
58 }
59
60 pub fn write_to_path_or_stdout<P, S: State>(
65 self,
66 path: Option<P>,
67 spectrum: &Spectrum<S>,
68 ) -> io::Result<()>
69 where
70 P: AsRef<Path>,
71 {
72 match path {
73 Some(path) => self.write_to_path(path, spectrum),
74 None => self.write_to_stdout(spectrum),
75 }
76 }
77}
78
79impl Default for Builder {
80 fn default() -> Self {
81 Builder {
82 format: Format::Text,
83 precision: 6,
84 }
85 }
86}