|
| 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 | + |
| 15 | +import Foundation |
| 16 | +import os.lock |
| 17 | + |
| 18 | +/// A reference wrapper around `os_unfair_lock`. Replace this class with |
| 19 | +/// `OSAllocatedUnfairLock` once we support only iOS 16+. For an explanation |
| 20 | +/// on why this is necessary, see the docs: |
| 21 | +/// https://developer.apple.com/documentation/os/osallocatedunfairlock |
| 22 | +public final class FIRAllocatedUnfairLock<State>: @unchecked Sendable { |
| 23 | + private var lockPointer: UnsafeMutablePointer<os_unfair_lock> |
| 24 | + private var state: State |
| 25 | + |
| 26 | + public init(initialState: sending State) { |
| 27 | + lockPointer = UnsafeMutablePointer<os_unfair_lock> |
| 28 | + .allocate(capacity: 1) |
| 29 | + lockPointer.initialize(to: os_unfair_lock()) |
| 30 | + state = initialState |
| 31 | + } |
| 32 | + |
| 33 | + public convenience init() where State == Void { |
| 34 | + self.init(initialState: ()) |
| 35 | + } |
| 36 | + |
| 37 | + public func lock() { |
| 38 | + os_unfair_lock_lock(lockPointer) |
| 39 | + } |
| 40 | + |
| 41 | + public func unlock() { |
| 42 | + os_unfair_lock_unlock(lockPointer) |
| 43 | + } |
| 44 | + |
| 45 | + @discardableResult |
| 46 | + public func withLock<R>(_ body: (inout State) throws -> R) rethrows -> R { |
| 47 | + let value: R |
| 48 | + lock() |
| 49 | + defer { unlock() } |
| 50 | + value = try body(&state) |
| 51 | + return value |
| 52 | + } |
| 53 | + |
| 54 | + @discardableResult |
| 55 | + public func withLock<R>(_ body: () throws -> R) rethrows -> R { |
| 56 | + let value: R |
| 57 | + lock() |
| 58 | + defer { unlock() } |
| 59 | + value = try body() |
| 60 | + return value |
| 61 | + } |
| 62 | + |
| 63 | + deinit { |
| 64 | + lockPointer.deallocate() |
| 65 | + } |
| 66 | +} |
0 commit comments