44 lines
1.2 KiB
Swift
44 lines
1.2 KiB
Swift
//
|
|
// SerializationUtils.swift
|
|
// FluxRead
|
|
//
|
|
|
|
import Foundation
|
|
|
|
class SerializationUtils {
|
|
|
|
enum SerializationError: Error, LocalizedError {
|
|
case invalidBase64String
|
|
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .invalidBase64String:
|
|
return "Provided string is not valid Base64."
|
|
}
|
|
}
|
|
}
|
|
|
|
static func toBinaryPlist<T: Encodable>(_ value: T) throws -> Data {
|
|
let encoder = PropertyListEncoder()
|
|
encoder.outputFormat = .binary
|
|
return try encoder.encode(value)
|
|
}
|
|
|
|
static func toBase64BinaryPlist<T: Encodable>(_ value: T) throws -> String {
|
|
let data = try toBinaryPlist(value)
|
|
return data.base64EncodedString()
|
|
}
|
|
|
|
static func fromBinaryPlist<T: Decodable>(_ data: Data, _ type: T.Type) throws -> T {
|
|
let decoder = PropertyListDecoder()
|
|
return try decoder.decode(type, from: data)
|
|
}
|
|
|
|
static func fromBase64Plist<T: Decodable>(_ base64: String, _ type: T.Type) throws -> T {
|
|
guard let data = Data(base64Encoded: base64) else {
|
|
throw SerializationError.invalidBase64String
|
|
}
|
|
return try fromBinaryPlist(data, type)
|
|
}
|
|
}
|