Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional memory cache #459

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions Haneke/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ open class Cache<T: DataConvertible> where T.Result == T, T : DataRepresentable
if let (format, memoryCache, diskCache) = self.formats[formatName] {
self.format(value: value, format: format) { formattedValue in
let wrapper = ObjectWrapper(value: formattedValue)
memoryCache.setObject(wrapper, forKey: key as AnyObject)
memoryCache?.setObject(wrapper, forKey: key as AnyObject)
// Value data is sent as @autoclosure to be executed in the disk cache queue.
diskCache.setData(self.dataFromValue(formattedValue, format: format), key: key)
succeed?(formattedValue)
Expand All @@ -78,7 +78,7 @@ open class Cache<T: DataConvertible> where T.Result == T, T : DataRepresentable
@discardableResult open func fetch(key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Cache.buildFetch(failure: fail, success: succeed)
if let (format, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.object(forKey: key as AnyObject) as? ObjectWrapper, let result = wrapper.hnk_value as? T {
if let wrapper = memoryCache?.object(forKey: key as AnyObject) as? ObjectWrapper, let result = wrapper.hnk_value as? T {
fetch.succeed(result)
diskCache.updateAccessDate(self.dataFromValue(result, format: format), key: key)
return fetch
Expand Down Expand Up @@ -124,15 +124,15 @@ open class Cache<T: DataConvertible> where T.Result == T, T : DataRepresentable

open func remove(key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName) {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
memoryCache.removeObject(forKey: key as AnyObject)
memoryCache?.removeObject(forKey: key as AnyObject)
diskCache.removeData(with: key)
}
}

open func removeAll(_ completion: (() -> ())? = nil) {
let group = DispatchGroup()
for (_, (_, memoryCache, diskCache)) in self.formats {
memoryCache.removeAllObjects()
memoryCache?.removeAllObjects()
group.enter()
diskCache.removeAllData {
group.leave()
Expand Down Expand Up @@ -171,18 +171,22 @@ open class Cache<T: DataConvertible> where T.Result == T, T : DataRepresentable

func onMemoryWarning() {
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
memoryCache?.removeAllObjects()
}
}

// MARK: Formats

public var formats : [String : (Format<T>, NSCache<AnyObject, AnyObject>, DiskCache)] = [:]
public var formats : [String : (Format<T>, NSCache<AnyObject, AnyObject>?, DiskCache)] = [:]

open func addFormat(_ format : Format<T>) {
let name = format.name
let formatPath = self.formatPath(withFormatName: name)
let memoryCache = NSCache<AnyObject, AnyObject>()
var memoryCache: NSCache<AnyObject, AnyObject>? = nil
if let memCapacity = format.memoryCapacity {
memoryCache = NSCache<AnyObject, AnyObject>()
memoryCache!.totalCostLimit = memCapacity
}
let diskCache = DiskCache(path: formatPath, capacity : format.diskCapacity)
self.formats[name] = (format, memoryCache, diskCache)
}
Expand Down Expand Up @@ -214,7 +218,7 @@ open class Cache<T: DataConvertible> where T.Result == T, T : DataRepresentable
return value.asData()
}

fileprivate func fetchFromDiskCache(_ diskCache : DiskCache, key: String, memoryCache : NSCache<AnyObject, AnyObject>, failure fail : ((Error?) -> ())?, success succeed : @escaping (T) -> ()) {
fileprivate func fetchFromDiskCache(_ diskCache : DiskCache, key: String, memoryCache : NSCache<AnyObject, AnyObject>?, failure fail : ((Error?) -> ())?, success succeed : @escaping (T) -> ()) {
diskCache.fetchData(key: key, failure: { error in
if let block = fail {
if (error as NSError?)?.code == NSFileReadNoSuchFileError {
Expand All @@ -234,7 +238,7 @@ open class Cache<T: DataConvertible> where T.Result == T, T : DataRepresentable
DispatchQueue.main.async(execute: {
succeed(descompressedValue)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key as AnyObject)
memoryCache?.setObject(wrapper, forKey: key as AnyObject)
})
}
})
Expand Down
2 changes: 1 addition & 1 deletion Haneke/CryptoSwiftMD5.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ class MD5 : HashBase {
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M = sliceToUInt32Array(chunk)
let M = sliceToUInt32Array(chunk)
assert(M.count == 16, "Invalid array")

// Initialize hash value for this chunk:
Expand Down
5 changes: 4 additions & 1 deletion Haneke/Format.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ public struct Format<T> {

public let diskCapacity : UInt64

public let memoryCapacity : Int?

public var transform : ((T) -> (T))?

public var convertToData : ((T) -> Data)?

public init(name: String, diskCapacity : UInt64 = UINT64_MAX, transform: ((T) -> (T))? = nil) {
public init(name: String, diskCapacity : UInt64 = UINT64_MAX, memoryCapacity: Int? = 0, transform: ((T) -> (T))? = nil) {
self.name = name
self.diskCapacity = diskCapacity
self.memoryCapacity = memoryCapacity
self.transform = transform
}

Expand Down
11 changes: 5 additions & 6 deletions Haneke/String+Haneke.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,12 @@ extension String {

let MD5Calculator = MD5(Array(data))
let MD5Data = MD5Calculator.calculate()
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(mutating: MD5Data)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.count)
let MD5String = NSMutableString()
for c in resultEnumerator {
MD5String.appendFormat("%02x", c)
let MD5String = MD5Data.withUnsafeBufferPointer { (ptr) -> String in
return ptr.reduce("") { (str, c) -> String in
str.appendingFormat("%02x", c)
}
}
return MD5String as String
return MD5String
}

func MD5Filename() -> String {
Expand Down
8 changes: 8 additions & 0 deletions HanekeTests/CacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,14 @@ class CacheTests: XCTestCase {
waitForExpectations(timeout: 0, handler: nil)
}

func testNilMemoryCache() {
let sut = Format<UIImage>(name: self.name, memoryCapacity: nil)

let cache = Cache<UIImage>(name: "Test")
cache.addFormat(sut)
XCTAssertNil(cache.formats[sut.name]?.1)
}

// MARK: Helpers

func clearMemoryCache() {
Expand Down
7 changes: 2 additions & 5 deletions HanekeTests/NSData+Test.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ import Foundation
extension Data {

static func dataWithLength(_ length : Int) -> Data {
let buffer: [UInt8] = [UInt8](repeating: 0, count: length)
// return Data(bytes: UnsafePointer<UInt8>(&buffer), count: length)
let pointer = UnsafeRawPointer(buffer)

return NSData(bytes: pointer, length: length) as Data
var buffer: [UInt8] = [UInt8](repeating: 0, count: length)
return NSData(bytes: &buffer, length: length) as Data
}

}