From 93ceba12247177e9868c11e7e7a4b3cb153c1b85 Mon Sep 17 00:00:00 2001 From: Ryan Tate Date: Wed, 20 Nov 2024 12:44:01 -0800 Subject: [PATCH] add try from vec bytes conversion for X5Chain Signed-off-by: Ryan Tate --- src/definitions/helpers/non_empty_vec.rs | 16 ++++++++++++++++ src/definitions/x509/x5chain.rs | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/definitions/helpers/non_empty_vec.rs b/src/definitions/helpers/non_empty_vec.rs index 21123f50..949c634d 100644 --- a/src/definitions/helpers/non_empty_vec.rs +++ b/src/definitions/helpers/non_empty_vec.rs @@ -58,6 +58,22 @@ impl NonEmptyVec { } } +impl NonEmptyVec { + pub fn try_from_iter>(iter: I) -> Result { + let mut v = Vec::new(); + let mut iter = iter.into_iter(); + if let Some(t) = iter.next() { + v.push(t); + } else { + return Err(Error::Empty); + } + for t in iter { + v.push(t); + } + Ok(NonEmptyVec(v)) + } +} + impl TryFrom> for NonEmptyVec { type Error = Error; diff --git a/src/definitions/x509/x5chain.rs b/src/definitions/x509/x5chain.rs index ee836620..1f285637 100644 --- a/src/definitions/x509/x5chain.rs +++ b/src/definitions/x509/x5chain.rs @@ -1,3 +1,4 @@ +use crate::definitions::helpers::non_empty_vec; use crate::definitions::helpers::NonEmptyVec; use crate::definitions::x509::error::Error as X509Error; use crate::definitions::x509::trust_anchor::check_validity_period; @@ -77,6 +78,22 @@ impl From> for X5Chain { } } +impl TryFrom> for X5Chain { + type Error = non_empty_vec::Error; + + fn try_from(v: Vec) -> Result { + NonEmptyVec::try_from_iter(v.into_iter()).map(Self) + } +} + +impl TryFrom>> for X5Chain { + type Error = non_empty_vec::Error; + + fn try_from(v: Vec>) -> Result { + NonEmptyVec::try_from_iter(v.into_iter().map(|bytes| X509 { bytes })).map(Self) + } +} + impl X5Chain { pub fn builder() -> Builder { Builder::default() @@ -124,6 +141,8 @@ impl X5Chain { } } + /// Returns the first certificate in the x.509 certificate chain, + /// which is expected be the reader's certificate. pub fn get_signer_key(&self) -> Result { let leaf = self.0.first().ok_or(X509Error::CborDecodingError)?; leaf.public_key().map(|key| key.into())