FIRAllocatedUnfairLock.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public func value() -> State {
  39. lock()
  40. defer { unlock() }
  41. return state
  42. }
  43. @discardableResult
  44. public func withLock<R>(_ body: (inout State) throws -> R) rethrows -> R {
  45. let value: R
  46. lock()
  47. defer { unlock() }
  48. value = try body(&state)
  49. return value
  50. }
  51. @discardableResult
  52. public func withLock<R>(_ body: () throws -> R) rethrows -> R {
  53. let value: R
  54. lock()
  55. defer { unlock() }
  56. value = try body()
  57. return value
  58. }
  59. deinit {
  60. lockPointer.deallocate()
  61. }
  62. }