├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── Package.swift ├── README.md ├── Sources └── WeakMapTable │ └── WeakMapTable.swift ├── Tests └── WeakMapTableTests │ └── WeakMapTableTests.swift ├── WeakMapTable.podspec └── codecov.yml /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | test: 11 | runs-on: macOS-latest 12 | strategy: 13 | matrix: 14 | env: 15 | - sdk: iphonesimulator 16 | destination: platform=iOS Simulator,name=iPhone 12 Pro,OS=latest 17 | 18 | - sdk: macosx 19 | destination: arch=x86_64 20 | 21 | - sdk: appletvsimulator 22 | destination: platform=tvOS Simulator,name=Apple TV,OS=latest 23 | 24 | steps: 25 | - uses: actions/checkout@v2 26 | 27 | - name: Select Xcode 12.4 28 | run: sudo xcode-select -s /Applications/Xcode_12.4.app 29 | 30 | - name: Generate Xcode Project 31 | run: swift package generate-xcodeproj --enable-code-coverage 32 | 33 | - name: Build and Test 34 | run: | 35 | set -o pipefail && xcodebuild clean build test \ 36 | -project "$PROJECT" \ 37 | -scheme "$SCHEME" \ 38 | -sdk "$SDK" \ 39 | -destination "$DESTINATION" \ 40 | -configuration Debug \ 41 | -enableCodeCoverage YES \ 42 | -resultBundlePath "./${{ matrix.env.sdk }}.xcresult" \ 43 | CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO | xcpretty -c; 44 | env: 45 | PROJECT: WeakMapTable.xcodeproj 46 | SCHEME: WeakMapTable-Package 47 | SDK: ${{ matrix.env.sdk }} 48 | DESTINATION: ${{ matrix.env.destination }} 49 | 50 | - name: Upload coverage to Codecov 51 | uses: codecov/codecov-action@v3.1.0 52 | with: 53 | xcode: true 54 | xcode_archive_path: "./${{ matrix.env.sdk }}.xcresult" 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | xcuserdata/ 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Suyeol Jeon (xoul.kr) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.3 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "WeakMapTable", 7 | platforms: [ 8 | .macOS(.v10_11), .iOS(.v9), .tvOS(.v9), .watchOS(.v3) 9 | ], 10 | products: [ 11 | .library(name: "WeakMapTable", targets: ["WeakMapTable"]), 12 | ], 13 | targets: [ 14 | .target(name: "WeakMapTable", dependencies: []), 15 | .testTarget(name: "WeakMapTableTests", dependencies: ["WeakMapTable"]), 16 | ], 17 | swiftLanguageVersions: [.v5] 18 | ) 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WeakMapTable 2 | 3 | ![Swift](https://img.shields.io/badge/Swift-5.1-orange.svg) 4 | [![CocoaPods](http://img.shields.io/cocoapods/v/WeakMapTable.svg)](https://cocoapods.org/pods/WeakMapTable) 5 | [![Build Status](https://github.com/ReactorKit/WeakMapTable/workflows/CI/badge.svg)](https://github.com/ReactorKit/WeakMapTable/actions) 6 | [![CodeCov](https://img.shields.io/codecov/c/github/ReactorKit/WeakMapTable.svg)](https://codecov.io/gh/ReactorKit/WeakMapTable) 7 | 8 | A weak-to-strong map table. It is inspired by [`NSMapTable`](https://developer.apple.com/documentation/foundation/nsmaptable) but **guarantees thread safety** and **deals better with weak references**. [`NSMapTable.weakToStrongObjects()`](https://developer.apple.com/documentation/foundation/nsmaptable/1391346-weaktostrongobjects) doesn't free the value object when the key object is deallocated but WeakMapTable does. 9 | 10 | ## APIs 11 | 12 | ```swift 13 | public func value(forKey key: Key) -> Value? 14 | public func value(forKey key: Key, default: @autoclosure () -> Value) -> Value 15 | public func forceCastedValue(forKey key: Key, default: @autoclosure () -> T) -> T 16 | public func setValue(_ value: Value?, forKey key: Key) 17 | ``` 18 | 19 | ## Installation 20 | 21 | **Podfile** 22 | 23 | ```ruby 24 | pod 'WeakMapTable' 25 | ``` 26 | 27 | ## License 28 | 29 | WeakMapTable is under MIT license. See the [LICENSE](LICENSE) file for more info. 30 | -------------------------------------------------------------------------------- /Sources/WeakMapTable/WeakMapTable.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | 4 | // MARK: - WeakMapTable 5 | 6 | final public class WeakMapTable where Key: AnyObject { 7 | private var dictionary: [Weak: Value] = [:] 8 | private let lock = NSRecursiveLock() 9 | 10 | 11 | // MARK: Initializing 12 | 13 | public init() { 14 | } 15 | 16 | 17 | // MARK: Getting and Setting Values 18 | 19 | public func value(forKey key: Key) -> Value? { 20 | let weakKey = Weak(key) 21 | 22 | self.lock.lock() 23 | defer { 24 | self.lock.unlock() 25 | self.installDeallocHook(to: key) 26 | } 27 | 28 | return self.unsafeValue(forKey: weakKey) 29 | } 30 | 31 | public func value(forKey key: Key, default: @autoclosure () -> Value) -> Value { 32 | let weakKey = Weak(key) 33 | 34 | self.lock.lock() 35 | defer { 36 | self.lock.unlock() 37 | self.installDeallocHook(to: key) 38 | } 39 | 40 | if let value = self.unsafeValue(forKey: weakKey) { 41 | return value 42 | } 43 | 44 | let defaultValue = `default`() 45 | self.unsafeSetValue(defaultValue, forKey: weakKey) 46 | return defaultValue 47 | } 48 | 49 | public func forceCastedValue(forKey key: Key, default: @autoclosure () -> T) -> T { 50 | return self.value(forKey: key, default: `default`() as! Value) as! T 51 | } 52 | 53 | public func setValue(_ value: Value?, forKey key: Key) { 54 | let weakKey = Weak(key) 55 | 56 | self.lock.lock() 57 | defer { 58 | self.lock.unlock() 59 | if value != nil { 60 | self.installDeallocHook(to: key) 61 | } 62 | } 63 | 64 | if let value = value { 65 | self.dictionary[weakKey] = value 66 | } else { 67 | self.dictionary.removeValue(forKey: weakKey) 68 | } 69 | } 70 | 71 | 72 | // MARK: Getting and Setting Values without Locking 73 | 74 | private func unsafeValue(forKey key: Weak) -> Value? { 75 | return self.dictionary[key] 76 | } 77 | 78 | private func unsafeSetValue(_ value: Value?, forKey key: Weak) { 79 | if let value = value { 80 | self.dictionary[key] = value 81 | } else { 82 | self.dictionary.removeValue(forKey: key) 83 | } 84 | } 85 | 86 | 87 | // MARK: Dealloc Hook 88 | 89 | private var deallocHookKey: Void? 90 | 91 | private func installDeallocHook(to key: Key) { 92 | let isInstalled = (objc_getAssociatedObject(key, &deallocHookKey) != nil) 93 | guard !isInstalled else { return } 94 | 95 | let weakKey = Weak(key) 96 | let hook = DeallocHook(handler: { [weak self] in 97 | self?.lock.lock() 98 | self?.dictionary.removeValue(forKey: weakKey) 99 | self?.lock.unlock() 100 | }) 101 | objc_setAssociatedObject(key, &deallocHookKey, hook, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) 102 | } 103 | } 104 | 105 | 106 | // MARK: - Weak 107 | 108 | private final class Weak: Hashable where T: AnyObject { 109 | private let objectHashValue: Int 110 | weak var object: T? 111 | 112 | init(_ object: T) { 113 | self.objectHashValue = ObjectIdentifier(object).hashValue 114 | self.object = object 115 | } 116 | 117 | func hash(into hasher: inout Hasher) { 118 | hasher.combine(self.objectHashValue) 119 | } 120 | 121 | static func == (lhs: Weak, rhs: Weak) -> Bool { 122 | return lhs.objectHashValue == rhs.objectHashValue 123 | } 124 | } 125 | 126 | 127 | // MARK: - DeallocHook 128 | 129 | private final class DeallocHook { 130 | private let handler: () -> Void 131 | 132 | init(handler: @escaping () -> Void) { 133 | self.handler = handler 134 | } 135 | 136 | deinit { 137 | self.handler() 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /Tests/WeakMapTableTests/WeakMapTableTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | import WeakMapTable 3 | 4 | final class WeakMapTableTests: XCTestCase { 5 | func testSetValueForKey() { 6 | let map = WeakMapTable() 7 | 8 | let (key1, value1) = (KeyObject(), ValueObject()) 9 | let (key2, value2) = (KeyObject(), ValueObject()) 10 | map.setValue(value1, forKey: key1) 11 | map.setValue(value2, forKey: key2) 12 | 13 | XCTAssert(map.value(forKey: key1) === value1) 14 | XCTAssert(map.value(forKey: key2) === value2) 15 | } 16 | 17 | func testSetAnotherValue() { 18 | let map = WeakMapTable() 19 | 20 | let key = KeyObject() 21 | weak var weakOldValue: ValueObject? 22 | weak var weakNewValue: ValueObject? 23 | 24 | _ = { 25 | let oldValue = ValueObject() 26 | map.setValue(oldValue, forKey: key) 27 | weakOldValue = oldValue 28 | 29 | let newValue = ValueObject() 30 | map.setValue(newValue, forKey: key) 31 | weakNewValue = newValue 32 | }() 33 | 34 | XCTAssertNil(weakOldValue) 35 | XCTAssertNotNil(weakNewValue) 36 | XCTAssert(map.value(forKey: key) === weakNewValue) 37 | } 38 | 39 | func testSetNil() { 40 | let map = WeakMapTable() 41 | 42 | let key = KeyObject() 43 | weak var weakValue: ValueObject? 44 | 45 | _ = { 46 | let value = ValueObject() 47 | map.setValue(value, forKey: key) 48 | weakValue = value 49 | 50 | map.setValue(nil, forKey: key) 51 | }() 52 | 53 | XCTAssertNil(map.value(forKey: key)) 54 | XCTAssertNil(weakValue) 55 | } 56 | 57 | func testDefaultValue() { 58 | let map = WeakMapTable() 59 | 60 | let key = KeyObject() 61 | let expectedValue = ValueObject() 62 | let actualValue = map.value(forKey: key, default: expectedValue) 63 | 64 | XCTAssert(actualValue === expectedValue) 65 | } 66 | 67 | func testReleaseKeyAndValue() { 68 | let map = WeakMapTable() 69 | 70 | weak var weakKey: KeyObject? 71 | weak var weakValue: ValueObject? 72 | 73 | _ = { 74 | let key = KeyObject() 75 | let value = ValueObject() 76 | map.setValue(value, forKey: key) 77 | weakKey = key 78 | weakValue = value 79 | }() 80 | 81 | XCTAssertNil(weakKey) 82 | XCTAssertNil(weakValue) 83 | } 84 | } 85 | 86 | private final class KeyObject { 87 | } 88 | 89 | private final class ValueObject { 90 | } 91 | -------------------------------------------------------------------------------- /WeakMapTable.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = "WeakMapTable" 3 | s.version = "1.2.1" 4 | s.summary = "A weak-to-strong map table" 5 | s.homepage = "https://github.com/ReactorKit/WeakMapTable" 6 | s.license = { :type => "MIT", :file => "LICENSE" } 7 | s.author = { "Suyeol Jeon" => "devxoul@gmail.com" } 8 | s.source = { :git => "https://github.com/ReactorKit/WeakMapTable.git", 9 | :tag => s.version.to_s } 10 | s.source_files = "Sources/**/*.{swift,h,m}" 11 | s.frameworks = "Foundation" 12 | s.swift_version = "5.1" 13 | 14 | s.ios.deployment_target = "9.0" 15 | s.osx.deployment_target = "10.11" 16 | s.tvos.deployment_target = "9.0" 17 | s.watchos.deployment_target = "3.0" 18 | end 19 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | ignore: 2 | - "Tests/" 3 | 4 | coverage: 5 | status: 6 | project: no 7 | patch: no 8 | changes: no 9 | --------------------------------------------------------------------------------