damus

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

AsciiCharacter.swift (1109B)


      1 //
      2 //  AsciiCharacter.swift
      3 //  damus
      4 //
      5 //  Created by William Casarin on 2023-07-21.
      6 //
      7 
      8 import Foundation
      9 
     10 struct AsciiCharacter: ExpressibleByStringLiteral, CustomStringConvertible, Equatable, Hashable {
     11     private let value: UInt8
     12 
     13     var cchar: CChar {
     14         return CChar(bitPattern: value)
     15     }
     16 
     17     var description: String {
     18         return String(UnicodeScalar(UInt8(bitPattern: cchar)))
     19     }
     20 
     21     init?(_ cchar: CChar) {
     22         guard cchar < 127 else { return nil }
     23         self.value = UInt8(cchar)
     24     }
     25 
     26     init?(_ character: Character) {
     27         guard let asciiValue = character.asciiValue, asciiValue < 128 else {
     28             return nil
     29         }
     30         self.value = asciiValue
     31     }
     32 
     33     // MARK: - ExpressibleByStringLiteral conformance
     34     init(stringLiteral value: StringLiteralType) {
     35         guard value.count == 1, let character = value.first, let ascii = AsciiCharacter(character) else {
     36             fatalError("Invalid ASCII character initialization.")
     37         }
     38         self = ascii
     39     }
     40 
     41     var character: Character {
     42         return Character(UnicodeScalar(value))
     43     }
     44 }