Format.swift (7726B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 4 /// A logical line of a logbook file: the text outside strings (each string is reduced to its opening 5 /// quote there), the decoded strings, and the position of the line in the original file. 6 struct LogLine { 7 var text: String 8 var strings: [String] 9 var range: Range<Int> // bytes, trailing newline included 10 11 var keyword: Substring { text.prefix { $0 != " " } } 12 var argument: Substring { 13 guard let space = text.firstIndex(of: " ") else { return "" } 14 return text[text.index(after: space)...] 15 } 16 } 17 18 enum LogFormat { 19 /// Splits a file into logical lines, like the Subsurface reader: a quoted string may 20 /// span several physical lines (continuation marked by a tab). 21 static func lines(_ data: [UInt8], skipSamples: Bool = false) -> [LogLine] { 22 var out = [LogLine]() 23 var pos = 0 24 let end = data.count 25 while pos < end { 26 let start = pos 27 let first = data[pos] 28 // Empty line or line starting with a tab: leftover of a merge conflict, ignored. 29 if first == 0x0a || first == 0x09 { 30 while pos < end { pos += 1; if data[pos - 1] == 0x0a { break } } 31 continue 32 } 33 // Profile samples: the bulk of the data, without strings; they can be skipped in one go. 34 if skipSamples, first == 0x20 || (first >= 0x30 && first <= 0x39) { 35 while pos < end { pos += 1; if data[pos - 1] == 0x0a { break } } 36 continue 37 } 38 var text = [UInt8]() 39 var strings = [String]() 40 while pos < end { 41 let c = data[pos]; pos += 1 42 if c == 0x0a { break } 43 text.append(c) 44 if c == 0x22 { 45 var s = [UInt8]() 46 scan: while pos < end { 47 let d = data[pos]; pos += 1 48 switch d { 49 case 0x0a: 50 s.append(0x0a) 51 if pos < end, data[pos] == 0x09 { pos += 1 } 52 case 0x5c: 53 if pos < end { s.append(data[pos]); pos += 1 } 54 case 0x22: 55 break scan 56 default: 57 s.append(d) 58 } 59 } 60 strings.append(String(decoding: s, as: UTF8.self)) 61 } 62 } 63 out.append(LogLine(text: String(decoding: text, as: UTF8.self), strings: strings, range: start..<pos)) 64 } 65 return out 66 } 67 68 /// Quotes a string the way Subsurface writes it. 69 static func quote(_ value: String) -> String { 70 var out = "\"" 71 let bytes = Array(value.utf8) 72 var i = 0 73 var buffer = [UInt8]() 74 while i < bytes.count { 75 let c = bytes[i] 76 switch c { 77 case 1...8, 11, 12, 14...31: 78 buffer.append(0x3f) 79 case 0x5c: 80 buffer.append(contentsOf: [0x5c, 0x5c]) 81 case 0x22: 82 buffer.append(contentsOf: [0x5c, 0x22]) 83 case 0x0a: 84 buffer.append(0x0a) 85 if !(i + 1 < bytes.count && bytes[i + 1] == 0x0a) { buffer.append(0x09) } 86 case 0x0d: 87 break 88 default: 89 buffer.append(c) 90 } 91 i += 1 92 } 93 out += String(decoding: buffer, as: UTF8.self) 94 return out + "\"" 95 } 96 97 /// Number at the start of a text, strtod-style (the rest, unit included, is ignored). 98 static func number<S: StringProtocol>(_ text: S) -> Double { 99 var digits = "" 100 var seenDot = false 101 for (i, ch) in text.enumerated() { 102 if ch == " " && digits.isEmpty { continue } 103 if (ch == "-" || ch == "+") && digits.isEmpty && i == 0 { digits.append(ch); continue } 104 if ch == "-" && digits.isEmpty { digits.append(ch); continue } 105 if ch.isASCII, ch.isNumber { digits.append(ch); continue } 106 if ch == ".", !seenDot { seenDot = true; digits.append(ch); continue } 107 break 108 } 109 return Double(digits) ?? 0 110 } 111 112 static func integer<S: StringProtocol>(_ text: S) -> Int { Int(number(text)) } 113 114 /// "m:ss" in seconds. 115 static func duration<S: StringProtocol>(_ text: S) -> Int { 116 let parts = text.split(separator: ":", maxSplits: 1) 117 let m = parts.first.map { integer($0) } ?? 0 118 let s = parts.count > 1 ? integer(parts[1]) : 0 119 return m * 60 + s 120 } 121 122 /// Thousandths written like Subsurface: at least one decimal, trailing zeros removed ("12.5", "3.0"). 123 static func milli(_ value: Int) -> String { 124 let sign = value < 0 ? "-" : "" 125 let v = abs(value) 126 var frac = String(format: "%03d", v % 1000) 127 if frac.hasSuffix("0") { frac.removeLast() } 128 if frac.hasSuffix("0") { frac.removeLast() } 129 return "\(sign)\(v / 1000).\(frac)" 130 } 131 132 static func milli(_ value: Double) -> String { milli(Int((value * 1000).rounded())) } 133 134 static func minutes(_ seconds: Int) -> String { "\(seconds / 60):" + String(format: "%02d", seconds % 60) } 135 136 /// Stable hash of a text (FNV-1a, 32 bits). 137 static func stableHash(_ text: String) -> UInt32 { 138 var hash: UInt32 = 2_166_136_261 139 for byte in text.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 } 140 return hash 141 } 142 143 /// Splits `key=value key2="string" word`; the strings come from the decoded list of the line. 144 static func keyValues<S: StringProtocol>(_ text: S, strings: [String]) -> [(key: String, value: String)] { 145 var out = [(String, String)]() 146 var next = 0 147 for token in text.split(separator: " ", omittingEmptySubsequences: true) { 148 if let eq = token.firstIndex(of: "=") { 149 let key = String(token[..<eq]) 150 var value = String(token[token.index(after: eq)...]) 151 if value.hasPrefix("\"") { 152 value = next < strings.count ? strings[next] : "" 153 next += 1 154 } 155 out.append((key, value)) 156 } else if token.hasPrefix("\"") { 157 // Standalone string (a list of tags, for example): consumed, without a key. 158 out.append(("", next < strings.count ? strings[next] : "")) 159 next += 1 160 } else { 161 out.append((String(token), "")) 162 } 163 } 164 return out 165 } 166 } 167 168 /// Calendar for Subsurface's "naive" times: everything is computed in UTC. 169 public enum NaiveTime { 170 public static let calendar: Calendar = { 171 var c = Calendar(identifier: .gregorian) 172 c.timeZone = TimeZone(identifier: "UTC")! 173 return c 174 }() 175 176 public static func timestamp(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Int? { 177 let parts = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute, second: second) 178 return calendar.date(from: parts).map { Int($0.timeIntervalSince1970) } 179 } 180 181 public static func components(_ when: Int) -> DateComponents { 182 calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekday], from: Date(timeIntervalSince1970: TimeInterval(when))) 183 } 184 185 /// Current local time expressed as a naive time. 186 public static func now(in zone: TimeZone = .current) -> Int { 187 let date = Date() 188 return Int(date.timeIntervalSince1970) + zone.secondsFromGMT(for: date) 189 } 190 }