Add built-in codable support

This commit is contained in:
Ali 2020-04-05 23:27:04 +04:00
parent 3e0755e923
commit d9397f470b

View File

@ -337,6 +337,12 @@ public final class PostboxEncoder {
self.encodeObject(value, forKey: "_")
}
public func encodeCodable<T: Codable>(_ value: T, forKey key: StaticString) {
if let data = try? JSONEncoder().encode(value) {
self.encodeData(data, forKey: key)
}
}
public func encodeObject(_ value: PostboxCoding, forKey key: StaticString) {
self.encodeKey(key)
var t: Int8 = ValueType.Object.rawValue
@ -922,6 +928,14 @@ public final class PostboxDecoder {
return self.decodeObjectForKey("_")
}
public func decodeCodable<T: Codable>(_ type: T.Type, forKey key: StaticString) -> T? {
if let data = self.decodeDataForKey(key) {
return try? JSONDecoder().decode(T.self, from: data)
} else {
return nil
}
}
public func decodeObjectForKey(_ key: StaticString) -> PostboxCoding? {
if PostboxDecoder.positionOnKey(self.buffer.memory, offset: &self.offset, maxOffset: self.buffer.length, length: self.buffer.length, key: key, valueType: .Object) {
var typeHash: Int32 = 0