From b356591ea352b34a28e4ff1ea5359ba50a096806 Mon Sep 17 00:00:00 2001 From: Yuki Kishimoto Date: Sat, 4 Jan 2025 11:00:18 +0100 Subject: [PATCH] database: impl `FlatBufferDecodeBorrowed` for `EventBorrow` Signed-off-by: Yuki Kishimoto --- CHANGELOG.md | 1 + crates/nostr-database/src/flatbuffers/mod.rs | 24 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f40ab0af4..02a26035f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ * nostr: add `CowTag` ([Yuki Kishimoto]) * nostr: add `EventBorrow` ([Yuki Kishimoto]) * database: add `Events::first_owned` and `Events::last_owned` ([Yuki Kishimoto]) +* database: impl `FlatBufferDecodeBorrowed` for `EventBorrow` ([Yuki Kishimoto]) * pool: add `Relay::try_connect` ([Yuki Kishimoto]) * pool: add `Relay::wait_for_connection` ([Yuki Kishimoto]) * pool: add `RelayPool::try_connect` ([Yuki Kishimoto]) diff --git a/crates/nostr-database/src/flatbuffers/mod.rs b/crates/nostr-database/src/flatbuffers/mod.rs index 1d94adcae..187ce565b 100644 --- a/crates/nostr-database/src/flatbuffers/mod.rs +++ b/crates/nostr-database/src/flatbuffers/mod.rs @@ -4,6 +4,7 @@ //! Nostr Database Flatbuffers +use std::borrow::Cow; use std::collections::HashSet; use std::fmt; @@ -145,6 +146,29 @@ impl FlatBufferDecode for Event { } } +impl<'a> FlatBufferDecodeBorrowed<'a> for EventBorrow<'a> { + fn decode(buf: &'a [u8]) -> Result { + let ev = event_fbs::root_as_event(buf)?; + + let fb_tags = ev.tags().ok_or(Error::NotFound)?; + let mut tags = Vec::with_capacity(fb_tags.len()); + + for tag in fb_tags.iter().filter_map(|t| t.data()) { + tags.push(CowTag::parse(tag.into_iter().map(Cow::Borrowed).collect())?); + } + + Ok(Self { + id: &ev.id().ok_or(Error::NotFound)?.0, + pubkey: &ev.pubkey().ok_or(Error::NotFound)?.0, + created_at: Timestamp::from_secs(ev.created_at()), + kind: ev.kind() as u16, // TODO: should use try_into + tags, + content: ev.content().ok_or(Error::NotFound)?, + sig: &ev.sig().ok_or(Error::NotFound)?.0, + }) + } +} + impl FlatBufferEncode for HashSet { fn encode<'a>(&self, fbb: &'a mut FlatBufferBuilder) -> &'a [u8] { fbb.reset();