Skip to content

Commit

Permalink
Allow encode<T: Encodable>(_ value: T) in JSONSingleValueEncodingCo…
Browse files Browse the repository at this point in the history
…ntainer

fixes #19
  • Loading branch information
fabianfett committed Mar 19, 2020
1 parent f5a249d commit ca81eae
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ struct JSONSingleValueEncodingContainer: SingleValueEncodingContainer {
}

mutating func encode(_ value: Bool) throws {
preconditionCanEncodeNewValue()
self.impl.singleValue = .bool(value)
}

Expand Down Expand Up @@ -68,23 +69,31 @@ struct JSONSingleValueEncodingContainer: SingleValueEncodingContainer {
}

mutating func encode(_ value: String) throws {
preconditionCanEncodeNewValue()
self.impl.singleValue = .string(value)
}

mutating func encode<T: Encodable>(_ value: T) throws {

preconditionCanEncodeNewValue()
try value.encode(to: self.impl)
}

func preconditionCanEncodeNewValue() {
precondition(self.impl.singleValue == nil, "Attempt to encode value through single value container when previously value already encoded.")
}
}

extension JSONSingleValueEncodingContainer {

@inline(__always) private mutating func encodeFixedWidthInteger<N: FixedWidthInteger>(_ value: N) throws {
preconditionCanEncodeNewValue()
self.impl.singleValue = .number(value.description)
}

@inline(__always) private mutating func encodeFloatingPoint<N: FloatingPoint>(_ value: N)
throws where N: CustomStringConvertible
{
preconditionCanEncodeNewValue()
self.impl.singleValue = .number(value.description)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import XCTest
@testable import PureSwiftJSONCoding
@testable import PureSwiftJSONParsing

class JSONSingleValueEncodingContainerTests: XCTestCase {

func testEncodeEncodable() {
struct Name: Encodable {
var firstName: String
var surname: String
}

struct Object: Encodable {
var name: Name

func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(name)
}
}

do {
let object = Object(name: Name(firstName: "Adam", surname: "Fowler"))
let json = try PureSwiftJSONCoding.JSONEncoder().encode(object)

let parsed = try JSONParser().parse(bytes: json)
XCTAssertEqual(parsed, .object(["firstName": .string("Adam"), "surname": .string("Fowler")]))
}
catch {
XCTFail("Unexpected error: \(error)")
}
}

}

0 comments on commit ca81eae

Please sign in to comment.