mirror of
https://github.com/Dev1an/MsgPack.git
synced 2026-03-25 08:45:55 +00:00
Encode custom encodables
This commit is contained in:
parent
0490d2cd6f
commit
8dd5237c36
2 changed files with 26 additions and 7 deletions
|
|
@ -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<K: CodingKey>: 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<K: CodingKey>: MessagePackEncodingContainer,
|
|||
}
|
||||
|
||||
func encode<T>(_ 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<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
|
||||
|
|
@ -275,3 +280,21 @@ class MsgPackKeyedEncodingContainer<K: CodingKey>: MessagePackEncodingContainer,
|
|||
preconditionFailure("not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
extension MsgPackKeyedEncodingContainer: Swift.Encoder {
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
|
||||
let keyedContainer = MsgPackKeyedEncodingContainer<Key>()
|
||||
temporaryContainer = keyedContainer
|
||||
return KeyedEncodingContainer(keyedContainer)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
let singleValueContainer = MsgPackSingleValueEncodingContainer()
|
||||
temporaryContainer = singleValueContainer
|
||||
return singleValueContainer
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
Loading…
Reference in a new issue