Cotton code
137 lines · 4.7 KB · SwiftRaw
import Foundation/// A JSON value with a type.////// The boundary speaks JSON, and an answer's `details` or an event's `payload`/// is shaped by the method that sent it — so the alternative to this is `Any`,/// which the repo bans and which would then be cast at every reader. This is/// the one place JSON is held untyped, and it is still typed: every case is/// named, nothing is `Any`, and a reader asks for what it expects (`.string`,/// `.int`, `subscript`) and gets `nil` when the value is something else.////// The Mac's `CottonClient/JSONValue.swift` is the same type. It is copied/// rather than shared because the two apps share no Swift package — the Mac is/// a `swift build` package on macOS and this is an Xcode app on iOS — and a/// third package existing only to hold sixty lines would be a build-graph/// dependency for every target of both.public enum JSONValue: Hashable, Sendable {    case null    case bool(Bool)    case number(Double)    case string(String)    case array([JSONValue])    case object([String: JSONValue])}extension JSONValue: Decodable {    public init(from decoder: Decoder) throws {        let container = try decoder.singleValueContainer()        if container.decodeNil() {            self = .null        } else if let value = try? container.decode(Bool.self) {            self = .bool(value)        } else if let value = try? container.decode(Double.self) {            self = .number(value)        } else if let value = try? container.decode(String.self) {            self = .string(value)        } else if let value = try? container.decode([JSONValue].self) {            self = .array(value)        } else if let value = try? container.decode([String: JSONValue].self) {            self = .object(value)        } else {            throw DecodingError.dataCorruptedError(                in: container,                debugDescription: "not a JSON value"            )        }    }}extension JSONValue: Encodable {    public func encode(to encoder: Encoder) throws {        var container = encoder.singleValueContainer()        switch self {        case .null: try container.encodeNil()        case .bool(let value): try container.encode(value)        case .number(let value): try container.encode(value)        case .string(let value): try container.encode(value)        case .array(let value): try container.encode(value)        case .object(let value): try container.encode(value)        }    }}extension JSONValue {    public var string: String? {        if case .string(let value) = self { return value }        return nil    }    public var bool: Bool? {        if case .bool(let value) = self { return value }        return nil    }    public var int: Int? {        if case .number(let value) = self { return Int(value) }        return nil    }    public var double: Double? {        if case .number(let value) = self { return value }        return nil    }    public var array: [JSONValue]? {        if case .array(let value) = self { return value }        return nil    }    /// The strings of a string array, skipping anything that is not one. What    /// a `data` event's `tables` is read with.    public var strings: [String]? {        guard case .array(let value) = self else { return nil }        return value.compactMap(\.string)    }    /// A member of an object, or `nil` when this is not an object or has no    /// such member.    public subscript(key: String) -> JSONValue? {        if case .object(let members) = self { return members[key] }        return nil    }}extension JSONValue {    /// A value as a window shows it in a cell: `—` for nothing, `yes`/`no`    /// for a flag, a whole number without its `.0`, and an array or object as    /// its JSON. The Mac's browser reads every field through this; a phone    /// screen has typed rows and does not.    public var displayText: String {        switch self {        case .null:            return "—"        case .bool(let value):            return value ? "yes" : "no"        case .number(let value):            return value == value.rounded() && abs(value) < 1e15                ? String(Int(value))                : String(value)        case .string(let value):            return value.isEmpty ? "—" : value        case .array, .object:            guard                let data = try? JSONEncoder().encode(self),                let text = String(data: data, encoding: .utf8)            else { return "—" }            return text        }    }}extension JSONValue: ExpressibleByStringLiteral {    /// A word written in a request as itself (`["op": "ask"]`).    public init(stringLiteral value: String) {        self = .string(value)    }}