Storage.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. // Copyright 2021 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. /// A type that reads from and writes to an underlying storage container.
  16. protocol Storage: Sendable {
  17. /// Reads and returns the data stored by this storage type.
  18. /// - Returns: The data read from storage.
  19. /// - Throws: An error if the read failed.
  20. func read() throws -> Data
  21. /// Writes the given data to this storage type.
  22. /// - Throws: An error if the write failed.
  23. func write(_ data: Data?) throws
  24. }
  25. /// Error types for `Storage` operations.
  26. enum StorageError: Error {
  27. case readError
  28. case writeError
  29. }
  30. // MARK: - FileStorage
  31. /// A object that provides API for reading and writing to a file system resource.
  32. final class FileStorage: Storage {
  33. /// A file system URL to the underlying file resource.
  34. private let url: URL
  35. /// Designated initializer.
  36. /// - Parameters:
  37. /// - url: A file system URL for the underlying file resource.
  38. init(url: URL) {
  39. self.url = url
  40. }
  41. /// Reads and returns the data from this object's associated file resource.
  42. ///
  43. /// - Returns: The data stored on disk.
  44. /// - Throws: An error if reading the contents of the file resource fails (i.e. file doesn't
  45. /// exist).
  46. func read() throws -> Data {
  47. do {
  48. return try Data(contentsOf: url)
  49. } catch {
  50. throw StorageError.readError
  51. }
  52. }
  53. /// Writes the given data to this object's associated file resource.
  54. ///
  55. /// When the given `data` is `nil`, this object's associated file resource is emptied.
  56. ///
  57. /// - Parameter data: The `Data?` to write to this object's associated file resource.
  58. func write(_ data: Data?) throws {
  59. do {
  60. try createDirectories(in: url.deletingLastPathComponent())
  61. if let data {
  62. try data.write(to: url, options: .atomic)
  63. } else {
  64. let emptyData = Data()
  65. try emptyData.write(to: url, options: .atomic)
  66. }
  67. } catch {
  68. throw StorageError.writeError
  69. }
  70. }
  71. /// Creates all directories in the given file system URL.
  72. ///
  73. /// If the directory for the given URL already exists, the error is ignored because the directory
  74. /// has already been created.
  75. ///
  76. /// - Parameter url: The URL to create directories in.
  77. private func createDirectories(in url: URL) throws {
  78. do {
  79. try FileManager.default.createDirectory(
  80. at: url,
  81. withIntermediateDirectories: true
  82. )
  83. } catch CocoaError.fileWriteFileExists {
  84. // Directory already exists.
  85. } catch { throw error }
  86. }
  87. }
  88. // MARK: - UserDefaultsStorage
  89. /// A object that provides API for reading and writing to a user defaults resource.
  90. final class UserDefaultsStorage: Storage {
  91. /// The suite name for the underlying defaults container.
  92. private let suiteName: String
  93. /// The key mapping to the object's associated resource in `defaults`.
  94. private let key: String
  95. /// The underlying defaults container.
  96. private var defaults: UserDefaults {
  97. // It's safe to force unwrap the below defaults instance because the
  98. // initializer only returns `nil` when the bundle id or `globalDomain`
  99. // is passed in as the `suiteName`.
  100. UserDefaults(suiteName: suiteName)!
  101. }
  102. /// Designated initializer.
  103. /// - Parameters:
  104. /// - suiteName: The suite name for the defaults container.
  105. /// - key: The key mapping to the value stored in the defaults container.
  106. init(suiteName: String, key: String) {
  107. self.suiteName = suiteName
  108. self.key = key
  109. }
  110. /// Reads and returns the data from this object's associated defaults resource.
  111. ///
  112. /// - Returns: The data stored on disk.
  113. /// - Throws: An error if no data has been stored to the defaults container.
  114. func read() throws -> Data {
  115. if let data = defaults.data(forKey: key) {
  116. return data
  117. } else {
  118. throw StorageError.readError
  119. }
  120. }
  121. /// Writes the given data to this object's associated defaults.
  122. ///
  123. /// When the given `data` is `nil`, the associated default is removed.
  124. ///
  125. /// - Parameter data: The `Data?` to write to this object's associated defaults.
  126. func write(_ data: Data?) throws {
  127. if let data {
  128. defaults.set(data, forKey: key)
  129. } else {
  130. defaults.removeObject(forKey: key)
  131. }
  132. }
  133. }