Skip to content

[Cherry-Picked] [NSCache] [SR-3904] Fix for object storage. #901

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

Merged
merged 7 commits into from
Mar 5, 2017
Merged
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
2 changes: 1 addition & 1 deletion Docs/Status.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ There is no _Complete_ status for test coverage because there are always additio
| `NSMutableSet` | Mostly Complete | Incomplete | `init?(coder:)` remains unimplemented |
| `NSCountedSet` | Mostly Complete | Incomplete | `init?(coder:)` remains unimplemented |
| `NSCFSet` | N/A | N/A | For internal use only |
| `NSCache` | Complete | None | |
| `NSCache` | Complete | Incomplete | |
| `NSSortDescriptor` | Unimplemented | None | |

* **RunLoop**: Timers, streams and run loops.
Expand Down
4 changes: 4 additions & 0 deletions Foundation.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@
6EB768281D18C12C00D4B719 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EB768271D18C12C00D4B719 /* UUID.swift */; };
7900433B1CACD33E00ECCBF1 /* TestNSCompoundPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 790043391CACD33E00ECCBF1 /* TestNSCompoundPredicate.swift */; };
7900433C1CACD33E00ECCBF1 /* TestNSPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7900433A1CACD33E00ECCBF1 /* TestNSPredicate.swift */; };
90E645DF1E4C89A400D0D47C /* TestNSCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90E645DE1E4C89A400D0D47C /* TestNSCache.swift */; };
AE35A1861CBAC85E0042DB84 /* SwiftFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = AE35A1851CBAC85E0042DB84 /* SwiftFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; };
BD8042161E09857800487EB8 /* TestNSLengthFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD8042151E09857800487EB8 /* TestNSLengthFormatter.swift */; };
BDFDF0A71DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */; };
Expand Down Expand Up @@ -752,6 +753,7 @@
848A30571C137B3500C83206 /* TestNSHTTPCookie.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = TestNSHTTPCookie.swift; path = TestFoundation/TestNSHTTPCookie.swift; sourceTree = SOURCE_ROOT; };
84BA558D1C16F90900F48C54 /* TestNSTimeZone.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSTimeZone.swift; sourceTree = "<group>"; };
88D28DE61C13AE9000494606 /* TestNSGeometry.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSGeometry.swift; sourceTree = "<group>"; };
90E645DE1E4C89A400D0D47C /* TestNSCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSCache.swift; sourceTree = "<group>"; };
A5A34B551C18C85D00FD972B /* TestNSByteCountFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSByteCountFormatter.swift; sourceTree = "<group>"; };
AE35A1851CBAC85E0042DB84 /* SwiftFoundation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SwiftFoundation.h; sourceTree = "<group>"; };
BD8042151E09857800487EB8 /* TestNSLengthFormatter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSLengthFormatter.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1398,6 +1400,7 @@
BF8E65301DC3B3CB005AB5C3 /* TestNotification.swift */,
BDFDF0A61DFF5B3E00C04CC5 /* TestNSPersonNameComponents.swift */,
CD1C7F7C1E303B47008E331C /* TestNSError.swift */,
90E645DE1E4C89A400D0D47C /* TestNSCache.swift */,
);
name = Tests;
sourceTree = "<group>";
Expand Down Expand Up @@ -2234,6 +2237,7 @@
CC5249C01D341D23007CB54D /* TestUnitConverter.swift in Sources */,
5B13B3331C582D4C00651CE2 /* TestNSJSONSerialization.swift in Sources */,
5B13B33C1C582D4C00651CE2 /* TestNSOrderedSet.swift in Sources */,
90E645DF1E4C89A400D0D47C /* TestNSCache.swift in Sources */,
5B13B34A1C582D4C00651CE2 /* TestNSURL.swift in Sources */,
EA54A6FB1DB16D53009E0809 /* TestObjCRuntime.swift in Sources */,
5B13B34D1C582D4C00651CE2 /* TestNSUUID.swift in Sources */,
Expand Down
58 changes: 47 additions & 11 deletions Foundation/NSCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,49 @@ private class NSCacheEntry<KeyType : AnyObject, ObjectType : AnyObject> {
}
}

fileprivate class NSCacheKey: NSObject {

var value: AnyObject

init(_ value: AnyObject) {
self.value = value
super.init()
}

override var hashValue: Int {
switch self.value {
case let nsObject as NSObject:
return nsObject.hashValue
case let hashable as Hashable:
return hashable.hashValue
default: return 0
}
}

override func isEqual(_ object: Any?) -> Bool {
guard let other = (object as? NSCacheKey) else { return false }

if self.value === other.value {
return true
} else {
guard let left = self.value as? NSObject,
let right = other.value as? NSObject else { return false }

return left.isEqual(right)
}
}
}

