Generalise digest hex conversion

This commit is contained in:
2024-11-23 18:30:04 +11:00
parent d9f5052d21
commit c69f2235a4
2 changed files with 26 additions and 22 deletions

View File

@ -105,28 +105,7 @@ extension ApkIndexDigest.DigestType: CustomStringConvertible {
}
extension ApkIndexDigest: CustomStringConvertible {
#if DEBUG
private static let hex = Array("0123456789ABCDEF".unicodeScalars)
public var description: String {
var s = "[\(self.type)] "
s.reserveCapacity(10 + self.data.count * 2)
Self.hex.withUnsafeBufferPointer { hp in
for b in self.data {
s.unicodeScalars.append(hp[Int(b >> 4)])
s.unicodeScalars.append(hp[Int(b & 15)])
}
}
return s
return "[\(self.type)] \(self.data.asHexString)"
}
#else
private static let hex = "0123456789ABCDEF".map(\.asciiValue!)
public var description: String {
Self.hex.withUnsafeBufferPointer { hp in
let hexChars = self.data.flatMap { b in
[hp[Int(b >> 4)], hp[Int(b & 15)]]
}
return "[\(self.type)] \(String(bytes: hexChars, encoding: .ascii)!)"
}
}
#endif
}

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
}