CodecHelper.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2024 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. /*
  16. *** IMPORTANT ***
  17. Although this class is marked as public,
  18. this class is not part of supported public API and is subject to change.
  19. It is only for internal use by Data Connect generated code.
  20. */
  21. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  22. public class CodecHelper<K: CodingKey> {
  23. // MARK: Encoding
  24. public func encode(_ value: Encodable, forKey: K,
  25. container: inout KeyedEncodingContainer<K>) throws {
  26. switch value {
  27. case let int64Value as Int64:
  28. let int64Converter = Int64CodableConverter()
  29. let int64Value = try int64Converter.encode(input: int64Value)
  30. try container.encode(int64Value, forKey: forKey)
  31. case let uuidValue as UUID:
  32. let uuidConverter = UUIDCodableConverter()
  33. let uuidValue = try uuidConverter.encode(input: uuidValue)
  34. try container.encode(uuidValue, forKey: forKey)
  35. default:
  36. try container.encode(value, forKey: forKey)
  37. }
  38. }
  39. // MARK: Decoding
  40. public func decode<T: Decodable>(_ type: T.Type, forKey: K,
  41. container: inout KeyedDecodingContainer<K>) throws -> T {
  42. if type == Int64.self || type == Int64?.self {
  43. let int64String = try container.decodeIfPresent(String.self, forKey: forKey)
  44. let int64Converter = Int64CodableConverter()
  45. let int64Value = try int64Converter.decode(input: int64String)
  46. return int64Value as! T
  47. } else if type == UUID.self || type == UUID?.self {
  48. let uuidString = try container.decodeIfPresent(String.self, forKey: forKey)
  49. let uuidConverter = UUIDCodableConverter()
  50. let uuidDecoded = try uuidConverter.decode(input: uuidString)
  51. return uuidDecoded as! T
  52. }
  53. return try container.decode(type, forKey: forKey)
  54. }
  55. public init() {}
  56. }