use std::error::Error;
use crate::hex::{bytes_to_hex_str, hex_str_to_bytes, HexError};
#[cfg(feature = "key-load")]
pub(crate) mod load;
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct PublicKey {
bytes: Vec<u8>,
}
impl PublicKey {
pub fn new(bytes: Vec<u8>) -> Self {
Self { bytes }
}
pub fn new_from_hex(hex: &str) -> Result<Self, KeyParseError> {
Ok(Self::new(hex_str_to_bytes(hex)?))
}
pub fn as_hex(&self) -> String {
bytes_to_hex_str(&self.bytes)
}
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
impl std::fmt::Debug for PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("PublicKey")
.field("bytes", &self.as_hex())
.finish()
}
}
impl std::fmt::Display for PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(&self.as_hex())
}
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct PrivateKey {
bytes: Vec<u8>,
}
impl PrivateKey {
pub fn new(bytes: Vec<u8>) -> Self {
Self { bytes }
}
pub fn new_from_hex(hex: &str) -> Result<Self, KeyParseError> {
Ok(Self::new(hex_str_to_bytes(hex)?))
}
pub fn as_hex(&self) -> String {
bytes_to_hex_str(&self.bytes)
}
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
#[derive(Debug)]
pub struct KeyParseError(pub String);
impl Error for KeyParseError {}
impl std::fmt::Display for KeyParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<HexError> for KeyParseError {
fn from(err: HexError) -> Self {
Self(err.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
const KEY_BYTES: &[u8] = &[0x01, 0x02, 0x03, 0x04];
#[test]
fn public_key() {
let key = PublicKey::new(KEY_BYTES.into());
assert_eq!(key.as_hex(), bytes_to_hex_str(KEY_BYTES));
assert_eq!(key.as_slice(), KEY_BYTES);
assert_eq!(key.into_bytes().as_slice(), KEY_BYTES);
}
#[test]
fn private_key() {
let key = PrivateKey::new(KEY_BYTES.into());
assert_eq!(key.as_hex(), bytes_to_hex_str(KEY_BYTES));
assert_eq!(key.as_slice(), KEY_BYTES);
assert_eq!(key.into_bytes().as_slice(), KEY_BYTES);
}
}