Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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