ClashX/Pods/RxSwift/Platform/AtomicInt.swift

72 lines
1.4 KiB
Swift
Raw Normal View History

2018-12-22 00:05:35 +08:00
//
// AtomicInt.swift
// Platform
//
// Created by Krunoslav Zaher on 10/28/18.
// Copyright © 2018 Krunoslav Zaher. All rights reserved.
//
2019-05-10 20:31:24 +08:00
import class Foundation.NSLock
2018-12-22 00:05:35 +08:00
2019-05-10 20:31:24 +08:00
final class AtomicInt: NSLock {
fileprivate var value: Int32
public init(_ value: Int32 = 0) {
self.value = value
2018-12-22 00:05:35 +08:00
}
2019-03-19 12:19:08 +08:00
}
2018-12-22 00:05:35 +08:00
2019-03-19 12:19:08 +08:00
@discardableResult
@inline(__always)
2019-05-10 20:31:24 +08:00
func add(_ this: AtomicInt, _ value: Int32) -> Int32 {
this.lock()
let oldValue = this.value
this.value += value
this.unlock()
return oldValue
2019-03-19 12:19:08 +08:00
}
2018-12-22 00:05:35 +08:00
2019-03-19 12:19:08 +08:00
@discardableResult
@inline(__always)
2019-05-10 20:31:24 +08:00
func sub(_ this: AtomicInt, _ value: Int32) -> Int32 {
this.lock()
let oldValue = this.value
this.value -= value
this.unlock()
return oldValue
2019-03-19 12:19:08 +08:00
}
2018-12-22 00:05:35 +08:00
2019-03-19 12:19:08 +08:00
@discardableResult
@inline(__always)
2019-05-10 20:31:24 +08:00
func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 {
this.lock()
let oldValue = this.value
this.value |= mask
this.unlock()
return oldValue
2018-12-22 00:05:35 +08:00
}
2019-03-19 12:19:08 +08:00
@inline(__always)
2019-05-10 20:31:24 +08:00
func load(_ this: AtomicInt) -> Int32 {
this.lock()
let oldValue = this.value
this.unlock()
return oldValue
2019-03-19 12:19:08 +08:00
}
@discardableResult
@inline(__always)
2019-05-10 20:31:24 +08:00
func increment(_ this: AtomicInt) -> Int32 {
2019-03-19 12:19:08 +08:00
return add(this, 1)
}
@discardableResult
@inline(__always)
2019-05-10 20:31:24 +08:00
func decrement(_ this: AtomicInt) -> Int32 {
2019-03-19 12:19:08 +08:00
return sub(this, 1)
}
@inline(__always)
2019-05-10 20:31:24 +08:00
func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool {
2019-03-19 12:19:08 +08:00
return (load(this) & mask) != 0
}