import Foundation /// A table read from CSV text, quote-aware as RFC 4180, and written back with its own delimiter. public struct CSVTable: Sendable, Equatable { /// In order of preference when more than one gives a table. public static let delimiters: [Character] = ["\t", ";", ","] public var rows: [[String]] public let delimiter: Character public init(rows: [[String]], delimiter: Character = ",") { self.rows = rows self.delimiter = delimiter } /// Reads the body of a stored table: the delimiter that gives every row the same field count, else the one /// that splits the first row most. public init(text: String) { if let table = Self.detect(text, minimumRows: 1) { self = table return } let splits = Self.delimiters.map { (delimiter: $0, records: Self.records(text, delimiter: $0).records) } let best = splits.max { ($0.records.first?.count ?? 0) < ($1.records.first?.count ?? 0) } let split = best.flatMap { ($0.records.first?.count ?? 0) > 1 ? $0 : nil } ?? splits[splits.count - 1] self.init(rows: split.records, delimiter: split.delimiter) let width = columnCount rows = rows.map { $0 + Array(repeating: "", count: width - $0.count) } } /// Pasted text as a table: at least two rows, every row the same number of fields, two or more, and no open quote. public static func detect(_ text: String) -> CSVTable? { detect(text, minimumRows: 2) } private static func detect(_ text: String, minimumRows: Int) -> CSVTable? { for delimiter in delimiters { let (records, closed) = records(text, delimiter: delimiter) guard closed, records.count >= minimumRows, let count = records.first?.count, count >= 2, records.allSatisfy({ $0.count == count }) else { continue } return CSVTable(rows: records, delimiter: delimiter) } return nil } /// The records of CSV text; empty lines are skipped, and `closed` is false when a quote is never closed. public static func records(_ text: String, delimiter: Character) -> (records: [[String]], closed: Bool) { var records: [[String]] = [] var fields: [String] = [] var field = "" var inQuotes = false var quoted = false var recordQuoted = false let characters = Array(text.replacingOccurrences(of: "\r\n", with: "\n")) func endRecord() { fields.append(field) if !(fields.count == 1 && fields[0].isEmpty && !recordQuoted) { records.append(fields) } fields = [] field = "" quoted = false recordQuoted = false } var index = 0 while index < characters.count { let character = characters[index] if inQuotes { if character == "\"" { if index + 1 < characters.count, characters[index + 1] == "\"" { field.append("\"") index += 1 } else { inQuotes = false } } else { field.append(character) } } else if character == "\"", field.isEmpty, !quoted { inQuotes = true quoted = true recordQuoted = true } else if character == delimiter { fields.append(field) field = "" quoted = false } else if character == "\n" { endRecord() } else { field.append(character) } index += 1 } if !field.isEmpty || !fields.isEmpty || recordQuoted { endRecord() } return (records, !inQuotes) } /// The CSV text, rows padded to the same width; a field is quoted only when it must be. public func text() -> String { let width = columnCount return rows.map { row in let padded = row + Array(repeating: "", count: width - row.count) // A lone empty field would be an empty line, which reads back as no row at all. if padded.count == 1, padded[0].isEmpty { return "\"\"" } return padded.map(quoted).joined(separator: String(delimiter)) }.joined(separator: "\n") } private func quoted(_ field: String) -> String { // Any delimiter, not only its own: a read-back picks the delimiter that splits every row the same. guard field.contains(where: { Self.delimiters.contains($0) || $0 == "\"" || $0 == "\n" || $0 == "\r" }) else { return field } return "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\"" } public var columnCount: Int { rows.map(\.count).max() ?? 0 } /// A table without a cell is no table any more. public var isEmpty: Bool { rows.isEmpty || columnCount == 0 } public subscript(row: Int, column: Int) -> String { get { column < rows[row].count ? rows[row][column] : "" } set { if rows[row].count <= column { rows[row] += Array(repeating: "", count: column + 1 - rows[row].count) } rows[row][column] = newValue } } public mutating func addRow() { rows.append(Array(repeating: "", count: max(1, columnCount))) } public mutating func addColumn() { let width = columnCount rows = rows.map { $0 + Array(repeating: "", count: width + 1 - $0.count) } } public mutating func removeRow(at index: Int) { rows.remove(at: index) } public mutating func removeColumn(at index: Int) { rows = rows.map { row in var row = row if index < row.count { row.remove(at: index) } return row } } }