NdbTagIterator.swift (1423B)
1 // 2 // NdbTagIterators.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-07-21. 6 // 7 8 import Foundation 9 10 11 /// The sequence of strings in a single nostr event tag 12 /// 13 /// Example 1: 14 /// ```json 15 /// ["r", "wss://nostr-relay.example.com", "read"] 16 /// ``` 17 /// 18 /// Example 2: 19 /// ```json 20 /// ["p", "8b2be0a0ad34805d76679272c28a77dbede9adcbfdca48c681ec8b624a1208a6"] 21 /// ``` 22 struct TagSequence: Sequence { 23 let note: NdbNote 24 let tag: ndb_tag_ptr 25 26 var count: UInt16 { 27 ndb_tag_count(tag.ptr) 28 } 29 30 func strings() -> [String] { 31 return self.map { $0.string() } 32 } 33 34 subscript(index: Int) -> NdbTagElem { 35 precondition(index < count, "Index out of bounds") 36 37 return NdbTagElem(note: note, tag: tag, index: Int32(index)) 38 } 39 40 func makeIterator() -> TagIterator { 41 return TagIterator(note: note, tag: tag) 42 } 43 } 44 45 struct TagIterator: IteratorProtocol { 46 typealias Element = NdbTagElem 47 48 mutating func next() -> NdbTagElem? { 49 guard index < ndb_tag_count(tag.ptr) else { return nil } 50 let el = NdbTagElem(note: note, tag: tag, index: index) 51 52 index += 1 53 54 return el 55 } 56 57 var index: Int32 58 let note: NdbNote 59 var tag: ndb_tag_ptr 60 61 var count: UInt16 { 62 ndb_tag_count(tag.ptr) 63 } 64 65 init(note: NdbNote, tag: ndb_tag_ptr) { 66 self.note = note 67 self.tag = tag 68 self.index = 0 69 } 70 }