-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
Defaults+Bridge.swift
443 lines (360 loc) · 11.3 KB
/
Defaults+Bridge.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
import SwiftUI
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension Defaults.CodableBridge {
public func serialize(_ value: Value?) -> Serializable? {
guard let value else {
return nil
}
do {
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .sortedKeys
let data = try jsonEncoder.encode(value)
return String(data: data, encoding: .utf8)
} catch {
print(error)
return nil
}
}
public func deserialize(_ object: Serializable?) -> Value? {
guard let object else {
return nil
}
return try? Value(jsonString: object)
}
}
/**
Any `Value` that conforms to `Codable` and `Defaults.Serializable` will use `CodableBridge` to do the serialization and deserialization.
*/
extension Defaults {
public struct TopLevelCodableBridge<Value: Codable>: CodableBridge {}
}
/**
`RawRepresentableCodableBridge` is needed because, for example, with `enum SomeEnum: String, Codable, Defaults.Serializable`, the compiler will be confused between `RawRepresentableBridge` and `TopLevelCodableBridge`.
*/
extension Defaults {
public struct RawRepresentableCodableBridge<Value: RawRepresentable & Codable>: CodableBridge {}
}
/**
This exists to avoid compiler ambiguity.
*/
extension Defaults {
public struct CodableNSSecureCodingBridge<Value: Codable & NSSecureCoding & NSObject>: CodableBridge {}
}
extension Defaults {
public struct URLBridge: CodableBridge {
public typealias Value = URL
}
}
extension Defaults {
public struct RawRepresentableBridge<Value: RawRepresentable>: Bridge {
public typealias Value = Value
public typealias Serializable = Value.RawValue
public func serialize(_ value: Value?) -> Serializable? {
value?.rawValue
}
public func deserialize(_ object: Serializable?) -> Value? {
guard let object else {
return nil
}
return Value(rawValue: object)
}
}
}
extension Defaults {
public struct NSSecureCodingBridge<Value: NSSecureCoding & NSObject>: Bridge {
public typealias Value = Value
public typealias Serializable = Data
public func serialize(_ value: Value?) -> Serializable? {
guard let value else {
return nil
}
return try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true)
}
public func deserialize(_ object: Serializable?) -> Value? {
guard let object else {
return nil
}
do {
return try NSKeyedUnarchiver.unarchivedObject(ofClass: Value.self, from: object)
} catch {
print(error)
return nil
}
}
}
}
extension Defaults {
public struct OptionalBridge<Wrapped: Serializable>: Bridge {
public typealias Value = Wrapped.Value
public typealias Serializable = Wrapped.Serializable
public func serialize(_ value: Value?) -> Serializable? {
Wrapped.bridge.serialize(value)
}
public func deserialize(_ object: Serializable?) -> Value? {
Wrapped.bridge.deserialize(object)
}
}
}
extension Defaults {
public struct ArrayBridge<Element: Serializable>: Bridge {
public typealias Value = [Element]
public typealias Serializable = [Element.Serializable]
public func serialize(_ value: Value?) -> Serializable? {
guard let array = value as? [Element.Value] else {
return nil
}
return array.map { Element.bridge.serialize($0) }.compact()
}
public func deserialize(_ array: Serializable?) -> Value? {
guard let array else {
return nil
}
return array.map { Element.bridge.deserialize($0) }.compact() as? Value
}
}
}
extension Defaults {
public struct DictionaryBridge<Key: LosslessStringConvertible & Hashable, Element: Serializable>: Bridge {
public typealias Value = [Key: Element.Value]
public typealias Serializable = [String: Element.Serializable]
public func serialize(_ dictionary: Value?) -> Serializable? {
guard let dictionary else {
return nil
}
// `Key` which stored in `UserDefaults` have to be `String`
return dictionary.reduce(into: Serializable()) { memo, tuple in
memo[String(tuple.key)] = Element.bridge.serialize(tuple.value)
}
}
public func deserialize(_ dictionary: Serializable?) -> Value? {
guard let dictionary else {
return nil
}
return dictionary.reduce(into: Value()) { memo, tuple in
// Use `LosslessStringConvertible` to create `Key` instance
guard let key = Key(tuple.key) else {
return
}
memo[key] = Element.bridge.deserialize(tuple.value)
}
}
}
}
/**
We need both `SetBridge` and `SetAlgebraBridge` because `Set` conforms to `Sequence` but `SetAlgebra` does not. `Set` conforms to `Sequence`, so we can convert it into an array with `Array.init<S>(S)` and store it in the `UserDefaults`. But `SetAlgebra` does not, so it is hard to convert it into an array. Thats why we need the `Defaults.SetAlgebraSerializable` protocol to convert it into an array.
*/
extension Defaults {
public struct SetBridge<Element: Serializable & Hashable>: Bridge {
public typealias Value = Set<Element>
public typealias Serializable = Any
public func serialize(_ set: Value?) -> Serializable? {
guard let set else {
return nil
}
if Element.isNativelySupportedType {
return Array(set)
}
return set.map { Element.bridge.serialize($0 as? Element.Value) }.compact()
}
public func deserialize(_ object: Serializable?) -> Value? {
if Element.isNativelySupportedType {
guard let array = object as? [Element] else {
return nil
}
return Set(array)
}
guard
let array = object as? [Element.Serializable],
let elements = array.map({ Element.bridge.deserialize($0) }).compact() as? [Element]
else {
return nil
}
return Set(elements)
}
}
}
extension Defaults {
public struct SetAlgebraBridge<Value: SetAlgebraSerializable>: Bridge where Value.Element: Serializable {
public typealias Value = Value
public typealias Element = Value.Element
public typealias Serializable = Any
public func serialize(_ setAlgebra: Value?) -> Serializable? {
guard let setAlgebra else {
return nil
}
if Element.isNativelySupportedType {
return setAlgebra.toArray()
}
return setAlgebra.toArray().map { Element.bridge.serialize($0 as? Element.Value) }.compact()
}
public func deserialize(_ object: Serializable?) -> Value? {
if Element.isNativelySupportedType {
guard let array = object as? [Element] else {
return nil
}
return Value(array)
}
guard
let array = object as? [Element.Serializable],
let elements = array.map({ Element.bridge.deserialize($0) }).compact() as? [Element]
else {
return nil
}
return Value(elements)
}
}
}
extension Defaults {
public struct CollectionBridge<Value: CollectionSerializable>: Bridge where Value.Element: Serializable {
public typealias Value = Value
public typealias Element = Value.Element
public typealias Serializable = Any
public func serialize(_ collection: Value?) -> Serializable? {
guard let collection else {
return nil
}
if Element.isNativelySupportedType {
return Array(collection)
}
return collection.map { Element.bridge.serialize($0 as? Element.Value) }.compact()
}
public func deserialize(_ object: Serializable?) -> Value? {
if Element.isNativelySupportedType {
guard let array = object as? [Element] else {
return nil
}
return Value(array)
}
guard
let array = object as? [Element.Serializable],
let elements = array.map({ Element.bridge.deserialize($0) }).compact() as? [Element]
else {
return nil
}
return Value(elements)
}
}
}
extension Defaults {
public struct UUIDBridge: Bridge {
public typealias Value = UUID
public typealias Serializable = String
public func serialize(_ value: Value?) -> Serializable? {
value?.uuidString
}
public func deserialize(_ object: Serializable?) -> Value? {
guard let object else {
return nil
}
return .init(uuidString: object)
}
}
}
extension Defaults {
public struct RangeBridge<T: RangeSerializable>: Bridge {
public typealias Value = T
public typealias Serializable = [Any]
typealias Bound = T.Bound
public func serialize(_ value: Value?) -> Serializable? {
guard let value else {
return nil
}
if Bound.isNativelySupportedType {
return [value.lowerBound, value.upperBound]
}
guard
let lowerBound = Bound.bridge.serialize(value.lowerBound as? Bound.Value),
let upperBound = Bound.bridge.serialize(value.upperBound as? Bound.Value)
else {
return nil
}
return [lowerBound, upperBound]
}
public func deserialize(_ object: Serializable?) -> Value? {
guard let object else {
return nil
}
if Bound.isNativelySupportedType {
guard
let lowerBound = object[safe: 0] as? Bound,
let upperBound = object[safe: 1] as? Bound
else {
return nil
}
return .init(uncheckedBounds: (lower: lowerBound, upper: upperBound))
}
guard
let lowerBound = Bound.bridge.deserialize(object[safe: 0] as? Bound.Serializable) as? Bound,
let upperBound = Bound.bridge.deserialize(object[safe: 1] as? Bound.Serializable) as? Bound
else {
return nil
}
return .init(uncheckedBounds: (lower: lowerBound, upper: upperBound))
}
}
}
extension Defaults {
/**
The bridge which is responsible for `SwiftUI.Color` serialization and deserialization.
It is unsafe to convert `SwiftUI.Color` to `UIColor` and use `UIColor.bridge` to serialize it, because `UIColor` does not hold a color space, but `Swift.Color` does (which means color space might get lost in the conversion). The bridge will always try to preserve the color space whenever `Color#cgColor` exists. Only when `Color#cgColor` is `nil`, will it use `UIColor.bridge` to do the serialization and deserialization.
*/
public struct ColorBridge: Bridge {
public typealias Value = Color
public typealias Serializable = Any
#if os(macOS)
private typealias XColor = NSColor
#else
private typealias XColor = UIColor
#endif
public func serialize(_ value: Value?) -> Serializable? {
guard let value else {
return nil
}
guard
let cgColor = value.cgColor,
let colorSpace = cgColor.colorSpace?.name as? String,
let components = cgColor.components
else {
return XColor.bridge.serialize(XColor(value))
}
return [colorSpace, components] as [Any]
}
public func deserialize(_ object: Serializable?) -> Value? {
if let object = object as? XColor.Serializable {
guard let nativeColor = XColor.bridge.deserialize(object) else {
return nil
}
return Value(nativeColor)
}
guard
let object = object as? [Any],
let rawColorspace = object[0] as? String,
let colorspace = CGColorSpace(name: rawColorspace as CFString),
let components = object[1] as? [CGFloat], // swiftlint:disable:this no_cgfloat
let cgColor = CGColor(colorSpace: colorspace, components: components)
else {
return nil
}
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, visionOS 1.0, iOSApplicationExtension 15.0, macOSApplicationExtension 12.0, tvOSApplicationExtension 15.0, watchOSApplicationExtension 8.0, visionOSApplicationExtension 1.0, *) {
return Value(cgColor: cgColor)
}
return Value(cgColor)
}
}
}
extension Defaults {
public struct AnyBridge: Defaults.Bridge {
public typealias Value = Defaults.AnySerializable
public typealias Serializable = Any
public func deserialize(_ object: Serializable?) -> Value? {
Value(value: object)
}
public func serialize(_ value: Value?) -> Serializable? {
value?.value
}
}
}