Skip to content

Commit

Permalink
Improve support for optionals in singleValueContainer
Browse files Browse the repository at this point in the history
  • Loading branch information
mrackwitz committed Jan 12, 2024
1 parent 5a1e1ca commit d3f5a6a
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 20 deletions.
5 changes: 0 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion Sources/BinaryCodable/Encoding/AbstractEncodingNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 20 additions & 14 deletions Sources/BinaryCodable/Encoding/ValueEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -24,7 +25,8 @@ final class ValueEncoder: AbstractEncodingNode, SingleValueEncodingContainer {
func encode<T>(_ 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
Expand All @@ -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
}
Expand All @@ -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
}
}
162 changes: 162 additions & 0 deletions Tests/BinaryCodableTests/PropertyWrapperCodingTests.swift
Original file line number Diff line number Diff line change
@@ -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<T: Codable & Equatable>: 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<T>.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<T: Codable & Equatable>: 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<T: Codable & Equatable>(
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<T>(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<T> = 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]
)
}
}

0 comments on commit d3f5a6a

Please sign in to comment.