//===----------------------------------------------------------------------===// // // This source file is part of the Swift Collections open source project // // Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // // SPDX-License-Identifier: Apache-2.0 WITH Swift-exception // //===----------------------------------------------------------------------===// #if COLLECTIONS_SINGLE_MODULE import Collections #else import InternalCollectionsUtilities import ContainersPreview import BasicContainers #endif /// Tracks the life times of `LifetimeTracked` instances, providing a method /// to validate checkpoints where no instances should exist. /// /// - Note: `LifetimeTracker` is not designed for multithreaded use. Trying to /// instantiate or deinitialize instances belonging to the same tracker /// from multiple concurrent threads (or reentrantly) will lead to /// exclusivity violations and therefore undefined behavior. public class LifetimeTracker { @usableFromInline package var _instances = 0 @usableFromInline package var _nextSerialNumber = 0 public init() {} deinit { check() } @inlinable public var instances: Int { _instances } public func check(file: StaticString = #filePath, line: UInt = #line) { expectEqual(instances, 0, "Potential leak of \(instances) objects", file: file, line: line) } public func instance(for payload: Payload) -> LifetimeTracked { LifetimeTracked(payload, for: self) } public func structInstance( for payload: consuming Payload ) -> LifetimeTrackedStruct { LifetimeTrackedStruct(payload, for: self) } public func instances(for items: S) -> [LifetimeTracked] { return items.map { LifetimeTracked($0, for: self) } } #if compiler(>=6.2) @available(SwiftStdlib 5.0, *) public func structInstances( count: Int, generator: (Int) -> Element ) -> RigidArray> { var i = 0 return RigidArray>(capacity: count) { span in while i < count, !span.isFull { span.append(LifetimeTrackedStruct(copying: generator(i), for: self)) i += 1 } } } #endif public func instances( for items: S, by transform: (S.Element) -> T ) -> [LifetimeTracked] { items.map { instance(for: transform($0)) } } } @inlinable public func withLifetimeTracking( file: StaticString = #filePath, line: UInt = #line, _ body: (LifetimeTracker) throws(E) -> R ) throws(E) -> R { let tracker = LifetimeTracker() defer { tracker.check(file: file, line: line) } return try body(tracker) }