noodles_bcf/io/writer/
builder.rs

1use std::{
2    fs::File,
3    io::{self, BufWriter, Write},
4    path::Path,
5};
6
7use noodles_bgzf as bgzf;
8
9use super::Writer;
10use crate::io::CompressionMethod;
11
12/// A BCF writer builder.
13#[derive(Debug, Default)]
14pub struct Builder {
15    compression_method: Option<CompressionMethod>,
16}
17
18impl Builder {
19    /// Sets the compression method.
20    ///
21    /// # Examples
22    ///
23    /// ```
24    /// use noodles_bcf::io::{writer::Builder, CompressionMethod};
25    /// let builder = Builder::default().set_compression_method(CompressionMethod::Bgzf);
26    /// ```
27    pub fn set_compression_method(mut self, compression_method: CompressionMethod) -> Self {
28        self.compression_method = Some(compression_method);
29        self
30    }
31
32    /// Builds a BCF writer from a path.
33    ///
34    /// # Examples
35    ///
36    /// ```no_run
37    /// use noodles_bcf::io::writer::Builder;
38    /// let writer = Builder::default().build_from_path("out.bam")?;
39    /// # Ok::<_, std::io::Error>(())
40    /// ```
41    pub fn build_from_path<P>(self, dst: P) -> io::Result<Writer<Box<dyn Write>>>
42    where
43        P: AsRef<Path>,
44    {
45        let file = File::create(dst)?;
46        Ok(self.build_from_writer(file))
47    }
48
49    /// Builds a BCF writer from a writer.
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// # use std::io;
55    /// use noodles_bcf::io::writer::Builder;
56    /// let writer = Builder::default().build_from_writer(io::sink());
57    /// ```
58    pub fn build_from_writer<'w, W>(self, writer: W) -> Writer<Box<dyn Write + 'w>>
59    where
60        W: Write + 'w,
61    {
62        let inner: Box<dyn Write> = match self.compression_method {
63            Some(CompressionMethod::Bgzf) | None => Box::new(bgzf::Writer::new(writer)),
64            Some(CompressionMethod::None) => Box::new(BufWriter::new(writer)),
65        };
66
67        Writer::from(inner)
68    }
69}