use std::str::FromStr;
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[derive(Debug, Clone, Eq)]
#[napi]
pub struct PublicKey {
key: [u8; 32],
}
impl From<iroh::PublicKey> for PublicKey {
fn from(key: iroh::PublicKey) -> Self {
PublicKey {
key: *key.as_bytes(),
}
}
}
impl From<&PublicKey> for iroh::PublicKey {
fn from(key: &PublicKey) -> Self {
let key: &[u8] = &key.key[..];
key.try_into().unwrap()
}
}
#[napi]
impl PublicKey {
#[napi]
pub fn is_equal(&self, other: &PublicKey) -> bool {
*self == *other
}
#[napi]
pub fn to_bytes(&self) -> Vec<u8> {
self.key.to_vec()
}
#[napi(factory)]
pub fn from_string(s: String) -> Result<Self> {
let key = iroh::PublicKey::from_str(&s).map_err(anyhow::Error::from)?;
Ok(key.into())
}
#[napi(factory)]
pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
if bytes.len() != 32 {
return Err(anyhow::anyhow!("the PublicKey must be 32 bytes in length").into());
}
let bytes: [u8; 32] = bytes.try_into().expect("checked above");
let key = iroh::PublicKey::from_bytes(&bytes).map_err(anyhow::Error::from)?;
Ok(key.into())
}
#[napi]
pub fn fmt_short(&self) -> String {
iroh::PublicKey::from(self).fmt_short()
}
#[napi]
pub fn to_string(&self) -> String {
iroh::PublicKey::from(self).to_string()
}
}
impl PartialEq for PublicKey {
fn eq(&self, other: &PublicKey) -> bool {
self.key == other.key
}
}