SPB Git

Repository Public License

JSONValue.swift 9.0 KB 237 lines swift

1import Foundation23/// A JSON value with integers kept distinct from doubles so canonical output is stable.4public enum JSONValue: Sendable {5    case null6    case bool(Bool)7    case int(Int)8    case double(Double)9    case string(String)10    case array([JSONValue])11    case object([String: JSONValue])12}1314/// Numbers compare by value, so `20` and `20.0` are the same JSON number (as in canonical output).15extension JSONValue: Hashable {16    public static func == (l: JSONValue, r: JSONValue) -> Bool {17        switch (l, r) {18        case (.null, .null): true19        case (.bool(let a), .bool(let b)): a == b20        case (.int(let a), .int(let b)): a == b21        case (.int(let a), .double(let b)), (.double(let b), .int(let a)): Double(a) == b22        case (.double(let a), .double(let b)): a == b23        case (.string(let a), .string(let b)): a == b24        case (.array(let a), .array(let b)): a == b25        case (.object(let a), .object(let b)): a == b26        default: false27        }28    }2930    public func hash(into hasher: inout Hasher) {31        switch self {32        case .null: hasher.combine(0)33        case .bool(let b): hasher.combine(1); hasher.combine(b)34        case .int(let i): hasher.combine(2); hasher.combine(Double(i))35        case .double(let d): hasher.combine(2); hasher.combine(d)36        case .string(let s): hasher.combine(3); hasher.combine(s)37        case .array(let a): hasher.combine(4); hasher.combine(a)38        case .object(let o): hasher.combine(5); hasher.combine(o)39        }40    }41}4243public struct JSONError: Error, LocalizedError, Sendable, Equatable {44    public let message: String45    public init(_ message: String) { self.message = message }46    public var errorDescription: String? { message }47}4849extension JSONValue {50    public static let emptyObject = JSONValue.object([:])5152    public var stringValue: String? { if case .string(let s) = self { s } else { nil } }53    public var boolValue: Bool? { if case .bool(let b) = self { b } else { nil } }54    public var intValue: Int? {55        switch self {56        case .int(let i): i57        case .double(let d) where d.rounded() == d && abs(d) < 9e15: Int(d)58        default: nil59        }60    }61    public var doubleValue: Double? {62        switch self {63        case .int(let i): Double(i)64        case .double(let d): d65        default: nil66        }67    }68    public var arrayValue: [JSONValue]? { if case .array(let a) = self { a } else { nil } }69    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { o } else { nil } }70    public var isNull: Bool { self == .null }7172    public subscript(key: String) -> JSONValue? { objectValue?[key] }73    public subscript(index: Int) -> JSONValue? {74        guard let a = arrayValue, a.indices.contains(index) else { return nil }75        return a[index]76    }7778    /// Short type name used in validation messages.79    public var typeName: String {80        switch self {81        case .null: "null"82        case .bool: "boolean"83        case .int, .double: "number"84        case .string: "string"85        case .array: "array"86        case .object: "object"87        }88    }8990    // MARK: Parsing9192    public static func parse(_ data: Data) throws -> JSONValue {93        let any: Any94        do { any = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) }95        catch { throw JSONError("Invalid JSON: \(error.localizedDescription)") }96        return try from(any: any)97    }9899    public static func parse(_ text: String) throws -> JSONValue { try parse(Data(text.utf8)) }100101    static func from(any: Any) throws -> JSONValue {102        switch any {103        case is NSNull: return .null104        case let n as NSNumber:105            if CFGetTypeID(n) == CFBooleanGetTypeID() { return .bool(n.boolValue) }106            if CFNumberIsFloatType(n) {107                let d = n.doubleValue108                guard d.isFinite else { throw JSONError("Non-finite number") }109                return .double(d)110            }111            return .int(n.intValue)112        case let s as String: return .string(s)113        case let a as [Any]: return .array(try a.map(from(any:)))114        case let o as [String: Any]: return .object(try o.mapValues(from(any:)))115        default: throw JSONError("Unsupported JSON value")116        }117    }118119    // MARK: Canonical serialization (ADR 0002)120121    /// Keys sorted by Unicode scalars, no whitespace, integers without fraction, `/` not escaped.122    public func canonicalString() -> String {123        var out = ""124        write(into: &out, pretty: false, indent: 0)125        return out126    }127128    public func canonicalData() -> Data { Data(canonicalString().utf8) }129130    /// Same key order as canonical output, indented for humans and diffs.131    public func prettyString() -> String {132        var out = ""133        write(into: &out, pretty: true, indent: 0)134        return out135    }136137    private func write(into out: inout String, pretty: Bool, indent: Int) {138        switch self {139        case .null: out += "null"140        case .bool(let b): out += b ? "true" : "false"141        case .int(let i): out += String(i)142        case .double(let d):143            if d.rounded() == d && abs(d) < 1e15 { out += String(Int(d)) } else { out += "\(d)" }144        case .string(let s): JSONValue.writeString(s, into: &out)145        case .array(let a):146            if a.isEmpty { out += "[]"; return }147            out += "["148            for (i, v) in a.enumerated() {149                if i > 0 { out += "," }150                if pretty { out += "\n" + String(repeating: "  ", count: indent + 1) }151                v.write(into: &out, pretty: pretty, indent: indent + 1)152            }153            if pretty { out += "\n" + String(repeating: "  ", count: indent) }154            out += "]"155        case .object(let o):156            if o.isEmpty { out += "{}"; return }157            out += "{"158            let keys = o.keys.sorted { $0.unicodeScalars.lexicographicallyPrecedes($1.unicodeScalars) }159            for (i, k) in keys.enumerated() {160                if i > 0 { out += "," }161                if pretty { out += "\n" + String(repeating: "  ", count: indent + 1) }162                JSONValue.writeString(k, into: &out)163                out += pretty ? ": " : ":"164                o[k]!.write(into: &out, pretty: pretty, indent: indent + 1)165            }166            if pretty { out += "\n" + String(repeating: "  ", count: indent) }167            out += "}"168        }169    }170171    private static func writeString(_ s: String, into out: inout String) {172        out += "\""173        for u in s.unicodeScalars {174            switch u {175            case "\"": out += "\\\""176            case "\\": out += "\\\\"177            case "\n": out += "\\n"178            case "\r": out += "\\r"179            case "\t": out += "\\t"180            default:181                if u.value < 0x20 { out += String(format: "\\u%04x", u.value) } else { out.unicodeScalars.append(u) }182            }183        }184        out += "\""185    }186}187188extension JSONValue: Codable {189    public init(from decoder: Decoder) throws {190        let c = try decoder.singleValueContainer()191        if c.decodeNil() { self = .null }192        else if let b = try? c.decode(Bool.self) { self = .bool(b) }193        else if let i = try? c.decode(Int.self) { self = .int(i) }194        else if let d = try? c.decode(Double.self) { self = .double(d) }195        else if let s = try? c.decode(String.self) { self = .string(s) }196        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }197        else { self = .object(try c.decode([String: JSONValue].self)) }198    }199200    public func encode(to encoder: Encoder) throws {201        var c = encoder.singleValueContainer()202        switch self {203        case .null: try c.encodeNil()204        case .bool(let b): try c.encode(b)205        case .int(let i): try c.encode(i)206        case .double(let d): try c.encode(d)207        case .string(let s): try c.encode(s)208        case .array(let a): try c.encode(a)209        case .object(let o): try c.encode(o)210        }211    }212}213214extension JSONValue: ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral,215    ExpressibleByBooleanLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByNilLiteral {216    public init(stringLiteral value: String) { self = .string(value) }217    public init(integerLiteral value: Int) { self = .int(value) }218    public init(floatLiteral value: Double) { self = .double(value) }219    public init(booleanLiteral value: Bool) { self = .bool(value) }220    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }221    public init(dictionaryLiteral elements: (String, JSONValue)...) {222        self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last }))223    }224    public init(nilLiteral: ()) { self = .null }225}226227extension JSONValue {228    /// Encode any Codable value into a JSONValue (used for manifests and tool payloads).229    public static func encode<T: Encodable>(_ value: T) throws -> JSONValue {230        try parse(JSONEncoder().encode(value))231    }232233    public func decode<T: Decodable>(_ type: T.Type) throws -> T {234        try JSONDecoder().decode(type, from: canonicalData())235    }236}237
Files main
Menu

Theme