this repo has no description
1//
2// KeyEncodingStrategy.swift
3// URLQueryItemCoder
4//
5// Created by Kyle Hughes on 3/16/23.
6//
7
8/// The strategy to use for automatically changing the value of keys before encoding.
9public enum KeyEncodingStrategy: Sendable {
10 /// A key encoding strategy that converts camel-case keys to snake-case keys.
11 ///
12 /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to the payload.
13 ///
14 /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and
15 /// `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt).
16 ///
17 /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result
18 /// is consistent regardless of the current user's locale and language preferences.
19 ///
20 /// Converting from camel case to snake case:
21 ///
22 /// 1. Splits words at the boundary of lower-case to upper-case
23 /// 2. Inserts `_` between words
24 /// 3. Lowercases the entire string
25 /// 4. Preserves starting and ending `_`.
26 ///
27 /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
28 ///
29 /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
30 case convertToSnakeCase
31
32 /// A key encoding strategy defined by the closure you supply.
33 ///
34 /// Provide a custom conversion to the key in the encoded payload from the keys specified by the encoded types.
35 ///
36 /// The full path to the current encoding position is provided for context (in case you need to locate this key
37 /// within the payload). The returned key is used in place of the last component in the coding path before encoding.
38 ///
39 /// If the result of the conversion is a duplicate key, then only one value will be present in the result.
40 case custom(@Sendable (_ codingPath: [any CodingKey]) -> any CodingKey)
41
42 /// A key encoding strategy that doesn’t change key names during encoding.
43 ///
44 /// The `KeyEncodingStrategy.useDefaultKeys` strategy is the strategy used if you don’t specify one.
45 ///
46 /// - Note: If you use a nested CodingKeys enumeration to define custom key names, this strategy continues to use
47 /// those names rather than reverting back to the original property names.
48 case useDefaultKeys
49
50 // MARK: Public Static Interface
51
52 /// The default encoding strategy.
53 ///
54 /// Equals `.useDefaultKeys`.
55 public static let `default`: KeyEncodingStrategy = .useDefaultKeys
56
57 // MARK: Internal Instance Interface
58
59 internal func encode(_ key: any CodingKey, at codingPath: [any CodingKey]) -> any CodingKey {
60 switch self {
61 case .convertToSnakeCase:
62 return StringCodingKey(stringValue: key.stringValue.convertToSnakeCase())
63 case let .custom(encoder):
64 return encoder(codingPath + [key])
65 case .useDefaultKeys:
66 return key
67 }
68 }
69}