Voxley / app · voxley.si / Sources / Voxley / WordList.swift
| 1 | import Foundation |
| 2 | |
| 3 | enum WordList { |
| 4 | enum ImportError: LocalizedError { |
| 5 | case empty, invalidQuotes |
| 6 | case overLimit(newEntries: Int, available: Int) |
| 7 | |
| 8 | var errorDescription: String? { |
| 9 | switch self { |
| 10 | case .empty: |
| 11 | "This file doesn’t contain any words or phrases." |
| 12 | case .invalidQuotes: |
| 13 | "Check the quotation marks in the word list and try again." |
| 14 | case .overLimit(let newEntries, let available): |
| 15 | "This file has \(newEntries) new entries, and \(available) will fit. Shorten the list or remove entries from your vocabulary." |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | static func key(for word: String) -> String { |
| 21 | word.folding(options: .caseInsensitive, locale: Locale(identifier: "en_US_POSIX")) |
| 22 | } |
| 23 | |
| 24 | static func parse(_ text: String) throws -> [String] { |
| 25 | var entries: [String] = [] |
| 26 | var field = "" |
| 27 | var state = FieldState.unquoted |
| 28 | var index = text.startIndex |
| 29 | if text.first == "\u{FEFF}" { text.formIndex(after: &index) } |
| 30 | |
| 31 | func finishField() { |
| 32 | let entry = field.split(whereSeparator: \.isNewline) |
| 33 | .map { $0.trimmingCharacters(in: .whitespaces) } |
| 34 | .filter { !$0.isEmpty } |
| 35 | .joined(separator: " ") |
| 36 | if !entry.isEmpty { entries.append(entry) } |
| 37 | field.removeAll(keepingCapacity: true) |
| 38 | state = .unquoted |
| 39 | } |
| 40 | |
| 41 | while index < text.endIndex { |
| 42 | let character = text[index] |
| 43 | text.formIndex(after: &index) |
| 44 | if state == .quoted { |
| 45 | if character != "\"" { |
| 46 | field.append(character) |
| 47 | } else if index < text.endIndex, text[index] == "\"" { |
| 48 | field.append("\"") |
| 49 | text.formIndex(after: &index) |
| 50 | } else { |
| 51 | state = .closedQuote |
| 52 | } |
| 53 | } else if character.isNewline || character == "," || character == ";" || character == "\t" { |
| 54 | finishField() |
| 55 | } else if state == .closedQuote { |
| 56 | guard character.isWhitespace else { throw ImportError.invalidQuotes } |
| 57 | } else if character == "\"", field.allSatisfy(\.isWhitespace) { |
| 58 | state = .quoted |
| 59 | field.removeAll(keepingCapacity: true) |
| 60 | } else { |
| 61 | field.append(character) |
| 62 | } |
| 63 | } |
| 64 | guard state != .quoted else { throw ImportError.invalidQuotes } |
| 65 | finishField() |
| 66 | return entries |
| 67 | } |
| 68 | |
| 69 | private enum FieldState { case unquoted, quoted, closedQuote } |
| 70 | } |