SPB Git

Repository Public

VQJSON.swift 10.6 KB 224 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Core/VQJSON.swift3// Description: A lossless JSON value. Every model of the package is read from it, and the sync models are backed by it4//              so that keys this version does not know survive a round trip.5import Foundation67/// A JSON value. Named `VQJSON` (not `JSONValue`) so it never collides with the `JSONValue` of either app's `VQuantCore`.8public enum VQJSON: Sendable, Hashable {9    case null10    case bool(Bool)11    case number(Double)12    case string(String)13    case array([VQJSON])14    case object([String: VQJSON])15}1617public typealias VQJSONObject = [String: VQJSON]1819// Not ExpressibleByNilLiteral on purpose: `optionalJSON == nil` must mean "absent", never "JSON null".20extension VQJSON: ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral,21    ExpressibleByStringLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {22    public init(booleanLiteral value: Bool) { self = .bool(value) }23    public init(integerLiteral value: Int) { self = .number(Double(value)) }24    public init(floatLiteral value: Double) { self = .number(value) }25    public init(stringLiteral value: String) { self = .string(value) }26    public init(arrayLiteral elements: VQJSON...) { self = .array(elements) }27    public init(dictionaryLiteral elements: (String, VQJSON)...) { self = .object(Dictionary(elements, uniquingKeysWith: { $1 })) }28}2930public extension VQJSON {31    init(_ value: String?) { self = value.map(VQJSON.string) ?? .null }32    init(_ value: Double?) { self = value.map { $0.isFinite ? VQJSON.number($0) : .null } ?? .null }33    init(_ value: Int?) { self = value.map { VQJSON.number(Double($0)) } ?? .null }34    init(_ value: Bool?) { self = value.map(VQJSON.bool) ?? .null }35    init(_ values: [String]) { self = .array(values.map(VQJSON.string)) }36    init(_ values: [Double]) { self = .array(values.map { VQJSON($0) }) }3738    subscript(key: String) -> VQJSON? { if case .object(let o) = self { return o[key] } else { return nil } }39    subscript(index: Int) -> VQJSON? { if case .array(let a) = self, a.indices.contains(index) { return a[index] } else { return nil } }4041    var isNull: Bool { self == .null }42    var stringValue: String? { if case .string(let s) = self { return s } else { return nil } }43    var boolValue: Bool? { if case .bool(let b) = self { return b } else { return nil } }44    /// A number; a string holding one is NOT converted (use `looseDouble` for provider payloads that mix both).45    var doubleValue: Double? { if case .number(let n) = self { return n } else { return nil } }46    var intValue: Int? { doubleValue.flatMap { $0.isFinite && abs($0) < 9e15 ? Int($0) : nil } }47    var arrayValue: [VQJSON]? { if case .array(let a) = self { return a } else { return nil } }48    var objectValue: VQJSONObject? { if case .object(let o) = self { return o } else { return nil } }49    /// A number, or a string that holds one.50    var looseDouble: Double? {51        switch self {52        case .number(let n): return n53        case .string(let s): return Double(s)54        default: return nil55        }56    }57    /// A string, or the text of a number/boolean (for labels built from mixed cells).58    var displayString: String? {59        switch self {60        case .string(let s): return s61        case .number(let n): return n.rounded() == n && abs(n) < 9e15 ? String(Int64(n)) : String(n)62        case .bool(let b): return b ? "true" : "false"63        default: return nil64        }65    }6667    // Tolerant field readers used by every `init(json:)` of the package: a missing key, a null or a value of the68    // wrong type gives the default, never an error.69    func str(_ key: String, _ fallback: String = "") -> String { self[key]?.stringValue ?? fallback }70    func optStr(_ key: String) -> String? { self[key]?.stringValue }71    func num(_ key: String) -> Double? { self[key]?.doubleValue }72    func int(_ key: String) -> Int? { self[key]?.intValue }73    func flag(_ key: String, _ fallback: Bool = false) -> Bool { self[key]?.boolValue ?? fallback }74    func optFlag(_ key: String) -> Bool? { self[key]?.boolValue }75    func list(_ key: String) -> [VQJSON] { self[key]?.arrayValue ?? [] }76    func strings(_ key: String) -> [String] { list(key).compactMap(\.stringValue) }77    func dict(_ key: String) -> VQJSONObject { self[key]?.objectValue ?? [:] }78    /// Epoch milliseconds → Date.79    func date(_ key: String) -> Date? { num(key).map { Date(timeIntervalSince1970: $0 / 1000) } }80    func models<T: VQJSONDecodable>(_ key: String, as type: T.Type = T.self) -> [T] { list(key).map(T.init(json:)) }81    func model<T: VQJSONDecodable>(_ key: String, as type: T.Type = T.self) -> T? {82        guard let v = self[key], v.objectValue != nil else { return nil }83        return T(json: v)84    }85}8687// MARK: parsing and serialising8889public extension VQJSON {90    struct ParseError: Error, Sendable, Equatable { public let message: String }9192    /// Parses UTF-8 JSON (any top-level value).93    static func parse(_ data: Data) throws -> VQJSON {94        do { return VQJSON(any: try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])) }95        catch { throw ParseError(message: "not valid JSON") }96    }97    static func parse(_ text: String) throws -> VQJSON { try parse(Data(text.utf8)) }9899    /// Compact UTF-8 JSON with sorted keys (stable: equal values give equal bytes).100    func data(pretty: Bool = false) -> Data {101        var out = ""102        write(to: &out, pretty: pretty, depth: 0)103        return Data(out.utf8)104    }105    func text(pretty: Bool = false) -> String { var out = ""; write(to: &out, pretty: pretty, depth: 0); return out }106107    internal init(any value: Any) {108        switch value {109        case is NSNull: self = .null110        case let n as NSNumber:111            if CFGetTypeID(n) == CFBooleanGetTypeID() { self = .bool(n.boolValue) } else { self = .number(n.doubleValue) }112        case let s as String: self = .string(s)113        case let a as [Any]: self = .array(a.map(VQJSON.init(any:)))114        case let o as [String: Any]: self = .object(o.mapValues(VQJSON.init(any:)))115        default: self = .null116        }117    }118119    private func write(to out: inout String, pretty: Bool, depth: Int) {120        func indent(_ d: Int) { if pretty { out += "\n" + String(repeating: "  ", count: d) } }121        switch self {122        case .null: out += "null"123        case .bool(let b): out += b ? "true" : "false"124        case .number(let n):125            if !n.isFinite { out += "null" }126            else if n.rounded() == n, abs(n) < 9e15 { out += String(Int64(n)) }127            else { out += String(n) }128        case .string(let s): VQJSON.escape(s, into: &out)129        case .array(let a):130            if a.isEmpty { out += "[]"; return }131            out += "["132            for (i, v) in a.enumerated() { if i > 0 { out += "," }; indent(depth + 1); v.write(to: &out, pretty: pretty, depth: depth + 1) }133            indent(depth); out += "]"134        case .object(let o):135            if o.isEmpty { out += "{}"; return }136            out += "{"137            for (i, k) in o.keys.sorted().enumerated() {138                if i > 0 { out += "," }139                indent(depth + 1)140                VQJSON.escape(k, into: &out)141                out += pretty ? ": " : ":"142                o[k]!.write(to: &out, pretty: pretty, depth: depth + 1)143            }144            indent(depth); out += "}"145        }146    }147148    private static func escape(_ s: String, into out: inout String) {149        out += "\""150        for u in s.unicodeScalars {151            switch u {152            case "\"": out += "\\\""153            case "\\": out += "\\\\"154            case "\n": out += "\\n"155            case "\r": out += "\\r"156            case "\t": out += "\\t"157            default:158                if u.value < 0x20 { out += String(format: "\\u%04x", u.value) } else { out.unicodeScalars.append(u) }159            }160        }161        out += "\""162    }163}164165extension VQJSON: Codable {166    public init(from decoder: Decoder) throws {167        let c = try decoder.singleValueContainer()168        if c.decodeNil() { self = .null }169        else if let b = try? c.decode(Bool.self) { self = .bool(b) }170        else if let n = try? c.decode(Double.self) { self = .number(n) }171        else if let s = try? c.decode(String.self) { self = .string(s) }172        else if let a = try? c.decode([VQJSON].self) { self = .array(a) }173        else if let o = try? c.decode([String: VQJSON].self) { self = .object(o) }174        else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "not a JSON value") }175    }176    public func encode(to encoder: Encoder) throws {177        var c = encoder.singleValueContainer()178        switch self {179        case .null: try c.encodeNil()180        case .bool(let b): try c.encode(b)181        case .number(let n): if n.rounded() == n, abs(n) < 9e15 { try c.encode(Int64(n)) } else { try c.encode(n) }182        case .string(let s): try c.encode(s)183        case .array(let a): try c.encode(a)184        case .object(let o): try c.encode(o)185        }186    }187}188189/// A model read tolerantly from JSON: `init(json:)` never fails. Unknown keys are ignored, missing ones get defaults.190public protocol VQJSONDecodable: Sendable {191    init(json: VQJSON)192}193194public extension VQJSONDecodable {195    static func decode(_ data: Data) throws -> Self { Self(json: try VQJSON.parse(data)) }196}197198/// A string-backed enumeration that never fails to decode: values this version does not know are kept as `.unknown`.199public enum VQOpen<Known: RawRepresentable & Sendable & Hashable>: Sendable, Hashable where Known.RawValue == String {200    case known(Known)201    case unknown(String)202203    public init(_ raw: String) { self = Known(rawValue: raw).map(VQOpen.known) ?? .unknown(raw) }204    public init(_ known: Known) { self = .known(known) }205    public var rawValue: String {206        switch self {207        case .known(let k): return k.rawValue208        case .unknown(let s): return s209        }210    }211    public var known: Known? { if case .known(let k) = self { return k } else { return nil } }212    public static func == (lhs: VQOpen, rhs: Known) -> Bool { lhs.known == rhs }213    public static func != (lhs: VQOpen, rhs: Known) -> Bool { lhs.known != rhs }214}215216public extension VQJSON {217    func open<K>(_ key: String, _ fallback: K) -> VQOpen<K> { self[key]?.stringValue.map(VQOpen<K>.init) ?? .known(fallback) }218    func optOpen<K>(_ key: String, as type: K.Type = K.self) -> VQOpen<K>? { self[key]?.stringValue.map(VQOpen<K>.init) }219}220221/// `model.tier == .frontier` for optional open enumerations (an absent value equals nothing).222public func == <K>(lhs: VQOpen<K>?, rhs: K) -> Bool { lhs?.known == rhs }223public func != <K>(lhs: VQOpen<K>?, rhs: K) -> Bool { lhs?.known != rhs }224
Files main
Menu

Theme