FIRAllocatedUnfairLock.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. 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 FIRAllocatedUnfairLock<State>: @unchecked Sendable {
  21. private var lockPointer: UnsafeMutablePointer<os_unfair_lock>
  22. private var state: State
  23. public init(initialState: sending State) {
  24. lockPointer = UnsafeMutablePointer<os_unfair_lock>
  25. .allocate(capacity: 1)
  26. lockPointer.initialize(to: os_unfair_lock())
  27. state = initialState
  28. }
  29. public convenience init() where State == Void {
  30. self.init(initialState: ())
  31. }
  32. public func lock() {
  33. os_unfair_lock_lock(lockPointer)
  34. }
  35. public func unlock() {
  36. os_unfair_lock_unlock(lockPointer)
  37. }
  38. @discardableResult
  39. public func withLock<R>(_ body: (inout State) throws -> R) rethrows -> R {
  40. let value: R
  41. lock()
  42. defer { unlock() }
  43. value = try body(&state)
  44. return value
  45. }
  46. @discardableResult
  47. public func withLock<R>(_ body: () throws -> R) rethrows -> R {
  48. let value: R
  49. lock()
  50. defer { unlock() }
  51. value = try body()
  52. return value
  53. }
  54. deinit {
  55. lockPointer.deallocate()
  56. }
  57. }