noodles_fasta/fai/async/
fs.rs

1//! Async FAI filesystem operations.
2
3use std::path::Path;
4
5use tokio::{
6    fs::File,
7    io::{self, BufReader, BufWriter},
8};
9
10use super::io::{Reader, Writer};
11use crate::fai::Index;
12
13/// Reads the entire contents of a FASTA index.
14///
15/// This is a convenience function and is equivalent to opening the file at the given path and
16/// parsing each record.
17///
18/// # Examples
19///
20/// ```no_run
21/// # #[tokio::main]
22/// # async fn main() -> tokio::io::Result<()> {
23/// use noodles_fasta::fai;
24/// let index = fai::r#async::fs::read("reference.fa.fai").await?;
25/// # Ok(())
26/// # }
27/// ```
28pub async fn read<P>(src: P) -> io::Result<Index>
29where
30    P: AsRef<Path>,
31{
32    let mut reader = File::open(src).await.map(BufReader::new).map(Reader::new)?;
33    reader.read_index().await
34}
35
36/// Writes a FASTA index to a file.
37///
38/// This is a convenience function and is equivalent to creating a file at the given path and
39/// writing the index.
40///
41/// # Examples
42///
43/// ```no_run
44/// # #[tokio::main]
45/// # async fn main() -> tokio::io::Result<()> {
46/// use noodles_fasta::fai;
47/// let index = fai::Index::default();
48/// fai::r#async::fs::write("reference.fa.fai", &index).await?;
49/// # Ok(())
50/// # }
51/// ```
52pub async fn write<P>(dst: P, index: &Index) -> io::Result<()>
53where
54    P: AsRef<Path>,
55{
56    let mut writer = File::create(dst)
57        .await
58        .map(BufWriter::new)
59        .map(Writer::new)?;
60
61    writer.write_index(index).await?;
62
63    writer.shutdown().await?;
64
65    Ok(())
66}