diff --git a/MsgPack/Encoder.swift b/MsgPack/Encoder.swift index 6b09c24..70323a1 100644 --- a/MsgPack/Encoder.swift +++ b/MsgPack/Encoder.swift @@ -97,7 +97,7 @@ class MessagePackEncodingContainer { } enum MsgPackEncodingError: Swift.Error { - case notImplemented, stringNotConvertibleToUTF8(String) + case notImplemented, stringNotConvertibleToUTF8(String), valueDidNotAskForContainer } class MsgPackSingleValueEncodingContainer: MessagePackEncodingContainer, SingleValueEncodingContainer { @@ -186,6 +186,7 @@ class MsgPackKeyedEncodingContainer: MessagePackEncodingContainer, var userInfo = [CodingUserInfoKey : Any]() var storage = [String: MessagePackEncodingContainer]() + var temporaryContainer: MessagePackEncodingContainer? override func getFormat() throws -> Format { return try Format.from(keyValuePairs: storage.map { @@ -254,7 +255,11 @@ class MsgPackKeyedEncodingContainer: MessagePackEncodingContainer, } func encode(_ value: T, forKey key: K) throws where T : Encodable { - throw MsgPackEncodingError.notImplemented + try value.encode(to: self) + guard let container = temporaryContainer else { + throw MsgPackEncodingError.valueDidNotAskForContainer + } + storage[key.stringValue] = container } func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer where NestedKey : CodingKey { @@ -275,3 +280,21 @@ class MsgPackKeyedEncodingContainer: MessagePackEncodingContainer, preconditionFailure("not implemented") } } + +extension MsgPackKeyedEncodingContainer: Swift.Encoder { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + let keyedContainer = MsgPackKeyedEncodingContainer() + temporaryContainer = keyedContainer + return KeyedEncodingContainer(keyedContainer) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + preconditionFailure() + } + + func singleValueContainer() -> SingleValueEncodingContainer { + let singleValueContainer = MsgPackSingleValueEncodingContainer() + temporaryContainer = singleValueContainer + return singleValueContainer + } +} diff --git a/Playground.playground/Contents.swift b/Playground.playground/Contents.swift index f887485..29663bf 100644 --- a/Playground.playground/Contents.swift +++ b/Playground.playground/Contents.swift @@ -24,8 +24,4 @@ struct Circle: Encodable { let radius: UInt } -do { - try encoder.encode(Circle(center: Position(x: -1, y: 2), radius: 50)).forEach { print(String($0, radix: 16)) } -} catch { - error -} +try encoder.encode(Circle(center: Position(x: -1, y: 2), radius: 67))