commit 9a48b12e3620e8978f10287faf2d975adaea5952
parent f9a09ea2be96917e301dcddd1aeb80838f0da74f
Author: William Casarin <jb55@jb55.com>
Date: Sun, 19 Jan 2025 12:39:27 -0800
enostr: introduce PubkeyRef
This will be used for typesafe and copy-free pubkey references
Signed-off-by: William Casarin <jb55@jb55.com>
Diffstat:
1 file changed, 44 insertions(+), 0 deletions(-)
diff --git a/crates/enostr/src/pubkey.rs b/crates/enostr/src/pubkey.rs
@@ -1,6 +1,7 @@
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::Error;
+use std::borrow::Borrow;
use std::fmt;
use std::ops::Deref;
use tracing::debug;
@@ -8,8 +9,35 @@ use tracing::debug;
#[derive(Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd)]
pub struct Pubkey([u8; 32]);
+#[derive(Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd)]
+pub struct PubkeyRef<'a>(&'a [u8; 32]);
+
static HRP_NPUB: bech32::Hrp = bech32::Hrp::parse_unchecked("npub");
+impl<'a> Borrow<[u8; 32]> for PubkeyRef<'a> {
+ fn borrow(&self) -> &[u8; 32] {
+ self.0
+ }
+}
+
+impl<'a> PubkeyRef<'a> {
+ pub fn new(bytes: &'a [u8; 32]) -> Self {
+ Self(bytes)
+ }
+
+ pub fn bytes(&self) -> &[u8; 32] {
+ self.0
+ }
+
+ pub fn to_owned(&self) -> Pubkey {
+ Pubkey::new(*self.bytes())
+ }
+
+ pub fn hex(&self) -> String {
+ hex::encode(self.bytes())
+ }
+}
+
impl Deref for Pubkey {
type Target = [u8; 32];
@@ -18,6 +46,12 @@ impl Deref for Pubkey {
}
}
+impl Borrow<[u8; 32]> for Pubkey {
+ fn borrow(&self) -> &[u8; 32] {
+ &self.0
+ }
+}
+
impl Pubkey {
pub fn new(data: [u8; 32]) -> Self {
Self(data)
@@ -31,6 +65,10 @@ impl Pubkey {
&self.0
}
+ pub fn as_ref(&self) -> PubkeyRef<'_> {
+ PubkeyRef(self.bytes())
+ }
+
pub fn parse(s: &str) -> Result<Self, Error> {
match Pubkey::from_hex(s) {
Ok(pk) => Ok(pk),
@@ -88,6 +126,12 @@ impl fmt::Display for Pubkey {
}
}
+impl fmt::Debug for PubkeyRef<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.hex())
+ }
+}
+
impl fmt::Debug for Pubkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.hex())