AtomicInt.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // AtomicInt.swift
  3. // Platform
  4. //
  5. // Created by Krunoslav Zaher on 10/28/18.
  6. // Copyright © 2018 Krunoslav Zaher. All rights reserved.
  7. //
  8. import Foundation
  9. final class AtomicInt: NSLock {
  10. fileprivate var value: Int32
  11. public init(_ value: Int32 = 0) {
  12. self.value = value
  13. }
  14. }
  15. @discardableResult
  16. @inline(__always)
  17. func add(_ this: AtomicInt, _ value: Int32) -> Int32 {
  18. this.lock()
  19. let oldValue = this.value
  20. this.value += value
  21. this.unlock()
  22. return oldValue
  23. }
  24. @discardableResult
  25. @inline(__always)
  26. func sub(_ this: AtomicInt, _ value: Int32) -> Int32 {
  27. this.lock()
  28. let oldValue = this.value
  29. this.value -= value
  30. this.unlock()
  31. return oldValue
  32. }
  33. @discardableResult
  34. @inline(__always)
  35. func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 {
  36. this.lock()
  37. let oldValue = this.value
  38. this.value |= mask
  39. this.unlock()
  40. return oldValue
  41. }
  42. @inline(__always)
  43. func load(_ this: AtomicInt) -> Int32 {
  44. this.lock()
  45. let oldValue = this.value
  46. this.unlock()
  47. return oldValue
  48. }
  49. @discardableResult
  50. @inline(__always)
  51. func increment(_ this: AtomicInt) -> Int32 {
  52. add(this, 1)
  53. }
  54. @discardableResult
  55. @inline(__always)
  56. func decrement(_ this: AtomicInt) -> Int32 {
  57. sub(this, 1)
  58. }
  59. @inline(__always)
  60. func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool {
  61. (load(this) & mask) != 0
  62. }