VectorValue+Codable.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2024 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #if SWIFT_PACKAGE
  17. @_exported import FirebaseFirestoreInternalWrapper
  18. #else
  19. @_exported import FirebaseFirestoreInternal
  20. #endif // SWIFT_PACKAGE
  21. /**
  22. * A protocol describing the encodable properties of a VectorValue.
  23. */
  24. private protocol CodableVectorValue: Codable {
  25. var array: [Double] { get }
  26. init(__array: [NSNumber])
  27. }
  28. /** The keys in a Timestamp. Must match the properties of CodableTimestamp. */
  29. private enum VectorValueKeys: String, CodingKey {
  30. case array
  31. }
  32. /**
  33. * An extension of VectorValue that implements the behavior of the Codable protocol.
  34. *
  35. * Note: this is implemented manually here because the Swift compiler can't synthesize these methods
  36. * when declaring an extension to conform to Codable.
  37. */
  38. extension CodableVectorValue {
  39. public init(from decoder: Decoder) throws {
  40. let container = try decoder.container(keyedBy: VectorValueKeys.self)
  41. let data = try container.decode([Double].self, forKey: .array)
  42. let array = data.map { double in
  43. NSNumber(value: double)
  44. }
  45. self.init(__array: array)
  46. }
  47. public func encode(to encoder: Encoder) throws {
  48. var container = encoder.container(keyedBy: VectorValueKeys.self)
  49. try container.encode(array, forKey: .array)
  50. }
  51. }
  52. /** Extends VectorValue to conform to Codable. */
  53. extension FirebaseFirestore.VectorValue: FirebaseFirestore.CodableVectorValue {}
  54. extension FirebaseFirestore.VectorValue: @retroactive Codable {}