SPB Git

Repository Public MIT

RegistryJSON.swift 4.6 KB 107 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassRegistry/RegistryJSON.swift8// Module           : SPGlassRegistry9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//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          : MIT33//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 Foundation4243/// Bounded JSON reading and stable JSON writing for registry documents.44public enum RegistryJSON {45    public static let maximumDocumentBytes = 1024 * 102446    public static let maximumFileBytes = 1024 * 102447    public static let maximumDepth = 124849    /// Decodes `type` after checking the size and nesting depth of the document.50    public static func decode<T: Decodable>(_ type: T.Type, from data: Data, what: String, limit: Int = maximumDocumentBytes) throws(RegistryError) -> T {51        guard data.count <= limit else { throw .tooLarge(what: what, bytes: data.count, limit: limit) }52        guard depth(of: data) <= maximumDepth else { throw .tooDeep(what: what, limit: maximumDepth) }53        do {54            return try JSONDecoder().decode(type, from: data)55        } catch let error as DecodingError {56            throw .malformed(what: what, detail: describe(error))57        } catch {58            throw .malformed(what: what, detail: "it is not valid JSON.")59        }60    }6162    /// Stable encoding: sorted keys, two-space indentation, trailing newline.63    public static func encode<T: Encodable>(_ value: T) throws(RegistryError) -> Data {64        let encoder = JSONEncoder()65        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]66        do {67            var data = try encoder.encode(value)68            data.append(0x0A)69            return data70        } catch {71            throw .malformed(what: "value", detail: "it could not be encoded.")72        }73    }7475    /// Maximum nesting of arrays and objects, computed on the bytes without building the document.76    public static func depth(of data: Data) -> Int {77        var depth = 0, maximum = 0, inString = false, escaped = false78        for byte in data {79            if inString {80                if escaped { escaped = false } else if byte == 0x5C { escaped = true } else if byte == 0x22 { inString = false }81                continue82            }83            switch byte {84            case 0x22: inString = true85            case 0x7B, 0x5B: depth += 1; maximum = max(maximum, depth)86            case 0x7D, 0x5D: depth -= 187            default: break88            }89        }90        return maximum91    }9293    private static func describe(_ error: DecodingError) -> String {94        func path(_ context: DecodingError.Context) -> String {95            let keys = context.codingPath.map { $0.intValue.map { "[\($0)]" } ?? $0.stringValue }.joined(separator: ".")96            return keys.isEmpty ? "the root" : RegistryError.clip(keys)97        }98        switch error {99        case .keyNotFound(let key, let context): return "missing field \"\(RegistryError.clip(key.stringValue))\" at \(path(context))."100        case .typeMismatch(_, let context): return "wrong type at \(path(context))."101        case .valueNotFound(_, let context): return "missing value at \(path(context))."102        case .dataCorrupted(let context): return context.codingPath.isEmpty ? "it is not valid JSON." : "invalid value at \(path(context))."103        @unknown default: return "unexpected structure."104        }105    }106}107
Files main
Menu

Theme