Generalise digest hex conversion

This commit is contained in:
a_dinosaur committed 2024-11-23 18:30:04 +11:00
1 parent d9f5052d21
commit c69f2235a4
2 files changed
+26 -22

No files matched your search

+25
View File
@@ -29,4 +29,29 @@ extension Data {
self.append(byte)
}
}
#if DEBUG
private static let hex = Array("0123456789ABCDEF".unicodeScalars)
var asHexString: String {
var s = ""
s.reserveCapacity(self.count * 2)
Self.hex.withUnsafeBufferPointer { hp in
for b in self {
s.unicodeScalars.append(hp[Int(b >> 4)])
s.unicodeScalars.append(hp[Int(b & 15)])
}
}
return s
}
#else
private static let hex = "0123456789ABCDEF".map(\.asciiValue!)
var asHexString: String {
Self.hex.withUnsafeBufferPointer { hp in
let hexChars = self.flatMap { b in
[hp[Int(b >> 4)], hp[Int(b & 15)]]
}
return String(bytes: hexChars, encoding: .ascii)!
}
}
#endif
}