|
| 1 | +// DecoderUserInfo+OptionSetHelpers.swift |
| 2 | +// ArgumentEncoding |
| 3 | +// |
| 4 | +// Copyright © 2023 MFB Technologies, Inc. All rights reserved. |
| 5 | + |
| 6 | +import Foundation |
| 7 | + |
| 8 | +/// Helper functions for configuring a decoder's `userInfo` dictionary for decoding `OptionSet`. |
| 9 | +/// Each of the overloads that does not require the configuration closure, will configure both |
| 10 | +/// `OptionSet<T>` and `OptionSet<T?>`. |
| 11 | +/// |
| 12 | +/// ```swift |
| 13 | +/// struct Container: ArgumentGroup, FormatterNode { |
| 14 | +/// let flagFormatter: FlagFormatter = .init(prefix: .doubleDash) |
| 15 | +/// let optionFormatter: OptionFormatter = .init(prefix: .doubleDash) |
| 16 | +/// @OptionSet var option: [String] = ["value1", "value2"] |
| 17 | +/// } |
| 18 | +/// let encoded = try JSONEncoder().encode(Container()) |
| 19 | +/// let decoder = JSONDecoder() |
| 20 | +/// decoder.userInfo.addOptionConfiguration(for: String.self) |
| 21 | +/// let decoded = try decoder.decode(Container.self, from: encoded) |
| 22 | +/// // decoded = ["--option", "value1", "--option", "value2"] |
| 23 | +/// ``` |
| 24 | +extension [CodingUserInfoKey: Any] { |
| 25 | + public mutating func addOptionSetConfiguration<T>( |
| 26 | + for _: OptionSet<T>.Type, |
| 27 | + configuration: @escaping OptionSet<T>.DecodingConfiguration |
| 28 | + ) where T: Decodable { |
| 29 | + guard let key = OptionSet<T>.configurationCodingUserInfoKey() else { |
| 30 | + return |
| 31 | + } |
| 32 | + self[key] = configuration |
| 33 | + } |
| 34 | + |
| 35 | + public mutating func addOptionSetConfiguration<T>(for _: T.Type) where T: Decodable, T: Sequence, |
| 36 | + T.Element: CustomStringConvertible |
| 37 | + { |
| 38 | + addOptionSetConfiguration(for: OptionSet<T>.self, configuration: OptionSet<T>.unwrap(_:)) |
| 39 | + } |
| 40 | + |
| 41 | + public mutating func addOptionSetConfiguration<T>(for _: T.Type) where T: Decodable, T: Sequence, |
| 42 | + T.Element: RawRepresentable, T.Element.RawValue: CustomStringConvertible |
| 43 | + { |
| 44 | + addOptionSetConfiguration(for: OptionSet<T>.self, configuration: OptionSet<T>.unwrap(_:)) |
| 45 | + } |
| 46 | + |
| 47 | + public mutating func addOptionSetConfiguration<T>(for _: T.Type) where T: Decodable, T: Sequence, |
| 48 | + T.Element: CustomStringConvertible, T.Element: RawRepresentable, T.Element.RawValue: CustomStringConvertible |
| 49 | + { |
| 50 | + addOptionSetConfiguration(for: OptionSet<T>.self, configuration: OptionSet<T>.unwrap(_:)) |
| 51 | + } |
| 52 | +} |
0 commit comments