Summary: - Sources: Models - Docs: README Stats: - 3 files changed, 16 insertions(+), 10 deletions(-)
48 lines
1.4 KiB
Swift
48 lines
1.4 KiB
Swift
import Foundation
|
|
|
|
public struct Serializer<Value: Codable & Sendable>: Sendable {
|
|
public let encode: @Sendable (Value) throws -> Data
|
|
public let decode: @Sendable (Data) throws -> Value
|
|
public let name: String
|
|
|
|
public init(
|
|
encode: @escaping @Sendable (Value) throws -> Data,
|
|
decode: @escaping @Sendable (Data) throws -> Value,
|
|
name: String = "custom"
|
|
) {
|
|
self.encode = encode
|
|
self.decode = decode
|
|
self.name = name
|
|
}
|
|
|
|
public static var json: Serializer<Value> {
|
|
Serializer<Value>(
|
|
encode: { try JSONEncoder().encode($0) },
|
|
decode: { try JSONDecoder().decode(Value.self, from: $0) },
|
|
name: "json"
|
|
)
|
|
}
|
|
|
|
public static var plist: Serializer<Value> {
|
|
Serializer<Value>(
|
|
encode: { try PropertyListEncoder().encode($0) },
|
|
decode: { try PropertyListDecoder().decode(Value.self, from: $0) },
|
|
name: "plist"
|
|
)
|
|
}
|
|
|
|
public static func custom(
|
|
encode: @escaping @Sendable (Value) throws -> Data,
|
|
decode: @escaping @Sendable (Data) throws -> Value,
|
|
name: String = "custom"
|
|
) -> Serializer<Value> {
|
|
Serializer<Value>(encode: encode, decode: decode, name: name)
|
|
}
|
|
}
|
|
|
|
public extension Serializer where Value == Data {
|
|
static var data: Serializer<Value> {
|
|
Serializer<Value>(encode: { $0 }, decode: { $0 }, name: "data")
|
|
}
|
|
}
|