Files
ichmagmaus111andClaude Opus 5.5 0622057a4f Ghostgram: open-source release
Ghostgram for iOS, rebuilt from scratch on Telegram iOS 13.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:57:09 +01:00

67 lines
1.5 KiB
Swift

import Foundation
public enum AtomicLockError: Error {
case isLocked
}
public final class Atomic<T> {
@usableFromInline
var lock: pthread_mutex_t
@usableFromInline
var value: T
public init(value: T) {
self.lock = pthread_mutex_t()
self.value = value
pthread_mutex_init(&self.lock, nil)
}
deinit {
pthread_mutex_destroy(&self.lock)
}
@inlinable
public func with<R>(_ f: (T) -> R) -> R {
pthread_mutex_lock(&self.lock)
let result = f(self.value)
pthread_mutex_unlock(&self.lock)
return result
}
@inlinable
public func tryWith<R>(_ f: (T) -> R) throws -> R {
if pthread_mutex_trylock(&self.lock) == 0 {
let result = f(self.value)
pthread_mutex_unlock(&self.lock)
return result
} else {
throw AtomicLockError.isLocked
}
}
@inlinable
public func modify(_ f: (T) -> T) -> T {
pthread_mutex_lock(&self.lock)
let result = f(self.value)
let previous = self.value
self.value = result
pthread_mutex_unlock(&self.lock)
withExtendedLifetime(previous, {})
return result
}
@inlinable
public func swap(_ value: T) -> T {
pthread_mutex_lock(&self.lock)
let previous = self.value
self.value = value
pthread_mutex_unlock(&self.lock)
return previous
}
}