-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyValueEncoder.swift
More file actions
763 lines (617 loc) · 24.3 KB
/
KeyValueEncoder.swift
File metadata and controls
763 lines (617 loc) · 24.3 KB
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//
// KeyValueEncoder.swift
// KeyValueCoder
//
// Created by Simon Whitty on 16/17/2023.
// Copyright 2023 Simon Whitty
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/swhitty/KeyValueCoder
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// Top level encoder that converts `Codable` instances into loosely typed `[String: Any]`, `[Any]` or `Any`.
public struct KeyValueEncoder: Sendable {
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey: any Sendable]
/// The strategy to use for encoding Date types.
public var dateEncodingStrategy: DateEncodingStrategy = .date
/// The strategy to use for encoding each types keys.
public var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys
/// The strategy to use for encoding `nil`. Defaults to `Optional<Any>.none` which can be cast to any optional type.
public var nilEncodingStrategy: NilEncodingStrategy = .default
/// Initializes `self` with default strategies.
public init () {
self.userInfo = [:]
}
/// Encodes a value into a loosely typed key value type. May be a container `[Any]`, `[String: Any]`
/// or any supported plist primitive `Bool`, `String`, `Int`, `UInt`, `URL`, `Data` or `Decimal`.
/// - Parameter value: The `Encodable` value to encode.
/// - Returns: The encoded value.
public func encode<T>(_ value: T) throws -> Any? where T: Encodable {
try encodeValue(value).getValue(strategy: nilEncodingStrategy)
}
/// Strategy used to encode nil values.
public typealias NilEncodingStrategy = NilCodingStrategy
/// Strategy to determine how to encode a type’s coding keys as String values.
public enum KeyEncodingStrategy: Sendable {
/// A key encoding strategy that converts camel-case keys to snake-case keys.
case convertToSnakeCase
/// A key encoding strategy that doesn’t change key names during encoding.
case useDefaultKeys
}
public enum DateEncodingStrategy: Sendable {
/// Encodes dates by directly casting to Any.
case date
/// Encodes dates to Int in terms of milliseconds since midnight UTC on January 1, 1970.
case millisecondsSince1970
/// Encodes dates to Int in terms of seconds since midnight UTC on January 1, 1970.
case secondsSince1970
/// Encodes dates to Any using a closure
case custom(@Sendable (Date) throws -> Any)
/// Encodes dates to ISO8601 strings.
static func iso8601(options: ISO8601DateFormatter.Options = [.withInternetDateTime]) -> Self {
.custom {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = options
return formatter.string(from: $0)
}
}
}
}
/// Strategy used to encode and decode nil values.
public enum NilCodingStrategy: Sendable {
/// `nil` values are removed
case removed
/// `nil` values are substituted with a placeholder value
case placeholder(any Sendable, isNull: @Sendable (Any) -> Bool)
/// `nil` values are substituted with `Optional<Any>.none`. Can be cast to any optional type.
public static var `default`: NilCodingStrategy { .placeholder(Optional<any Sendable>.none as any Sendable, isNull: isOptionalNone) }
/// `nil` values are substituted with `"$null"` placeholder string. Compatible with `PropertyListEncoder`.
public static var stringNull: NilCodingStrategy { .placeholder("$null", isNull: { ($0 as? String == "$null") }) }
/// `nil` values are substituted with `"NSNull()"`. Compatible with `JSONSerialization`.
public static var nsNull: NilCodingStrategy { .placeholder(NSNull(), isNull: { $0 is NSNull }) }
}
#if canImport(Combine)
import Combine
extension KeyValueEncoder: TopLevelEncoder {
public typealias Output = Any?
}
#endif
extension KeyValueEncoder {
struct EncodingStrategy {
var optionals: NilEncodingStrategy
var keys: KeyEncodingStrategy
var dates: DateEncodingStrategy
}
static func makePlistCompatible() -> KeyValueEncoder {
var encoder = KeyValueEncoder()
encoder.nilEncodingStrategy = .stringNull
return encoder
}
enum EncodedValue {
case null
case value(Any)
case provider(() throws -> EncodedValue)
func getValue(strategy: NilEncodingStrategy) throws -> Any? {
switch self {
case .null:
return strategy.value
case let .value(val):
return val
case let .provider(closure):
return try closure().getValue(strategy: strategy)
}
}
}
func encodeValue<T: Encodable>(_ value: T) throws -> EncodedValue {
return try Encoder(userInfo: userInfo, strategy: strategy).encodeToValue(value)
}
}
extension KeyValueEncoder.NilEncodingStrategy {
public func isNull(_ value: Any?) -> Bool {
guard let value else { return true }
return isNull(value)
}
public func isNull(_ value: Any) -> Bool {
switch self {
case .removed:
return Self.isOptionalNone(value)
case .placeholder(_, isNull: let closure):
return closure(value)
}
}
static func isOptionalNone(_ value: Any) -> Bool {
if case nil as Any? = value {
return true
} else {
return false
}
}
}
private extension KeyValueEncoder.NilEncodingStrategy {
var value: Any? {
switch self {
case .removed: return nil
case .placeholder(let value, _): return value
}
}
}
private extension KeyValueEncoder {
var strategy: EncodingStrategy {
EncodingStrategy(
optionals: nilEncodingStrategy,
keys: keyEncodingStrategy,
dates: dateEncodingStrategy
)
}
final class Encoder: Swift.Encoder {
let codingPath: [any CodingKey]
let userInfo: [CodingUserInfoKey: Any]
let strategy: EncodingStrategy
init(codingPath: [any CodingKey] = [], userInfo: [CodingUserInfoKey: Any], strategy: EncodingStrategy) {
self.codingPath = codingPath
self.userInfo = userInfo
self.strategy = strategy
}
private(set) var container: EncodedValue? {
didSet {
precondition(oldValue == nil)
}
}
func getEncodedValue() throws -> EncodedValue {
guard let container else {
return .value([String: Any]())
}
return container
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
let keyed = KeyedContainer<Key>(codingPath: codingPath, userInfo: userInfo, strategy: strategy)
container = .provider(keyed.getEncodedValue)
return KeyedEncodingContainer(keyed)
}
func unkeyedContainer() -> any UnkeyedEncodingContainer {
let unkeyed = UnkeyedContainer(codingPath: codingPath, userInfo: userInfo, strategy: strategy)
container = .provider(unkeyed.getEncodedValue)
return unkeyed
}
func singleValueContainer() -> any SingleValueEncodingContainer {
let single = SingleContainer(codingPath: codingPath, userInfo: userInfo, strategy: strategy)
container = .provider(single.getEncodedValue)
return single
}
func encodeToValue<T>(_ value: T) throws -> EncodedValue where T: Encodable {
guard let encoded = try EncodedValue.makeValue(for: value, at: codingPath, using: strategy) else {
try value.encode(to: self)
return try getEncodedValue()
}
return encoded
}
}
}
private extension KeyValueEncoder {
final class KeyedContainer<K: CodingKey>: KeyedEncodingContainerProtocol {
typealias Key = K
let codingPath: [any CodingKey]
private let userInfo: [CodingUserInfoKey: Any]
private let strategy: EncodingStrategy
init(codingPath: [any CodingKey], userInfo: [CodingUserInfoKey: Any], strategy: EncodingStrategy) {
self.codingPath = codingPath
self.storage = [:]
self.userInfo = userInfo
self.strategy = strategy
}
private var storage: [String: EncodedValue]
func setValue(_ value: Any, forKey key: Key) {
storage[strategy.keys.makeStorageKey(for: key.stringValue)] = .value(value)
}
func setValue(_ value: EncodedValue, forKey key: Key) {
storage[strategy.keys.makeStorageKey(for: key.stringValue)] = value
}
func getEncodedValue() throws -> EncodedValue {
try .value(storage.compactMapValues { try $0.getValue(strategy: strategy.optionals) })
}
func encodeNil(forKey key: Key) {
storage[key.stringValue] = .null
}
func encode(_ value: Bool, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Int, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Int8, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Int16, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Int32, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Int64, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: UInt, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: UInt8, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: UInt16, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: UInt32, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: UInt64, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: String, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Float, forKey key: Key) {
setValue(value, forKey: key)
}
func encode(_ value: Double, forKey key: Key) {
setValue(value, forKey: key)
}
func encode<T: Encodable>(_ value: T, forKey key: Key) throws {
if let val = try EncodedValue.makeValue(for: value, at: codingPath, using: strategy) {
setValue(val, forKey: key)
return
}
let encoder = Encoder(codingPath: codingPath.appending(key: key), userInfo: userInfo, strategy: strategy)
if let value = try encoder.encodeToValue(value).getValue(strategy: strategy.optionals) {
setValue(value, forKey: key)
} else {
setValue(.null, forKey: key)
}
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let path = codingPath.appending(key: key)
let keyed = KeyedContainer<NestedKey>(codingPath: path, userInfo: userInfo, strategy: strategy)
storage[key.stringValue] = .provider(keyed.getEncodedValue)
return KeyedEncodingContainer(keyed)
}
func nestedUnkeyedContainer(forKey key: K) -> any UnkeyedEncodingContainer {
let path = codingPath.appending(key: key)
let unkeyed = UnkeyedContainer(codingPath: path, userInfo: userInfo, strategy: strategy)
storage[key.stringValue] = .provider(unkeyed.getEncodedValue)
return unkeyed
}
func superEncoder() -> any Swift.Encoder {
return superEncoder(forKey: Key(stringValue: "super")!)
}
func superEncoder(forKey key: Key) -> any Swift.Encoder {
let path = codingPath.appending(key: key)
let encoder = Encoder(codingPath: path, userInfo: userInfo, strategy: strategy)
storage[key.stringValue] = .provider(encoder.getEncodedValue)
return encoder
}
}
final class UnkeyedContainer: Swift.UnkeyedEncodingContainer {
let codingPath: [any CodingKey]
private let userInfo: [CodingUserInfoKey: Any]
private let strategy: EncodingStrategy
init(codingPath: [any CodingKey], userInfo: [CodingUserInfoKey: Any], strategy: EncodingStrategy) {
self.codingPath = codingPath
self.userInfo = userInfo
self.strategy = strategy
}
private var storage: [EncodedValue] = []
func getEncodedValue() throws -> EncodedValue {
return try .value(storage.compactMap { try $0.getValue(strategy: strategy.optionals) })
}
public var count: Int {
return storage.count
}
func appendValue(_ value: Any) {
storage.append(.value(value))
}
func appendValue(_ value: EncodedValue) {
storage.append(value)
}
func encodeNil() {
storage.append(.null)
}
func encode(_ value: Bool) {
appendValue(value)
}
func encode(_ value: Int) {
appendValue(value)
}
func encode(_ value: Int8) {
appendValue(value)
}
func encode(_ value: Int16) {
appendValue(value)
}
func encode(_ value: Int32) {
appendValue(value)
}
func encode(_ value: Int64) {
appendValue(value)
}
func encode(_ value: UInt) {
appendValue(value)
}
func encode(_ value: UInt8) {
appendValue(value)
}
func encode(_ value: UInt16) {
appendValue(value)
}
func encode(_ value: UInt32) {
appendValue(value)
}
func encode(_ value: UInt64) {
appendValue(value)
}
func encode(_ value: String) {
appendValue(value)
}
func encode(_ value: Float) {
appendValue(value)
}
func encode(_ value: Double) {
appendValue(value)
}
func encode<T: Encodable>(_ value: T) throws {
if let val = try EncodedValue.makeValue(for: value, at: codingPath.appending(index: count), using: strategy) {
appendValue(val)
return
}
let encoder = Encoder(
codingPath: codingPath.appending(index: count),
userInfo: userInfo,
strategy: strategy
)
if let value = try encoder.encodeToValue(value).getValue(strategy: strategy.optionals) {
appendValue(value)
} else {
appendValue(.null)
}
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
let path = codingPath.appending(index: count)
let keyed = KeyedContainer<NestedKey>(codingPath: path, userInfo: userInfo, strategy: strategy)
storage.append(.provider(keyed.getEncodedValue))
return KeyedEncodingContainer(keyed)
}
func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer {
let path = codingPath.appending(index: count)
let unkeyed = UnkeyedContainer(codingPath: path, userInfo: userInfo, strategy: strategy)
storage.append(.provider(unkeyed.getEncodedValue))
return unkeyed
}
func superEncoder() -> any Swift.Encoder {
let path = codingPath.appending(index: count)
let encoder = Encoder(codingPath: path, userInfo: userInfo, strategy: strategy)
storage.append(.provider(encoder.getEncodedValue))
return encoder
}
}
final class SingleContainer: SingleValueEncodingContainer {
let codingPath: [any CodingKey]
private let userInfo: [CodingUserInfoKey: Any]
private let strategy: EncodingStrategy
init(codingPath: [any CodingKey], userInfo: [CodingUserInfoKey: Any], strategy: EncodingStrategy) {
self.codingPath = codingPath
self.userInfo = userInfo
self.strategy = strategy
}
private var value: EncodedValue?
func getEncodedValue() throws -> EncodedValue {
guard let value else { return .value([String: Any]()) }
return value
}
func encodeNil() {
self.value = .null
}
func encode(_ value: Bool) {
self.value = .value(value)
}
func encode(_ value: String) {
self.value = .value(value)
}
func encode(_ value: Double) {
self.value = .value(value)
}
func encode(_ value: Float) {
self.value = .value(value)
}
func encode(_ value: Int) {
self.value = .value(value)
}
func encode(_ value: Int8) {
self.value = .value(value)
}
func encode(_ value: Int16) {
self.value = .value(value)
}
func encode(_ value: Int32) {
self.value = .value(value)
}
func encode(_ value: Int64) {
self.value = .value(value)
}
func encode(_ value: UInt) {
self.value = .value(value)
}
func encode(_ value: UInt8) {
self.value = .value(value)
}
func encode(_ value: UInt16) {
self.value = .value(value)
}
func encode(_ value: UInt32) {
self.value = .value(value)
}
func encode(_ value: UInt64) {
self.value = .value(value)
}
func encode<T>(_ value: T) throws where T: Encodable {
if let encoded = try EncodedValue.makeValue(for: value, at: codingPath, using: strategy) {
self.value = encoded
return
}
let encoder = Encoder(codingPath: codingPath, userInfo: userInfo, strategy: strategy)
if let value = try encoder.encodeToValue(value).getValue(strategy: strategy.optionals) {
self.value = .value(value)
} else {
self.value = .null
}
}
}
}
extension KeyValueEncoder.KeyEncodingStrategy {
func makeStorageKey(for key: String) -> String {
switch self {
case .useDefaultKeys: return key
case .convertToSnakeCase: return key.toSnakeCase()
}
}
}
extension String {
func toSnakeCase() -> String {
camelCaseWords
.map { $0.lowercased() }
.joined(separator: "_")
}
var camelCaseWords: [Substring] {
var words: [Range<String.Index>] = []
var wordStart = startIndex
var searchRange = index(after: wordStart)..<endIndex
while let upperCaseRange = self[searchRange].rangeOfCharacter(from: .uppercaseLetters, options: []) {
let untilUpperCase = wordStart..<upperCaseRange.lowerBound
words.append(untilUpperCase)
// Find next lowercase character
searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
guard let lowerCaseRange = self[searchRange].rangeOfCharacter(from: .lowercaseLetters, options: []) else {
// There are no more lower case letters. Just end here.
wordStart = searchRange.lowerBound
break
}
// group runs of multiple capitals together instead of splitting into words
let nextCharacterAfterCapital = self.index(after: upperCaseRange.lowerBound)
if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
// Next is lowercase
wordStart = upperCaseRange.lowerBound
} else {
// Multiple uppercase in sequence. Stop at the capital before the lower case character.
let beforeLowerIndex = self.index(before: lowerCaseRange.lowerBound)
words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
wordStart = beforeLowerIndex
}
searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
}
words.append(wordStart..<searchRange.upperBound)
return words.map { self[$0] }
}
}
extension Array where Element == any CodingKey {
func appending(key codingKey: any CodingKey) -> [any CodingKey] {
var path = self
path.append(codingKey)
return path
}
func appending(index: Int) -> [any CodingKey] {
var path = self
path.append(AnyCodingKey(intValue: index))
return path
}
func makeKeyPath(appending key: (any CodingKey)? = nil) -> String {
var path = map(\.keyPath)
if let key = key {
path.append(key.keyPath)
}
return "SELF\(path.joined())"
}
}
private extension CodingKey {
var keyPath: String {
if let intValue = self.intValue {
return "[\(intValue)]"
} else {
return ".\(stringValue)"
}
}
}
struct AnyCodingKey: CodingKey {
var intValue: Int? {
return index
}
var stringValue: String
var index: Int?
init(intValue index: Int) {
self.index = index
self.stringValue = "Index \(index)"
}
init(stringValue: String) {
self.stringValue = stringValue
}
}
extension KeyValueEncoder.EncodedValue {
static func makeValue(
for value: Any,
at codingPath: [any CodingKey],
using strategy: KeyValueEncoder.EncodingStrategy
) throws -> Self? {
do {
return try makeValue(for: value, using: strategy)
} catch {
let valueDescription = strategy.optionals.isNull(value) ? "nil" : String(describing: type(of: value))
let context = EncodingError.Context(
codingPath: codingPath,
debugDescription: "\(valueDescription) at \(codingPath.makeKeyPath()) cannot be encoded. \(error.localizedDescription)",
underlyingError: error
)
throw EncodingError.invalidValue(value, context)
}
}
static func makeValue(for value: Any, using strategy: KeyValueEncoder.EncodingStrategy) throws -> Self? {
if let dataValue = value as? Data {
return .value(dataValue)
} else if let dateValue = value as? Date {
return try makeValue(for: dateValue, using: strategy.dates)
} else if let urlValue = value as? URL {
return .value(urlValue)
} else if let decimalValue = value as? Decimal {
return .value(decimalValue)
} else {
return nil
}
}
static func makeValue(for date: Date, using strategy: KeyValueEncoder.DateEncodingStrategy) throws -> Self? {
switch strategy {
case .date:
return .value(date)
case .custom(let transform):
return try .value(transform(date))
case .millisecondsSince1970:
return .value(Int64(date.timeIntervalSince1970 * 1000))
case .secondsSince1970:
return .value(Int64(date.timeIntervalSince1970))
}
}
}