open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {
private var _entries = Dictionary<UnsafeRawPointer, NSCacheEntry<KeyType, ObjectType>>()

private var _entries = Dictionary<NSCacheKey, NSCacheEntry<KeyType, ObjectType>>()
private let _lock = NSLock()
private var _totalCost = 0
private var _byCost: NSCacheEntry<KeyType, ObjectType>?

open var name: String = ""
open var totalCostLimit: Int = -1 // limits are imprecise/not strict
open var countLimit: Int = -1 // limits are imprecise/not strict
open var totalCostLimit: Int = 0 // limits are imprecise/not strict
open var countLimit: Int = 0 // limits are imprecise/not strict
open var evictsObjectsWithDiscardedContent: Bool = false

public override init() {}
Expand All @@ -38,10 +72,10 @@ open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {
open func object(forKey key: KeyType) -> ObjectType? {
var object: ObjectType?

let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self)
let key = NSCacheKey(key)

_lock.lock()
if let entry = _entries[keyRef] {
if let entry = _entries[key] {
object = entry.value
}
_lock.unlock()
Expand Down Expand Up @@ -81,7 +115,7 @@ open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {
}

open func setObject(_ obj: ObjectType, forKey key: KeyType, cost g: Int) {
let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self)
let keyRef = NSCacheKey(key)

_lock.lock()
_totalCost += g
Expand All @@ -104,7 +138,9 @@ open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {
insert(entry)
}
} else {
_entries[keyRef] = NSCacheEntry(key: key, value: obj, cost: g)
let entry = NSCacheEntry(key: key, value: obj, cost: g)
_entries[keyRef] = entry
insert(entry)
}
_lock.unlock()

Expand Down Expand Up @@ -149,14 +185,14 @@ open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {

_lock.lock()
for entry in toRemove {
_entries.removeValue(forKey: unsafeBitCast(entry.key, to: UnsafeRawPointer.self)) // the cost list is already fixed up in the purge routines
_entries.removeValue(forKey: NSCacheKey(entry.key)) // the cost list is already fixed up in the purge routines
}
_lock.unlock()
}

open func removeObject(forKey key: AnyObject) {
let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self)
open func removeObject(forKey key: KeyType) {
let keyRef = NSCacheKey(key)

_lock.lock()
if let entry = _entries.removeValue(forKey: keyRef) {
_totalCost -= entry.cost
Expand Down
109 changes: 109 additions & 0 deletions TestFoundation/TestNSCache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//

#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif

class TestNSCache : XCTestCase {

static var allTests: [(String, (TestNSCache) -> () throws -> Void)] {
return [
("test_setWithUnmutableKeys", test_setWithUnmutableKeys),
("test_setWithMutableKeys", test_setWithMutableKeys),
("test_costLimit", test_costLimit),
("test_countLimit", test_countLimit),
]
}

func test_setWithUnmutableKeys() {
let cache = NSCache<NSString, NSString>()

var key1 = NSString(string: "key")
var key2 = NSString(string: "key")
var value = NSString(string: "value")

cache.setObject(value, forKey: key1)

XCTAssertEqual(cache.object(forKey: key1), value, "should be equal to \(value) when using first key")
XCTAssertEqual(cache.object(forKey: key2), value, "should be equal to \(value) when using second key")

value = NSString(string: "value1")
cache.setObject(value, forKey: key2)

XCTAssertEqual(cache.object(forKey: key1), value, "should be equal to \(value) when using first key")
XCTAssertEqual(cache.object(forKey: key2), value, "should be equal to \(value) when using second key")

key1 = "kkey"
key2 = "kkey"
let value1 = NSString(string: "value1")
let value2 = NSString(string: "value1")
cache.setObject(value1, forKey: key1)

XCTAssertEqual(cache.object(forKey: key1), value1, "should be equal to \(value1) when using first key")
XCTAssertEqual(cache.object(forKey: key2), value1, "should be equal to \(value1) when using second key")
XCTAssertEqual(cache.object(forKey: key1), value2, "should be equal to \(value1) when using first key")
XCTAssertEqual(cache.object(forKey: key2), value2, "should be equal to \(value1) when using second key")
}

func test_setWithMutableKeys() {
let cache = NSCache<NSMutableString, NSString>()

let key1 = NSMutableString(string: "key")
let key2 = NSMutableString(string: "key")
let value = NSString(string: "value")

cache.setObject(value, forKey: key1)

XCTAssertEqual(cache.object(forKey: key1), value, "should be equal to \(value) when using first key")
XCTAssertEqual(cache.object(forKey: key2), value, "should be equal to \(value) when using second key")

key1.append("1")

XCTAssertEqual(cache.object(forKey: key1), value, "should be equal to \(value) when using first key")
XCTAssertNil(cache.object(forKey: key2), "should be nil")
}

func test_costLimit() {
let cache = NSCache<NSString, NSString>()
cache.totalCostLimit = 10

cache.setObject("object0", forKey: "0", cost: 4)
cache.setObject("object2", forKey: "2", cost: 5)

cache.setObject("object1", forKey: "1", cost: 5)

XCTAssertNil(cache.object(forKey: "0"), "should be nil")
XCTAssertEqual(cache.object(forKey: "2"), "object2", "should be equal to 'object2'")
XCTAssertEqual(cache.object(forKey: "1"), "object1", "should be equal to 'object1'")
}

func test_countLimit() {
let cache = NSCache<NSString, NSString>()
cache.countLimit = 2

let key1 = NSString(string: "key1")
let key2 = NSString(string: "key2")
let key3 = NSString(string: "key3")
let value = NSString(string: "value")

cache.setObject(value, forKey: key1)
cache.setObject(value, forKey: key2)
cache.setObject(value, forKey: key3)

XCTAssertEqual(cache.object(forKey: key2), value, "should be equal to \(value)")
XCTAssertEqual(cache.object(forKey: key3), value, "should be equal to \(value)")
XCTAssertNil(cache.object(forKey: key1), "should be nil")

}
}
1 change: 1 addition & 0 deletions TestFoundation/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ XCTMain([
testCase(TestNSArray.allTests),
testCase(TestNSBundle.allTests),
testCase(TestNSByteCountFormatter.allTests),
testCase(TestNSCache.allTests),
testCase(TestNSCalendar.allTests),
testCase(TestNSCharacterSet.allTests),
testCase(TestNSCompoundPredicate.allTests),
Expand Down