From 766ecf919c8cc66ece38f8f088c50990135f567a Mon Sep 17 00:00:00 2001 From: Steve Vlaminck Date: Tue, 24 Mar 2020 07:29:05 -0500 Subject: [PATCH] add functions removeAll, contains, and first to ThreadSafeList --- .../ThreadSafeList.swift | 22 +++++++++++++++++++ .../ThreadSafeCollectionsTests.swift | 5 +++++ 2 files changed, 27 insertions(+) diff --git a/Sources/ThreadSafeCollections/ThreadSafeList.swift b/Sources/ThreadSafeCollections/ThreadSafeList.swift index 7891ae0..d9fe8b8 100644 --- a/Sources/ThreadSafeCollections/ThreadSafeList.swift +++ b/Sources/ThreadSafeCollections/ThreadSafeList.swift @@ -60,6 +60,12 @@ public class ThreadSafeList { } } + public func removeAll(where shouldBeRemoved: @escaping (V) -> Bool) { + itemQueue.async(flags: .barrier) { // safely write + self.items.removeAll(where: shouldBeRemoved) + } + } + public func getAll() -> [V] { var allItems = [V]() itemQueue.sync { // safely read @@ -76,6 +82,22 @@ public class ThreadSafeList { return count } + public func contains(where predicate: (V) throws -> Bool) rethrows -> Bool { + var doesContain = false + try itemQueue.sync { // safely read + doesContain = try self.items.contains(where: predicate) + } + return doesContain + } + + public func first(where predicate: (V) throws -> Bool) rethrows -> V? { + var foundItem: V? = nil + try itemQueue.sync { // safely read + foundItem = try self.items.first(where: predicate) + } + return foundItem + } + public subscript(index: Int) -> V? { get { return self.get(index) diff --git a/Tests/ThreadSafeCollectionsTests/ThreadSafeCollectionsTests.swift b/Tests/ThreadSafeCollectionsTests/ThreadSafeCollectionsTests.swift index 84f825e..de9c82f 100644 --- a/Tests/ThreadSafeCollectionsTests/ThreadSafeCollectionsTests.swift +++ b/Tests/ThreadSafeCollectionsTests/ThreadSafeCollectionsTests.swift @@ -38,6 +38,11 @@ final class ThreadSafeCollectionsTests: XCTestCase { XCTAssertEqual(0, m.count()) m.append(contentsOf: items) XCTAssertEqual(100, m.count()) + XCTAssertTrue(m.contains(where: { $0 == 5 })) + XCTAssertEqual(5, m.first(where: { $0 == 5 })) + m.removeAll(where: { $0 == 5 }) + XCTAssertFalse(m.contains(where: { $0 == 5 })) + XCTAssertNil(m.first(where: { $0 == 5 })) } }