damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

IdType.swift (1477B)


      1 //
      2 //  IdType.swift
      3 //  damus
      4 //
      5 //  Created by William Casarin on 2023-07-28.
      6 //
      7 
      8 import Foundation
      9 
     10 protocol IdType: Codable, CustomStringConvertible, Hashable, Equatable {
     11     var id: Data { get }
     12 
     13     init(_ data: Data)
     14     init(from decoder: Decoder) throws
     15     func encode(to encoder: Encoder) throws
     16 }
     17 
     18 
     19 extension IdType {
     20     func hex() -> String {
     21         hex_encode(self.id)
     22     }
     23 
     24     var bytes: [UInt8] {
     25         self.id.bytes
     26     }
     27 
     28     static var empty: Self {
     29         return Self.init(Data(repeating: 0, count: 32))
     30     }
     31 
     32     var description: String {
     33         self.hex()
     34     }
     35 
     36     init(from decoder: Decoder) throws {
     37         self.init(try hex_decoder(decoder))
     38     }
     39 
     40     func encode(to encoder: Encoder) throws {
     41         try hex_encoder(to: encoder, data: self.id)
     42     }
     43 }
     44 
     45 func hex_decoder(_ decoder: Decoder, expected_len: Int = 32) throws -> Data {
     46     let container = try decoder.singleValueContainer()
     47     guard let arr = hex_decode(try container.decode(String.self)) else {
     48         throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "hex string"))
     49     }
     50 
     51     if arr.count != expected_len {
     52         throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "too long"))
     53     }
     54 
     55     return Data(bytes: arr, count: arr.count)
     56 }
     57 
     58 func hex_encoder(to encoder: Encoder, data: Data) throws {
     59     var container = encoder.singleValueContainer()
     60     try container.encode(hex_encode(data))
     61 }
     62