Platform.Linux.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // Platform.Linux.swift
  3. // Platform
  4. //
  5. // Created by Krunoslav Zaher on 12/29/15.
  6. // Copyright © 2015 Krunoslav Zaher. All rights reserved.
  7. //
  8. #if os(Linux)
  9. import XCTest
  10. import Glibc
  11. import SwiftShims
  12. import class Foundation.Thread
  13. final class AtomicInt {
  14. typealias IntegerLiteralType = Int
  15. fileprivate var value: Int32 = 0
  16. fileprivate var _lock = RecursiveLock()
  17. func lock() {
  18. _lock.lock()
  19. }
  20. func unlock() {
  21. _lock.unlock()
  22. }
  23. func valueSnapshot() -> Int32 {
  24. return value
  25. }
  26. }
  27. extension AtomicInt: ExpressibleByIntegerLiteral {
  28. convenience init(integerLiteral value: Int) {
  29. self.init()
  30. self.value = Int32(value)
  31. }
  32. }
  33. func >(lhs: AtomicInt, rhs: Int32) -> Bool {
  34. return lhs.value > rhs
  35. }
  36. func ==(lhs: AtomicInt, rhs: Int32) -> Bool {
  37. return lhs.value == rhs
  38. }
  39. func AtomicFlagSet(_ mask: UInt32, _ atomic: inout AtomicInt) -> Bool {
  40. atomic.lock(); defer { atomic.unlock() }
  41. return (atomic.value & Int32(mask)) != 0
  42. }
  43. func AtomicOr(_ mask: UInt32, _ atomic: inout AtomicInt) -> Int32 {
  44. atomic.lock(); defer { atomic.unlock() }
  45. let value = atomic.value
  46. atomic.value |= Int32(mask)
  47. return value
  48. }
  49. func AtomicIncrement(_ atomic: inout AtomicInt) -> Int32 {
  50. atomic.lock(); defer { atomic.unlock() }
  51. atomic.value += 1
  52. return atomic.value
  53. }
  54. func AtomicDecrement(_ atomic: inout AtomicInt) -> Int32 {
  55. atomic.lock(); defer { atomic.unlock() }
  56. atomic.value -= 1
  57. return atomic.value
  58. }
  59. func AtomicCompareAndSwap(_ l: Int32, _ r: Int32, _ atomic: inout AtomicInt) -> Bool {
  60. atomic.lock(); defer { atomic.unlock() }
  61. if atomic.value == l {
  62. atomic.value = r
  63. return true
  64. }
  65. return false
  66. }
  67. extension Thread {
  68. static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: String) {
  69. let currentThread = Thread.current
  70. var threadDictionary = currentThread.threadDictionary
  71. if let newValue = value {
  72. threadDictionary[key] = newValue
  73. }
  74. else {
  75. threadDictionary[key] = nil
  76. }
  77. currentThread.threadDictionary = threadDictionary
  78. }
  79. static func getThreadLocalStorageValueForKey<T: AnyObject>(_ key: String) -> T? {
  80. let currentThread = Thread.current
  81. let threadDictionary = currentThread.threadDictionary
  82. return threadDictionary[key] as? T
  83. }
  84. }
  85. #endif