Skip to content

Commit

Permalink
Rewrite Atomic to be less heavy
Browse files Browse the repository at this point in the history
  • Loading branch information
EricRabil committed Sep 1, 2022
1 parent bfc2b1b commit 0b35586
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions Sources/Swexy/Utilities/Atomic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,45 @@
import Foundation

@propertyWrapper
public class Atomic<T> {
private var _wrappedValue: T
public enum Atomic<T> {
case atomic(innerValue: T, semaphore: DispatchSemaphore)

@usableFromInline typealias MemoryLayout = (T, DispatchSemaphore)

@usableFromInline var memoryLayout: MemoryLayout {
@_transparent get {
unsafeBitCast(self, to: MemoryLayout.self)
}
}

@_transparent @usableFromInline var semaphore: DispatchSemaphore {
memoryLayout.1
}

@usableFromInline var _wrappedValue: T {
@_transparent get {
memoryLayout.0
}
@_transparent set {
self = .atomic(innerValue: newValue, semaphore: semaphore)
}
}

private let semaphore = DispatchSemaphore(value: 1)
public var wrappedValue: T {
_read {
@_transparent get {
semaphore.wait()
yield _wrappedValue
let returnValue = _wrappedValue
semaphore.signal()
return returnValue
}
_modify {
@_transparent set {
semaphore.wait()
yield &_wrappedValue
_wrappedValue = newValue
semaphore.signal()
}
}

public init(wrappedValue: T) {
_wrappedValue = wrappedValue
@_transparent public init(wrappedValue: T) {
self = .atomic(innerValue: wrappedValue, semaphore: DispatchSemaphore(value: 1))
}
}

0 comments on commit 0b35586

Please sign in to comment.