CodableHelpers.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  16. protocol CodableConverter {
  17. associatedtype E: Encodable
  18. associatedtype D: Decodable
  19. func encode(input: E) throws -> D
  20. func decode(input: D) throws -> E
  21. }
  22. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  23. class Int64CodableConverter: CodableConverter {
  24. func encode(input: Int64?) throws -> String? {
  25. guard let input else {
  26. return nil
  27. }
  28. let int64String = "\(input)"
  29. return int64String
  30. }
  31. func decode(input: String?) throws -> Int64? {
  32. guard let input else {
  33. return nil
  34. }
  35. guard let int64Value = Int64(input) else {
  36. throw DataConnectError.decodeFailed
  37. }
  38. return int64Value
  39. }
  40. }
  41. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  42. class UUIDCodableConverter: CodableConverter {
  43. func encode(input: UUID?) throws -> String? {
  44. guard let input else {
  45. return nil
  46. }
  47. let uuidNoDashString = convertToNoDashUUID(uuid: input)
  48. return uuidNoDashString
  49. }
  50. func decode(input: String?) throws -> UUID? {
  51. guard let input,
  52. let dashesAddedUUID = addDashesToUUIDString(uuidKeyString: input)
  53. else {
  54. return nil
  55. }
  56. return UUID(uuidString: dashesAddedUUID)
  57. }
  58. private func convertToNoDashUUID(uuid: UUID) -> String {
  59. return uuid.uuidString.replacingOccurrences(of: "-", with: "").lowercased()
  60. }
  61. private func addDashesToUUIDString(uuidKeyString: String) -> String? {
  62. guard uuidKeyString.count == 32 else {
  63. return nil
  64. }
  65. let sourceChars = [Character](uuidKeyString)
  66. var targetChars = [Character]()
  67. var indx = 0
  68. while indx < sourceChars.count {
  69. switch indx {
  70. case 8, 12, 16, 20:
  71. targetChars.append("-")
  72. default:
  73. break
  74. }
  75. targetChars.append(sourceChars[indx])
  76. indx += 1
  77. }
  78. return String(targetChars)
  79. }
  80. }