rustls_cert_file_reader/
reader.rs

1//! Certificate and key files reader.
2
3use std::{io, marker::PhantomData, path::PathBuf};
4
5use crate::Format;
6
7/// Reads the files.
8#[derive(Debug)]
9pub struct FileReader<T> {
10    /// The file path to read.
11    pub path: PathBuf,
12    /// The file format to read.
13    pub format: Format,
14    /// The indicator of what's being read.
15    pub reading: PhantomData<T>,
16}
17
18impl<T> FileReader<T> {
19    /// Create a new [`FileReader`].
20    pub fn new(path: impl Into<PathBuf>, format: Format) -> Self {
21        let path = path.into();
22        let reading = PhantomData;
23        Self {
24            path,
25            format,
26            reading,
27        }
28    }
29
30    /// Read the references file as raw bytes.
31    async fn read_file(&self) -> Result<Vec<u8>, io::Error> {
32        tokio::fs::read(&self.path).await
33    }
34}
35
36impl rustls_cert_read::ReadCerts for FileReader<Vec<rustls_pki_types::CertificateDer<'_>>> {
37    type Error = io::Error;
38
39    async fn read_certs(
40        &self,
41    ) -> Result<Vec<rustls_pki_types::CertificateDer<'static>>, Self::Error> {
42        let data = self.read_file().await?;
43        match self.format {
44            Format::DER => Ok(vec![data.into()]),
45            Format::PEM => {
46                let mut cursor = std::io::Cursor::new(data);
47                crate::pem::parse_certs(&mut cursor)
48            }
49        }
50    }
51}
52
53impl rustls_cert_read::ReadKey for FileReader<rustls_pki_types::PrivateKeyDer<'_>> {
54    type Error = io::Error;
55
56    async fn read_key(&self) -> Result<rustls_pki_types::PrivateKeyDer<'static>, Self::Error> {
57        let data = self.read_file().await?;
58        match self.format {
59            Format::DER => Ok(rustls_pki_types::PrivateKeyDer::Pkcs8(data.into())),
60            Format::PEM => {
61                let mut cursor = std::io::Cursor::new(data);
62                crate::pem::parse_key(&mut cursor)
63            }
64        }
65    }
66}