Storage.swift 4.5 KB

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