Skip to content

Instantly share code, notes, and snippets.

@myobie
Created March 11, 2021 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/09bf6d6635bfc26c093e1b5ccaa4c1b8 to your computer and use it in GitHub Desktop.
Save myobie/09bf6d6635bfc26c093e1b5ccaa4c1b8 to your computer and use it in GitHub Desktop.
import Foundation
public struct Identifier:
Codable, CustomStringConvertible, ExpressibleByStringLiteral,
Hashable, RawRepresentable
{
public let rawValue: [UInt8]
public let dataValue: Data
private let stringValue: String
public var description: String { stringValue }
public var ns_string: NSString { stringValue as NSString }
public init() {
self.init(ofSize: 16)
}
public init(ofSize count: Int) {
var bytes = [UInt8](repeating: 0, count: count)
if SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) != errSecSuccess {
fatalError("Cannot generate random bytes so we are dead...")
}
self.init(rawValue: bytes)
}
public init(rawValue: [UInt8]) {
self.rawValue = rawValue
self.dataValue = Data(rawValue)
self.stringValue = rawValue.map { String($0, radix: 16) }.joined()
}
public init(data: Data) {
self.init(rawValue: data.map { $0 })
}
public init(string: String) {
if string.count % 2 == 0 && string.allSatisfy({ $0.isHexDigit }) {
let bytes = stride(from: 0, to: string.count, by: 2).map { i -> UInt8 in
let startIndex = string.index(string.startIndex, offsetBy: i)
let endIndex = string.index(string.startIndex, offsetBy: i + 1)
return UInt8(string[startIndex ..< endIndex], radix: 16)!
}
self.init(rawValue: bytes)
} else {
self.init(rawValue: string.utf8.map { $0 })
}
}
public init(stringLiteral value: String) {
self.init(string: value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment