|
21 | 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
22 | 22 | // THE SOFTWARE. |
23 | 23 | // |
| 24 | +import Foundation |
24 | 25 |
|
25 | | -public struct Blob { |
| 26 | +public final class Blob { |
26 | 27 |
|
27 | | - public let bytes: [UInt8] |
| 28 | + public let data: NSData |
28 | 29 |
|
29 | | - public init(bytes: [UInt8]) { |
30 | | - self.bytes = bytes |
| 30 | + public var bytes: UnsafeRawPointer { |
| 31 | + data.bytes |
31 | 32 | } |
32 | 33 |
|
33 | | - public init(bytes: UnsafeRawPointer, length: Int) { |
34 | | - let i8bufptr = UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: length) |
35 | | - self.init(bytes: [UInt8](i8bufptr)) |
| 34 | + public var length: Int { |
| 35 | + data.count |
36 | 36 | } |
37 | 37 |
|
38 | | - public func toHex() -> String { |
39 | | - bytes.map { |
40 | | - ($0 < 16 ? "0" : "") + String($0, radix: 16, uppercase: false) |
41 | | - }.joined(separator: "") |
| 38 | + public convenience init(bytes: [UInt8]) { |
| 39 | + let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count) |
| 40 | + for idx in 0..<bytes.count { |
| 41 | + buffer.advanced(by: idx).pointee = bytes[idx] |
| 42 | + } |
| 43 | + |
| 44 | + let data = NSData( |
| 45 | + bytesNoCopy: UnsafeMutableRawPointer(buffer), |
| 46 | + length: bytes.count, |
| 47 | + freeWhenDone: true |
| 48 | + ) |
| 49 | + self.init(data: data) |
42 | 50 | } |
43 | 51 |
|
| 52 | + public convenience init(bytes: UnsafeRawPointer, length: Int) { |
| 53 | + self.init(data: NSData(bytes: bytes, length: length)) |
| 54 | + } |
| 55 | + |
| 56 | + public init(data: NSData) { |
| 57 | + self.data = data |
| 58 | + } |
| 59 | + |
| 60 | + public func toHex() -> String { |
| 61 | + let bytes = bytes.assumingMemoryBound(to: UInt8.self) |
| 62 | + |
| 63 | + var hex = "" |
| 64 | + for idx in 0..<length { |
| 65 | + let byte = bytes.advanced(by: idx).pointee |
| 66 | + if byte < 16 { |
| 67 | + hex += "0" |
| 68 | + } |
| 69 | + hex += String(byte, radix: 16, uppercase: false) |
| 70 | + } |
| 71 | + return hex |
| 72 | + } |
44 | 73 | } |
45 | 74 |
|
46 | 75 | extension Blob: CustomStringConvertible { |
|
0 commit comments