MemoryStorage.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. //
  2. // MemoryStorage.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/10/15.
  6. //
  7. // Copyright (c) 2018年 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. /// Represents a storage which stores a certain type of value in memory. It provides fast access,
  28. /// but limited storing size. The stored value type needs to conform to `CacheCostCalculatable`,
  29. /// and its `cacheCost` will be used to determine the cost of size for the cache item.
  30. ///
  31. /// You can config a `MemoryStorage` in its initializer by passing a `MemoryStorage.Config` value.
  32. /// or modifying the `config` property after it being created. The backend of `MemoryStorage` has
  33. /// upper limitaion on cost size in memory and item count. All items in the storage has an expiration
  34. /// date. When retrieved, if the target item is already expired, it will be recognized as it does not
  35. /// exist in the storage. The `MemoryStorage` also contains a scheduled self clean task, to evict expired
  36. /// items from memory.
  37. public class MemoryStorage<T: CacheCostCalculatable>: Storage {
  38. /// Represents the config used in a `MemoryStorage`.
  39. public struct Config {
  40. /// Total cost limit of the storage in bytes.
  41. public var totalCostLimit: Int
  42. /// The item count limit of the memory storage.
  43. public var countLimit: Int = .max
  44. /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`,
  45. /// means that the memory cache would expire in 5 minutes.
  46. public var expiration: StorageExpiration = .seconds(300)
  47. /// The time interval between the storage do clean work for swiping expired items.
  48. /// Default is 120, means the auto eviction happens once per two minutes.
  49. public var cleanInterval: TimeInterval = 120
  50. /// Creates a config from a given `totalCostLimit` value.
  51. ///
  52. /// - Parameter totalCostLimit: Total cost limit of the storage in bytes.
  53. ///
  54. /// - Note:
  55. /// Other members of `MemoryStorage.Config` will use their default values when created.
  56. public init(totalCostLimit: Int) {
  57. self.totalCostLimit = totalCostLimit
  58. }
  59. }
  60. let storage = NSCache<NSString, StorageObject<T>>()
  61. var keys = Set<String>()
  62. var cleanTimer: Timer? = nil
  63. let lock = NSLock()
  64. /// The config used in this storage. It is a setable value and you can
  65. /// use it to config the storage in air.
  66. public var config: Config {
  67. didSet {
  68. storage.totalCostLimit = config.totalCostLimit
  69. storage.countLimit = config.countLimit
  70. }
  71. }
  72. /// Creates a `MemoryStorage` with a given `config`.
  73. ///
  74. /// - Parameter config: The config used to create the storage. It determines the max size limitation,
  75. /// default expiration setting and more.
  76. public init(config: Config) {
  77. self.config = config
  78. storage.totalCostLimit = config.totalCostLimit
  79. storage.countLimit = config.countLimit
  80. cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
  81. guard let self = self else { return }
  82. self.removeExpired()
  83. }
  84. }
  85. func removeExpired() {
  86. lock.lock()
  87. defer { lock.unlock() }
  88. for key in keys {
  89. let nsKey = key as NSString
  90. guard let object = storage.object(forKey: nsKey) else {
  91. keys.remove(key)
  92. continue
  93. }
  94. if object.estimatedExpiration.isPast {
  95. storage.removeObject(forKey: nsKey)
  96. keys.remove(key)
  97. }
  98. }
  99. }
  100. // Storing in memory will not throw. It is just for meeting protocol requirement and
  101. // forwarding to no throwing method.
  102. func store(
  103. value: T,
  104. forKey key: String,
  105. expiration: StorageExpiration? = nil) throws
  106. {
  107. storeNoThrow(value: value, forKey: key, expiration: expiration)
  108. }
  109. func storeNoThrow(
  110. value: T,
  111. forKey key: String,
  112. expiration: StorageExpiration? = nil)
  113. {
  114. lock.lock()
  115. defer { lock.unlock() }
  116. let object = StorageObject(value, expiration: expiration ?? config.expiration)
  117. storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
  118. keys.insert(key)
  119. }
  120. func value(forKey key: String) throws -> T? {
  121. return try value(forKey: key, extendingExpiration: true)
  122. }
  123. func value(forKey key: String, extendingExpiration: Bool) throws -> T? {
  124. guard let object = storage.object(forKey: key as NSString) else {
  125. return nil
  126. }
  127. guard object.estimatedExpiration.isFuture else {
  128. return nil
  129. }
  130. if extendingExpiration { object.extendExpiration() }
  131. return object.value
  132. }
  133. func isCached(forKey key: String) -> Bool {
  134. do {
  135. guard let _ = try value(forKey: key, extendingExpiration: false) else {
  136. return false
  137. }
  138. return true
  139. } catch {
  140. return false
  141. }
  142. }
  143. func remove(forKey key: String) throws {
  144. lock.lock()
  145. defer { lock.unlock() }
  146. storage.removeObject(forKey: key as NSString)
  147. keys.remove(key)
  148. }
  149. func removeAll() throws {
  150. lock.lock()
  151. defer { lock.unlock() }
  152. storage.removeAllObjects()
  153. keys.removeAll()
  154. }
  155. }