Skip to main content

x509_validator/
store.rs

1use std::collections::HashMap;
2
3use crate::{Certificate, CertificateExt};
4
5/// A collection of certificates for use in verification.
6#[derive(Debug, Clone)]
7pub struct CertificateStore<'a> {
8    by_subject: HashMap<Vec<u8>, Vec<Certificate<'a>>>, // keyed by subject's raw DER bytes
9}
10
11impl<'a> Default for CertificateStore<'a> {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17/// Initialize a certificate store from a sequence of certificates.
18impl<'a> FromIterator<Certificate<'a>> for CertificateStore<'a> {
19    fn from_iter<T: IntoIterator<Item = Certificate<'a>>>(certificates: T) -> Self {
20        let mut store = Self::new();
21        for cert in certificates {
22            store.append(cert);
23        }
24        store
25    }
26}
27
28impl<'a> CertificateStore<'a> {
29    pub fn new() -> Self {
30        Self {
31            by_subject: HashMap::new(),
32        }
33    }
34
35    pub fn append(&mut self, certificate: Certificate<'a>) {
36        let key = certificate.subject_key();
37        self.by_subject
38            .entry(key)
39            .or_default()
40            .push(certificate);
41    }
42
43    pub fn find_by_subject(&self, subject_key: &[u8]) -> &[Certificate<'a>] {
44        self.by_subject
45            .get(subject_key)
46            .map(Vec::as_slice)
47            .unwrap_or(&[])
48    }
49}