SPB Git

Repository Public

TronJSON.swift 11.3 KB 306 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraTron/TronJSON.swift8// Module           : Qyvora Tron9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath4344/// A JSON value whose numbers keep their text. The node API prints balances and fees in sun as plain JSON numbers;45/// a parser that goes through `Double` would round anything above 2^53, so the digits are kept as they were sent and46/// converted to integers exactly, or not at all.47///48/// The parser is strict (RFC 8259, no duplicate key, no lone surrogate, bounded depth and number length) and returns49/// nil for anything else: a hostile answer cannot trap it.50enum TronJSON: Equatable, Sendable {51    case null52    case bool(Bool)53    /// The number as written: `-?digits[.digits][e[+-]digits]`.54    case number(String)55    case string(String)56    case array([TronJSON])57    case object([String: TronJSON])5859    static let maximumDepth = 4860    static let maximumNumberLength = 646162    subscript(key: String) -> TronJSON? {63        if case .object(let o) = self { return o[key] }64        return nil65    }6667    var string: String? {68        if case .string(let s) = self { return s }69        return nil70    }7172    var array: [TronJSON]? {73        if case .array(let a) = self { return a }74        return nil75    }7677    var object: [String: TronJSON]? {78        if case .object(let o) = self { return o }79        return nil80    }8182    var bool: Bool? {83        if case .bool(let b) = self { return b }84        return nil85    }8687    /// A non-negative integer below 2^64 written as a JSON number of digits only, or as such a text.88    var uint64: UInt64? {89        switch self {90        case .number(let text), .string(let text):91            guard !text.isEmpty, text.utf8.count <= 20, text.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }) else { return nil }92            return UInt64(text)93        default:94            return nil95        }96    }9798    // MARK: Parsing99100    static func parse(_ data: Data) -> TronJSON? { parse(Bytes(data)) }101102    static func parse(_ bytes: Bytes) -> TronJSON? {103        var parser = Parser(bytes: bytes)104        parser.skipSpace()105        guard let value = parser.value(depth: 0) else { return nil }106        parser.skipSpace()107        return parser.index == bytes.count ? value : nil108    }109110    private struct Parser {111        let bytes: Bytes112        var index = 0113114        mutating func skipSpace() {115            while index < bytes.count, bytes[index] == 0x20 || bytes[index] == 0x09 || bytes[index] == 0x0a || bytes[index] == 0x0d { index += 1 }116        }117118        mutating func literal(_ text: StaticString) -> Bool {119            let n = text.utf8CodeUnitCount120            guard index + n <= bytes.count else { return false }121            let matches = text.withUTF8Buffer { buffer in (0..<n).allSatisfy { bytes[index + $0] == buffer[$0] } }122            if matches { index += n }123            return matches124        }125126        mutating func value(depth: Int) -> TronJSON? {127            guard depth <= TronJSON.maximumDepth, index < bytes.count else { return nil }128            switch bytes[index] {129            case 0x7b: return object(depth: depth)130            case 0x5b: return array(depth: depth)131            case 0x22: return string().map { .string($0) }132            case 0x74: return literal("true") ? .bool(true) : nil133            case 0x66: return literal("false") ? .bool(false) : nil134            case 0x6e: return literal("null") ? .null : nil135            case 0x2d, 0x30...0x39: return number()136            default: return nil137            }138        }139140        mutating func digits() -> Int {141            let start = index142            while index < bytes.count, bytes[index] >= 0x30, bytes[index] <= 0x39 { index += 1 }143            return index - start144        }145146        mutating func number() -> TronJSON? {147            let start = index148            if bytes[index] == 0x2d { index += 1 }149            guard index < bytes.count else { return nil }150            if bytes[index] == 0x30 {151                index += 1152            } else {153                guard digits() > 0 else { return nil }154            }155            if index < bytes.count, bytes[index] == 0x2e {156                index += 1157                guard digits() > 0 else { return nil }158            }159            if index < bytes.count, bytes[index] == 0x65 || bytes[index] == 0x45 {160                index += 1161                if index < bytes.count, bytes[index] == 0x2b || bytes[index] == 0x2d { index += 1 }162                guard digits() > 0 else { return nil }163            }164            guard index - start <= TronJSON.maximumNumberLength else { return nil }165            return .number(String(decoding: bytes[start..<index], as: UTF8.self))166        }167168        mutating func hex4() -> UInt32? {169            guard index + 4 <= bytes.count else { return nil }170            var v: UInt32 = 0171            for _ in 0..<4 {172                let c = bytes[index]173                let d: UInt32174                switch c {175                case 0x30...0x39: d = UInt32(c - 0x30)176                case 0x41...0x46: d = UInt32(c - 0x41 + 10)177                case 0x61...0x66: d = UInt32(c - 0x61 + 10)178                default: return nil179                }180                v = v << 4 | d181                index += 1182            }183            return v184        }185186        mutating func string() -> String? {187            guard index < bytes.count, bytes[index] == 0x22 else { return nil }188            index += 1189            var out = Bytes()190            while index < bytes.count {191                let c = bytes[index]192                index += 1193                switch c {194                case 0x22:195                    return String(validating: out, as: UTF8.self)196                case 0x5c:197                    guard index < bytes.count else { return nil }198                    let e = bytes[index]199                    index += 1200                    switch e {201                    case 0x22, 0x5c, 0x2f: out.append(e)202                    case 0x62: out.append(0x08)203                    case 0x66: out.append(0x0c)204                    case 0x6e: out.append(0x0a)205                    case 0x72: out.append(0x0d)206                    case 0x74: out.append(0x09)207                    case 0x75:208                        guard var scalar = hex4() else { return nil }209                        if (0xd800...0xdbff).contains(scalar) {210                            guard index + 2 <= bytes.count, bytes[index] == 0x5c, bytes[index + 1] == 0x75 else { return nil }211                            index += 2212                            guard let low = hex4(), (0xdc00...0xdfff).contains(low) else { return nil }213                            scalar = 0x10000 + ((scalar - 0xd800) << 10) + (low - 0xdc00)214                        }215                        guard let u = Unicode.Scalar(scalar) else { return nil }216                        out.append(contentsOf: Bytes(String(Character(u)).utf8))217                    default: return nil218                    }219                case 0x00...0x1f:220                    return nil221                default:222                    out.append(c)223                }224            }225            return nil226        }227228        mutating func array(depth: Int) -> TronJSON? {229            index += 1230            var items = [TronJSON]()231            skipSpace()232            if index < bytes.count, bytes[index] == 0x5d {233                index += 1234                return .array(items)235            }236            while true {237                skipSpace()238                guard let v = value(depth: depth + 1) else { return nil }239                items.append(v)240                skipSpace()241                guard index < bytes.count else { return nil }242                if bytes[index] == 0x2c { index += 1; continue }243                guard bytes[index] == 0x5d else { return nil }244                index += 1245                return .array(items)246            }247        }248249        mutating func object(depth: Int) -> TronJSON? {250            index += 1251            var members = [String: TronJSON]()252            skipSpace()253            if index < bytes.count, bytes[index] == 0x7d {254                index += 1255                return .object(members)256            }257            while true {258                skipSpace()259                guard let key = string() else { return nil }260                skipSpace()261                guard index < bytes.count, bytes[index] == 0x3a else { return nil }262                index += 1263                skipSpace()264                guard let v = value(depth: depth + 1) else { return nil }265                guard members.updateValue(v, forKey: key) == nil else { return nil }266                skipSpace()267                guard index < bytes.count else { return nil }268                if bytes[index] == 0x2c { index += 1; continue }269                guard bytes[index] == 0x7d else { return nil }270                index += 1271                return .object(members)272            }273        }274    }275276    // MARK: Writing (request bodies)277278    var serialized: Data { Data(text.utf8) }279280    private var text: String {281        switch self {282        case .null: return "null"283        case .bool(let b): return b ? "true" : "false"284        case .number(let n): return n285        case .string(let s): return Self.quote(s)286        case .array(let a): return "[" + a.map(\.text).joined(separator: ",") + "]"287        case .object(let o): return "{" + o.keys.sorted().map { Self.quote($0) + ":" + (o[$0]?.text ?? "null") }.joined(separator: ",") + "}"288        }289    }290291    private static func quote(_ s: String) -> String {292        var out = "\""293        for u in s.unicodeScalars {294            switch u.value {295            case 0x22: out += "\\\""296            case 0x5c: out += "\\\\"297            case 0x00...0x1f, 0x7f:298                let h = String(u.value, radix: 16)299                out += "\\u" + String(repeating: "0", count: 4 - h.count) + h300            default: out.unicodeScalars.append(u)301            }302        }303        return out + "\""304    }305}306
Files main
Menu

Theme