From d3f5a6a43bd1fc1a3a9fcbcbee01ae99eed5b7b2 Mon Sep 17 00:00:00 2001 From: Marius Rackwitz Date: Fri, 12 Jan 2024 13:21:26 +0100 Subject: [PATCH] Improve support for optionals in singleValueContainer --- README.md | 5 - .../Encoding/AbstractEncodingNode.swift | 2 +- .../BinaryCodable/Encoding/ValueEncoder.swift | 34 ++-- .../PropertyWrapperCodingTests.swift | 162 ++++++++++++++++++ 4 files changed, 183 insertions(+), 20 deletions(-) create mode 100644 Tests/BinaryCodableTests/PropertyWrapperCodingTests.swift diff --git a/README.md b/README.md index 129fb52..9e29f77 100644 --- a/README.md +++ b/README.md @@ -117,11 +117,6 @@ All possible errors occuring during encoding produce `EncodingError` errors, whi Both are the default Errors provided by Swift, supplied with information describing the nature of the error. See the documentation of the types to learn more about the different error conditions. -#### Unsupported features - -It is currently not supported to call `func encodeNil()` on `SingleValueEncodingContainer` for custom implementations of `func encode(to:)`. -Future versions may include a special setting to enforce compatibility with this option. - #### Handling corrupted data The [binary format](BinaryFormat.md) provides no provisions to detect data corruption, and various errors can occur as the result of added, changed, or missing bytes and bits. diff --git a/Sources/BinaryCodable/Encoding/AbstractEncodingNode.swift b/Sources/BinaryCodable/Encoding/AbstractEncodingNode.swift index d4c7fad..30e91d2 100644 --- a/Sources/BinaryCodable/Encoding/AbstractEncodingNode.swift +++ b/Sources/BinaryCodable/Encoding/AbstractEncodingNode.swift @@ -18,7 +18,7 @@ class AbstractEncodingNode: AbstractNode { userInfo.has(.sortKeys) } - let containsOptional: Bool + var containsOptional: Bool init(path: [CodingKey], info: UserInfo, optional: Bool) { self.containsOptional = optional diff --git a/Sources/BinaryCodable/Encoding/ValueEncoder.swift b/Sources/BinaryCodable/Encoding/ValueEncoder.swift index f85e163..94a6ab6 100644 --- a/Sources/BinaryCodable/Encoding/ValueEncoder.swift +++ b/Sources/BinaryCodable/Encoding/ValueEncoder.swift @@ -3,14 +3,15 @@ import Foundation final class ValueEncoder: AbstractEncodingNode, SingleValueEncodingContainer { private var container: EncodingContainer? + private var containerHasOptionalContent: Bool = false private var hasValue = false func encodeNil() throws { - if !containsOptional { - fatalError("Calling `encodeNil()` on `SingleValueEncodingContainer` is not supported") + assign { + containsOptional = true + return nil } - assign { nil } } private func assign(_ encoded: () throws -> EncodingContainer?) rethrows { @@ -24,7 +25,8 @@ final class ValueEncoder: AbstractEncodingNode, SingleValueEncodingContainer { func encode(_ value: T) throws where T : Encodable { if value is AnyOptional { try assign { - try EncodingNode(path: codingPath, info: userInfo, optional: true).encoding(value) + containerHasOptionalContent = true + return try EncodingNode(path: codingPath, info: userInfo, optional: true).encoding(value) } } else if let primitive = value as? EncodablePrimitive { // Note: This assignment also work for optionals with a value, so @@ -48,10 +50,10 @@ extension ValueEncoder: EncodingContainer { var data: Data { if containsOptional { - if isNil { + guard let container else { return Data([0]) } - return Data([1]) + (container?.dataWithLengthInformationIfRequired ?? .empty) + return Data([1]) + container.dataWithLengthInformationIfRequired } return container?.data ?? .empty } @@ -77,22 +79,26 @@ extension ValueEncoder: EncodingContainer { container?.isEmpty ?? true } - private var optionalData: Data { + private var optionalDataWithinKeyedContainer: Data { guard let container else { return Data([0]) } + guard !containerHasOptionalContent else { + return container.data + } return Data([1]) + container.dataWithLengthInformationIfRequired } func encodeWithKey(_ key: CodingKeyWrapper) -> Data { - guard containsOptional else { + if containsOptional || containerHasOptionalContent { + guard !isNil else { + // Nothing to do, nil is ommited for keyed containers + return Data() + } + let data = optionalDataWithinKeyedContainer + return key.encode(for: .variableLength) + data.count.variableLengthEncoding + data + } else { return key.encode(for: container?.dataType ?? .byte) + (container?.dataWithLengthInformationIfRequired ?? .empty) } - guard !isNil else { - // Nothing to do, nil is ommited for keyed containers - return Data() - } - let data = optionalData - return key.encode(for: .variableLength) + data.count.variableLengthEncoding + optionalData } } diff --git a/Tests/BinaryCodableTests/PropertyWrapperCodingTests.swift b/Tests/BinaryCodableTests/PropertyWrapperCodingTests.swift new file mode 100644 index 0000000..92daa9f --- /dev/null +++ b/Tests/BinaryCodableTests/PropertyWrapperCodingTests.swift @@ -0,0 +1,162 @@ +import XCTest +import BinaryCodable + +/// While from the perspective of `Codable` nothing about property wrapper is special, +/// they tend to encode their values via `singleValueContainer()`, which requires +/// some considerations when it comes to dealing with optionals. +/// +final class PropertyWrapperCodingTests: XCTestCase { + struct KeyedWrapper: Codable, Equatable { + enum CodingKeys: String, CodingKey { + case wrapper + } + + @Wrapper + var value: T + + init(_ value: T) { + self._value = Wrapper(wrappedValue: value) + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self._value = try container.decode(Wrapper.self, forKey: .wrapper) + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(_value, forKey: .wrapper) + } + } + + @propertyWrapper + struct Wrapper: Codable, Equatable { + let wrappedValue: T + + init(wrappedValue: T) { + self.wrappedValue = wrappedValue + } + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + self.wrappedValue = try container.decode(T.self) + } + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(wrappedValue) + } + } + + struct WrappedString: Codable, Equatable { + let val: String + } + + func assert( + encoding wrapped: T, + as type: T.Type = T.self, + expectByteSuffix byteSuffix: [UInt8], + file: StaticString = #file, + line: UInt = #line + ) throws { + let bytePrefix: [UInt8] = [ + 0b01111010, 119, 114, 97, 112, 112, 101, 114, // String key 'wrapper', varint, + ] + + let wrapper = KeyedWrapper(wrapped) + let data = try BinaryEncoder.encode(wrapper) + + // If the prefix differs, this error affects the test helper, so report it here + XCTAssertEqual(Array(data.prefix(bytePrefix.count)), bytePrefix) + + // If the suffix differs, this error is specific to the individual test case, + // so report it on the call-side + XCTAssertEqual(Array(data.suffix(from: bytePrefix.count)), byteSuffix, file: file, line: line) + + let decodedWrapper: KeyedWrapper = try BinaryDecoder.decode(from: data) + XCTAssertEqual(decodedWrapper, wrapper, file: file, line: line) + } + + func testOptionalWrappedStringSome() throws { + try assert( + encoding: WrappedString(val: "Some"), + as: WrappedString?.self, + expectByteSuffix: [ + 11, // Length 11 + 1, // 1 as in the optional is present + 9, // Length 9 + 0b00111010, 118, 97, 108, // String key 'val', varint + 4, // Length 4, + 83, 111, 109, 101, // String "Some" + ] + ) + } + + func testOptionalWrappedStringNone() throws { + try assert( + encoding: nil, + as: WrappedString?.self, + expectByteSuffix: [ + 1, // Length 1 + 0, // Optional is absent + ] + ) + } + + func testOptionalBool() throws { + try assert( + encoding: .some(true), + as: Bool?.self, + expectByteSuffix: [ + 2, // Length 2 + 1, // Optional is present + 1, // Boolean is true + ] + ) + + try assert( + encoding: .some(false), + as: Bool?.self, + expectByteSuffix: [ + 2, // Length 2 + 1, // Optional is present + 0, // Boolean is false + ] + ) + + try assert( + encoding: nil, + as: Bool?.self, + expectByteSuffix: [ + 1, // Length 1 + 0, // Optional is present + ] + ) + } + + func testDoubleOptionalBool() throws { + try assert( + encoding: .some(.some(true)), + as: Bool??.self, + expectByteSuffix: [3, 1, 1, 1] + ) + + try assert( + encoding: .some(.some(false)), + as: Bool??.self, + expectByteSuffix: [3, 1, 1, 0] + ) + + try assert( + encoding: .some(nil), + as: Bool??.self, + expectByteSuffix: [2, 1, 0] + ) + + try assert( + encoding: nil, + as: Bool??.self, + expectByteSuffix: [1, 0] + ) + } +}