From f9a09ea2be96917e301dcddd1aeb80838f0da74f Mon Sep 17 00:00:00 2001 From: William Casarin Date: Fri, 17 Jan 2025 12:40:24 -0800 Subject: [PATCH] note: introduce RootNoteId RootNoteId is simply a newtype for specifying an ID that is a root note id (in the sense of a nip10 note) This makes it more clear at the type level when referring to note ids Signed-off-by: William Casarin --- crates/notedeck/src/note.rs | 74 +++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/crates/notedeck/src/note.rs b/crates/notedeck/src/note.rs index ac4fef39..1ce4aeee 100644 --- a/crates/notedeck/src/note.rs +++ b/crates/notedeck/src/note.rs @@ -1,5 +1,7 @@ use crate::notecache::NoteCache; +use enostr::NoteId; use nostrdb::{Ndb, Note, NoteKey, QueryResult, Transaction}; +use std::borrow::Borrow; use std::cmp::Ordering; #[derive(Debug, Eq, PartialEq, Copy, Clone)] @@ -8,6 +10,78 @@ pub struct NoteRef { pub created_at: u64, } +#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] +pub struct RootNoteIdBuf([u8; 32]); + +#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] +pub struct RootNoteId<'a>(&'a [u8; 32]); + +impl RootNoteIdBuf { + pub fn to_note_id(self) -> NoteId { + NoteId::new(self.0) + } + + pub fn bytes(&self) -> &[u8; 32] { + &self.0 + } + + pub fn new( + ndb: &Ndb, + note_cache: &mut NoteCache, + txn: &Transaction, + id: &[u8; 32], + ) -> Result { + root_note_id_from_selected_id(ndb, note_cache, txn, id).map(|rnid| Self(*rnid.bytes())) + } + + pub fn new_unsafe(id: [u8; 32]) -> Self { + Self(id) + } + + pub fn borrow(&self) -> RootNoteId<'_> { + RootNoteId(self.bytes()) + } +} + +impl<'a> RootNoteId<'a> { + pub fn to_note_id(self) -> NoteId { + NoteId::new(*self.0) + } + + pub fn bytes(&self) -> &[u8; 32] { + self.0 + } + + pub fn to_owned(&self) -> RootNoteIdBuf { + RootNoteIdBuf::new_unsafe(*self.bytes()) + } + + pub fn new( + ndb: &Ndb, + note_cache: &mut NoteCache, + txn: &'a Transaction, + id: &'a [u8; 32], + ) -> Result, RootIdError> { + root_note_id_from_selected_id(ndb, note_cache, txn, id) + } + + pub fn new_unsafe(id: &'a [u8; 32]) -> Self { + Self(id) + } +} + +impl Borrow<[u8; 32]> for RootNoteIdBuf { + fn borrow(&self) -> &[u8; 32] { + &self.0 + } +} + +impl<'a> Borrow<[u8; 32]> for RootNoteId<'a> { + fn borrow(&self) -> &[u8; 32] { + self.0 + } +} + impl NoteRef { pub fn new(key: NoteKey, created_at: u64) -> Self { NoteRef { key, created_at }