Cotton code
58 lines · 2.0 KB · SwiftRaw
// A column's value as the interpreter holds it: JSON's shapes, nothing more.// A plain value, so a face and the Gallery read it with no core in the build.import Foundation/// A column value. JSON's shapes, nothing more: the column's type says how to/// read it (a date is `.text` in ISO 8601, an amount is `.object` with `minor`/// and `currency`, a link is `.text` holding the target record's id).public enum RecordValue: Hashable, Sendable, Codable {    case null    case text(String)    case number(Double)    case bool(Bool)    case list([RecordValue])    case object([String: RecordValue])    public init(from decoder: Decoder) throws {        let c = try decoder.singleValueContainer()        if c.decodeNil() { self = .null }        else if let b = try? c.decode(Bool.self) { self = .bool(b) }        else if let n = try? c.decode(Double.self) { self = .number(n) }        else if let s = try? c.decode(String.self) { self = .text(s) }        else if let l = try? c.decode([RecordValue].self) { self = .list(l) }        else { self = .object(try c.decode([String: RecordValue].self)) }    }    public func encode(to encoder: Encoder) throws {        var c = encoder.singleValueContainer()        switch self {        case .null: try c.encodeNil()        case .text(let s): try c.encode(s)        case .number(let n): try c.encode(n)        case .bool(let b): try c.encode(b)        case .list(let l): try c.encode(l)        case .object(let o): try c.encode(o)        }    }    public var text: String? {        switch self {        case .text(let s): return s.isEmpty ? nil : s        case .number(let n): return n.rounded() == n ? String(Int(n)) : String(n)        default: return nil        }    }    public var number: Double? {        if case .number(let n) = self { return n }        return nil    }    public var bool: Bool? {        if case .bool(let b) = self { return b }        return nil    }    public var isNull: Bool { self == .null }}