SPB Git

Repository Public

JSONValue.swift 13.3 KB 330 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/JSONValue.swift3// Description: JSONValue helpers: strict parser keeping integers as integers, canonical encoder with sorted keys,4//              semantic equality, literals and accessors.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension JSONValue {11    // MARK: Parsing1213    /// Parses JSON bytes (UTF-8). Integer literals that fit in 64 bits become `.int`, every other number `.double`.14    public init(data: Data) throws {15        var parser = JSONParser(bytes: [UInt8](data))16        self = try parser.parseDocument()17    }1819    /// Parses a JSON string.20    public init(jsonString: String) throws { try self.init(data: Data(jsonString.utf8)) }2122    // MARK: Canonical encoding2324    /// Canonical JSON: object keys sorted by Unicode scalar order, no whitespace, integral doubles written as integers,25    /// non-finite doubles written as `null`. Two semantically equal values give the same bytes.26    public func canonicalData() -> Data {27        var out = [UInt8]()28        write(into: &out, pretty: false, indent: 0)29        return Data(out)30    }3132    /// Canonical JSON as a string; `pretty` adds two-space indentation.33    public func canonicalString(pretty: Bool = false) -> String {34        var out = [UInt8]()35        write(into: &out, pretty: pretty, indent: 0)36        return String(decoding: out, as: UTF8.self)37    }3839    private func write(into out: inout [UInt8], pretty: Bool, indent: Int) {40        func newline(_ level: Int) {41            guard pretty else { return }42            out.append(0x0A)43            out.append(contentsOf: repeatElement(0x20, count: level * 2))44        }45        switch self {46        case .null: out.append(contentsOf: "null".utf8)47        case .bool(let b): out.append(contentsOf: (b ? "true" : "false").utf8)48        case .int(let i): out.append(contentsOf: String(i).utf8)49        case .double(let d): out.append(contentsOf: JSONValue.numberString(d).utf8)50        case .string(let s): JSONValue.writeString(s, into: &out)51        case .array(let a):52            out.append(0x5B)53            for (n, v) in a.enumerated() {54                if n > 0 { out.append(0x2C) }55                newline(indent + 1)56                v.write(into: &out, pretty: pretty, indent: indent + 1)57            }58            if !a.isEmpty { newline(indent) }59            out.append(0x5D)60        case .object(let o):61            out.append(0x7B)62            let keys = o.keys.sorted { $0.unicodeScalars.lexicographicallyPrecedes($1.unicodeScalars) }63            for (n, k) in keys.enumerated() {64                if n > 0 { out.append(0x2C) }65                newline(indent + 1)66                JSONValue.writeString(k, into: &out)67                out.append(0x3A)68                if pretty { out.append(0x20) }69                o[k]!.write(into: &out, pretty: pretty, indent: indent + 1)70            }71            if !o.isEmpty { newline(indent) }72            out.append(0x7D)73        }74    }7576    static func numberString(_ d: Double) -> String {77        guard d.isFinite else { return "null" }78        if d == d.rounded(), abs(d) < 9.007199254740992e15 { return String(Int64(d)) }79        return "\(d)"80    }8182    private static func writeString(_ s: String, into out: inout [UInt8]) {83        out.append(0x22)84        for b in s.utf8 {85            switch b {86            case 0x22: out.append(contentsOf: [0x5C, 0x22])87            case 0x5C: out.append(contentsOf: [0x5C, 0x5C])88            case 0x0A: out.append(contentsOf: [0x5C, 0x6E])89            case 0x0D: out.append(contentsOf: [0x5C, 0x72])90            case 0x09: out.append(contentsOf: [0x5C, 0x74])91            case 0..<0x20:92                let hex = Array("0123456789abcdef".utf8)93                out.append(contentsOf: [0x5C, 0x75, 0x30, 0x30, hex[Int(b >> 4)], hex[Int(b & 15)]])94            default: out.append(b)95            }96        }97        out.append(0x22)98    }99100    // MARK: Semantic equality101102    /// Equality as JavaScript sees it: key order is irrelevant and `.int(2)` equals `.double(2.0)`.103    public func semanticallyEquals(_ other: JSONValue) -> Bool {104        switch (self, other) {105        case (.null, .null): return true106        case (.bool(let a), .bool(let b)): return a == b107        case (.int(let a), .int(let b)): return a == b108        case (.double(let a), .double(let b)): return a == b109        case (.int(let a), .double(let b)), (.double(let b), .int(let a)): return Double(a) == b110        case (.string(let a), .string(let b)): return a == b111        case (.array(let a), .array(let b)):112            return a.count == b.count && zip(a, b).allSatisfy { $0.semanticallyEquals($1) }113        case (.object(let a), .object(let b)):114            return a.count == b.count && a.allSatisfy { k, v in b[k].map { v.semanticallyEquals($0) } ?? false }115        default: return false116        }117    }118119    // MARK: Accessors120121    public var isNull: Bool { if case .null = self { return true }; return false }122    public var stringValue: String? { if case .string(let s) = self { return s }; return nil }123    public var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }124    /// The integer value; an integral double is accepted.125    public var intValue: Int? {126        switch self {127        case .int(let i): return Int(exactly: i)128        case .double(let d): return Int(exactly: d)129        default: return nil130        }131    }132    public var doubleValue: Double? {133        switch self {134        case .int(let i): return Double(i)135        case .double(let d): return d136        default: return nil137        }138    }139    public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }140    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }141    public subscript(key: String) -> JSONValue? { objectValue?[key] }142}143144extension JSONValue: ExpressibleByNilLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral,145    ExpressibleByFloatLiteral, ExpressibleByStringLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {146    public init(nilLiteral: ()) { self = .null }147    public init(booleanLiteral value: Bool) { self = .bool(value) }148    public init(integerLiteral value: Int64) { self = .int(value) }149    public init(floatLiteral value: Double) { self = .double(value) }150    public init(stringLiteral value: String) { self = .string(value) }151    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }152    public init(dictionaryLiteral elements: (String, JSONValue)...) {153        self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last }))154    }155}156157// MARK: - Parser158159private struct JSONParser {160    let bytes: [UInt8]161    var i = 0162    var depth = 0163164    init(bytes: [UInt8]) { self.bytes = bytes }165166    func fail(_ message: String) -> DocumentError { .invalidJSON(message, offset: i) }167168    mutating func skipWhitespace() {169        while i < bytes.count, bytes[i] == 0x20 || bytes[i] == 0x0A || bytes[i] == 0x0D || bytes[i] == 0x09 { i += 1 }170    }171172    mutating func parseDocument() throws -> JSONValue {173        if bytes.count >= 3, bytes[0] == 0xEF, bytes[1] == 0xBB, bytes[2] == 0xBF { i = 3 }174        let v = try parseValue()175        skipWhitespace()176        guard i == bytes.count else { throw fail("Unexpected trailing characters") }177        return v178    }179180    mutating func expect(_ word: String) throws {181        let w = Array(word.utf8)182        guard i + w.count <= bytes.count, Array(bytes[i..<i + w.count]) == w else { throw fail("Invalid literal") }183        i += w.count184    }185186    mutating func parseValue() throws -> JSONValue {187        skipWhitespace()188        guard i < bytes.count else { throw fail("Unexpected end of input") }189        switch bytes[i] {190        case 0x6E: try expect("null"); return .null191        case 0x74: try expect("true"); return .bool(true)192        case 0x66: try expect("false"); return .bool(false)193        case 0x22: return .string(try parseString())194        case 0x5B:195            depth += 1196            defer { depth -= 1 }197            guard depth <= 512 else { throw fail("Nesting too deep") }198            i += 1199            var items: [JSONValue] = []200            skipWhitespace()201            if i < bytes.count, bytes[i] == 0x5D { i += 1; return .array(items) }202            while true {203                items.append(try parseValue())204                skipWhitespace()205                guard i < bytes.count else { throw fail("Unterminated array") }206                if bytes[i] == 0x2C { i += 1; continue }207                if bytes[i] == 0x5D { i += 1; return .array(items) }208                throw fail("Expected , or ]")209            }210        case 0x7B:211            depth += 1212            defer { depth -= 1 }213            guard depth <= 512 else { throw fail("Nesting too deep") }214            i += 1215            var object: [String: JSONValue] = [:]216            skipWhitespace()217            if i < bytes.count, bytes[i] == 0x7D { i += 1; return .object(object) }218            while true {219                skipWhitespace()220                guard i < bytes.count, bytes[i] == 0x22 else { throw fail("Expected a string key") }221                let key = try parseString()222                skipWhitespace()223                guard i < bytes.count, bytes[i] == 0x3A else { throw fail("Expected :") }224                i += 1225                object[key] = try parseValue()226                skipWhitespace()227                guard i < bytes.count else { throw fail("Unterminated object") }228                if bytes[i] == 0x2C { i += 1; continue }229                if bytes[i] == 0x7D { i += 1; return .object(object) }230                throw fail("Expected , or }")231            }232        default: return try parseNumber()233        }234    }235236    mutating func parseNumber() throws -> JSONValue {237        let start = i238        var integral = true239        if i < bytes.count, bytes[i] == 0x2D { i += 1 }240        let digitsStart = i241        while i < bytes.count, bytes[i] >= 0x30, bytes[i] <= 0x39 { i += 1 }242        guard i > digitsStart else { throw fail("Invalid value") }243        if bytes[digitsStart] == 0x30, i - digitsStart > 1 { throw fail("Leading zero in number") }244        if i < bytes.count, bytes[i] == 0x2E {245            integral = false246            i += 1247            let f = i248            while i < bytes.count, bytes[i] >= 0x30, bytes[i] <= 0x39 { i += 1 }249            guard i > f else { throw fail("Invalid number") }250        }251        if i < bytes.count, bytes[i] == 0x65 || bytes[i] == 0x45 {252            integral = false253            i += 1254            if i < bytes.count, bytes[i] == 0x2B || bytes[i] == 0x2D { i += 1 }255            let e = i256            while i < bytes.count, bytes[i] >= 0x30, bytes[i] <= 0x39 { i += 1 }257            guard i > e else { throw fail("Invalid number") }258        }259        let s = String(decoding: bytes[start..<i], as: UTF8.self)260        if integral, let v = Int64(s) { return .int(v) }261        guard let d = Double(s) else { throw fail("Invalid number") }262        return .double(d)263    }264265    mutating func hex4() throws -> UInt32 {266        guard i + 4 <= bytes.count else { throw fail("Invalid unicode escape") }267        var v: UInt32 = 0268        for _ in 0..<4 {269            let b = bytes[i]270            let d: UInt32271            switch b {272            case 0x30...0x39: d = UInt32(b - 0x30)273            case 0x41...0x46: d = UInt32(b - 0x41 + 10)274            case 0x61...0x66: d = UInt32(b - 0x61 + 10)275            default: throw fail("Invalid unicode escape")276            }277            v = v << 4 | d278            i += 1279        }280        return v281    }282283    mutating func parseString() throws -> String {284        i += 1 // opening quote285        var buf = [UInt8]()286        func append(_ scalar: UInt32, to buf: inout [UInt8]) {287            let u = Unicode.Scalar(scalar) ?? "\u{FFFD}"288            buf.append(contentsOf: Array(String(Character(u)).utf8))289        }290        while true {291            guard i < bytes.count else { throw fail("Unterminated string") }292            let b = bytes[i]293            if b == 0x22 { i += 1; break }294            if b < 0x20 { throw fail("Control character in string") }295            if b != 0x5C { buf.append(b); i += 1; continue }296            i += 1297            guard i < bytes.count else { throw fail("Unterminated string") }298            let e = bytes[i]299            i += 1300            switch e {301            case 0x22: buf.append(0x22)302            case 0x5C: buf.append(0x5C)303            case 0x2F: buf.append(0x2F)304            case 0x62: buf.append(0x08)305            case 0x66: buf.append(0x0C)306            case 0x6E: buf.append(0x0A)307            case 0x72: buf.append(0x0D)308            case 0x74: buf.append(0x09)309            case 0x75:310                let hi = try hex4()311                if (0xD800..<0xDC00).contains(hi), i + 1 < bytes.count, bytes[i] == 0x5C, bytes[i + 1] == 0x75 {312                    let save = i313                    i += 2314                    let lo = try hex4()315                    if (0xDC00..<0xE000).contains(lo) {316                        append(0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00), to: &buf)317                    } else {318                        i = save319                        append(0xFFFD, to: &buf)320                    }321                } else {322                    append(hi, to: &buf) // a lone surrogate becomes U+FFFD323                }324            default: throw fail("Invalid escape")325            }326        }327        return String(decoding: buf, as: UTF8.self)328    }329}330
Files main
Menu

Theme