/// Minimal JSON value-stream scanner used by the yaml-test-suite gap /// tests to split concatenated in-JSON expectation documents. struct JSONStreamScanner { let text: String var out: [String] = [] var depth = 0 var inString = false var escaped = false var start: String.Index? mutating func scan() -> [String] { var index = text.startIndex while index < text.endIndex { if inString { stepInString(text[index]) } else { stepStructural(text[index], at: index) } index = text.index(after: index) } if let begin = start { out.append(String(text[begin...])) } return out.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } } private mutating func stepInString(_ character: Character) { if escaped { escaped = false } else if character == "\\" { escaped = true } else if character == "\"" { inString = false } } private mutating func stepStructural(_ character: Character, at index: String.Index) { switch character { case "\"": if start == nil { start = index } inString = true case "{", "[": if start == nil { start = index } depth += 1 case "}", "]": depth -= 1 if depth == 0, let begin = start { out.append(String(text[begin ... index])) start = nil } case " ", "\n", "\r", "\t": if depth == 0, let begin = start { out.append(String(text[begin ..< index])) start = nil } default: if depth == 0, start == nil { start = index } } } }