Skip to content

Commit 0715e95

Browse files
committed
Fix blob equality
1 parent 3b91a00 commit 0715e95

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

Sources/SQLite/Core/Blob.swift

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ public final class Blob {
3636
}
3737

3838
public convenience init(bytes: [UInt8]) {
39+
guard bytes.count > 0 else {
40+
self.init(data: NSData())
41+
return
42+
}
3943
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count)
4044
for idx in 0..<bytes.count {
4145
buffer.advanced(by: idx).pointee = bytes[idx]
@@ -54,10 +58,12 @@ public final class Blob {
5458
}
5559

5660
public init(data: NSData) {
61+
precondition(!(data is NSMutableData), "Blob cannot be initialized with mutable data")
5762
self.data = data
5863
}
5964

6065
public func toHex() -> String {
66+
guard length > 0 else { return "" }
6167
let bytes = bytes.assumingMemoryBound(to: UInt8.self)
6268

6369
var hex = ""
@@ -85,5 +91,5 @@ extension Blob: Equatable {
8591
}
8692

8793
public func ==(lhs: Blob, rhs: Blob) -> Bool {
88-
lhs.bytes == rhs.bytes
94+
lhs.data == rhs.data
8995
}

Tests/SQLiteTests/Core/BlobTests.swift

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@ class BlobTests: XCTestCase {
55

66
func test_toHex() {
77
let blob = Blob(bytes: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 250, 255])
8-
98
XCTAssertEqual(blob.toHex(), "000a141e28323c46505a6496faff")
109
}
1110

11+
func test_toHex_empty() {
12+
let blob = Blob(bytes: [])
13+
XCTAssertEqual(blob.toHex(), "")
14+
}
15+
1216
func test_init_array() {
1317
let blob = Blob(bytes: [42, 42, 42])
1418
XCTAssertEqual(blob.byteArray, [42, 42, 42])
@@ -20,6 +24,16 @@ class BlobTests: XCTestCase {
2024
let blob = Blob(bytes: pointer, length: 3)
2125
XCTAssertEqual(blob.byteArray, [42, 42, 42])
2226
}
27+
28+
func test_equality() {
29+
let blob1 = Blob(bytes: [42, 42, 42])
30+
let blob2 = Blob(bytes: [42, 42, 42])
31+
let blob3 = Blob(bytes: [42, 42, 43])
32+
33+
XCTAssertEqual(Blob(bytes: []), Blob(bytes: []))
34+
XCTAssertEqual(blob1, blob2)
35+
XCTAssertNotEqual(blob1, blob3)
36+
}
2337
}
2438

2539
extension Blob {

0 commit comments

Comments
 (0)