Skip to main content

solti_tls/
source.rs

1//! Abstract source of PEM bytes: file path or in-memory buffer.
2
3use std::path::PathBuf;
4
5use crate::TlsError;
6
7/// Where a PEM blob lives.
8#[derive(Debug, Clone)]
9pub enum PemSource {
10    /// PEM file on disk; read at `into_rustls_config()` time.
11    Path(PathBuf),
12    /// Already-loaded PEM bytes.
13    Bytes(Vec<u8>),
14}
15
16impl PemSource {
17    /// Read the PEM bytes from source:
18    /// - [`PemSource::Path`] opens the file;
19    /// - [`PemSource::Bytes`] it returns a clone of the in-memory buffer.
20    pub fn read(&self) -> Result<Vec<u8>, TlsError> {
21        match self {
22            PemSource::Path(p) => Ok(std::fs::read(p)?),
23            PemSource::Bytes(b) => Ok(b.clone()),
24        }
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use std::io::Write;
32
33    #[test]
34    fn read_returns_bytes_variant_verbatim() {
35        let src = PemSource::Bytes(b"hello pem".to_vec());
36        let out = src.read().unwrap();
37        assert_eq!(out, b"hello pem");
38    }
39
40    #[test]
41    fn read_loads_path_variant_from_disk() {
42        let mut tmp = tempfile::NamedTempFile::new().unwrap();
43        tmp.write_all(b"on-disk bytes").unwrap();
44
45        let src = PemSource::Path(tmp.path().to_path_buf());
46        let out = src.read().unwrap();
47        assert_eq!(out, b"on-disk bytes");
48    }
49
50    #[test]
51    fn read_returns_io_error_for_missing_path() {
52        let src = PemSource::Path("/definitely/does/not/exist.pem".into());
53        let err = src.read().unwrap_err();
54        assert!(matches!(err, crate::TlsError::Io(_)));
55    }
56}