Repository Public
1import Foundation23/// Minimal dynamic JSON tree for reading reference fixtures.4public enum JSON: Sendable {5 case null6 case bool(Bool)7 case number(Double)8 case string(String)9 case array([JSON])10 case object([String: JSON])1112 public init(_ any: Any) {13 switch any {14 case let n as NSNumber:15 if CFGetTypeID(n) == CFBooleanGetTypeID() { self = .bool(n.boolValue) } else { self = .number(n.doubleValue) }16 case let s as String: self = .string(s)17 case let a as [Any]: self = .array(a.map { JSON($0) })18 case let o as [String: Any]: self = .object(o.mapValues { JSON($0) })19 default: self = .null20 }21 }2223 public subscript(key: String) -> JSON {24 if case .object(let o) = self, let v = o[key] { return v }25 return .null26 }27 public subscript(index: Int) -> JSON {28 if case .array(let a) = self, index >= 0, index < a.count { return a[index] }29 return .null30 }31 public var isNull: Bool { if case .null = self { true } else { false } }32 /// Number; the strings "inf", "-inf" and "nan" (and null → NaN) are decoded too.33 public var d: Double {34 switch self {35 case .number(let n): return n36 case .bool(let b): return b ? 1 : 037 case .string(let s):38 switch s { case "inf": return .infinity; case "-inf": return -.infinity; default: return Double(s) ?? .nan }39 default: return .nan40 }41 }42 public var i: Int { Int(d) }43 public var b: Bool { if case .bool(let v) = self { v } else { d != 0 } }44 public var s: String { if case .string(let v) = self { v } else { "" } }45 public var list: [JSON] { if case .array(let a) = self { a } else { [] } }46 public var dict: [String: JSON] { if case .object(let o) = self { o } else { [:] } }47 public var arr: [Double] { list.map(\.d) }48 public var ints: [Int] { list.map(\.i) }49 public var strings: [String] { list.map(\.s) }50 public var mat: [[Double]] { list.map(\.arr) }51 public var keys: [String] { dict.keys.sorted() }52}5354public enum Fixture {55 /// Loads `Fixtures/<name>.json` from a test bundle (`Bundle.module` of the calling test target).56 public static func load(_ name: String, _ bundle: Bundle) -> JSON {57 guard let url = bundle.url(forResource: name, withExtension: "json", subdirectory: "Fixtures"),58 let data = try? Data(contentsOf: url),59 let obj = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) else {60 fatalError("Missing or unreadable fixture \(name).json")61 }62 return JSON(obj)63 }64}6566/// True when `a` matches `b` within a relative tolerance `rel` (scaled by |b|) or an absolute tolerance `abs`.67/// Two NaNs, or two equal infinities, match.68public func isClose(_ a: Double, _ b: Double, rel: Double = 1e-10, abs absTol: Double = 0) -> Bool {69 if a.isNaN || b.isNaN { return a.isNaN && b.isNaN }70 if a == b { return true }71 if a.isInfinite || b.isInfinite { return false }72 let diff = Swift.abs(a - b)73 return diff <= absTol || diff <= rel * Swift.max(Swift.abs(a), Swift.abs(b))74}7576/// Element-wise `isClose` for vectors of equal length.77public func allClose(_ a: [Double], _ b: [Double], rel: Double = 1e-10, abs absTol: Double = 0) -> Bool {78 a.count == b.count && zip(a, b).allSatisfy { isClose($0, $1, rel: rel, abs: absTol) }79}8081/// Largest relative error between two vectors (∞ on a length mismatch); handy in failure messages.82public func maxRelativeError(_ a: [Double], _ b: [Double]) -> Double {83 guard a.count == b.count else { return .infinity }84 var worst = 0.085 for (x, y) in zip(a, b) {86 if x == y || (x.isNaN && y.isNaN) { continue }87 let scale = Swift.max(Swift.abs(x), Swift.abs(y))88 worst = Swift.max(worst, scale > 0 ? Swift.abs(x - y) / scale : 0)89 }90 return worst91}92