├── .gitignore ├── codecov.yml ├── Package.swift ├── WeakMapTable.podspec ├── LICENSE ├── README.md ├── .github └── workflows │ └── ci.yml ├── Tests └── WeakMapTableTests │ └── WeakMapTableTests.swift └── Sources └── WeakMapTable └── WeakMapTable.swift /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | xcuserdata/ 6 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | ignore: 2 | - "Tests/" 3 | 4 | coverage: 5 | status: 6 | project: no 7 | patch: no 8 | changes: no 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | 13 | env: 14 | SCHEME: WeakMapTable 15 | CODECOV_PACKAGE_NAME: WeakMapTable 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | env: 21 | - sdk: iphonesimulator 22 | - sdk: macosx 23 | - sdk: appletvsimulator 24 | 25 | steps: 26 | - uses: actions/checkout@v4 27 | 28 | - name: List SDKs and Devices 29 | run: xcodebuild -showsdks; xcrun xctrace list devices 30 | 31 | - uses: maxim-lobanov/setup-xcode@v1 32 | with: 33 | xcode-version: latest-stable 34 | 35 | - name: Select iOS Simulator dynamically 36 | if: matrix.env.sdk == 'iphonesimulator' 37 | run: | 38 | OS_VERSION=$(xcrun simctl list runtimes | grep 'iOS' | grep -oE '[0-9]+\.[0-9]+' | sort -Vr | head -n1) 39 | DEVICE_NAME=$(xcrun simctl list devices | grep -A 20 "^-- iOS $OS_VERSION --" | grep -E '^ *iPhone [0-9]+ \(' | grep -v 'Pro\|Plus\|SE\|unavailable' | sed -E 's/^[[:space:]]*([^()]+) \(.*/\1/' | sort -t' ' -k2 -n -r | head -n1) 40 | echo "Using simulator: $DEVICE_NAME (iOS $OS_VERSION)" 41 | echo "DESTINATION=platform=iOS Simulator,name=$DEVICE_NAME,OS=$OS_VERSION" >> $GITHUB_ENV 42 | 43 | - name: Set macOS destination 44 | if: matrix.env.sdk == 'macosx' 45 | run: echo "DESTINATION=arch=x86_64" >> $GITHUB_ENV 46 | 47 | - name: Set tvOS destination 48 | if: matrix.env.sdk == 'appletvsimulator' 49 | run: echo "DESTINATION=platform=tvOS Simulator,name=Apple TV,OS=latest" >> $GITHUB_ENV 50 | 51 | - name: Build and Test 52 | run: | 53 | set -o pipefail && xcodebuild build test \ 54 | -scheme "$SCHEME" \ 55 | -sdk "$SDK" \ 56 | -destination "$DESTINATION" \ 57 | -configuration Debug \ 58 | -enableCodeCoverage YES \ 59 | -resultBundlePath "./${{ matrix.env.sdk }}.xcresult" \ 60 | CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO | xcpretty -c; 61 | env: 62 | SDK: ${{ matrix.env.sdk }} 63 | DESTINATION: ${{ env.DESTINATION }} 64 | 65 | - name: Upload coverage to Codecov 66 | uses: codecov/codecov-action@v3.1.0 67 | with: 68 | xcode: true 69 | xcode_archive_path: "./${{ matrix.env.sdk }}.xcresult" 70 | -------------------------------------------------------------------------------- /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 | func testRemoveAll() { 86 | let map = WeakMapTable() 87 | let key = KeyObject() 88 | weak var weakValue: ValueObject? 89 | 90 | _ = { 91 | let value = ValueObject() 92 | map.setValue(value, forKey: key) 93 | weakValue = value 94 | 95 | map.removeAll() 96 | }() 97 | 98 | XCTAssertNil(map.value(forKey: key)) 99 | XCTAssertNil(weakValue) 100 | } 101 | } 102 | 103 | private final class KeyObject { 104 | } 105 | 106 | private final class ValueObject { 107 | } 108 | -------------------------------------------------------------------------------- /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 | public func removeAll() { 72 | self.lock.lock() 73 | defer { 74 | self.lock.unlock() 75 | } 76 | self.dictionary.removeAll() 77 | } 78 | 79 | // MARK: Getting and Setting Values without Locking 80 | 81 | private func unsafeValue(forKey key: Weak) -> Value? { 82 | return self.dictionary[key] 83 | } 84 | 85 | private func unsafeSetValue(_ value: Value?, forKey key: Weak) { 86 | if let value = value { 87 | self.dictionary[key] = value 88 | } else { 89 | self.dictionary.removeValue(forKey: key) 90 | } 91 | } 92 | 93 | 94 | // MARK: Dealloc Hook 95 | 96 | private var deallocHookKey: Void? 97 | 98 | private func installDeallocHook(to key: Key) { 99 | let isInstalled = (objc_getAssociatedObject(key, &deallocHookKey) != nil) 100 | guard !isInstalled else { return } 101 | 102 | let weakKey = Weak(key) 103 | let hook = DeallocHook(handler: { [weak self] in 104 | self?.lock.lock() 105 | self?.dictionary.removeValue(forKey: weakKey) 106 | self?.lock.unlock() 107 | }) 108 | objc_setAssociatedObject(key, &deallocHookKey, hook, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) 109 | } 110 | } 111 | 112 | 113 | // MARK: - Weak 114 | 115 | private final class Weak: Hashable where T: AnyObject { 116 | private let objectHashValue: Int 117 | weak var object: T? 118 | 119 | init(_ object: T) { 120 | self.objectHashValue = ObjectIdentifier(object).hashValue 121 | self.object = object 122 | } 123 | 124 | func hash(into hasher: inout Hasher) { 125 | hasher.combine(self.objectHashValue) 126 | } 127 | 128 | static func == (lhs: Weak, rhs: Weak) -> Bool { 129 | return lhs.objectHashValue == rhs.objectHashValue 130 | } 131 | } 132 | 133 | 134 | // MARK: - DeallocHook 135 | 136 | private final class DeallocHook { 137 | private let handler: () -> Void 138 | 139 | init(handler: @escaping () -> Void) { 140 | self.handler = handler 141 | } 142 | 143 | deinit { 144 | self.handler() 145 | } 146 | } 147 | --------------------------------------------------------------------------------