-
Notifications
You must be signed in to change notification settings - Fork 0
/
PerfectINI.swift
524 lines (453 loc) · 13.9 KB
/
PerfectINI.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import Foundation
public enum INICodingError: Error {
case unsupported
case missing
case malformed
}
open class INIEncoder: Encoder {
public var codingPath: [CodingKey] = []
public var userInfo: [CodingUserInfoKey : Any] = [:]
internal let _depth: Int
public init() {
_depth = 0
}
internal init(depth: Int = 0) {
_depth = depth + 1
guard _depth < 2 else {
fatalError("INI file layout doesn't supported nested sections")
}
}
func push<Key: CodingKey>(key: Key, value: Any) throws {
guard let k = CodingUserInfoKey.init(rawValue: key.stringValue) else {
throw INICodingError.unsupported
}
userInfo[k] = value
}
public func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
return KeyedEncodingContainer(INIWriter<Key>(self))
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("unsupported unkeyedContainer")
}
public func singleValueContainer() -> SingleValueEncodingContainer {
fatalError("unsupported singleValueContainer")
}
open func encode<T : Encodable>(_ value: T) throws -> Data {
try value.encode(to: self)
var data = Data()
// only top level needs to return the printed sheet.
guard _depth == 0 else {
return data
}
var top: [String: Any] = [:]
for (k, v) in userInfo {
if v is [CodingUserInfoKey: Any], let dic = v as? [CodingUserInfoKey: Any] {
data.append(contentsOf: "\n[\(k.rawValue)]\n".utf8)
for (subk, subv) in dic {
if subv is [CodingUserInfoKey: Any] {
throw INICodingError.unsupported
} else {
data.append(contentsOf: "\(subk.rawValue) = \(subv)\n".utf8)
}
}
} else {
top[k.rawValue] = v
}
}
var anonymous = Data()
for (k, v) in top {
anonymous.append(contentsOf: "\(k) = \(v)\n".utf8)
}
return anonymous + data
}
}
fileprivate struct INIWriter<K : CodingKey>: KeyedEncodingContainerProtocol {
typealias Key = K
let codingPath: [CodingKey] = []
let _p: INIEncoder
init(_ parent: INIEncoder) {
self._p = parent
}
mutating func encodeNil(forKey key: K) throws {
throw INICodingError.unsupported
}
mutating func encode(_ value: Bool, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Int, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Int8, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Int16, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Int32, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Int64, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: UInt, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: UInt8, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: UInt16, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: UInt32, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: UInt64, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Float, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: Double, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode(_ value: String, forKey key: K) throws {
try self._p.push(key: key, value: value)
}
mutating func encode<T>(_ value: T, forKey key: K) throws where T : Encodable {
let child = INIEncoder(depth: _p._depth)
_ = try child.encode(value)
try self._p.push(key: key, value: child.userInfo)
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError("unimplemented nestedContainer")
}
mutating func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer {
fatalError("unimplemented nestedUnkeyedContainer")
}
mutating func superEncoder() -> Encoder {
fatalError("unimplemented superEncoder")
}
mutating func superEncoder(forKey key: K) -> Encoder {
fatalError("unimplemented superEncoder forKey")
}
}
fileprivate class Stack<T> {
internal var array: [T] = []
public func push(_ element: T) {
array.append(element)
}
public func pop () -> T? {
if array.isEmpty { return nil }
let element = array.removeLast()
return element
}
public func top () -> T? {
return array.last
}
public var isEmpty: Bool { return array.isEmpty }
}
fileprivate class INIParser {
var _sections: [String:Any] = [:]
enum State {
case title, variable, value, singleQuotation, doubleQuotation
}
enum ContentType {
case section(String)
case assignment(String, String)
}
internal func parse(line: String) throws -> ContentType? {
var cache = ""
var state = State.variable
let stack = Stack<State>()
var variable: String? = nil
for c in line {
switch c {
case "[":
if state == .variable {
cache = ""
stack.push(state)
state = .title
}
break
case "]":
if state == .title {
guard let last = stack.pop() else { throw INICodingError.unsupported }
state = last
return ContentType.section(cache)
}
break
case "=":
if state == .variable {
variable = cache
cache = ""
state = .value
}
break
case "#", ";":
if state == .value {
if let v = variable {
return ContentType.assignment(v, cache)
} else {
throw INICodingError.unsupported
}
} else {
return nil
}
case "\"":
if state == .doubleQuotation {
guard let last = stack.pop() else {
throw INICodingError.unsupported
}
state = last
} else {
stack.push(state)
state = .doubleQuotation
}
cache.append(c)
break
case "\'":
if state == .singleQuotation {
guard let last = stack.pop() else {
throw INICodingError.unsupported
}
state = last
} else {
stack.push(state)
state = .singleQuotation
}
cache.append(c)
break
default:
cache.append(c)
}
}
guard state == .value, let v = variable else {
throw INICodingError.unsupported
}
return ContentType.assignment(
v.trimmingCharacters(in: [" ", "\t", "\n", "\r"]),
cache.trimmingCharacters(in: [" ", "\t", "\n", "\r"]))
}
public init(_ data: Data) throws {
guard let text = String(bytes: data, encoding: .utf8) else {
throw INICodingError.unsupported
}
let lines: [String] = text.split(separator: "\n").map { String($0) }
var title = ""
for line in lines {
if let content = try parse(line: line) {
switch content {
case .section(let newTitle):
if newTitle.isEmpty {
break
}
title = newTitle
break
case .assignment(let variable, let value):
if title.isEmpty {
_sections[variable] = value
} else {
if var sec = _sections[title] as? [String:Any] {
sec[variable] = value
_sections[title] = sec
} else {
_sections[title] = [variable: value]
}
}
break
}
}
}
}
}
fileprivate struct INIReader<K : CodingKey>: KeyedDecodingContainerProtocol {
var codingPath: [CodingKey] = []
typealias Key = K
var allKeys: [K] {
return _p.storage.keys.map { Key(stringValue: $0)! }
}
let _p: INIDecoder
public init(parent: INIDecoder) {
_p = parent
}
func contains(_ key: K) -> Bool {
return _p.storage.keys.contains(key.stringValue)
}
func decodeNil(forKey key: K) throws -> Bool {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
return str.isEmpty
}
func decode(_ type: Bool.Type, forKey key: K) throws -> Bool {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
switch str.lowercased() {
case "true": return true
case "false": return false
case "0": return false
default:
return true
}
}
func decode(_ type: Int.Type, forKey key: K) throws -> Int {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Int(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Int8(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Int16(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Int32(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Int64(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: UInt.Type, forKey key: K) throws -> UInt {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = UInt(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = UInt8(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = UInt16(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = UInt32(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = UInt64(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: Float.Type, forKey key: K) throws -> Float {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Float(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: Double.Type, forKey key: K) throws -> Double {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
guard let i = Double(str) else {
throw INICodingError.malformed
}
return i
}
func decode(_ type: String.Type, forKey key: K) throws -> String {
guard let str = _p.storage[key.stringValue] as? String else {
throw INICodingError.missing
}
return str
}
func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T : Decodable {
guard let dic = _p.storage[key.stringValue] as? [String:Any] else {
throw INICodingError.missing
}
let decoder = INIDecoder()
decoder.storage = dic
return try decoder.decode(T.self)
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
throw INICodingError.unsupported
}
func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer {
throw INICodingError.unsupported
}
func superDecoder() throws -> Decoder {
throw INICodingError.unsupported
}
func superDecoder(forKey key: K) throws -> Decoder {
throw INICodingError.unsupported
}
}
open class INIDecoder: Decoder {
public var codingPath: [CodingKey] = []
public var userInfo: [CodingUserInfoKey : Any] = [:]
fileprivate var storage: [String: Any] = [:]
fileprivate var parser: INIParser? = nil
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
let reader = INIReader<Key>(parent: self)
return KeyedDecodingContainer(reader)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
fatalError("unsupported unkeyedContainer")
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
fatalError("unsupported singleValueContainer")
}
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
let ps = try INIParser(data)
storage = ps._sections
parser = ps
return try type.init(from: self)
}
internal func decode<T: Decodable>(_ type: T.Type) throws -> T {
return try type.init(from: self)
}
}