Skip to content

Commit

Permalink
Fixed decoding nil
Browse files Browse the repository at this point in the history
  • Loading branch information
colemancda committed Dec 25, 2019
1 parent 978c38f commit 0ecdc45
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 33 deletions.
9 changes: 3 additions & 6 deletions Sources/Decoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,9 @@ internal struct TLVKeyedDecodingContainer <K: CodingKey> : KeyedDecodingContaine

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

// check if key exists
guard let item = try self.value(for: key) else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key.stringValue)."))
}

return item.value.isEmpty
// check if key exists since there is no way to represent nil in TLV
// empty data and strings should not be falsely reported as nil
return try self.value(for: key) == nil
}

func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
Expand Down
48 changes: 21 additions & 27 deletions Tests/TLVCodingTests/TLVCodingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ final class TLVCodingTests: XCTestCase {
("testUUID", testUUID),
("testDate", testDate),
("testDateSecondsSince1970", testDateSecondsSince1970),
("testOutputFormatting", testOutputFormatting),
("testNil", testNil)
("testOutputFormatting", testOutputFormatting)
]

func testCodable() {
Expand Down Expand Up @@ -85,6 +84,26 @@ final class TLVCodingTests: XCTestCase {
Data([])
)

compare(
CustomEncodable(
data: Data(),
uuid: nil,
number: nil,
date: nil
),
Data([0, 0])
)

compare(
CustomEncodable(
data: Data([0x00, 0x01]),
uuid: nil,
number: nil,
date: nil
),
Data([0, 2, 0x00, 0x01])
)

compare(
Profile(
person: Person(
Expand Down Expand Up @@ -352,31 +371,6 @@ final class TLVCodingTests: XCTestCase {

XCTAssertNotEqual(try encoder.encode(value), try encoder.encode(valueUnordered))
}

func testNil() {

let data = Data([
0,0,
3,0
])

let value = CustomEncodable(
data: nil,
uuid: nil,
number: nil,
date: nil
)

var decoder = TLVDecoder()
decoder.log = { print("Decoder:", $0) }
do {
let decodedValue = try decoder.decode(type(of: value), from: data)
XCTAssertEqual(decodedValue, value)
} catch {
dump(error)
XCTFail("Could not decode \(value)")
}
}
}

private extension TLVCodingTests {
Expand Down

0 comments on commit 0ecdc45

Please sign in to comment.