SPB Git

Repository Public

JSONValue.swift 5.3 KB 106 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Foundation/JSONValue.swift3// Description: A lossless, Sendable JSON value. Used where the server's object must be kept exactly as served (objects approved4//              by passkey, provider-specific details) and for request bodies built from mixed values.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public enum JSONValue: Sendable, Hashable, Codable {11    case null12    case bool(Bool)13    /** An integer that fits in 64 bits. Larger integers and fractions are `.double`; amounts are never numbers in this API (strings). */14    case int(Int64)15    case double(Double)16    case string(String)17    case array([JSONValue])18    case object([String: JSONValue])1920    public init(from decoder: Decoder) throws {21        let c = try decoder.singleValueContainer()22        if c.decodeNil() { self = .null }23        else if let b = try? c.decode(Bool.self) { self = .bool(b) }24        else if let i = try? c.decode(Int64.self) { self = .int(i) }25        else if let d = try? c.decode(Double.self) { self = .double(d) }26        else if let s = try? c.decode(String.self) { self = .string(s) }27        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }28        else { self = .object(try c.decode([String: JSONValue].self)) }29    }3031    public func encode(to encoder: Encoder) throws {32        var c = encoder.singleValueContainer()33        switch self {34        case .null: try c.encodeNil()35        case .bool(let b): try c.encode(b)36        case .int(let i): try c.encode(i)37        case .double(let d): try c.encode(d)38        case .string(let s): try c.encode(s)39        case .array(let a): try c.encode(a)40        case .object(let o): try c.encode(o)41        }42    }4344    public subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] } else { return nil } }45    public subscript(index: Int) -> JSONValue? { if case .array(let a) = self, a.indices.contains(index) { return a[index] } else { return nil } }4647    public var stringValue: String? { if case .string(let s) = self { return s } else { return nil } }48    public var boolValue: Bool? { if case .bool(let b) = self { return b } else { return nil } }49    public var intValue: Int64? {50        switch self { case .int(let i): return i; case .double(let d) where d == d.rounded() && abs(d) < 9e15: return Int64(d); default: return nil }51    }52    public var doubleValue: Double? {53        switch self { case .int(let i): return Double(i); case .double(let d): return d; default: return nil }54    }55    public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a } else { return nil } }56    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o } else { return nil } }57    public var isNull: Bool { if case .null = self { return true } else { return false } }5859    /** Decode this value as a typed model (same decoder configuration as the API client). */60    public func decode<T: Decodable>(_ type: T.Type = T.self) throws -> T {61        try APICoding.decoder().decode(T.self, from: try APICoding.encoder().encode(self))62    }63    /** Wrap any Encodable as a JSON value. */64    public static func from<T: Encodable>(_ value: T) throws -> JSONValue {65        try APICoding.decoder().decode(JSONValue.self, from: try APICoding.encoder().encode(value))66    }67}6869extension JSONValue: ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByNilLiteral,70    ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {71    public init(stringLiteral value: String) { self = .string(value) }72    public init(booleanLiteral value: Bool) { self = .bool(value) }73    public init(integerLiteral value: Int64) { self = .int(value) }74    public init(nilLiteral: ()) { self = .null }75    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }76    public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { _, b in b })) }77}7879/** One JSON coding configuration for the whole package: dates are ISO 8601 with or without fractional seconds. */80public enum APICoding {81    public static func decoder() -> JSONDecoder {82        let d = JSONDecoder()83        d.dateDecodingStrategy = .custom { dec in84            let c = try dec.singleValueContainer()85            if let ms = try? c.decode(Double.self) { return Date(timeIntervalSince1970: ms > 1e11 ? ms / 1000 : ms) }86            let s = try c.decode(String.self)87            if let d = ISO8601.parse(s) { return d }88            throw DecodingError.dataCorruptedError(in: c, debugDescription: "invalid date \(s)")89        }90        return d91    }92    public static func encoder() -> JSONEncoder {93        let e = JSONEncoder()94        e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]95        e.dateEncodingStrategy = .custom { date, enc in var c = enc.singleValueContainer(); try c.encode(ISO8601.string(date)) }96        return e97    }98}99100public enum ISO8601 {101    public static func parse(_ s: String) -> Date? {102        (try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(s)) ?? (try? Date.ISO8601FormatStyle().parse(s))103    }104    public static func string(_ d: Date) -> String { d.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true)) }105}106
Files main
Menu

Theme