Platform.Darwin.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // Platform.Darwin.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(macOS) || os(iOS) || os(tvOS) || os(watchOS)
  9. import Darwin
  10. import class Foundation.Thread
  11. import func Foundation.OSAtomicCompareAndSwap32Barrier
  12. import func Foundation.OSAtomicIncrement32Barrier
  13. import func Foundation.OSAtomicDecrement32Barrier
  14. import protocol Foundation.NSCopying
  15. typealias AtomicInt = Int32
  16. fileprivate func castToUInt32Pointer(_ pointer: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<UInt32> {
  17. let raw = UnsafeMutableRawPointer(pointer)
  18. return raw.assumingMemoryBound(to: UInt32.self)
  19. }
  20. let AtomicCompareAndSwap = OSAtomicCompareAndSwap32Barrier
  21. let AtomicIncrement = OSAtomicIncrement32Barrier
  22. let AtomicDecrement = OSAtomicDecrement32Barrier
  23. func AtomicOr(_ mask: UInt32, _ theValue : UnsafeMutablePointer<Int32>) -> Int32 {
  24. return OSAtomicOr32OrigBarrier(mask, castToUInt32Pointer(theValue))
  25. }
  26. func AtomicFlagSet(_ mask: UInt32, _ theValue : UnsafeMutablePointer<Int32>) -> Bool {
  27. // just used to create a barrier
  28. OSAtomicXor32OrigBarrier(0, castToUInt32Pointer(theValue))
  29. return (theValue.pointee & Int32(mask)) != 0
  30. }
  31. extension Thread {
  32. static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: NSCopying
  33. ) {
  34. let currentThread = Thread.current
  35. let threadDictionary = currentThread.threadDictionary
  36. if let newValue = value {
  37. threadDictionary[key] = newValue
  38. }
  39. else {
  40. threadDictionary[key] = nil
  41. }
  42. }
  43. static func getThreadLocalStorageValueForKey<T>(_ key: NSCopying) -> T? {
  44. let currentThread = Thread.current
  45. let threadDictionary = currentThread.threadDictionary
  46. return threadDictionary[key] as? T
  47. }
  48. }
  49. extension AtomicInt {
  50. func valueSnapshot() -> Int32 {
  51. return self
  52. }
  53. }
  54. #endif