Skip to content

Commit 0ecdc45

Browse files
committed
Fixed decoding nil
1 parent 978c38f commit 0ecdc45

File tree

2 files changed

+24
-33
lines changed

2 files changed

+24
-33
lines changed

Sources/Decoder.swift

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -471,12 +471,9 @@ internal struct TLVKeyedDecodingContainer <K: CodingKey> : KeyedDecodingContaine
471471

472472
self.decoder.log?("Check if nil at path \"\(decoder.codingPath.path)\"")
473473

474-
// check if key exists
475-
guard let item = try self.value(for: key) else {
476-
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key.stringValue)."))
477-
}
478-
479-
return item.value.isEmpty
474+
// check if key exists since there is no way to represent nil in TLV
475+
// empty data and strings should not be falsely reported as nil
476+
return try self.value(for: key) == nil
480477
}
481478

482479
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {

Tests/TLVCodingTests/TLVCodingTests.swift

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ final class TLVCodingTests: XCTestCase {
1818
("testUUID", testUUID),
1919
("testDate", testDate),
2020
("testDateSecondsSince1970", testDateSecondsSince1970),
21-
("testOutputFormatting", testOutputFormatting),
22-
("testNil", testNil)
21+
("testOutputFormatting", testOutputFormatting)
2322
]
2423

2524
func testCodable() {
@@ -85,6 +84,26 @@ final class TLVCodingTests: XCTestCase {
8584
Data([])
8685
)
8786

87+
compare(
88+
CustomEncodable(
89+
data: Data(),
90+
uuid: nil,
91+
number: nil,
92+
date: nil
93+
),
94+
Data([0, 0])
95+
)
96+
97+
compare(
98+
CustomEncodable(
99+
data: Data([0x00, 0x01]),
100+
uuid: nil,
101+
number: nil,
102+
date: nil
103+
),
104+
Data([0, 2, 0x00, 0x01])
105+
)
106+
88107
compare(
89108
Profile(
90109
person: Person(
@@ -352,31 +371,6 @@ final class TLVCodingTests: XCTestCase {
352371

353372
XCTAssertNotEqual(try encoder.encode(value), try encoder.encode(valueUnordered))
354373
}
355-
356-
func testNil() {
357-
358-
let data = Data([
359-
0,0,
360-
3,0
361-
])
362-
363-
let value = CustomEncodable(
364-
data: nil,
365-
uuid: nil,
366-
number: nil,
367-
date: nil
368-
)
369-
370-
var decoder = TLVDecoder()
371-
decoder.log = { print("Decoder:", $0) }
372-
do {
373-
let decodedValue = try decoder.decode(type(of: value), from: data)
374-
XCTAssertEqual(decodedValue, value)
375-
} catch {
376-
dump(error)
377-
XCTFail("Could not decode \(value)")
378-
}
379-
}
380374
}
381375

382376
private extension TLVCodingTests {

0 commit comments

Comments
 (0)