UnfairLock.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2025 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. private import os.lock
  16. /// A reference wrapper around `os_unfair_lock`. Replace this class with
  17. /// `OSAllocatedUnfairLock` once we support only iOS 16+. For an explanation
  18. /// on why this is necessary, see the docs:
  19. /// https://developer.apple.com/documentation/os/osallocatedunfairlock
  20. public final class UnfairLock<Value>: @unchecked Sendable {
  21. private var lockPointer: UnsafeMutablePointer<os_unfair_lock>
  22. private var _value: Value
  23. public init(_ value: consuming sending Value) {
  24. lockPointer = UnsafeMutablePointer<os_unfair_lock>
  25. .allocate(capacity: 1)
  26. lockPointer.initialize(to: os_unfair_lock())
  27. _value = value
  28. }
  29. deinit {
  30. lockPointer.deallocate()
  31. }
  32. public func value() -> Value {
  33. lock()
  34. defer { unlock() }
  35. return _value
  36. }
  37. @discardableResult
  38. public borrowing func withLock<Result>(_ body: (inout sending Value) throws
  39. -> sending Result) rethrows -> sending Result {
  40. lock()
  41. defer { unlock() }
  42. return try body(&_value)
  43. }
  44. @discardableResult
  45. public borrowing func withLock<Result>(_ body: (inout sending Value) -> sending Result)
  46. -> sending Result {
  47. lock()
  48. defer { unlock() }
  49. return body(&_value)
  50. }
  51. private func lock() {
  52. os_unfair_lock_lock(lockPointer)
  53. }
  54. private func unlock() {
  55. os_unfair_lock_unlock(lockPointer)
  56. }
  57. }