UnownedNdbNote.swift (2571B)
1 // 2 // UnownedNdbNote.swift 3 // damus 4 // 5 // Created by Daniel D’Aquino on 2025-03-25. 6 // 7 8 /// A function that allows an unowned NdbNote to be lent out temporarily 9 /// 10 /// Use this to provide access to NostrDB unowned notes in a way that has much better compile-time safety guarantees. 11 /// 12 /// # Usage examples 13 /// 14 /// ## Lending out or providing Ndb notes 15 /// 16 /// ```swift 17 /// // Define the lender 18 /// let lender: NdbNoteLender = { lend in 19 /// guard let ndbNoteTxn = ndb.lookup_note(noteId) else { // Note: Must have access to `Ndb` 20 /// throw NdbNoteLenderError.errorLoadingNote // Throw errors if loading fails 21 /// } 22 /// guard let unownedNote = UnownedNdbNote(ndbNoteTxn) else { 23 /// throw NdbNoteLenderError.errorLoadingNote 24 /// } 25 /// lend(unownedNote) // Lend out the Unowned Ndb note 26 /// } 27 /// return lender // Return or pass the lender to another class 28 /// ``` 29 /// 30 /// ## Borrowing Ndb notes 31 /// 32 /// Assuming you are given a lender, here is how you can use it: 33 /// 34 /// ```swift 35 /// let borrow: NdbNoteLender = functionThatProvidesALender() 36 /// try? borrow { note in // You can optionally handle errors if borrowing fails 37 /// self.date = note.createdAt // You can do things with the note without copying it over 38 /// // self.note = note // Not allowed by the compiler 39 /// self.note = note.toOwned() // You can copy the note if needed 40 /// } 41 /// ``` 42 typealias NdbNoteLender = ((_: borrowing UnownedNdbNote) -> Void) throws -> Void 43 44 enum NdbNoteLenderError: Error { 45 case errorLoadingNote 46 } 47 48 49 /// A wrapper to NdbNote that allows unowned NdbNotes to be safely handled 50 struct UnownedNdbNote: ~Copyable { 51 private let _ndbNote: NdbNote 52 53 init(_ txn: NdbTxn<NdbNote>) { 54 self._ndbNote = txn.unsafeUnownedValue 55 } 56 57 init?(_ txn: NdbTxn<NdbNote?>) { 58 guard let note = txn.unsafeUnownedValue else { return nil } 59 self._ndbNote = note 60 } 61 62 init(_ ndbNote: NdbNote) { 63 self._ndbNote = ndbNote 64 } 65 66 var kind: UInt32 { _ndbNote.kind } 67 var known_kind: NostrKind? { _ndbNote.known_kind } 68 var content: String { _ndbNote.content } 69 var tags: TagsSequence { _ndbNote.tags } 70 var pubkey: Pubkey { _ndbNote.pubkey } 71 var createdAt: UInt32 { _ndbNote.created_at } 72 var id: NoteId { _ndbNote.id } 73 var sig: Signature { _ndbNote.sig } 74 75 func toOwned() -> NdbNote { 76 return _ndbNote.to_owned() 77 } 78 }