use std::fmt::Debug;
use std::sync::Arc;
use base_xx::{
ByteVec, SerialiseError,
byte_vec::{Encodable, TryIntoByteVec},
encoded_string::Decodable,
};
use crate::signing_algorithm::SigningAlgorithm;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Signature {
algorithm: SigningAlgorithm,
signature: Arc<ByteVec>,
}
impl Default for Signature {
fn default() -> Self {
Self {
algorithm: SigningAlgorithm::ED25519,
signature: Arc::new(ByteVec::new(Arc::new(vec![0u8; 64]))),
}
}
}
impl Signature {
#[must_use]
pub const fn new(signature: Arc<ByteVec>) -> Self {
Self {
algorithm: SigningAlgorithm::ED25519,
signature,
}
}
#[must_use]
pub const fn new_with_algorithm(algorithm: SigningAlgorithm, signature: Arc<ByteVec>) -> Self {
Self {
algorithm,
signature,
}
}
#[must_use]
pub fn get_signature(&self) -> Arc<ByteVec> {
Arc::clone(&self.signature)
}
#[must_use]
pub const fn get_algorithm(&self) -> SigningAlgorithm {
self.algorithm
}
}
impl TryIntoByteVec for Signature {
fn try_into_byte_vec(value: Arc<Self>) -> Result<Arc<ByteVec>, SerialiseError> {
let algorithm: u8 = value.get_algorithm().into();
let mut bytes = vec![algorithm];
bytes.extend_from_slice(value.get_signature().get_bytes());
Ok(Arc::new(ByteVec::new(Arc::new(bytes))))
}
}
impl TryFrom<Arc<ByteVec>> for Signature {
type Error = SerialiseError;
fn try_from(value: Arc<ByteVec>) -> Result<Self, Self::Error> {
match SigningAlgorithm::try_from(value.get_bytes()[0]) {
Ok(algorithm) => {
let bytes = value.get_bytes()[1..].to_vec();
Ok(Self::new_with_algorithm(
algorithm,
Arc::new(ByteVec::new(Arc::new(bytes))),
))
}
Err(e) => Err(e),
}
}
}
impl Encodable for Signature {}
impl Decodable for Signature {}