Skip to content

Commit 8e8f273

Browse files
committed
Add Atomic
1 parent be6984d commit 8e8f273

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Sources/SwiftExtensions/SwiftExtensions.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,3 +771,33 @@ public struct Unit: Hashable, Codable {
771771
}
772772

773773
public let unit = Unit()
774+
775+
// MARK: - Atomic
776+
777+
/// Masks `DispatchQueue`, without requiring `Foundation`.
778+
public protocol Synchronized {
779+
func sync<Output>(execute: () throws -> Output) rethrows -> Output
780+
}
781+
782+
/// Wraps a mutable value and ensures atomic access to it.
783+
///
784+
/// source: https://www.objc.io/blog/2018/12/18/atomic-variables/
785+
public final class Atomic<Queue: Synchronized, Wrapped> {
786+
private let queue: Queue
787+
private var value: Wrapped
788+
789+
public init(queue: Queue, value: Wrapped) {
790+
self.queue = queue
791+
self.value = value
792+
}
793+
794+
public var get: Wrapped {
795+
queue.sync { self.value }
796+
}
797+
798+
public func modify(_ transform: (inout Wrapped) -> Void) {
799+
queue.sync {
800+
transform(&self.value)
801+
}
802+
}
803+
}

0 commit comments

Comments
 (0)