AllocationTracker.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. //
  5. import UIKit
  6. @objcMembers class AllocationTracker: NSObject {
  7. public static let shared = AllocationTracker()
  8. private var allocationDict: [String: Int] = [:]
  9. private lazy var isTestEnvironment = {
  10. let arguments = ProcessInfo.processInfo.arguments
  11. return arguments.contains(where: { $0 == "-TestEnvironment" })
  12. }()
  13. public func addAllocation(_ name: String) {
  14. if !isTestEnvironment {
  15. return
  16. }
  17. allocationDict[name, default: 0] += 1
  18. }
  19. public func removeAllocation(_ name: String) {
  20. if !isTestEnvironment {
  21. return
  22. }
  23. if let currentAllocations = allocationDict[name] {
  24. if currentAllocations == 1 {
  25. allocationDict.removeValue(forKey: name)
  26. } else {
  27. allocationDict[name] = currentAllocations - 1
  28. }
  29. } else {
  30. print("WARNING: Removing non-existing allocation")
  31. }
  32. }
  33. override var description: String {
  34. if !isTestEnvironment {
  35. return "Not running in testing environment."
  36. }
  37. if let jsonData = try? JSONSerialization.data(withJSONObject: allocationDict, options: .sortedKeys),
  38. let jsonString = String(data: jsonData, encoding: .utf8) {
  39. return jsonString
  40. }
  41. return "Unknown"
  42. }
  43. }