use crate::{Error, Result, SubjectPublicKeyInfo};
#[cfg(feature = "alloc")]
use {crate::PublicKeyDocument, der::Document};
#[cfg(feature = "pem")]
use {alloc::string::String, der::pem::LineEnding};
#[cfg(feature = "std")]
use std::path::Path;
pub trait DecodePublicKey:
for<'a> TryFrom<SubjectPublicKeyInfo<'a>, Error = Error> + Sized
{
fn from_public_key_der(bytes: &[u8]) -> Result<Self> {
Self::try_from(SubjectPublicKeyInfo::try_from(bytes)?)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn from_public_key_doc(doc: &PublicKeyDocument) -> Result<Self> {
Self::try_from(doc.decode())
}
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
fn from_public_key_pem(s: &str) -> Result<Self> {
PublicKeyDocument::from_public_key_pem(s).and_then(|doc| Self::from_public_key_doc(&doc))
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
fn read_public_key_der_file(path: impl AsRef<Path>) -> Result<Self> {
PublicKeyDocument::read_public_key_der_file(path)
.and_then(|doc| Self::from_public_key_doc(&doc))
}
#[cfg(all(feature = "pem", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "pem", feature = "std"))))]
fn read_public_key_pem_file(path: impl AsRef<Path>) -> Result<Self> {
PublicKeyDocument::read_public_key_pem_file(path)
.and_then(|doc| Self::from_public_key_doc(&doc))
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub trait EncodePublicKey {
fn to_public_key_der(&self) -> Result<PublicKeyDocument>;
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
fn to_public_key_pem(&self, line_ending: LineEnding) -> Result<String> {
self.to_public_key_der()?.to_public_key_pem(line_ending)
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
fn write_public_key_der_file(&self, path: impl AsRef<Path>) -> Result<()> {
self.to_public_key_der()?.write_public_key_der_file(path)
}
#[cfg(all(feature = "pem", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "pem", feature = "std"))))]
fn write_public_key_pem_file(
&self,
path: impl AsRef<Path>,
line_ending: LineEnding,
) -> Result<()> {
self.to_public_key_der()?
.write_public_key_pem_file(path, line_ending)
}
}