sfs_core/spectrum/io/
write.rs

1//! Utilities for writing spectra.
2
3use std::{fs, io, path::Path};
4
5use crate::{spectrum::State, Spectrum};
6
7use super::{text, Format};
8
9/// A builder to write a spectrum.
10#[derive(Debug)]
11pub struct Builder {
12    format: Format,
13    precision: usize,
14}
15
16impl Builder {
17    /// Set format to write.
18    ///
19    /// If unset, the plain text format will be used.
20    pub fn set_format(mut self, format: Format) -> Self {
21        self.format = format;
22        self
23    }
24
25    /// Set precision.
26    ///
27    /// This is only used for the plain text format.
28    /// If unset, a precision of six digits will be used.
29    pub fn set_precision(mut self, precision: usize) -> Self {
30        self.precision = precision;
31        self
32    }
33
34    /// Write spectrum to writer.
35    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    /// Write spectrum to stdout.
46    pub fn write_to_stdout<S: State>(self, spectrum: &Spectrum<S>) -> io::Result<()> {
47        self.write(&mut io::stdout().lock(), spectrum)
48    }
49
50    /// Write spectrum to path.
51    ///
52    /// If path already exists, it will be overwritten.
53    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    /// Write spectrum to path or stdout.
61    ///
62    /// If the provided path is `None`, read from stdin.
63    /// If path already exists, it will be overwritten.
64    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}