You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.3 KiB

5 years ago
2 years ago
5 years ago
2 years ago
5 years ago
2 years ago
5 years ago
2 years ago
5 years ago
  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. }