Storage.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 {
  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. /// The file manager used to perform file system operations.
  36. private let fileManager: FileManager
  37. /// Designated initializer.
  38. /// - Parameters:
  39. /// - url: A file system URL for the underlying file resource.
  40. /// - fileManager: A file manager. Defaults to `default` manager.
  41. init(url: URL, fileManager: FileManager = .default) {
  42. self.url = url
  43. self.fileManager = fileManager
  44. }
  45. /// Reads and returns the data from this object's associated file resource.
  46. ///
  47. /// - Returns: The data stored on disk.
  48. /// - Throws: An error if reading the contents of the file resource fails (i.e. file doesn't
  49. /// exist).
  50. func read() throws -> Data {
  51. do {
  52. return try Data(contentsOf: url)
  53. } catch {
  54. throw StorageError.readError
  55. }
  56. }
  57. /// Writes the given data to this object's associated file resource.
  58. ///
  59. /// When the given `data` is `nil`, this object's associated file resource is emptied.
  60. ///
  61. /// - Parameter data: The `Data?` to write to this object's associated file resource.
  62. func write(_ data: Data?) throws {
  63. do {
  64. try createDirectories(in: url.deletingLastPathComponent())
  65. if let data {
  66. try data.write(to: url, options: .atomic)
  67. } else {
  68. let emptyData = Data()
  69. try emptyData.write(to: url, options: .atomic)
  70. }
  71. } catch {
  72. throw StorageError.writeError
  73. }
  74. }
  75. /// Creates all directories in the given file system URL.
  76. ///
  77. /// If the directory for the given URL already exists, the error is ignored because the directory
  78. /// has already been created.
  79. ///
  80. /// - Parameter url: The URL to create directories in.
  81. private func createDirectories(in url: URL) throws {
  82. do {
  83. try fileManager.createDirectory(
  84. at: url,
  85. withIntermediateDirectories: true
  86. )
  87. } catch CocoaError.fileWriteFileExists {
  88. // Directory already exists.
  89. } catch { throw error }
  90. }
  91. }
  92. // MARK: - UserDefaultsStorage
  93. /// A object that provides API for reading and writing to a user defaults resource.
  94. final class UserDefaultsStorage: Storage {
  95. /// The underlying defaults container.
  96. private let defaults: UserDefaults
  97. /// The key mapping to the object's associated resource in `defaults`.
  98. private let key: String
  99. /// Designated initializer.
  100. /// - Parameters:
  101. /// - defaults: The defaults container.
  102. /// - key: The key mapping to the value stored in the defaults container.
  103. init(defaults: UserDefaults, key: String) {
  104. self.defaults = defaults
  105. self.key = key
  106. }
  107. /// Reads and returns the data from this object's associated defaults resource.
  108. ///
  109. /// - Returns: The data stored on disk.
  110. /// - Throws: An error if no data has been stored to the defaults container.
  111. func read() throws -> Data {
  112. if let data = defaults.data(forKey: key) {
  113. return data
  114. } else {
  115. throw StorageError.readError
  116. }
  117. }
  118. /// Writes the given data to this object's associated defaults.
  119. ///
  120. /// When the given `data` is `nil`, the associated default is removed.
  121. ///
  122. /// - Parameter data: The `Data?` to write to this object's associated defaults.
  123. func write(_ data: Data?) throws {
  124. if let data {
  125. defaults.set(data, forKey: key)
  126. } else {
  127. defaults.removeObject(forKey: key)
  128. }
  129. }
  130. }