content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
//\n// PacketTunnelActor+Mocks.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 25/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadMockData\nimport MullvadREST\nimport PacketTunnelCore\n\nextension PacketTunnelActorTimings {\n static var timingsForTests: PacketTunnelActorTimings {\n return PacketTunnelActorTimings(\n bootRecoveryPeriodicity: .milliseconds(10),\n wgKeyPropagationDelay: .zero\n )\n }\n}\n\nextension PacketTunnelActor {\n static func mock(\n tunnelAdapter: TunnelAdapterProtocol = TunnelAdapterDummy(),\n tunnelMonitor: TunnelMonitorProtocol = TunnelMonitorStub.nonFallible(),\n defaultPathObserver: DefaultPathObserverProtocol = DefaultPathObserverFake(),\n blockedStateErrorMapper: BlockedStateErrorMapperProtocol = BlockedStateErrorMapperStub(),\n relaySelector: RelaySelectorProtocol = RelaySelectorStub.nonFallible(),\n settingsReader: SettingsReaderProtocol = SettingsReaderStub.staticConfiguration()\n ) -> PacketTunnelActor {\n return PacketTunnelActor(\n timings: .timingsForTests,\n tunnelAdapter: tunnelAdapter,\n tunnelMonitor: tunnelMonitor,\n defaultPathObserver: defaultPathObserver,\n blockedStateErrorMapper: blockedStateErrorMapper,\n relaySelector: relaySelector,\n settingsReader: settingsReader,\n protocolObfuscator: ProtocolObfuscationStub()\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\PacketTunnelActor+Mocks.swift | PacketTunnelActor+Mocks.swift | Swift | 1,526 | 0.95 | 0 | 0.175 | node-utils | 731 | 2023-08-02T16:45:30.149204 | Apache-2.0 | true | 92cc9a4b6271355c3647f2604b174b2f |
//\n// PacketTunnelActorStub.swift\n// PacketTunnelCoreTests\n//\n// Created by Jon Petersson on 2023-10-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport PacketTunnelCore\nimport XCTest\n\nstruct PacketTunnelActorStub: PacketTunnelActorProtocol {\n let innerState: ObservedState = .disconnected\n var stateExpectation: XCTestExpectation?\n var reconnectExpectation: XCTestExpectation?\n var keyRotationExpectation: XCTestExpectation?\n\n var observedState: ObservedState {\n get async {\n stateExpectation?.fulfill()\n return innerState\n }\n }\n\n func reconnect(to nextRelays: NextRelays, reconnectReason: ActorReconnectReason) {\n reconnectExpectation?.fulfill()\n }\n\n func notifyKeyRotation(date: Date?) {\n keyRotationExpectation?.fulfill()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\PacketTunnelActorStub.swift | PacketTunnelActorStub.swift | Swift | 854 | 0.95 | 0 | 0.25 | python-kit | 402 | 2024-12-01T01:06:08.890121 | GPL-3.0 | true | 211bf744951842f8367c55538953bbfd |
//\n// PingerMock.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 16/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport Network\n@testable import PacketTunnelCore\n\n/// Ping client mock that can be used to simulate network transmission errors and delays.\nclass PingerMock: PingerProtocol {\n typealias OutcomeDecider = (IPv4Address, UInt16) -> Outcome\n\n private let decideOutcome: OutcomeDecider\n private let networkStatsReporting: NetworkStatsReporting\n private let stateLock = NSLock()\n private var state = State()\n\n var onReply: ((PingerReply) -> Void)? {\n get {\n stateLock.withLock { state.onReply }\n }\n set {\n stateLock.withLock { state.onReply = newValue }\n }\n }\n\n init(networkStatsReporting: NetworkStatsReporting, decideOutcome: @escaping OutcomeDecider) {\n self.networkStatsReporting = networkStatsReporting\n self.decideOutcome = decideOutcome\n }\n\n func startPinging(destAddress: IPv4Address) throws {\n stateLock.withLock {\n state.destAddress = destAddress\n state.isSocketOpen = true\n }\n }\n\n func stopPinging() {\n stateLock.withLock {\n state.isSocketOpen = false\n }\n }\n\n func send() throws -> PingerSendResult {\n // Used for simulation. In reality can be any number.\n // But for realism it is: IPv4 header (20 bytes) + ICMP header (8 bytes)\n let icmpPacketSize: UInt = 28\n\n guard let address = state.destAddress else {\n fatalError("Address somehow not set when sending ping")\n }\n\n let nextSequenceId = try stateLock.withLock {\n guard state.isSocketOpen else { throw POSIXError(.ENOTCONN) }\n\n return state.incrementSequenceId()\n }\n\n switch decideOutcome(address, nextSequenceId) {\n case let .sendReply(reply, delay):\n DispatchQueue.main.asyncAfter(wallDeadline: .now() + delay) { [weak self] in\n guard let self else { return }\n\n networkStatsReporting.reportBytesReceived(UInt64(icmpPacketSize))\n\n switch reply {\n case .normal:\n onReply?(.success(address, nextSequenceId))\n case .malformed:\n onReply?(.parseError(ParseError()))\n }\n }\n\n case .ignore:\n break\n\n case .sendFailure:\n throw POSIXError(.ECONNREFUSED)\n }\n\n networkStatsReporting.reportBytesSent(UInt64(icmpPacketSize))\n\n return PingerSendResult(sequenceNumber: nextSequenceId)\n }\n\n // MARK: - Types\n\n /// Internal state\n private struct State {\n var sequenceId: UInt16 = 0\n var isSocketOpen = false\n var onReply: ((PingerReply) -> Void)?\n var destAddress: IPv4Address?\n\n mutating func incrementSequenceId() -> UInt16 {\n sequenceId += 1\n return sequenceId\n }\n }\n\n /// Simulated ICMP reply.\n enum Reply {\n /// Simulate normal ping reply.\n case normal\n\n /// Simulate malformed ping reply.\n case malformed\n }\n\n /// The outcome of ping request simulation.\n enum Outcome {\n /// Simulate ping reply transmission.\n case sendReply(reply: Reply = .normal, afterDelay: Duration = .milliseconds(100))\n\n /// Simulate packet that was lost or left unanswered.\n case ignore\n\n /// Simulate failure to send ICMP packet (i.e `sendto()` error).\n case sendFailure\n }\n\n struct ParseError: LocalizedError {\n var errorDescription: String? {\n return "ICMP response parse error"\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\PingerMock.swift | PingerMock.swift | Swift | 3,772 | 0.95 | 0.045113 | 0.179245 | awesome-app | 778 | 2024-07-26T21:17:34.783756 | BSD-3-Clause | true | d1e17a6c1d9ca3f3c9f1914634cb08a0 |
//\n// PostQuantumKeyExchangingUpdaterStub.swift\n// PacketTunnelCoreTests\n//\n// Created by Mojgan on 2024-07-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadTypes\n@testable import PacketTunnelCore\n\nfinal class PostQuantumKeyExchangingUpdaterStub: PostQuantumKeyExchangingUpdaterProtocol {\n var reconfigurationHandler: ConfigUpdater?\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\PostQuantumKeyExchangingUpdaterStub.swift | PostQuantumKeyExchangingUpdaterStub.swift | Swift | 401 | 0.95 | 0.066667 | 0.538462 | python-kit | 708 | 2025-07-06T19:13:16.696580 | MIT | true | 08fe96eaf2e8ec4ae18a6a4a65ec40e4 |
//\n// ProtocolObfuscationStub.swift\n// PacketTunnelCoreTests\n//\n// Created by Marco Nikic on 2023-11-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadSettings\n@testable import MullvadTypes\n@testable import PacketTunnelCore\n\nstruct ProtocolObfuscationStub: ProtocolObfuscation {\n var remotePort: UInt16 { 42 }\n\n func obfuscate(\n _ endpoint: MullvadEndpoint,\n settings: LatestTunnelSettings,\n retryAttempts: UInt\n ) -> ProtocolObfuscationResult {\n .init(endpoint: endpoint, method: .off)\n }\n\n var transportLayer: TransportLayer? { .udp }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\ProtocolObfuscationStub.swift | ProtocolObfuscationStub.swift | Swift | 644 | 0.95 | 0 | 0.318182 | vue-tools | 115 | 2024-02-05T10:25:11.042310 | GPL-3.0 | true | 73799545c2742679250f0d50000ffc66 |
//\n// SettingsReaderStub.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 05/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\nimport WireGuardKitTypes\n\n/// Settings reader stub that can be configured with a block to provide the desired behavior when testing.\nstruct SettingsReaderStub: SettingsReaderProtocol {\n let block: () throws -> Settings\n\n func read() throws -> Settings {\n return try block()\n }\n}\n\nextension SettingsReaderStub {\n /// Initialize non-fallible settings reader stub that will always return the same static configuration generated at the time of creation.\n static func staticConfiguration() -> SettingsReaderStub {\n let staticSettings = Settings(\n privateKey: PrivateKey(),\n interfaceAddresses: [IPAddressRange(from: "127.0.0.1/32")!],\n tunnelSettings: LatestTunnelSettings(\n relayConstraints: RelayConstraints(),\n dnsSettings: DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings(state: .off),\n tunnelQuantumResistance: .automatic,\n tunnelMultihopState: .off,\n daita: DAITASettings()\n )\n )\n\n return SettingsReaderStub {\n return staticSettings\n }\n }\n\n static func postQuantumConfiguration() -> SettingsReaderStub {\n let staticSettings = Settings(\n privateKey: PrivateKey(),\n interfaceAddresses: [IPAddressRange(from: "127.0.0.1/32")!],\n tunnelSettings: LatestTunnelSettings(\n relayConstraints: RelayConstraints(),\n dnsSettings: DNSSettings(),\n wireGuardObfuscation: WireGuardObfuscationSettings(state: .off),\n tunnelQuantumResistance: .on,\n tunnelMultihopState: .off,\n daita: DAITASettings()\n )\n )\n return SettingsReaderStub {\n return staticSettings\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\SettingsReaderStub.swift | SettingsReaderStub.swift | Swift | 2,102 | 0.95 | 0.016129 | 0.160714 | python-kit | 636 | 2025-03-04T10:22:38.821232 | GPL-3.0 | true | 2b94868f9b2ed5cdb904d4d6ced7c31e |
//\n// TunnelAdapterDummy.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 05/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport PacketTunnelCore\n@testable import WireGuardKitTypes\n\n/// Dummy tunnel adapter that does nothing and reports no errors.\nclass TunnelAdapterDummy: TunnelAdapterProtocol, @unchecked Sendable {\n func startMultihop(\n entryConfiguration: TunnelAdapterConfiguration?,\n exitConfiguration: TunnelAdapterConfiguration,\n daita: DaitaConfiguration?\n ) async throws {}\n\n func start(configuration: TunnelAdapterConfiguration, daita: DaitaConfiguration?) async throws {}\n\n func stop() async throws {}\n\n func update(configuration: TunnelAdapterConfiguration) async throws {}\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\TunnelAdapterDummy.swift | TunnelAdapterDummy.swift | Swift | 786 | 0.95 | 0.038462 | 0.380952 | vue-tools | 323 | 2024-09-26T22:41:55.659989 | BSD-3-Clause | true | bad0893fdae01340df23e757b63f8d76 |
//\n// TunnelDeviceInfoStub.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 16/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport PacketTunnelCore\n\n/// Tunnel device stub that returns fixed interface name and feeds network stats from the type implementing `NetworkStatsProviding`\nstruct TunnelDeviceInfoStub: TunnelDeviceInfoProtocol {\n let networkStatsProviding: NetworkStatsProviding\n\n var interfaceName: String? {\n return "utun0"\n }\n\n func getStats() throws -> WgStats {\n return WgStats(\n bytesReceived: networkStatsProviding.bytesReceived,\n bytesSent: networkStatsProviding.bytesSent\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\TunnelDeviceInfoStub.swift | TunnelDeviceInfoStub.swift | Swift | 715 | 0.95 | 0 | 0.363636 | vue-tools | 997 | 2023-11-19T15:28:58.320899 | BSD-3-Clause | true | f6c8a53276183a9180a1dfc3cb487efb |
//\n// TunnelMonitorStub.swift\n// PacketTunnelCoreTests\n//\n// Created by pronebird on 05/09/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\nimport PacketTunnelCore\n\n/// Tunnel monitor stub that can be configured with block handler to simulate a specific behavior.\nclass TunnelMonitorStub: TunnelMonitorProtocol, @unchecked Sendable {\n enum Command {\n case start, stop\n }\n\n class Dispatcher {\n typealias BlockHandler = (TunnelMonitorEvent, DispatchTimeInterval) -> Void\n\n private let block: BlockHandler\n init(_ block: @escaping BlockHandler) {\n self.block = block\n }\n\n func send(_ event: TunnelMonitorEvent, after delay: DispatchTimeInterval = .never) {\n block(event, delay)\n }\n }\n\n typealias EventHandler = (TunnelMonitorEvent) -> Void\n typealias SimulationHandler = (Command, Dispatcher) -> Void\n\n private let stateLock = NSLock()\n\n var onEvent: EventHandler? {\n get {\n stateLock.withLock { _onEvent }\n }\n set {\n stateLock.withLock {\n _onEvent = newValue\n }\n }\n }\n\n private var _onEvent: EventHandler?\n private let simulationBlock: SimulationHandler\n\n init(_ simulationBlock: @escaping SimulationHandler) {\n self.simulationBlock = simulationBlock\n }\n\n func start(probeAddress: IPv4Address) {\n sendCommand(.start)\n }\n\n func stop() {\n sendCommand(.stop)\n }\n\n func onWake() {}\n\n func onSleep() {}\n\n func handleNetworkPathUpdate(_ networkPath: Network.NWPath.Status) {}\n\n func dispatch(_ event: TunnelMonitorEvent, after delay: DispatchTimeInterval = .never) {\n if case .never = delay {\n onEvent?(event)\n } else {\n DispatchQueue.main.asyncAfter(wallDeadline: .now() + delay) { [weak self] in\n self?.onEvent?(event)\n }\n }\n }\n\n private func sendCommand(_ command: Command) {\n let dispatcher = Dispatcher { [weak self] event, delay in\n self?.dispatch(event, after: delay)\n }\n simulationBlock(command, dispatcher)\n }\n}\n\nextension TunnelMonitorStub {\n /// Returns a mock of tunnel monitor that always reports that connection is established after a short delay.\n static func nonFallible() -> TunnelMonitorStub {\n TunnelMonitorStub { command, dispatcher in\n if case .start = command {\n dispatcher.send(.connectionEstablished, after: .milliseconds(10))\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\TunnelMonitorStub.swift | TunnelMonitorStub.swift | Swift | 2,611 | 0.95 | 0.041667 | 0.115385 | python-kit | 698 | 2023-10-26T12:40:06.124416 | Apache-2.0 | true | a6ef70d242095793980cb8d44e62e144 |
//\n// TunnelObfuscationStub.swift\n// PacketTunnelCoreTests\n//\n// Created by Marco Nikic on 2023-11-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n@testable import MullvadRustRuntime\n@testable import MullvadTypes\nimport Network\n\nstruct TunnelObfuscationStub: TunnelObfuscation {\n var transportLayer: TransportLayer { .udp }\n\n let remotePort: UInt16\n init(remoteAddress: IPAddress, tcpPort: UInt16, obfuscationProtocol: TunnelObfuscationProtocol) {\n remotePort = tcpPort\n }\n\n func start() {}\n\n func stop() {}\n\n var localUdpPort: UInt16 { 42 }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\TunnelObfuscationStub.swift | TunnelObfuscationStub.swift | Swift | 612 | 0.95 | 0 | 0.333333 | python-kit | 695 | 2024-12-16T00:31:45.220760 | GPL-3.0 | true | a282e3ef6eb71c1e0d0f33db31ac8fa7 |
//\n// URLRequestProxyStub.swift\n// PacketTunnelCoreTests\n//\n// Created by Jon Petersson on 2023-10-11.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport PacketTunnelCore\nimport XCTest\n\nstruct URLRequestProxyStub: URLRequestProxyProtocol {\n var sendRequestExpectation: XCTestExpectation?\n var cancelRequestExpectation: XCTestExpectation?\n\n func sendRequest(\n _ proxyRequest: PacketTunnelCore.ProxyURLRequest,\n completionHandler: @escaping @Sendable (PacketTunnelCore.ProxyURLResponse) -> Void\n ) {\n sendRequestExpectation?.fulfill()\n }\n\n func sendRequest(_ proxyRequest: PacketTunnelCore.ProxyURLRequest) async -> PacketTunnelCore.ProxyURLResponse {\n sendRequestExpectation?.fulfill()\n return ProxyURLResponse(data: nil, response: nil, error: nil)\n }\n\n func cancelRequest(identifier: UUID) {\n cancelRequestExpectation?.fulfill()\n }\n}\n\nstruct APIRequestProxyStub: APIRequestProxyProtocol {\n var sendRequestExpectation: XCTestExpectation?\n var cancelRequestExpectation: XCTestExpectation?\n\n func sendRequest(\n _ proxyRequest: ProxyAPIRequest,\n completion: @escaping @Sendable (ProxyAPIResponse) -> Void\n ) {\n sendRequestExpectation?.fulfill()\n }\n\n func sendRequest(_ proxyRequest: ProxyAPIRequest) async -> ProxyAPIResponse {\n sendRequestExpectation?.fulfill()\n return ProxyAPIResponse(data: nil, error: nil)\n }\n\n func cancelRequest(identifier: UUID) {\n cancelRequestExpectation?.fulfill()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\PacketTunnelCoreTests\Mocks\URLRequestProxyStub.swift | URLRequestProxyStub.swift | Swift | 1,590 | 0.95 | 0 | 0.155556 | node-utils | 868 | 2024-05-19T08:56:46.222419 | BSD-3-Clause | true | d514825ec8052dbc8f20a7a25f02d6e3 |
//\n// Coordinator.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/01/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport UIKit\n\n/**\n Base coordinator class.\n\n Coordinators help to abstract the navigation and business logic from view controllers making them\n more manageable and reusable.\n */\n@MainActor\nopen class Coordinator: NSObject, Sendable {\n /// Private trace log.\n private lazy var logger = Logger(label: "\(Self.self)")\n\n /// Weak reference to parent coordinator.\n private weak var _parent: Coordinator?\n\n /// Mutable collection of child coordinators.\n private var _children: [Coordinator] = []\n\n /// Modal presentation configuration assigned on presented coordinator.\n fileprivate var modalConfiguration: ModalPresentationConfiguration?\n\n /// An array of blocks that are invoked upon interactive dismissal.\n fileprivate var interactiveDismissalObservers: [(Coordinator) -> Void] = []\n\n /// Child coordinators.\n public var childCoordinators: [Coordinator] {\n _children\n }\n\n /// Parent coordinator.\n public var parent: Coordinator? {\n _parent\n }\n\n // MARK: - Children\n\n /**\n Add child coordinator.\n\n Adding the same coordinator twice is a no-op.\n */\n public func addChild(_ child: Coordinator) {\n guard !_children.contains(child) else { return }\n\n _children.append(child)\n child._parent = self\n\n logger.trace("Add child \(child)")\n }\n\n /**\n Remove child coordinator.\n\n Removing coordinator that's no longer a child of this coordinator is a no-op.\n */\n public func removeChild(_ child: Coordinator) {\n guard let index = _children.firstIndex(where: { $0 == child }) else { return }\n\n _children.remove(at: index)\n child._parent = nil\n\n logger.trace("Remove child \(child)")\n }\n\n /**\n Remove coordinator from its parent.\n */\n public func removeFromParent() {\n _parent?.removeChild(self)\n }\n}\n\n/**\n Protocol describing coordinators that can be presented using modal presentation.\n */\npublic protocol Presentable: Coordinator, Sendable {\n /**\n View controller that is presented modally. It's expected it to be the topmost view controller\n managed by coordinator.\n */\n var presentedViewController: UIViewController { get }\n}\n\n/**\n Protocol describing `Presentable` coordinators that can be popped from a navigation stack.\n */\npublic protocol Poppable: Presentable {\n func popFromNavigationStack(\n animated: Bool,\n completion: (() -> Void)?\n )\n}\n\n/**\n Protocol describing coordinators that provide modal presentation context.\n */\npublic protocol Presenting: Coordinator {\n /**\n View controller providing modal presentation context.\n */\n var presentationContext: UIViewController { get }\n}\n\nextension Presenting where Self: Presentable {\n /**\n View controller providing modal presentation context.\n */\n public var presentationContext: UIViewController {\n return presentedViewController\n }\n}\n\nextension Presenting {\n /**\n Present child coordinator.\n\n Automatically adds child and removes it upon interactive dismissal.\n */\n public func presentChild(\n _ child: some Presentable,\n animated: Bool,\n configuration: ModalPresentationConfiguration = ModalPresentationConfiguration(),\n completion: (() -> Void)? = nil\n ) {\n var configuration = configuration\n\n configuration.notifyInteractiveDismissal { [weak child] in\n guard let child else { return }\n\n child.modalConfiguration = nil\n child.removeFromParent()\n\n let observers = child.interactiveDismissalObservers\n child.interactiveDismissalObservers = []\n\n for observer in observers {\n observer(child)\n }\n }\n\n configuration.apply(to: child.presentedViewController)\n\n child.modalConfiguration = configuration\n\n addChild(child)\n\n topmostPresentationContext(from: presentationContext).present(\n child.presentedViewController,\n animated: animated,\n completion: completion\n )\n }\n\n private func topmostPresentationContext(from: UIViewController) -> UIViewController {\n var context = presentationContext\n\n while let childContext = context.presentedViewController, context != childContext {\n context = childContext\n }\n\n return context\n }\n}\n\nextension Presentable {\n /**\n Dismiss this coordinator.\n\n Automatically removes itself from parent.\n */\n public func dismiss(animated: Bool, completion: (@MainActor () -> Void)? = nil) {\n removeFromParent()\n\n presentedViewController.dismiss(animated: animated, completion: completion)\n }\n\n /**\n Add block based observer triggered if coordinator is dismissed via user interaction.\n */\n public func onInteractiveDismissal(_ handler: @escaping @Sendable (Coordinator) -> Void) {\n interactiveDismissalObservers.append(handler)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\Coordinator.swift | Coordinator.swift | Swift | 5,158 | 0.95 | 0.025907 | 0.267974 | vue-tools | 522 | 2025-03-14T17:09:36.729918 | BSD-3-Clause | false | 7e90f05199f5cefafbd9134d726dfad0 |
//\n// ModalPresentationConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 14/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/**\n A struct holding modal presentation configuration.\n */\n@MainActor\npublic struct ModalPresentationConfiguration {\n var preferredContentSize: CGSize?\n var modalPresentationStyle: UIModalPresentationStyle?\n var modalTransitionStyle: UIModalTransitionStyle?\n var isModalInPresentation: Bool?\n var transitioningDelegate: UIViewControllerTransitioningDelegate?\n var presentationControllerDelegate: UIAdaptivePresentationControllerDelegate?\n\n public init(\n preferredContentSize: CGSize? = nil,\n modalPresentationStyle: UIModalPresentationStyle? = nil,\n modalTransitionStyle: UIModalTransitionStyle? = nil,\n isModalInPresentation: Bool? = nil,\n transitioningDelegate: UIViewControllerTransitioningDelegate? = nil,\n presentationControllerDelegate: UIAdaptivePresentationControllerDelegate? = nil\n ) {\n self.preferredContentSize = preferredContentSize\n self.modalPresentationStyle = modalPresentationStyle\n self.modalTransitionStyle = modalTransitionStyle\n self.isModalInPresentation = isModalInPresentation\n self.transitioningDelegate = transitioningDelegate\n self.presentationControllerDelegate = presentationControllerDelegate\n }\n\n public func apply(to vc: UIViewController) {\n vc.transitioningDelegate = transitioningDelegate\n\n if let modalPresentationStyle {\n vc.modalPresentationStyle = modalPresentationStyle\n }\n\n if let modalTransitionStyle {\n vc.modalTransitionStyle = modalTransitionStyle\n }\n\n if let preferredContentSize {\n vc.preferredContentSize = preferredContentSize\n }\n\n if let isModalInPresentation {\n vc.isModalInPresentation = isModalInPresentation\n }\n\n vc.presentationController?.delegate = presentationControllerDelegate\n }\n\n /**\n Wraps `presentationControllerDelegate` into forwarding delegate that intercepts interactive\n dismissal and calls `dismissalHandler` while proxying all delegate calls to the former\n delegate.\n */\n public mutating func notifyInteractiveDismissal(_ dismissalHandler: @escaping () -> Void) {\n presentationControllerDelegate =\n PresentationControllerDismissalInterceptor(\n forwardingTarget: presentationControllerDelegate\n ) { _ in\n dismissalHandler()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\ModalPresentationConfiguration.swift | ModalPresentationConfiguration.swift | Swift | 2,607 | 0.95 | 0.067568 | 0.171875 | awesome-app | 28 | 2024-05-26T19:45:01.805877 | MIT | false | 60a179edb8d5eb8c1d788f81ae6bce18 |
//\n// PresentationControllerDismissalInterceptor.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/02/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/**\n Presentation controller delegate class that intercepts interactive dismissal and calls\n `dismissHandler` closure. Forwards all delegate calls to the `forwardingTarget`.\n */\nfinal class PresentationControllerDismissalInterceptor: NSObject,\n UIAdaptivePresentationControllerDelegate {\n private let dismissHandler: (UIPresentationController) -> Void\n nonisolated(unsafe) private let forwardingTarget: UIAdaptivePresentationControllerDelegate?\n private let protocolSelectors: [Selector]\n\n init(\n forwardingTarget: UIAdaptivePresentationControllerDelegate?,\n dismissHandler: @escaping (UIPresentationController) -> Void\n ) {\n self.forwardingTarget = forwardingTarget\n self.dismissHandler = dismissHandler\n\n protocolSelectors = getProtocolMethods(\n UIAdaptivePresentationControllerDelegate.self,\n isRequired: false,\n isInstanceMethod: true\n )\n }\n\n override func responds(to aSelector: Selector!) -> Bool {\n super.responds(to: aSelector) || (\n protocolSelectors.contains(aSelector) &&\n forwardingTarget?.responds(to: aSelector) ?? false\n )\n }\n\n override func forwardingTarget(for aSelector: Selector!) -> Any? {\n if protocolSelectors.contains(aSelector) {\n if super.responds(to: aSelector) {\n return nil\n } else if forwardingTarget?.responds(to: aSelector) ?? false {\n return forwardingTarget\n }\n }\n return super.forwardingTarget(for: aSelector)\n }\n\n func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {\n dismissHandler(presentationController)\n forwardingTarget?.presentationControllerDidDismiss?(presentationController)\n }\n}\n\nprivate func getProtocolMethods(\n _ protocolType: Protocol,\n isRequired: Bool,\n isInstanceMethod: Bool\n) -> [Selector] {\n var methodCount: UInt32 = 0\n let methodDescriptions = protocol_copyMethodDescriptionList(\n protocolType,\n isRequired,\n isInstanceMethod,\n &methodCount\n )\n\n defer { methodDescriptions.map { free($0) } }\n\n return (0 ..< methodCount).compactMap { index in\n methodDescriptions?[Int(index)].name\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\PresentationControllerDismissalInterceptor.swift | PresentationControllerDismissalInterceptor.swift | Swift | 2,487 | 0.95 | 0.090909 | 0.134328 | awesome-app | 284 | 2023-08-05T23:34:37.153323 | BSD-3-Clause | false | b9c6a79c915ddb87546ddeb02e959ca7 |
//\n// ApplicationRouter.swift\n// MullvadVPN\n//\n// Created by pronebird on 16/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport UIKit\n\n/**\n Main application router.\n */\n@MainActor\npublic final class ApplicationRouter<RouteType: AppRouteProtocol>: Sendable {\n nonisolated(unsafe) private let logger = Logger(label: "ApplicationRouter")\n\n private(set) var modalStack: [RouteType.RouteGroupType] = []\n private(set) var presentedRoutes: [RouteType.RouteGroupType: [PresentedRoute<RouteType>]] = [:]\n\n private var pendingRoutes = [PendingRoute<RouteType>]()\n private var isProcessingPendingRoutes = false\n\n private unowned let delegate: any ApplicationRouterDelegate<RouteType>\n\n /**\n Designated initializer.\n\n Delegate object is unonwed and the caller has to guarantee that the router does not outlive it.\n */\n public init(_ delegate: some ApplicationRouterDelegate<RouteType>) {\n self.delegate = delegate\n }\n\n /**\n Returns `true` is the given route group is currently being presented.\n */\n public func isPresenting(group: RouteType.RouteGroupType) -> Bool {\n modalStack.contains(group)\n }\n\n /**\n Returns `true` if is the given route is currently being presented.\n */\n public func isPresenting(route: RouteType) -> Bool {\n guard let presentedRoute = presentedRoutes[route.routeGroup] else {\n return false\n }\n return presentedRoute.contains(where: { $0.route == route })\n }\n\n /**\n Enqueue route for presetnation.\n */\n public func present(_ route: RouteType, animated: Bool = true, metadata: Any? = nil) {\n enqueue(PendingRoute(\n operation: .present(route),\n animated: animated,\n metadata: metadata\n ))\n }\n\n /**\n Enqueue dismissal of the route.\n */\n public func dismiss(_ route: RouteType, animated: Bool = true) {\n enqueue(PendingRoute(\n operation: .dismiss(.singleRoute(route)),\n animated: animated\n ))\n }\n\n /**\n Enqueue dismissal of a group of routes.\n */\n public func dismissAll(_ group: RouteType.RouteGroupType, animated: Bool = true) {\n enqueue(PendingRoute(\n operation: .dismiss(.group(group)),\n animated: animated\n ))\n }\n\n private func enqueue(_ pendingRoute: PendingRoute<RouteType>) {\n logger.debug("\(pendingRoute.operation).")\n\n pendingRoutes.append(pendingRoute)\n\n if !isProcessingPendingRoutes {\n processPendingRoutes()\n }\n }\n\n private func presentRoute(\n _ route: RouteType,\n animated: Bool,\n metadata: Any?,\n completion: @escaping @Sendable @MainActor (PendingPresentationResult) -> Void\n ) {\n /**\n Pass sub-route for routes supporting sub-navigation.\n */\n if route.supportsSubNavigation, modalStack.contains(route.routeGroup),\n var presentedRoute = presentedRoutes[route.routeGroup]?.first {\n let context = RouteSubnavigationContext(\n presentedRoute: presentedRoute,\n route: route,\n isAnimated: animated\n )\n\n presentedRoute.route = route\n presentedRoutes[route.routeGroup] = [presentedRoute]\n\n delegate.applicationRouter(self, handleSubNavigationWithContext: context) {\n completion(.success)\n }\n\n return\n }\n\n /**\n Drop duplicate exclusive routes.\n */\n if route.isExclusive, modalStack.contains(route.routeGroup) {\n completion(.drop)\n return\n }\n\n /**\n Drop if the last presented route within the group is the same.\n */\n if !route.isExclusive, presentedRoutes[route.routeGroup]?.last?.route == route {\n completion(.drop)\n return\n }\n\n /**\n Check if route can be presented above the last route in the modal stack.\n */\n if let\n // Get current modal route.\n lastRouteGroup = modalStack.last,\n // Check if incoming route is modal.\n route.routeGroup.isModal,\n // Check whether incoming route can be presented on top of current.\n (lastRouteGroup > route.routeGroup) ||\n // OR, check whether incoming exclusive route can be presented on top of current.\n (lastRouteGroup >= route.routeGroup && route.isExclusive) {\n completion(.blockedByModalContext)\n return\n }\n\n /**\n Consult with delegate whether the route should still be presented.\n */\n if delegate.applicationRouter(self, shouldPresent: route) {\n let context = RoutePresentationContext(route: route, isAnimated: animated, metadata: metadata)\n\n delegate.applicationRouter(self, presentWithContext: context, animated: animated) { coordinator in\n /// Synchronize router when modal controllers are removed by swipe.\n /// The delegate (`ApplicationCoordinator`) is `@MainActor` by virtue of being a `Coordinator`\n MainActor.assumeIsolated {\n if let presentable = coordinator as? Presentable {\n presentable.onInteractiveDismissal { [weak self] coordinator in\n MainActor.assumeIsolated {\n self?.handleInteractiveDismissal(route: route, coordinator: coordinator)\n }\n }\n }\n\n self.addPresentedRoute(PresentedRoute(route: route, coordinator: coordinator))\n\n completion(.success)\n }\n }\n } else {\n completion(.drop)\n }\n }\n\n private func dismissGroup(\n _ dismissGroup: RouteType.RouteGroupType,\n animated: Bool,\n completion: @escaping @Sendable (PendingDismissalResult) -> Void\n ) {\n /**\n Check if routes corresponding to the group requested for dismissal are present.\n */\n guard modalStack.contains(dismissGroup) else {\n completion(.drop)\n return\n }\n\n /**\n Check if the group can be dismissed and it's not blocked by another group presented above.\n */\n if modalStack.last != dismissGroup, dismissGroup.isModal {\n completion(.blockedByModalAbove)\n return\n }\n\n let dismissedRoutes = presentedRoutes[dismissGroup] ?? []\n assert(!dismissedRoutes.isEmpty)\n\n let context = RouteDismissalContext(\n dismissedRoutes: dismissedRoutes,\n isClosing: true,\n isAnimated: animated\n )\n\n /**\n Consult with delegate whether the route should still be dismissed.\n */\n guard delegate.applicationRouter(self, shouldDismissWithContext: context) else {\n completion(.drop)\n return\n }\n\n presentedRoutes.removeValue(forKey: dismissGroup)\n modalStack.removeAll { $0 == dismissGroup }\n\n delegate.applicationRouter(self, dismissWithContext: context) {\n completion(.success)\n }\n }\n\n private func dismissRoute(\n _ dismissRoute: RouteType,\n animated: Bool,\n completion: @escaping @Sendable (PendingDismissalResult) -> Void\n ) {\n var routes = presentedRoutes[dismissRoute.routeGroup] ?? []\n\n // Find the index of route to pop.\n guard let index = routes.lastIndex(where: { $0.route == dismissRoute }) else {\n completion(.drop)\n return\n }\n\n // Check if dismissing the last route in horizontal navigation group.\n let isLastRoute = routes.count == 1\n\n // Check if the route can be dismissed and there is no other modal above.\n if let lastModalGroup = modalStack.last,\n lastModalGroup != dismissRoute.routeGroup,\n dismissRoute.routeGroup.isModal,\n isLastRoute {\n completion(.blockedByModalAbove)\n return\n }\n\n let context = RouteDismissalContext(\n dismissedRoutes: [routes[index]],\n isClosing: isLastRoute,\n isAnimated: animated\n )\n\n /**\n Consult with delegate whether the route should still be dismissed.\n */\n guard delegate.applicationRouter(self, shouldDismissWithContext: context) else {\n completion(.drop)\n return\n }\n\n if isLastRoute {\n presentedRoutes.removeValue(forKey: dismissRoute.routeGroup)\n modalStack.removeAll { $0 == dismissRoute.routeGroup }\n } else {\n routes.remove(at: index)\n presentedRoutes[dismissRoute.routeGroup] = routes\n }\n\n delegate.applicationRouter(self, dismissWithContext: context) {\n completion(.success)\n }\n }\n\n private func processPendingRoutes(skipRouteGroups: Set<RouteType.RouteGroupType> = []) {\n isProcessingPendingRoutes = true\n\n let pendingRoute = pendingRoutes.first { pendingRoute in\n !skipRouteGroups.contains(pendingRoute.operation.routeGroup)\n }\n\n guard let pendingRoute else {\n isProcessingPendingRoutes = false\n return\n }\n\n switch pendingRoute.operation {\n case let .present(route):\n presentRoute(route, animated: pendingRoute.animated, metadata: pendingRoute.metadata) { result in\n switch result {\n case .success, .drop:\n self.finishPendingRoute(pendingRoute)\n\n case .blockedByModalContext:\n /**\n Present next route if this one is not ready to be presented.\n */\n self.processPendingRoutes(\n skipRouteGroups: skipRouteGroups.union([route.routeGroup])\n )\n }\n }\n\n case let .dismiss(dismissMatch):\n handleDismissal(dismissMatch, animated: pendingRoute.animated) { result in\n MainActor.assumeIsolated {\n switch result {\n case .success, .drop:\n self.finishPendingRoute(pendingRoute)\n\n case .blockedByModalAbove:\n /**\n If router cannot dismiss modal because there is one above,\n try walking down the queue and see if there is a dismissal request that could\n resolve that.\n */\n self.processPendingRoutes(\n skipRouteGroups: skipRouteGroups.union([dismissMatch.routeGroup])\n )\n }\n }\n }\n }\n }\n\n private func handleDismissal(\n _ dismissMatch: DismissMatch<RouteType>,\n animated: Bool,\n completion: @escaping @Sendable (PendingDismissalResult) -> Void\n ) {\n switch dismissMatch {\n case let .singleRoute(route):\n dismissRoute(route, animated: animated, completion: completion)\n\n case let .group(group):\n dismissGroup(group, animated: animated, completion: completion)\n }\n }\n\n private func finishPendingRoute(_ pendingRoute: PendingRoute<RouteType>) {\n if let index = pendingRoutes.firstIndex(of: pendingRoute) {\n pendingRoutes.remove(at: index)\n }\n\n processPendingRoutes()\n }\n\n private func handleInteractiveDismissal(route: RouteType, coordinator: Coordinator) {\n var routes = presentedRoutes[route.routeGroup] ?? []\n\n routes.removeAll { presentedRoute in\n presentedRoute.coordinator == coordinator\n }\n\n if routes.isEmpty {\n presentedRoutes.removeValue(forKey: route.routeGroup)\n modalStack.removeAll { $0 == route.routeGroup }\n } else {\n presentedRoutes[route.routeGroup] = routes\n }\n\n if !isProcessingPendingRoutes {\n processPendingRoutes()\n }\n }\n\n private func addPresentedRoute(_ presented: PresentedRoute<RouteType>) {\n let group = presented.route.routeGroup\n var routes = presentedRoutes[group] ?? []\n\n if presented.route.isExclusive {\n routes = [presented]\n } else {\n routes.append(presented)\n }\n\n presentedRoutes[group] = routes\n\n if !modalStack.contains(group) {\n if group.isModal {\n modalStack.append(group)\n } else {\n modalStack.insert(group, at: 0)\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\Router\ApplicationRouter.swift | ApplicationRouter.swift | Swift | 12,875 | 0.95 | 0.089286 | 0.156627 | react-lib | 990 | 2024-02-12T14:57:13.912503 | GPL-3.0 | false | 23cf7255fbf0982c7761924f195888f0 |
//\n// ApplicationRouterDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/**\n Application router delegate\n */\npublic protocol ApplicationRouterDelegate<RouteType>: AnyObject, Sendable {\n associatedtype RouteType: AppRouteProtocol\n\n /**\n Delegate should present the route and pass corresponding `Coordinator` upon completion.\n */\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n presentWithContext context: RoutePresentationContext<RouteType>,\n animated: Bool,\n completion: @escaping @Sendable (Coordinator) -> Void\n )\n\n /**\n Delegate should dismiss the route.\n */\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n dismissWithContext context: RouteDismissalContext<RouteType>,\n completion: @escaping @Sendable () -> Void\n )\n\n /**\n Delegate may reconsider if route presentation is still needed.\n\n Return `true` to proceed with presenation, otherwise `false` to prevent it.\n */\n func applicationRouter(_ router: ApplicationRouter<RouteType>, shouldPresent route: RouteType) -> Bool\n\n /**\n Delegate may reconsider if route dismissal should be done.\n\n Return `true` to proceed with dismissal, otherwise `false` to prevent it.\n */\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n shouldDismissWithContext context: RouteDismissalContext<RouteType>\n ) -> Bool\n\n /**\n Delegate should handle sub-navigation for routes supporting it then call completion to tell\n router when it's done.\n */\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n handleSubNavigationWithContext context: RouteSubnavigationContext<RouteType>,\n completion: @escaping @Sendable @MainActor () -> Void\n )\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\Router\ApplicationRouterDelegate.swift | ApplicationRouterDelegate.swift | Swift | 1,924 | 0.95 | 0.048387 | 0.358491 | node-utils | 914 | 2024-02-21T15:18:53.003702 | MIT | false | a4d7663217033c069b92755a511e38e9 |
//\n// ApplicationRouterTypes.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/**\n Struct describing a routing request for presentation or dismissal.\n */\nstruct PendingRoute<RouteType: AppRouteProtocol>: Sendable {\n var operation: RouteOperation<RouteType>\n var animated: Bool\n nonisolated(unsafe) var metadata: Any?\n}\n\nextension PendingRoute: Equatable {\n static func == (lhs: PendingRoute<RouteType>, rhs: PendingRoute<RouteType>) -> Bool {\n lhs.operation == rhs.operation\n }\n}\n\n/**\n Enum type describing an attempt to fulfill the route presentation request.\n **/\nenum PendingPresentationResult: Sendable {\n /**\n Successfully presented the route.\n */\n case success\n\n /**\n The request to present this route should be dropped.\n */\n case drop\n\n /**\n The request to present this route cannot be fulfilled because the modal context does not allow\n for that.\n\n For example, on iPad, primary context cannot be presented above settings, because it enables\n access to settings by making the settings cog accessible via custom presentation controller.\n In such case the router will attempt to fulfill other requests in hope that perhaps settings\n can be dismissed first before getting back to that request.\n */\n case blockedByModalContext\n}\n\n/**\n Enum type describing an attempt to fulfill the route dismissal request.\n */\nenum PendingDismissalResult: Sendable {\n /**\n Successfully dismissed the route.\n */\n case success\n\n /**\n The request to present this route should be dropped.\n */\n case drop\n\n /**\n The route cannot be dismissed immediately because it's blocked by another modal presented\n above.\n\n The router will attempt to fulfill other requests first in hope to unblock the route by\n dismissing the modal above before getting back to that request.\n */\n case blockedByModalAbove\n}\n\n/**\n Enum describing operation over the route.\n */\nenum RouteOperation<RouteType: AppRouteProtocol>: Equatable, CustomDebugStringConvertible, Sendable {\n /**\n Present route.\n */\n case present(RouteType)\n\n /**\n Dismiss route.\n */\n case dismiss(DismissMatch<RouteType>)\n\n /**\n Returns a group of affected routes.\n */\n var routeGroup: RouteType.RouteGroupType {\n switch self {\n case let .present(route):\n return route.routeGroup\n case let .dismiss(dismissMatch):\n return dismissMatch.routeGroup\n }\n }\n\n var debugDescription: String {\n let action: String\n switch self {\n case let .present(routeType):\n action = "Presenting .\(routeType)"\n case let .dismiss(match):\n action = "Dismissing .\(match)"\n }\n return "\(action)"\n }\n}\n\n/**\n Enum type describing a single route or a group of routes requested to be dismissed.\n */\nenum DismissMatch<RouteType: AppRouteProtocol>: Equatable, CustomDebugStringConvertible, Sendable {\n case group(RouteType.RouteGroupType)\n case singleRoute(RouteType)\n\n /**\n Returns a group of affected routes.\n */\n var routeGroup: RouteType.RouteGroupType {\n switch self {\n case let .group(group):\n return group\n case let .singleRoute(route):\n return route.routeGroup\n }\n }\n\n var debugDescription: String {\n switch self {\n case let .group(group):\n return "\(group)"\n case let .singleRoute(route):\n return "\(route)"\n }\n }\n}\n\n/**\n Struct describing presented route.\n */\npublic struct PresentedRoute<RouteType: AppRouteProtocol>: Equatable, Sendable {\n public var route: RouteType\n public var coordinator: Coordinator\n}\n\n/**\n Struct holding information used by delegate to perform dismissal of the route(s) in subject.\n */\npublic struct RouteDismissalContext<RouteType: AppRouteProtocol> {\n /**\n Specific routes that are being dismissed.\n */\n public var dismissedRoutes: [PresentedRoute<RouteType>]\n\n /**\n Whether the entire group is being dismissed.\n */\n public var isClosing: Bool\n\n /**\n Whether transition is animated.\n */\n public var isAnimated: Bool\n}\n\n/**\n Struct holding information used by delegate to perform presentation of a specific route.\n */\npublic struct RoutePresentationContext<RouteType: AppRouteProtocol>: Sendable {\n /**\n Route that's being presented.\n */\n public var route: RouteType\n\n /**\n Whether transition is animated.\n */\n public var isAnimated: Bool\n\n /**\n Metadata associated with the route.\n */\n nonisolated(unsafe) public var metadata: Any?\n}\n\n/**\n Struct holding information used by delegate to perform sub-navigation of the route in subject.\n */\npublic struct RouteSubnavigationContext<RouteType: AppRouteProtocol>: Sendable {\n public var presentedRoute: PresentedRoute<RouteType>\n public var route: RouteType\n public var isAnimated: Bool\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\Router\ApplicationRouterTypes.swift | ApplicationRouterTypes.swift | Swift | 5,097 | 0.95 | 0.030303 | 0.331395 | awesome-app | 659 | 2024-06-11T11:03:28.527543 | MIT | false | da299380a608afd8996558bb484b9c2d |
//\n// AppRouteProtocol.swift\n// MullvadVPN\n//\n// Created by pronebird on 17/08/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/**\n Formal protocol describing a group of routes.\n */\npublic protocol AppRouteGroupProtocol: Comparable, Equatable, Hashable, Sendable {\n /**\n Returns `true` if group is presented modally, otherwise `false` if group is a part of root view\n controller.\n */\n var isModal: Bool { get }\n\n /**\n Defines a modal level that's used for restricting modal presentation.\n\n A group with higher modal level can be presented above a group with lower level but not the other way around. For example, if a modal group is represented by\n `UIAlertController`, it should have the highest level (i.e `Int.max`) to prevent other modals from being presented above it, however it enables alert\n controller to be presented above any other modal.\n */\n var modalLevel: Int { get }\n}\n\n/**\n Default implementation of `Comparable` for `AppRouteGroupProtocol` which compares `modalLevel` of both sides.\n */\nextension AppRouteGroupProtocol {\n public static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.modalLevel < rhs.modalLevel\n }\n\n public static func <= (lhs: Self, rhs: Self) -> Bool {\n lhs.modalLevel <= rhs.modalLevel\n }\n}\n\n/**\n Formal protocol describing a single route.\n */\npublic protocol AppRouteProtocol: Equatable, Hashable, Sendable {\n associatedtype RouteGroupType: AppRouteGroupProtocol\n\n /**\n Returns `true` when only one route of a kind can be displayed.\n */\n var isExclusive: Bool { get }\n\n /**\n Returns `true` if the route supports sub-navigation.\n */\n var supportsSubNavigation: Bool { get }\n\n /**\n Navigation group to which the route belongs to.\n */\n var routeGroup: RouteGroupType { get }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Routing\Router\AppRouteProtocol.swift | AppRouteProtocol.swift | Swift | 1,868 | 0.95 | 0.09375 | 0.425926 | awesome-app | 768 | 2023-10-03T09:15:36.907156 | GPL-3.0 | false | 969db1fc2a2e1c6535a1f918c6ced031 |
//\n// RouterBlockDelegate.swift\n// RoutingTests\n//\n// Created by Jon Petersson on 2023-08-22.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Routing\n\nfinal class RouterBlockDelegate<RouteType: AppRouteProtocol>: ApplicationRouterDelegate, @unchecked Sendable {\n var handleRoute: ((RoutePresentationContext<RouteType>, Bool, (Coordinator) -> Void) -> Void)?\n var handleDismiss: ((RouteDismissalContext<RouteType>, () -> Void) -> Void)?\n var shouldPresent: ((RouteType) -> Bool)?\n var shouldDismiss: ((RouteDismissalContext<RouteType>) -> Bool)?\n var handleSubnavigation: (@Sendable @MainActor (RouteSubnavigationContext<RouteType>, () -> Void) -> Void)?\n\n nonisolated func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n presentWithContext context: RoutePresentationContext<RouteType>,\n animated: Bool,\n completion: @escaping @Sendable (Coordinator) -> Void\n ) {\n MainActor.assumeIsolated {\n handleRoute?(context, animated, completion) ?? completion(Coordinator())\n }\n }\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n dismissWithContext context: RouteDismissalContext<RouteType>,\n completion: @escaping @Sendable () -> Void\n ) {\n handleDismiss?(context, completion) ?? completion()\n }\n\n func applicationRouter(_ router: ApplicationRouter<RouteType>, shouldPresent route: RouteType) -> Bool {\n return shouldPresent?(route) ?? true\n }\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n shouldDismissWithContext context: RouteDismissalContext<RouteType>\n ) -> Bool {\n return shouldDismiss?(context) ?? true\n }\n\n func applicationRouter(\n _ router: ApplicationRouter<RouteType>,\n handleSubNavigationWithContext context: RouteSubnavigationContext<RouteType>,\n completion: @escaping @Sendable @MainActor () -> Void\n ) {\n MainActor.assumeIsolated {\n handleSubnavigation?(context, completion) ?? completion()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\RoutingTests\RouterBlockDelegate.swift | RouterBlockDelegate.swift | Swift | 2,114 | 0.95 | 0.017241 | 0.137255 | vue-tools | 293 | 2025-01-21T03:21:47.826744 | Apache-2.0 | true | ab02a6cd614b662971fb86105e3c852e |
//\n// ApplicationConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 05/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\nenum ApplicationConfiguration {\n static var hostName: String {\n // swiftlint:disable:next force_cast\n Bundle.main.object(forInfoDictionaryKey: "HostName") as! String\n }\n\n /// Shared container security group identifier.\n static var securityGroupIdentifier: String {\n // swiftlint:disable:next force_cast\n Bundle.main.object(forInfoDictionaryKey: "ApplicationSecurityGroupIdentifier") as! String\n }\n\n /// Container URL for security group.\n static var containerURL: URL {\n FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: securityGroupIdentifier)!\n }\n\n /// Returns URL for new log file associated with application target and located within the specified container.\n static func newLogFileURL(for target: ApplicationTarget, in containerURL: URL) -> URL {\n containerURL.appendingPathComponent(\n "\(target.bundleIdentifier)_\(Date().logFileFormatted).log",\n isDirectory: false\n )\n }\n\n /// Returns URLs for log files associated with application target and located within the specified container.\n static func logFileURLs(for target: ApplicationTarget, in containerURL: URL) -> [URL] {\n let fileManager = FileManager.default\n let filePathsInDirectory = try? fileManager.contentsOfDirectory(atPath: containerURL.relativePath)\n\n let filteredFilePaths: [URL] = filePathsInDirectory?.compactMap { path in\n let pathIsLog = path.split(separator: ".").last == "log"\n // Pattern should be "<Target Bundle ID>_", eg. "net.mullvad.MullvadVPN_".\n let pathBelongsToTarget = path.contains("\(target.bundleIdentifier)_")\n\n return pathIsLog && pathBelongsToTarget ? containerURL.appendingPathComponent(path) : nil\n } ?? []\n\n let sortedFilePaths = try? filteredFilePaths.sorted { path1, path2 in\n let path1Attributes = try fileManager.attributesOfItem(atPath: path1.relativePath)\n let date1 = (path1Attributes[.creationDate] as? Date) ?? Date.distantPast\n\n let path2Attributes = try fileManager.attributesOfItem(atPath: path2.relativePath)\n let date2 = (path2Attributes[.creationDate] as? Date) ?? Date.distantPast\n\n return date1 > date2\n }\n\n return sortedFilePaths ?? []\n }\n\n // Maximum file size for writing and reading logs.\n static let logMaximumFileSize: UInt64 = 131_072 // 128 kB.\n\n /// Privacy policy URL.\n static let privacyPolicyURL = URL(string: "https://\(Self.hostName)/help/privacy-policy/")!\n\n /// Make a start regarding policy URL.\n static let privacyGuidesURL = URL(string: "https://\(Self.hostName)/help/first-steps-towards-online-privacy/")!\n\n /// FAQ & Guides URL.\n static let faqAndGuidesURL = URL(string: "https://\(Self.hostName)/help/tag/mullvad-app/")!\n\n /// Maximum number of devices per account.\n static let maxAllowedDevices = 5\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Shared\ApplicationConfiguration.swift | ApplicationConfiguration.swift | Swift | 3,143 | 0.95 | 0.12987 | 0.316667 | python-kit | 153 | 2024-06-06T08:47:52.977713 | Apache-2.0 | false | 0dd72b5d3767cdaee1a53ecaf733c259 |
//\n// ApplicationTarget.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum ApplicationTarget: CaseIterable {\n case mainApp, packetTunnel\n\n /// Returns target bundle identifier.\n var bundleIdentifier: String {\n // "MainApplicationIdentifier" does not exist if running tests\n let mainBundleIdentifier = Bundle.main\n .object(forInfoDictionaryKey: "MainApplicationIdentifier") as? String ?? "tests"\n switch self {\n case .mainApp:\n return mainBundleIdentifier\n case .packetTunnel:\n return "\(mainBundleIdentifier).PacketTunnel"\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Shared\ApplicationTarget.swift | ApplicationTarget.swift | Swift | 719 | 0.95 | 0.076923 | 0.391304 | vue-tools | 996 | 2024-12-18T01:43:14.959402 | Apache-2.0 | false | 74d83e935e84b133d93e4e0452b94d68 |
//\n// LaunchArguments.swift\n// MullvadTypes\n//\n// Created by Mojgan on 2024-05-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\npublic protocol Taggable {\n static var tag: String { get }\n}\n\npublic extension Taggable {\n static var tag: String {\n String(describing: self)\n }\n}\n\npublic enum MullvadExecutableTarget: Codable {\n case uiTests, screenshots, main\n}\n\n// This arguments are picked up in AppDelegate.\npublic struct LaunchArguments: Codable, Taggable {\n // Defines which target is running\n public var target: MullvadExecutableTarget = .main\n\n // Disable animations to speed up tests.\n public var areAnimationsDisabled = false\n}\n\npublic extension ProcessInfo {\n func decode<T: Taggable & Decodable>(_: T.Type) throws -> T {\n guard let environment = environment[T.tag] else {\n throw DecodingError.valueNotFound(\n T.self,\n DecodingError.Context(codingPath: [], debugDescription: "\(T.self) not found in environment")\n )\n }\n return try T.decode(from: environment)\n }\n}\n\nextension Encodable {\n public func toJSON(_ encoder: JSONEncoder = JSONEncoder()) throws -> String {\n let data = try encoder.encode(self)\n guard let result = String(bytes: data, encoding: .utf8) else {\n throw EncodingError.invalidValue(\n self,\n EncodingError.Context(codingPath: [], debugDescription: "Could not encode self to a utf-8 string")\n )\n }\n return result\n }\n}\n\nprivate extension Decodable {\n static func decode(from json: String) throws -> Self {\n guard let data = json.data(using: .utf8) else {\n throw DecodingError.valueNotFound(\n Self.self,\n DecodingError.Context(\n codingPath: [],\n debugDescription: "Could not convert \(json) into UTF-8 Data"\n )\n )\n }\n\n return try JSONDecoder().decode(self, from: data)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\Shared\LaunchArguments.swift | LaunchArguments.swift | Swift | 2,063 | 0.95 | 0.041096 | 0.15873 | react-lib | 570 | 2023-10-25T15:31:11.513593 | BSD-3-Clause | false | 0ee6b4e116919552e1991ce921ad09fb |
//\n// TCPListener.swift\n// TunnelObfuscationTests\n//\n// Created by pronebird on 27/06/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Network\n\n/// Minimal implementation of a TCP listener.\nclass TCPOneShotListener {\n private let dispatchQueue = DispatchQueue(label: "TCPListener")\n private let listener: NWListener\n\n /// A stream of new TCP connections.\n /// The caller may iterate over this stream to accept new TCP connections.\n ///\n /// `TCPConnection` objects are returned unopen, so the caller has to call `TCPConnection.start()` to accept the\n /// connection before initiating the data exchange.\n let newConnections: AsyncStream<TCPConnection>\n\n init() throws {\n let listener = try NWListener(using: .tcp)\n\n newConnections = AsyncStream { continuation in\n listener.newConnectionHandler = { nwConnection in\n continuation.yield(TCPConnection(nwConnection: nwConnection))\n }\n continuation.onTermination = { _ in\n listener.newConnectionHandler = nil\n }\n }\n\n self.listener = listener\n }\n\n deinit {\n cancel()\n }\n\n /// Local TCP port bound by listener on which it accepts new connections.\n var listenPort: UInt16 {\n return listener.port?.rawValue ?? 0\n }\n\n /// Start listening on a randomly assigned port which should be available via `listenPort` once this call returns\n /// control back to the caller.\n ///\n /// Waits for the underlying connection to become ready before returning control to the caller, otherwise throws an\n /// error if connection state indicates as such.\n func start() async throws {\n try await withCheckedThrowingContinuation { continuation in\n listener.stateUpdateHandler = { state in\n switch state {\n case .ready:\n continuation.resume(returning: ())\n case let .failed(error):\n continuation.resume(throwing: error)\n case .cancelled:\n continuation.resume(throwing: CancellationError())\n default:\n return\n }\n // Reset state update handler after resuming continuation.\n self.listener.stateUpdateHandler = nil\n }\n listener.start(queue: dispatchQueue)\n }\n }\n\n func cancel() {\n listener.cancel()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\TunnelObfuscationTests\TCPListener.swift | TCPListener.swift | Swift | 2,486 | 0.95 | 0.08 | 0.307692 | node-utils | 11 | 2025-02-23T01:15:29.281557 | MIT | true | de44906599feefc23f7087bedc37fa35 |
// swift-tools-version:5.10\nimport PackageDescription\n\nlet package = Package(\n name: "PostgresClientKitExample",\n dependencies: [\n .package(\n url: "https://github.com/codewinsdotcom/PostgresClientKit.git",\n revision: "v1.5.0"\n )\n ],\n targets: [\n .executableTarget(\n name: "PostgresClientKitExample",\n dependencies: [ "PostgresClientKit" ])\n ]\n)\n | dataset_sample\swift\neondatabase_neon\test_runner\pg_clients\PostgresClientKitExample\Package.swift | Package.swift | Swift | 425 | 0.95 | 0 | 0.0625 | python-kit | 615 | 2023-11-17T22:21:11.486704 | GPL-3.0 | true | 3accfae4c7641af46748971e51576910 |
import Foundation\n\nimport PostgresClientKit\n\ndo {\n let env = ProcessInfo.processInfo.environment\n\n var configuration = PostgresClientKit.ConnectionConfiguration()\n let host = env["NEON_HOST"] ?? ""\n configuration.host = host\n configuration.port = 5432\n configuration.database = env["NEON_DATABASE"] ?? ""\n configuration.user = env["NEON_USER"] ?? ""\n\n // PostgresClientKit uses Kitura/BlueSSLService which doesn't support SNI\n // PostgresClientKit doesn't support setting connection options, so we use "Workaround D"\n // See https://neon.tech/sni\n let password = env["NEON_PASSWORD"] ?? ""\n let endpoint_id = host.split(separator: ".")[0]\n let workaroundD = "project=\(endpoint_id);\(password)"\n configuration.credential = .cleartextPassword(password: workaroundD)\n\n let connection = try PostgresClientKit.Connection(configuration: configuration)\n defer { connection.close() }\n\n let text = "SELECT 1;"\n let statement = try connection.prepareStatement(text: text)\n defer { statement.close() }\n\n let cursor = try statement.execute(parameterValues: [ ])\n defer { cursor.close() }\n\n for row in cursor {\n let columns = try row.get().columns\n print(columns[0])\n }\n} catch {\n print(error)\n}\n | dataset_sample\swift\neondatabase_neon\test_runner\pg_clients\PostgresClientKitExample\Sources\PostgresClientKitExample\main.swift | main.swift | Swift | 1,270 | 0.95 | 0.153846 | 0.096774 | awesome-app | 55 | 2024-02-15T23:51:10.271743 | BSD-3-Clause | true | a9a45b91afddf491b417c11ea7f13000 |
// swift-tools-version:5.10\nimport PackageDescription\n\nlet package = Package(\n name: "PostgresNIOExample",\n dependencies: [\n .package(url: "https://github.com/vapor/postgres-nio.git", from: "1.21.5")\n ],\n targets: [\n .executableTarget(\n name: "PostgresNIOExample",\n dependencies: [\n .product(name: "PostgresNIO", package: "postgres-nio"),\n ]\n )\n ]\n)\n | dataset_sample\swift\neondatabase_neon\test_runner\pg_clients\PostgresNIOExample\Package.swift | Package.swift | Swift | 427 | 0.95 | 0 | 0.0625 | awesome-app | 331 | 2024-04-22T00:11:23.810359 | GPL-3.0 | true | 2a51ccf3893079c21e156c310daece90 |
import Foundation\n\nimport PostgresNIO\nimport NIOPosix\nimport Logging\n\nawait Task {\n do {\n let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)\n let logger = Logger(label: "postgres-logger")\n\n let env = ProcessInfo.processInfo.environment\n\n let sslContext = try! NIOSSLContext(configuration: .makeClientConfiguration())\n\n let config = PostgresConnection.Configuration(\n host: env["NEON_HOST"] ?? "",\n port: 5432,\n username: env["NEON_USER"] ?? "",\n password: env["NEON_PASSWORD"] ?? "",\n database: env["NEON_DATABASE"] ?? "",\n tls: .require(sslContext)\n )\n\n let connection = try await PostgresConnection.connect(\n on: eventLoopGroup.next(),\n configuration: config,\n id: 1,\n logger: logger\n )\n\n let rows = try await connection.query("SELECT 1 as col", logger: logger)\n for try await (n) in rows.decode((Int).self, context: .default) {\n print(n)\n }\n\n // Close your connection once done\n try await connection.close()\n\n // Shutdown the EventLoopGroup, once all connections are closed.\n try await eventLoopGroup.shutdownGracefully()\n } catch {\n print(error)\n }\n}.value\n | dataset_sample\swift\neondatabase_neon\test_runner\pg_clients\PostgresNIOExample\Sources\PostgresNIOExample\main.swift | main.swift | Swift | 1,187 | 0.95 | 0.177778 | 0.055556 | react-lib | 221 | 2024-02-03T09:59:11.305307 | MIT | true | 938da9f883315e611c6eaa41e9217177 |
// swift-tools-version:4.0\n// The swift-tools-version declares the minimum version of Swift required to build this package.\nimport PackageDescription\n\nlet package = Package(\n name: "Fastlane",\n products: [\n .library(name: "Fastlane", targets: ["Fastlane"])\n ],\n dependencies: [\n .package(url: "https://github.com/kareman/SwiftShell", .upToNextMajor(from: "5.1.0"))\n ],\n targets: [\n .target(\n name: "Fastlane",\n dependencies: ["SwiftShell"],\n path: "./fastlane/swift",\n exclude: ["Actions.swift", "Plugins.swift", "main.swift", "formatting", "FastlaneSwiftRunner"]\n ),\n ],\n swiftLanguageVersions: [4]\n)\n \n | dataset_sample\swift\ruby\Package.swift | Package.swift | Swift | 700 | 0.95 | 0 | 0.095238 | awesome-app | 161 | 2024-11-03T12:10:19.496032 | MIT | false | 120f24c6c7882d303a82c59a7f25e3e3 |
import UIKit\nimport Flutter\n\n@main\n@objc class AppDelegate: FlutterAppDelegate {\n override func application(\n _ application: UIApplication,\n didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?\n ) -> Bool {\n GeneratedPluginRegistrant.register(with: self)\n dummyMethodToEnforceBundling();\n return super.application(application, didFinishLaunchingWithOptions: launchOptions)\n }\n \n public func dummyMethodToEnforceBundling() {\n dummy_method_to_enforce_bundling();\n session_get_rgba(nil, 0);\n }\n}\n | dataset_sample\swift\rustdesk_rustdesk\flutter\ios\Runner\AppDelegate.swift | AppDelegate.swift | Swift | 555 | 0.85 | 0.052632 | 0 | awesome-app | 960 | 2023-11-28T18:32:02.707687 | GPL-3.0 | false | f462a68bcdbf718cb3e5a216faec83b9 |
import Cocoa\nimport FlutterMacOS\n\n@main\nclass AppDelegate: FlutterAppDelegate {\n var launched = false;\n override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {\n dummy_method_to_enforce_bundling()\n // https://github.com/leanflutter/window_manager/issues/214\n return false\n }\n \n override func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {\n if (launched) {\n handle_applicationShouldOpenUntitledFile();\n }\n return true\n }\n \n override func applicationDidFinishLaunching(_ aNotification: Notification) {\n launched = true;\n NSApplication.shared.activate(ignoringOtherApps: true);\n }\n}\n | dataset_sample\swift\rustdesk_rustdesk\flutter\macos\Runner\AppDelegate.swift | AppDelegate.swift | Swift | 722 | 0.95 | 0.083333 | 0.047619 | awesome-app | 457 | 2024-08-31T11:26:28.368447 | BSD-3-Clause | false | 4b74ac2ac1e601c4efd48f7148fa6305 |
import Cocoa\nimport AVFoundation\nimport FlutterMacOS\nimport desktop_multi_window\n// import bitsdojo_window_macos\n\nimport desktop_drop\nimport device_info_plus\nimport flutter_custom_cursor\nimport package_info_plus\nimport path_provider_foundation\nimport screen_retriever\nimport sqflite\n// import tray_manager\nimport uni_links_desktop\nimport url_launcher_macos\nimport wakelock_plus\nimport window_manager\nimport window_size\nimport texture_rgba_renderer\n\nclass MainFlutterWindow: NSWindow {\n override func awakeFromNib() {\n rustdesk_core_main();\n let flutterViewController = FlutterViewController.init()\n let windowFrame = self.frame\n self.contentViewController = flutterViewController\n self.setFrame(windowFrame, display: true)\n // register self method handler\n let registrar = flutterViewController.registrar(forPlugin: "RustDeskPlugin")\n setMethodHandler(registrar: registrar)\n \n RegisterGeneratedPlugins(registry: flutterViewController)\n\n FlutterMultiWindowPlugin.setOnWindowCreatedCallback { controller in\n // Register the plugin which you want access from other isolate.\n // DesktopLifecyclePlugin.register(with: controller.registrar(forPlugin: "DesktopLifecyclePlugin"))\n // Note: copy below from above RegisterGeneratedPlugins\n self.setMethodHandler(registrar: controller.registrar(forPlugin: "RustDeskPlugin"))\n DesktopDropPlugin.register(with: controller.registrar(forPlugin: "DesktopDropPlugin"))\n DeviceInfoPlusMacosPlugin.register(with: controller.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))\n FlutterCustomCursorPlugin.register(with: controller.registrar(forPlugin: "FlutterCustomCursorPlugin"))\n FPPPackageInfoPlusPlugin.register(with: controller.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))\n PathProviderPlugin.register(with: controller.registrar(forPlugin: "PathProviderPlugin"))\n SqflitePlugin.register(with: controller.registrar(forPlugin: "SqflitePlugin"))\n // TrayManagerPlugin.register(with: controller.registrar(forPlugin: "TrayManagerPlugin"))\n UniLinksDesktopPlugin.register(with: controller.registrar(forPlugin: "UniLinksDesktopPlugin"))\n UrlLauncherPlugin.register(with: controller.registrar(forPlugin: "UrlLauncherPlugin"))\n WakelockPlusMacosPlugin.register(with: controller.registrar(forPlugin: "WakelockPlusMacosPlugin"))\n WindowSizePlugin.register(with: controller.registrar(forPlugin: "WindowSizePlugin"))\n TextureRgbaRendererPlugin.register(with: controller.registrar(forPlugin: "TextureRgbaRendererPlugin"))\n }\n \n super.awakeFromNib()\n }\n \n override public func order(_ place: NSWindow.OrderingMode, relativeTo otherWin: Int) {\n super.order(place, relativeTo: otherWin)\n hiddenWindowAtLaunch()\n }\n \n /// Override window theme.\n public func setWindowInterfaceMode(window: NSWindow, themeName: String) {\n window.appearance = NSAppearance(named: themeName == "light" ? .aqua : .darkAqua)\n }\n \n public func setMethodHandler(registrar: FlutterPluginRegistrar) {\n let channel = FlutterMethodChannel(name: "org.rustdesk.rustdesk/macos", binaryMessenger: registrar.messenger)\n channel.setMethodCallHandler({\n (call, result) -> Void in\n switch call.method {\n case "setWindowTheme":\n let arg = call.arguments as! [String: Any]\n let themeName = arg["themeName"] as? String\n guard let window = registrar.view?.window else {\n result(nil)\n return\n }\n self.setWindowInterfaceMode(window: window,themeName: themeName ?? "light")\n result(nil)\n break;\n case "terminate":\n NSApplication.shared.terminate(self)\n result(nil)\n case "canRecordAudio":\n switch AVCaptureDevice.authorizationStatus(for: .audio) {\n case .authorized:\n result(1)\n break\n case .notDetermined:\n result(0)\n break\n default:\n result(-1)\n break\n }\n case "requestRecordAudio":\n AVCaptureDevice.requestAccess(for: .audio, completionHandler: { granted in\n result(granted)\n })\n break\n default:\n result(FlutterMethodNotImplemented)\n }\n })\n }\n}\n | dataset_sample\swift\rustdesk_rustdesk\flutter\macos\Runner\MainFlutterWindow.swift | MainFlutterWindow.swift | Swift | 4,843 | 0.95 | 0.046729 | 0.080808 | node-utils | 242 | 2024-04-05T21:05:02.088624 | GPL-3.0 | false | 725be84e607bbf273b12143eed09daf7 |
/* Options:\nDate: 2025-03-28 01:55:02\nSwiftVersion: 6.0\nVersion: 8.61\nTip: To override a DTO option, remove "//" prefix before updating\nBaseUrl: http://localhost:20000\n\n//BaseClass: \n//AddModelExtensions: True\n//AddServiceStackTypes: True\n//MakePropertiesOptional: True\n//IncludeTypes: \n//ExcludeTypes: \n//ExcludeGenericBaseTypes: False\n//AddResponseStatus: False\n//AddImplicitVersion: \n//AddDescriptionAsComments: True\n//InitializeCollections: False\n//TreatTypesAsStrings: \n//DefaultImports: Foundation,ServiceStack\n*/\n\nimport Foundation\nimport ServiceStack\n\n// @Route("/metadata/app")\n// @DataContract\npublic class MetadataApp : IReturn, IGet, Codable\n{\n public typealias Return = AppMetadata\n\n // @DataMember(Order=1)\n public var view:String?\n\n // @DataMember(Order=2)\n public var includeTypes:[String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminCreateRole : IReturn, IPost, Codable\n{\n public typealias Return = IdResponse\n\n // @DataMember(Order=1)\n public var name:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminGetRoles : IReturn, IGet, Codable\n{\n public typealias Return = AdminGetRolesResponse\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminGetRole : IReturn, IGet, Codable\n{\n public typealias Return = AdminGetRoleResponse\n\n // @DataMember(Order=1)\n public var id:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminUpdateRole : IReturn, IPost, Codable\n{\n public typealias Return = IdResponse\n\n // @DataMember(Order=1)\n public var id:String?\n\n // @DataMember(Order=2)\n public var name:String?\n\n // @DataMember(Order=3)\n public var addClaims:[Property]?\n\n // @DataMember(Order=4)\n public var removeClaims:[Property]?\n\n // @DataMember(Order=5)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminDeleteRole : IReturnVoid, IDelete, Codable\n{\n // @DataMember(Order=1)\n public var id:String?\n\n required public init(){}\n}\n\npublic class AdminDashboard : IReturn, IGet, Codable\n{\n public typealias Return = AdminDashboardResponse\n\n required public init(){}\n}\n\n/**\n* Sign In\n*/\n// @Route("/auth", "GET,POST")\n// @Route("/auth/{provider}", "GET,POST")\n// @Api(Description="Sign In")\n// @DataContract\npublic class Authenticate : IReturn, IPost, Codable\n{\n public typealias Return = AuthenticateResponse\n\n /**\n * AuthProvider, e.g. credentials\n */\n // @DataMember(Order=1)\n public var provider:String?\n\n // @DataMember(Order=2)\n public var userName:String?\n\n // @DataMember(Order=3)\n public var password:String?\n\n // @DataMember(Order=4)\n public var rememberMe:Bool?\n\n // @DataMember(Order=5)\n public var accessToken:String?\n\n // @DataMember(Order=6)\n public var accessTokenSecret:String?\n\n // @DataMember(Order=7)\n public var returnUrl:String?\n\n // @DataMember(Order=8)\n public var errorView:String?\n\n // @DataMember(Order=9)\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @Route("/assignroles", "POST")\n// @DataContract\npublic class AssignRoles : IReturn, IPost, Codable\n{\n public typealias Return = AssignRolesResponse\n\n // @DataMember(Order=1)\n public var userName:String?\n\n // @DataMember(Order=2)\n public var permissions:[String]?\n\n // @DataMember(Order=3)\n public var roles:[String]?\n\n // @DataMember(Order=4)\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @Route("/unassignroles", "POST")\n// @DataContract\npublic class UnAssignRoles : IReturn, IPost, Codable\n{\n public typealias Return = UnAssignRolesResponse\n\n // @DataMember(Order=1)\n public var userName:String?\n\n // @DataMember(Order=2)\n public var permissions:[String]?\n\n // @DataMember(Order=3)\n public var roles:[String]?\n\n // @DataMember(Order=4)\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminGetUser : IReturn, IGet, Codable\n{\n public typealias Return = AdminUserResponse\n\n // @DataMember(Order=10)\n public var id:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminQueryUsers : IReturn, IGet, Codable\n{\n public typealias Return = AdminUsersResponse\n\n // @DataMember(Order=1)\n public var query:String?\n\n // @DataMember(Order=2)\n public var orderBy:String?\n\n // @DataMember(Order=3)\n public var skip:Int?\n\n // @DataMember(Order=4)\n public var take:Int?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminCreateUser : AdminUserBase, IReturn, IPost\n{\n public typealias Return = AdminUserResponse\n\n // @DataMember(Order=10)\n public var roles:[String]?\n\n // @DataMember(Order=11)\n public var permissions:[String]?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case roles\n case permissions\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n roles = try container.decodeIfPresent([String].self, forKey: .roles) ?? []\n permissions = try container.decodeIfPresent([String].self, forKey: .permissions) ?? []\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if roles != nil { try container.encode(roles, forKey: .roles) }\n if permissions != nil { try container.encode(permissions, forKey: .permissions) }\n }\n}\n\n// @DataContract\npublic class AdminUpdateUser : AdminUserBase, IReturn, IPut\n{\n public typealias Return = AdminUserResponse\n\n // @DataMember(Order=10)\n public var id:String?\n\n // @DataMember(Order=11)\n public var lockUser:Bool?\n\n // @DataMember(Order=12)\n public var unlockUser:Bool?\n\n // @DataMember(Order=13)\n public var lockUserUntil:Date?\n\n // @DataMember(Order=14)\n public var addRoles:[String]?\n\n // @DataMember(Order=15)\n public var removeRoles:[String]?\n\n // @DataMember(Order=16)\n public var addPermissions:[String]?\n\n // @DataMember(Order=17)\n public var removePermissions:[String]?\n\n // @DataMember(Order=18)\n public var addClaims:[Property]?\n\n // @DataMember(Order=19)\n public var removeClaims:[Property]?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case id\n case lockUser\n case unlockUser\n case lockUserUntil\n case addRoles\n case removeRoles\n case addPermissions\n case removePermissions\n case addClaims\n case removeClaims\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n id = try container.decodeIfPresent(String.self, forKey: .id)\n lockUser = try container.decodeIfPresent(Bool.self, forKey: .lockUser)\n unlockUser = try container.decodeIfPresent(Bool.self, forKey: .unlockUser)\n lockUserUntil = try container.decodeIfPresent(Date.self, forKey: .lockUserUntil)\n addRoles = try container.decodeIfPresent([String].self, forKey: .addRoles) ?? []\n removeRoles = try container.decodeIfPresent([String].self, forKey: .removeRoles) ?? []\n addPermissions = try container.decodeIfPresent([String].self, forKey: .addPermissions) ?? []\n removePermissions = try container.decodeIfPresent([String].self, forKey: .removePermissions) ?? []\n addClaims = try container.decodeIfPresent([Property].self, forKey: .addClaims) ?? []\n removeClaims = try container.decodeIfPresent([Property].self, forKey: .removeClaims) ?? []\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if id != nil { try container.encode(id, forKey: .id) }\n if lockUser != nil { try container.encode(lockUser, forKey: .lockUser) }\n if unlockUser != nil { try container.encode(unlockUser, forKey: .unlockUser) }\n if lockUserUntil != nil { try container.encode(lockUserUntil, forKey: .lockUserUntil) }\n if addRoles != nil { try container.encode(addRoles, forKey: .addRoles) }\n if removeRoles != nil { try container.encode(removeRoles, forKey: .removeRoles) }\n if addPermissions != nil { try container.encode(addPermissions, forKey: .addPermissions) }\n if removePermissions != nil { try container.encode(removePermissions, forKey: .removePermissions) }\n if addClaims != nil { try container.encode(addClaims, forKey: .addClaims) }\n if removeClaims != nil { try container.encode(removeClaims, forKey: .removeClaims) }\n }\n}\n\n// @DataContract\npublic class AdminDeleteUser : IReturn, IDelete, Codable\n{\n public typealias Return = AdminDeleteUserResponse\n\n // @DataMember(Order=10)\n public var id:String?\n\n required public init(){}\n}\n\npublic class AdminQueryRequestLogs : QueryDb<RequestLog>, IReturn\n{\n public typealias Return = QueryResponse<RequestLog>\n\n public var month:Date?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case month\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n month = try container.decodeIfPresent(Date.self, forKey: .month)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if month != nil { try container.encode(month, forKey: .month) }\n }\n}\n\npublic class AdminProfiling : IReturn, Codable\n{\n public typealias Return = AdminProfilingResponse\n\n public var source:String?\n public var eventType:String?\n public var threadId:Int?\n public var traceId:String?\n public var userAuthId:String?\n public var sessionId:String?\n public var tag:String?\n public var skip:Int?\n public var take:Int?\n public var orderBy:String?\n public var withErrors:Bool?\n public var pending:Bool?\n\n required public init(){}\n}\n\npublic class AdminRedis : IReturn, IPost, Codable\n{\n public typealias Return = AdminRedisResponse\n\n public var db:Int?\n public var query:String?\n public var reconnect:RedisEndpointInfo?\n public var take:Int?\n public var position:Int?\n public var args:[String]?\n\n required public init(){}\n}\n\npublic class AdminDatabase : IReturn, IGet, Codable\n{\n public typealias Return = AdminDatabaseResponse\n\n public var db:String?\n public var schema:String?\n public var table:String?\n public var fields:[String]?\n public var take:Int?\n public var skip:Int?\n public var orderBy:String?\n public var include:String?\n\n required public init(){}\n}\n\npublic class ViewCommands : IReturn, IGet, Codable\n{\n public typealias Return = ViewCommandsResponse\n\n public var include:[String]?\n public var skip:Int?\n public var take:Int?\n\n required public init(){}\n}\n\npublic class ExecuteCommand : IReturn, IPost, Codable\n{\n public typealias Return = ExecuteCommandResponse\n\n public var command:String?\n public var requestJson:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminQueryApiKeys : IReturn, IGet, Codable\n{\n public typealias Return = AdminApiKeysResponse\n\n // @DataMember(Order=1)\n public var id:Int?\n\n // @DataMember(Order=2)\n public var apiKey:String?\n\n // @DataMember(Order=3)\n public var search:String?\n\n // @DataMember(Order=4)\n public var userId:String?\n\n // @DataMember(Order=5)\n public var userName:String?\n\n // @DataMember(Order=6)\n public var orderBy:String?\n\n // @DataMember(Order=7)\n public var skip:Int?\n\n // @DataMember(Order=8)\n public var take:Int?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminCreateApiKey : IReturn, IPost, Codable\n{\n public typealias Return = AdminApiKeyResponse\n\n // @DataMember(Order=1)\n public var name:String?\n\n // @DataMember(Order=2)\n public var userId:String?\n\n // @DataMember(Order=3)\n public var userName:String?\n\n // @DataMember(Order=4)\n public var scopes:[String]?\n\n // @DataMember(Order=5)\n public var features:[String]?\n\n // @DataMember(Order=6)\n public var restrictTo:[String]?\n\n // @DataMember(Order=7)\n public var expiryDate:Date?\n\n // @DataMember(Order=8)\n public var notes:String?\n\n // @DataMember(Order=9)\n public var refId:Int?\n\n // @DataMember(Order=10)\n public var refIdStr:String?\n\n // @DataMember(Order=11)\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminUpdateApiKey : IReturn, IPatch, Codable\n{\n public typealias Return = EmptyResponse\n\n // @DataMember(Order=1)\n // @Validate(Validator="GreaterThan(0)")\n public var id:Int?\n\n // @DataMember(Order=2)\n public var name:String?\n\n // @DataMember(Order=3)\n public var userId:String?\n\n // @DataMember(Order=4)\n public var userName:String?\n\n // @DataMember(Order=5)\n public var scopes:[String]?\n\n // @DataMember(Order=6)\n public var features:[String]?\n\n // @DataMember(Order=7)\n public var restrictTo:[String]?\n\n // @DataMember(Order=8)\n public var expiryDate:Date?\n\n // @DataMember(Order=9)\n public var cancelledDate:Date?\n\n // @DataMember(Order=10)\n public var notes:String?\n\n // @DataMember(Order=11)\n public var refId:Int?\n\n // @DataMember(Order=12)\n public var refIdStr:String?\n\n // @DataMember(Order=13)\n public var meta:[String:String]?\n\n // @DataMember(Order=14)\n public var reset:[String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminDeleteApiKey : IReturn, IDelete, Codable\n{\n public typealias Return = EmptyResponse\n\n // @DataMember(Order=1)\n // @Validate(Validator="GreaterThan(0)")\n public var id:Int?\n\n required public init(){}\n}\n\npublic class AdminJobDashboard : IReturn, IGet, Codable\n{\n public typealias Return = AdminJobDashboardResponse\n\n public var from:Date?\n public var to:Date?\n\n required public init(){}\n}\n\npublic class AdminJobInfo : IReturn, IGet, Codable\n{\n public typealias Return = AdminJobInfoResponse\n\n public var month:Date?\n\n required public init(){}\n}\n\npublic class AdminGetJob : IReturn, IGet, Codable\n{\n public typealias Return = AdminGetJobResponse\n\n public var id:Int?\n public var refId:String?\n\n required public init(){}\n}\n\npublic class AdminGetJobProgress : IReturn, IGet, Codable\n{\n public typealias Return = AdminGetJobProgressResponse\n\n // @Validate(Validator="GreaterThan(0)")\n public var id:Int?\n\n public var logStart:Int?\n\n required public init(){}\n}\n\npublic class AdminQueryBackgroundJobs : QueryDb<BackgroundJob>, IReturn\n{\n public typealias Return = QueryResponse<BackgroundJob>\n\n public var id:Int?\n public var refId:String?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case id\n case refId\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n id = try container.decodeIfPresent(Int.self, forKey: .id)\n refId = try container.decodeIfPresent(String.self, forKey: .refId)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if id != nil { try container.encode(id, forKey: .id) }\n if refId != nil { try container.encode(refId, forKey: .refId) }\n }\n}\n\npublic class AdminQueryJobSummary : QueryDb<JobSummary>, IReturn\n{\n public typealias Return = QueryResponse<JobSummary>\n\n public var id:Int?\n public var refId:String?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case id\n case refId\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n id = try container.decodeIfPresent(Int.self, forKey: .id)\n refId = try container.decodeIfPresent(String.self, forKey: .refId)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if id != nil { try container.encode(id, forKey: .id) }\n if refId != nil { try container.encode(refId, forKey: .refId) }\n }\n}\n\npublic class AdminQueryScheduledTasks : QueryDb<ScheduledTask>, IReturn\n{\n public typealias Return = QueryResponse<ScheduledTask>\n\n required public init(){ super.init() }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n }\n}\n\npublic class AdminQueryCompletedJobs : QueryDb<CompletedJob>, IReturn\n{\n public typealias Return = QueryResponse<CompletedJob>\n\n public var month:Date?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case month\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n month = try container.decodeIfPresent(Date.self, forKey: .month)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if month != nil { try container.encode(month, forKey: .month) }\n }\n}\n\npublic class AdminQueryFailedJobs : QueryDb<FailedJob>, IReturn\n{\n public typealias Return = QueryResponse<FailedJob>\n\n public var month:Date?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case month\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n month = try container.decodeIfPresent(Date.self, forKey: .month)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if month != nil { try container.encode(month, forKey: .month) }\n }\n}\n\npublic class AdminRequeueFailedJobs : IReturn, Codable\n{\n public typealias Return = AdminRequeueFailedJobsJobsResponse\n\n public var ids:[Int]?\n\n required public init(){}\n}\n\npublic class AdminCancelJobs : IReturn, IGet, Codable\n{\n public typealias Return = AdminCancelJobsResponse\n\n public var ids:[Int]?\n public var worker:String?\n public var state:BackgroundJobState?\n public var cancelWorker:String?\n\n required public init(){}\n}\n\n// @Route("/requestlogs")\n// @DataContract\npublic class RequestLogs : IReturn, IGet, Codable\n{\n public typealias Return = RequestLogsResponse\n\n // @DataMember(Order=1)\n public var beforeSecs:Int?\n\n // @DataMember(Order=2)\n public var afterSecs:Int?\n\n // @DataMember(Order=3)\n public var operationName:String?\n\n // @DataMember(Order=4)\n public var ipAddress:String?\n\n // @DataMember(Order=5)\n public var forwardedFor:String?\n\n // @DataMember(Order=6)\n public var userAuthId:String?\n\n // @DataMember(Order=7)\n public var sessionId:String?\n\n // @DataMember(Order=8)\n public var referer:String?\n\n // @DataMember(Order=9)\n public var pathInfo:String?\n\n // @DataMember(Order=10)\n public var bearerToken:String?\n\n // @DataMember(Order=11)\n public var ids:[Int]?\n\n // @DataMember(Order=12)\n public var beforeId:Int?\n\n // @DataMember(Order=13)\n public var afterId:Int?\n\n // @DataMember(Order=14)\n public var hasResponse:Bool?\n\n // @DataMember(Order=15)\n public var withErrors:Bool?\n\n // @DataMember(Order=16)\n public var enableSessionTracking:Bool?\n\n // @DataMember(Order=17)\n public var enableResponseTracking:Bool?\n\n // @DataMember(Order=18)\n public var enableErrorTracking:Bool?\n\n // @DataMember(Order=19)\n @TimeSpan public var durationLongerThan:TimeInterval?\n\n // @DataMember(Order=20)\n @TimeSpan public var durationLessThan:TimeInterval?\n\n // @DataMember(Order=21)\n public var skip:Int?\n\n // @DataMember(Order=22)\n public var take:Int?\n\n // @DataMember(Order=23)\n public var orderBy:String?\n\n // @DataMember(Order=24)\n public var month:Date?\n\n required public init(){}\n}\n\n// @DataContract\npublic class GetAnalyticsInfo : IReturn, IGet, Codable\n{\n public typealias Return = GetAnalyticsInfoResponse\n\n // @DataMember(Order=1)\n public var month:Date?\n\n // @DataMember(Order=2)\n public var type:String?\n\n // @DataMember(Order=3)\n public var op:String?\n\n // @DataMember(Order=4)\n public var apiKey:String?\n\n // @DataMember(Order=5)\n public var userId:String?\n\n // @DataMember(Order=6)\n public var ip:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class GetAnalyticsReports : IReturn, IGet, Codable\n{\n public typealias Return = GetAnalyticsReportsResponse\n\n // @DataMember(Order=1)\n public var month:Date?\n\n // @DataMember(Order=2)\n public var filter:String?\n\n // @DataMember(Order=3)\n public var value:String?\n\n // @DataMember(Order=4)\n public var force:Bool?\n\n required public init(){}\n}\n\n// @Route("/validation/rules/{Type}")\n// @DataContract\npublic class GetValidationRules : IReturn, IGet, Codable\n{\n public typealias Return = GetValidationRulesResponse\n\n // @DataMember(Order=1)\n public var authSecret:String?\n\n // @DataMember(Order=2)\n public var type:String?\n\n required public init(){}\n}\n\n// @Route("/validation/rules")\n// @DataContract\npublic class ModifyValidationRules : IReturnVoid, Codable\n{\n // @DataMember(Order=1)\n public var authSecret:String?\n\n // @DataMember(Order=2)\n public var saveRules:[ValidationRule]?\n\n // @DataMember(Order=3)\n public var deleteRuleIds:[Int]?\n\n // @DataMember(Order=4)\n public var suspendRuleIds:[Int]?\n\n // @DataMember(Order=5)\n public var unsuspendRuleIds:[Int]?\n\n // @DataMember(Order=6)\n public var clearCache:Bool?\n\n required public init(){}\n}\n\npublic class AppMetadata : Codable\n{\n public var date:Date?\n public var app:AppInfo?\n public var ui:UiInfo?\n public var config:ConfigInfo?\n public var contentTypeFormats:[String:String]?\n public var httpHandlers:[String:String]?\n public var plugins:PluginInfo?\n public var customPlugins:[String:CustomPluginInfo]?\n public var api:MetadataTypes?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class IdResponse : Codable\n{\n // @DataMember(Order=1)\n public var id:String?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminGetRolesResponse : Codable\n{\n // @DataMember(Order=1)\n public var results:[AdminRole]?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminGetRoleResponse : Codable\n{\n // @DataMember(Order=1)\n public var result:AdminRole?\n\n // @DataMember(Order=2)\n public var claims:[Property]?\n\n // @DataMember(Order=3)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminDashboardResponse : Codable\n{\n public var serverStats:ServerStats?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AuthenticateResponse : IHasSessionId, IHasBearerToken, Codable\n{\n // @DataMember(Order=1)\n public var userId:String?\n\n // @DataMember(Order=2)\n public var sessionId:String?\n\n // @DataMember(Order=3)\n public var userName:String?\n\n // @DataMember(Order=4)\n public var displayName:String?\n\n // @DataMember(Order=5)\n public var referrerUrl:String?\n\n // @DataMember(Order=6)\n public var bearerToken:String?\n\n // @DataMember(Order=7)\n public var refreshToken:String?\n\n // @DataMember(Order=8)\n public var refreshTokenExpiry:Date?\n\n // @DataMember(Order=9)\n public var profileUrl:String?\n\n // @DataMember(Order=10)\n public var roles:[String]?\n\n // @DataMember(Order=11)\n public var permissions:[String]?\n\n // @DataMember(Order=12)\n public var authProvider:String?\n\n // @DataMember(Order=13)\n public var responseStatus:ResponseStatus?\n\n // @DataMember(Order=14)\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AssignRolesResponse : Codable\n{\n // @DataMember(Order=1)\n public var allRoles:[String]?\n\n // @DataMember(Order=2)\n public var allPermissions:[String]?\n\n // @DataMember(Order=3)\n public var meta:[String:String]?\n\n // @DataMember(Order=4)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class UnAssignRolesResponse : Codable\n{\n // @DataMember(Order=1)\n public var allRoles:[String]?\n\n // @DataMember(Order=2)\n public var allPermissions:[String]?\n\n // @DataMember(Order=3)\n public var meta:[String:String]?\n\n // @DataMember(Order=4)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminUserResponse : Codable\n{\n // @DataMember(Order=1)\n public var id:String?\n\n // @DataMember(Order=2)\n public var result:[String:String]?\n\n // @DataMember(Order=3)\n public var details:[[String:String]]?\n\n // @DataMember(Order=4)\n public var claims:[Property]?\n\n // @DataMember(Order=5)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminUsersResponse : Codable\n{\n // @DataMember(Order=1)\n public var results:[[String:String]]?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminDeleteUserResponse : Codable\n{\n // @DataMember(Order=1)\n public var id:String?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminProfilingResponse : Codable\n{\n public var results:[DiagnosticEntry] = []\n public var total:Int?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminRedisResponse : Codable\n{\n public var db:Int?\n public var searchResults:[RedisSearchResult]?\n public var info:[String:String]?\n public var endpoint:RedisEndpointInfo?\n public var result:RedisText?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminDatabaseResponse : Codable\n{\n public var results:[[String:String]] = []\n public var total:Int?\n public var columns:[MetadataPropertyType]?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class ViewCommandsResponse : Codable\n{\n public var commandTotals:[CommandSummary] = []\n public var latestCommands:[CommandResult] = []\n public var latestFailed:[CommandResult] = []\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class ExecuteCommandResponse : Codable\n{\n public var commandResult:CommandResult?\n public var result:String?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminApiKeysResponse : Codable\n{\n // @DataMember(Order=1)\n public var results:[PartialApiKey]?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminApiKeyResponse : Codable\n{\n // @DataMember(Order=1)\n public var result:String?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminJobDashboardResponse : Codable\n{\n public var commands:[JobStatSummary] = []\n public var apis:[JobStatSummary] = []\n public var workers:[JobStatSummary] = []\n public var today:[HourSummary] = []\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminJobInfoResponse : Codable\n{\n public var monthDbs:[Date] = []\n public var tableCounts:[String:Int] = [:]\n public var workerStats:[WorkerStats] = []\n public var queueCounts:[String:Int] = [:]\n public var workerCounts:[String:Int] = [:]\n public var stateCounts:[BackgroundJobState:Int] = [:]\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminGetJobResponse : Codable\n{\n public var result:JobSummary?\n public var queued:BackgroundJob?\n public var completed:CompletedJob?\n public var failed:FailedJob?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminGetJobProgressResponse : Codable\n{\n public var state:BackgroundJobState?\n public var progress:Double?\n public var status:String?\n public var logs:String?\n public var durationMs:Int?\n public var error:ResponseStatus?\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminRequeueFailedJobsJobsResponse : Codable\n{\n public var results:[Int] = []\n public var errors:[Int:String] = [:]\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\npublic class AdminCancelJobsResponse : Codable\n{\n public var results:[Int] = []\n public var errors:[Int:String] = [:]\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class RequestLogsResponse : Codable\n{\n // @DataMember(Order=1)\n public var results:[RequestLogEntry]?\n\n // @DataMember(Order=2)\n public var usage:[String:String]?\n\n // @DataMember(Order=3)\n public var total:Int?\n\n // @DataMember(Order=4)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class GetAnalyticsInfoResponse : Codable\n{\n // @DataMember(Order=1)\n public var months:[String]?\n\n // @DataMember(Order=2)\n public var result:AnalyticsLogInfo?\n\n // @DataMember(Order=3)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class GetAnalyticsReportsResponse : Codable\n{\n // @DataMember(Order=1)\n public var result:AnalyticsReports?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class GetValidationRulesResponse : Codable\n{\n // @DataMember(Order=1)\n public var results:[ValidationRule]?\n\n // @DataMember(Order=2)\n public var responseStatus:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class Property : Codable\n{\n // @DataMember(Order=1)\n public var name:String?\n\n // @DataMember(Order=2)\n public var value:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminUserBase : Codable\n{\n // @DataMember(Order=1)\n public var userName:String?\n\n // @DataMember(Order=2)\n public var firstName:String?\n\n // @DataMember(Order=3)\n public var lastName:String?\n\n // @DataMember(Order=4)\n public var displayName:String?\n\n // @DataMember(Order=5)\n public var email:String?\n\n // @DataMember(Order=6)\n public var password:String?\n\n // @DataMember(Order=7)\n public var profileUrl:String?\n\n // @DataMember(Order=8)\n public var phoneNumber:String?\n\n // @DataMember(Order=9)\n public var userAuthProperties:[String:String]?\n\n // @DataMember(Order=10)\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class RequestLog : Codable\n{\n public var id:Int?\n public var traceId:String?\n public var operationName:String?\n public var dateTime:Date?\n public var statusCode:Int?\n public var statusDescription:String?\n public var httpMethod:String?\n public var absoluteUri:String?\n public var pathInfo:String?\n public var request:String?\n // @StringLength(Int32.max)\n public var requestBody:String?\n\n public var userAuthId:String?\n public var sessionId:String?\n public var ipAddress:String?\n public var forwardedFor:String?\n public var referer:String?\n public var headers:[String:String] = [:]\n public var formData:[String:String]?\n public var items:[String:String] = [:]\n public var responseHeaders:[String:String]?\n public var response:String?\n public var responseBody:String?\n public var sessionBody:String?\n public var error:ResponseStatus?\n public var exceptionSource:String?\n public var exceptionDataBody:String?\n @TimeSpan public var requestDuration:TimeInterval?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class RedisEndpointInfo : Codable\n{\n public var host:String?\n public var port:Int?\n public var ssl:Bool?\n public var db:Int?\n public var username:String?\n public var password:String?\n\n required public init(){}\n}\n\npublic class BackgroundJob : BackgroundJobBase\n{\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case id\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n id = try container.decodeIfPresent(Int.self, forKey: .id)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if id != nil { try container.encode(id, forKey: .id) }\n }\n}\n\npublic class JobSummary : Codable\n{\n public var id:Int?\n public var parentId:Int?\n public var refId:String?\n public var worker:String?\n public var tag:String?\n public var batchId:String?\n public var createdDate:Date?\n public var createdBy:String?\n public var requestType:String?\n public var command:String?\n public var request:String?\n public var response:String?\n public var userId:String?\n public var callback:String?\n public var startedDate:Date?\n public var completedDate:Date?\n public var state:BackgroundJobState?\n public var durationMs:Int?\n public var attempts:Int?\n public var errorCode:String?\n public var errorMessage:String?\n\n required public init(){}\n}\n\npublic class ScheduledTask : Codable\n{\n public var id:Int?\n public var name:String?\n @TimeSpan public var interval:TimeInterval?\n public var cronExpression:String?\n public var requestType:String?\n public var command:String?\n public var request:String?\n public var requestBody:String?\n public var options:BackgroundJobOptions?\n public var lastRun:Date?\n public var lastJobId:Int?\n\n required public init(){}\n}\n\npublic class CompletedJob : BackgroundJobBase\n{\n required public init(){ super.init() }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n }\n}\n\npublic class FailedJob : BackgroundJobBase\n{\n required public init(){ super.init() }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n }\n}\n\npublic enum BackgroundJobState : String, Codable\n{\n case Queued\n case Started\n case Executed\n case Completed\n case Failed\n case Cancelled\n}\n\npublic class ValidationRule : ValidateRule\n{\n public var id:Int?\n // @Required()\n public var type:String?\n\n public var field:String?\n public var createdBy:String?\n public var createdDate:Date?\n public var modifiedBy:String?\n public var modifiedDate:Date?\n public var suspendedBy:String?\n public var suspendedDate:Date?\n public var notes:String?\n\n required public init(){ super.init() }\n\n private enum CodingKeys : String, CodingKey {\n case id\n case type\n case field\n case createdBy\n case createdDate\n case modifiedBy\n case modifiedDate\n case suspendedBy\n case suspendedDate\n case notes\n }\n\n required public init(from decoder: Decoder) throws {\n try super.init(from: decoder)\n let container = try decoder.container(keyedBy: CodingKeys.self)\n id = try container.decodeIfPresent(Int.self, forKey: .id)\n type = try container.decodeIfPresent(String.self, forKey: .type)\n field = try container.decodeIfPresent(String.self, forKey: .field)\n createdBy = try container.decodeIfPresent(String.self, forKey: .createdBy)\n createdDate = try container.decodeIfPresent(Date.self, forKey: .createdDate)\n modifiedBy = try container.decodeIfPresent(String.self, forKey: .modifiedBy)\n modifiedDate = try container.decodeIfPresent(Date.self, forKey: .modifiedDate)\n suspendedBy = try container.decodeIfPresent(String.self, forKey: .suspendedBy)\n suspendedDate = try container.decodeIfPresent(Date.self, forKey: .suspendedDate)\n notes = try container.decodeIfPresent(String.self, forKey: .notes)\n }\n\n public override func encode(to encoder: Encoder) throws {\n try super.encode(to: encoder)\n var container = encoder.container(keyedBy: CodingKeys.self)\n if id != nil { try container.encode(id, forKey: .id) }\n if type != nil { try container.encode(type, forKey: .type) }\n if field != nil { try container.encode(field, forKey: .field) }\n if createdBy != nil { try container.encode(createdBy, forKey: .createdBy) }\n if createdDate != nil { try container.encode(createdDate, forKey: .createdDate) }\n if modifiedBy != nil { try container.encode(modifiedBy, forKey: .modifiedBy) }\n if modifiedDate != nil { try container.encode(modifiedDate, forKey: .modifiedDate) }\n if suspendedBy != nil { try container.encode(suspendedBy, forKey: .suspendedBy) }\n if suspendedDate != nil { try container.encode(suspendedDate, forKey: .suspendedDate) }\n if notes != nil { try container.encode(notes, forKey: .notes) }\n }\n}\n\npublic class AppInfo : Codable\n{\n public var baseUrl:String?\n public var serviceStackVersion:String?\n public var serviceName:String?\n public var apiVersion:String?\n public var serviceDescription:String?\n public var serviceIconUrl:String?\n public var brandUrl:String?\n public var brandImageUrl:String?\n public var textColor:String?\n public var linkColor:String?\n public var backgroundColor:String?\n public var backgroundImageUrl:String?\n public var iconUrl:String?\n public var jsTextCase:String?\n public var useSystemJson:String?\n public var endpointRouting:[String]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class UiInfo : Codable\n{\n public var brandIcon:ImageInfo?\n public var hideTags:[String]?\n public var modules:[String]?\n public var alwaysHideTags:[String]?\n public var adminLinks:[LinkInfo]?\n public var theme:ThemeInfo?\n public var locode:LocodeUi?\n public var explorer:ExplorerUi?\n public var admin:AdminUi?\n public var defaultFormats:ApiFormat?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class ConfigInfo : Codable\n{\n public var debugMode:Bool?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class PluginInfo : Codable\n{\n public var loaded:[String]?\n public var auth:AuthInfo?\n public var apiKey:ApiKeyInfo?\n public var commands:CommandsInfo?\n public var autoQuery:AutoQueryInfo?\n public var validation:ValidationInfo?\n public var sharpPages:SharpPagesInfo?\n public var requestLogs:RequestLogsInfo?\n public var profiling:ProfilingInfo?\n public var filesUpload:FilesUploadInfo?\n public var adminUsers:AdminUsersInfo?\n public var adminIdentityUsers:AdminIdentityUsersInfo?\n public var adminRedis:AdminRedisInfo?\n public var adminDatabase:AdminDatabaseInfo?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class CustomPluginInfo : Codable\n{\n public var accessRole:String?\n public var serviceRoutes:[String:[String]]?\n public var enabled:[String]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class MetadataTypes : Codable\n{\n public var config:MetadataTypesConfig?\n public var namespaces:[String]?\n public var types:[MetadataType]?\n public var operations:[MetadataOperationType]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AdminRole : Codable\n{\n required public init(){}\n}\n\npublic class ServerStats : Codable\n{\n public var redis:[String:Int]?\n public var serverEvents:[String:String]?\n public var mqDescription:String?\n public var mqWorkers:[String:Int]?\n\n required public init(){}\n}\n\npublic class DiagnosticEntry : Codable\n{\n public var id:Int?\n public var traceId:String?\n public var source:String?\n public var eventType:String?\n public var message:String?\n public var operation:String?\n public var threadId:Int?\n public var error:ResponseStatus?\n public var commandType:String?\n public var command:String?\n public var userAuthId:String?\n public var sessionId:String?\n public var arg:String?\n public var args:[String]?\n public var argLengths:[Int]?\n public var namedArgs:[String:String]?\n @TimeSpan public var duration:TimeInterval?\n public var timestamp:Int?\n public var date:Date?\n public var tag:String?\n public var stackTrace:String?\n public var meta:[String:String] = [:]\n\n required public init(){}\n}\n\npublic class RedisSearchResult : Codable\n{\n public var id:String?\n public var type:String?\n public var ttl:Int?\n public var size:Int?\n\n required public init(){}\n}\n\npublic class RedisText : Codable\n{\n public var text:String?\n public var children:[RedisText]?\n\n required public init(){}\n}\n\npublic class MetadataPropertyType : Codable\n{\n public var name:String?\n public var type:String?\n public var namespace:String?\n public var isValueType:Bool?\n public var isEnum:Bool?\n public var isPrimaryKey:Bool?\n public var genericArgs:[String]?\n public var value:String?\n public var Description:String?\n public var dataMember:MetadataDataMember?\n public var readOnly:Bool?\n public var paramType:String?\n public var displayType:String?\n public var isRequired:Bool?\n public var allowableValues:[String]?\n public var allowableMin:Int?\n public var allowableMax:Int?\n public var attributes:[MetadataAttribute]?\n public var uploadTo:String?\n public var input:InputInfo?\n public var format:FormatInfo?\n public var ref:RefInfo?\n\n required public init(){}\n}\n\npublic class CommandSummary : Codable\n{\n public var type:String?\n public var name:String?\n public var count:Int?\n public var failed:Int?\n public var retries:Int?\n public var totalMs:Int?\n public var minMs:Int?\n public var maxMs:Int?\n public var averageMs:Double?\n public var medianMs:Double?\n public var lastError:ResponseStatus?\n public var timings:ConcurrentQueue<Int>?\n\n required public init(){}\n}\n\npublic class CommandResult : Codable\n{\n public var type:String?\n public var name:String?\n public var ms:Int?\n public var at:Date?\n public var request:String?\n public var retries:Int?\n public var attempt:Int?\n public var error:ResponseStatus?\n\n required public init(){}\n}\n\n// @DataContract\npublic class PartialApiKey : Codable\n{\n // @DataMember(Order=1)\n public var id:Int?\n\n // @DataMember(Order=2)\n public var name:String?\n\n // @DataMember(Order=3)\n public var userId:String?\n\n // @DataMember(Order=4)\n public var userName:String?\n\n // @DataMember(Order=5)\n public var visibleKey:String?\n\n // @DataMember(Order=6)\n public var environment:String?\n\n // @DataMember(Order=7)\n public var createdDate:Date?\n\n // @DataMember(Order=8)\n public var expiryDate:Date?\n\n // @DataMember(Order=9)\n public var cancelledDate:Date?\n\n // @DataMember(Order=10)\n public var lastUsedDate:Date?\n\n // @DataMember(Order=11)\n public var scopes:[String]?\n\n // @DataMember(Order=12)\n public var features:[String]?\n\n // @DataMember(Order=13)\n public var restrictTo:[String]?\n\n // @DataMember(Order=14)\n public var notes:String?\n\n // @DataMember(Order=15)\n public var refId:Int?\n\n // @DataMember(Order=16)\n public var refIdStr:String?\n\n // @DataMember(Order=17)\n public var meta:[String:String]?\n\n // @DataMember(Order=18)\n public var active:Bool?\n\n required public init(){}\n}\n\npublic class JobStatSummary : Codable\n{\n public var name:String?\n public var total:Int?\n public var completed:Int?\n public var retries:Int?\n public var failed:Int?\n public var cancelled:Int?\n\n required public init(){}\n}\n\npublic class HourSummary : Codable\n{\n public var hour:String?\n public var total:Int?\n public var completed:Int?\n public var failed:Int?\n public var cancelled:Int?\n\n required public init(){}\n}\n\npublic class WorkerStats : Codable\n{\n public var name:String?\n public var queued:Int?\n public var received:Int?\n public var completed:Int?\n public var retries:Int?\n public var failed:Int?\n public var runningJob:Int?\n @TimeSpan public var runningTime:TimeInterval?\n\n required public init(){}\n}\n\npublic class RequestLogEntry : Codable\n{\n public var id:Int?\n public var traceId:String?\n public var operationName:String?\n public var dateTime:Date?\n public var statusCode:Int?\n public var statusDescription:String?\n public var httpMethod:String?\n public var absoluteUri:String?\n public var pathInfo:String?\n // @StringLength(Int32.max)\n public var requestBody:String?\n\n public var requestDto:String?\n public var userAuthId:String?\n public var sessionId:String?\n public var ipAddress:String?\n public var forwardedFor:String?\n public var referer:String?\n public var headers:[String:String]?\n public var formData:[String:String]?\n public var items:[String:String]?\n public var responseHeaders:[String:String]?\n public var session:String?\n public var responseDto:String?\n public var errorResponse:String?\n public var exceptionSource:String?\n public var exceptionData:[String:String]?\n @TimeSpan public var requestDuration:TimeInterval?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AnalyticsLogInfo : Codable\n{\n // @DataMember(Order=1)\n public var id:Int?\n\n // @DataMember(Order=2)\n public var dateTime:Date?\n\n // @DataMember(Order=3)\n public var browser:String?\n\n // @DataMember(Order=4)\n public var device:String?\n\n // @DataMember(Order=5)\n public var bot:String?\n\n // @DataMember(Order=6)\n public var op:String?\n\n // @DataMember(Order=7)\n public var userId:String?\n\n // @DataMember(Order=8)\n public var userName:String?\n\n // @DataMember(Order=9)\n public var apiKey:String?\n\n // @DataMember(Order=10)\n public var ip:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class AnalyticsReports : Codable\n{\n // @DataMember(Order=1)\n public var id:Int?\n\n // @DataMember(Order=2)\n public var created:Date?\n\n // @DataMember(Order=3)\n public var version:Double?\n\n // @DataMember(Order=4)\n public var apis:[String:RequestSummary]?\n\n // @DataMember(Order=5)\n public var users:[String:RequestSummary]?\n\n // @DataMember(Order=6)\n public var tags:[String:RequestSummary]?\n\n // @DataMember(Order=7)\n public var status:[String:RequestSummary]?\n\n // @DataMember(Order=8)\n public var days:[String:RequestSummary]?\n\n // @DataMember(Order=9)\n public var apiKeys:[String:RequestSummary]?\n\n // @DataMember(Order=10)\n public var ips:[String:RequestSummary]?\n\n // @DataMember(Order=11)\n public var browsers:[String:RequestSummary]?\n\n // @DataMember(Order=12)\n public var devices:[String:RequestSummary]?\n\n // @DataMember(Order=13)\n public var bots:[String:RequestSummary]?\n\n // @DataMember(Order=14)\n public var durations:[String:Int]?\n\n required public init(){}\n}\n\npublic class BackgroundJobBase : Codable\n{\n public var id:Int?\n public var parentId:Int?\n public var refId:String?\n public var worker:String?\n public var tag:String?\n public var batchId:String?\n public var callback:String?\n public var dependsOn:Int?\n public var runAfter:Date?\n public var createdDate:Date?\n public var createdBy:String?\n public var requestId:String?\n public var requestType:String?\n public var command:String?\n public var request:String?\n public var requestBody:String?\n public var userId:String?\n public var response:String?\n public var responseBody:String?\n public var state:BackgroundJobState?\n public var startedDate:Date?\n public var completedDate:Date?\n public var notifiedDate:Date?\n public var retryLimit:Int?\n public var attempts:Int?\n public var durationMs:Int?\n public var timeoutSecs:Int?\n public var progress:Double?\n public var status:String?\n public var logs:String?\n public var lastActivityDate:Date?\n public var replyTo:String?\n public var errorCode:String?\n public var error:ResponseStatus?\n public var args:[String:String]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class BackgroundJobOptions : Codable\n{\n public var refId:String?\n public var parentId:Int?\n public var worker:String?\n public var runAfter:Date?\n public var callback:String?\n public var dependsOn:Int?\n public var userId:String?\n public var retryLimit:Int?\n public var replyTo:String?\n public var tag:String?\n public var batchId:String?\n public var createdBy:String?\n public var timeoutSecs:Int?\n @TimeSpan public var timeout:TimeInterval?\n public var args:[String:String]?\n public var runCommand:Bool?\n\n required public init(){}\n}\n\npublic class ValidateRule : Codable\n{\n public var validator:String?\n public var condition:String?\n public var errorCode:String?\n public var message:String?\n\n required public init(){}\n}\n\npublic class ImageInfo : Codable\n{\n public var svg:String?\n public var uri:String?\n public var alt:String?\n public var cls:String?\n\n required public init(){}\n}\n\npublic class LinkInfo : Codable\n{\n public var id:String?\n public var href:String?\n public var label:String?\n public var icon:ImageInfo?\n public var show:String?\n public var hide:String?\n\n required public init(){}\n}\n\npublic class ThemeInfo : Codable\n{\n public var form:String?\n public var modelIcon:ImageInfo?\n\n required public init(){}\n}\n\npublic class LocodeUi : Codable\n{\n public var css:ApiCss?\n public var tags:AppTags?\n public var maxFieldLength:Int?\n public var maxNestedFields:Int?\n public var maxNestedFieldLength:Int?\n\n required public init(){}\n}\n\npublic class ExplorerUi : Codable\n{\n public var css:ApiCss?\n public var tags:AppTags?\n\n required public init(){}\n}\n\npublic class AdminUi : Codable\n{\n public var css:ApiCss?\n\n required public init(){}\n}\n\npublic class ApiFormat : Codable\n{\n public var locale:String?\n public var assumeUtc:Bool?\n public var number:FormatInfo?\n public var date:FormatInfo?\n\n required public init(){}\n}\n\npublic class AuthInfo : Codable\n{\n public var hasAuthSecret:Bool?\n public var hasAuthRepository:Bool?\n public var includesRoles:Bool?\n public var includesOAuthTokens:Bool?\n public var htmlRedirect:String?\n public var authProviders:[MetaAuthProvider]?\n public var identityAuth:IdentityAuthInfo?\n public var roleLinks:[String:[LinkInfo]]?\n public var serviceRoutes:[String:[String]]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class ApiKeyInfo : Codable\n{\n public var label:String?\n public var httpHeader:String?\n public var scopes:[String]?\n public var features:[String]?\n public var requestTypes:[String]?\n public var expiresIn:[KeyValuePair<String,String>]?\n public var hide:[String]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class CommandsInfo : Codable\n{\n public var commands:[CommandInfo]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class AutoQueryInfo : Codable\n{\n public var maxLimit:Int?\n public var untypedQueries:Bool?\n public var rawSqlFilters:Bool?\n public var autoQueryViewer:Bool?\n public var async:Bool?\n public var orderByPrimaryKey:Bool?\n public var crudEvents:Bool?\n public var crudEventsServices:Bool?\n public var accessRole:String?\n public var namedConnection:String?\n public var viewerConventions:[AutoQueryConvention]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class ValidationInfo : Codable\n{\n public var hasValidationSource:Bool?\n public var hasValidationSourceAdmin:Bool?\n public var serviceRoutes:[String:[String]]?\n public var typeValidators:[ScriptMethodType]?\n public var propertyValidators:[ScriptMethodType]?\n public var accessRole:String?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class SharpPagesInfo : Codable\n{\n public var apiPath:String?\n public var scriptAdminRole:String?\n public var metadataDebugAdminRole:String?\n public var metadataDebug:Bool?\n public var spaFallback:Bool?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class RequestLogsInfo : Codable\n{\n public var accessRole:String?\n public var requestLogger:String?\n public var defaultLimit:Int?\n public var serviceRoutes:[String:[String]]?\n public var analytics:RequestLogsAnalytics?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class ProfilingInfo : Codable\n{\n public var accessRole:String?\n public var defaultLimit:Int?\n public var summaryFields:[String]?\n public var tagLabel:String?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class FilesUploadInfo : Codable\n{\n public var basePath:String?\n public var locations:[FilesUploadLocation]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class AdminUsersInfo : Codable\n{\n public var accessRole:String?\n public var enabled:[String]?\n public var userAuth:MetadataType?\n public var allRoles:[String]?\n public var allPermissions:[String]?\n public var queryUserAuthProperties:[String]?\n public var queryMediaRules:[MediaRule]?\n public var formLayout:[InputInfo]?\n public var css:ApiCss?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class AdminIdentityUsersInfo : Codable\n{\n public var accessRole:String?\n public var enabled:[String]?\n public var identityUser:MetadataType?\n public var allRoles:[String]?\n public var allPermissions:[String]?\n public var queryIdentityUserProperties:[String]?\n public var queryMediaRules:[MediaRule]?\n public var formLayout:[InputInfo]?\n public var css:ApiCss?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class AdminRedisInfo : Codable\n{\n public var queryLimit:Int?\n public var databases:[Int]?\n public var modifiableConnection:Bool?\n public var endpoint:RedisEndpointInfo?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class AdminDatabaseInfo : Codable\n{\n public var queryLimit:Int?\n public var databases:[DatabaseInfo]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class MetadataTypesConfig : Codable\n{\n public var baseUrl:String?\n public var usePath:String?\n public var makePartial:Bool?\n public var makeVirtual:Bool?\n public var makeInternal:Bool?\n public var baseClass:String?\n public var package:String?\n public var addReturnMarker:Bool?\n public var addDescriptionAsComments:Bool?\n public var addDocAnnotations:Bool?\n public var addDataContractAttributes:Bool?\n public var addIndexesToDataMembers:Bool?\n public var addGeneratedCodeAttributes:Bool?\n public var addImplicitVersion:Int?\n public var addResponseStatus:Bool?\n public var addServiceStackTypes:Bool?\n public var addModelExtensions:Bool?\n public var addPropertyAccessors:Bool?\n public var excludeGenericBaseTypes:Bool?\n public var settersReturnThis:Bool?\n public var addNullableAnnotations:Bool?\n public var makePropertiesOptional:Bool?\n public var exportAsTypes:Bool?\n public var excludeImplementedInterfaces:Bool?\n public var addDefaultXmlNamespace:String?\n public var makeDataContractsExtensible:Bool?\n public var initializeCollections:Bool?\n public var addNamespaces:[String]?\n public var defaultNamespaces:[String]?\n public var defaultImports:[String]?\n public var includeTypes:[String]?\n public var excludeTypes:[String]?\n public var exportTags:[String]?\n public var treatTypesAsStrings:[String]?\n public var exportValueTypes:Bool?\n public var globalNamespace:String?\n public var excludeNamespace:Bool?\n public var dataClass:String?\n public var dataClassJson:String?\n public var ignoreTypes:[String]?\n public var exportTypes:[String]?\n public var exportAttributes:[String]?\n public var ignoreTypesInNamespaces:[String]?\n\n required public init(){}\n}\n\npublic class MetadataType : Codable\n{\n public var name:String?\n public var namespace:String?\n public var genericArgs:[String]?\n public var inherits:MetadataTypeName?\n public var implements:[MetadataTypeName]?\n public var displayType:String?\n public var Description:String?\n public var notes:String?\n public var icon:ImageInfo?\n public var isNested:Bool?\n public var isEnum:Bool?\n public var isEnumInt:Bool?\n public var isInterface:Bool?\n public var isAbstract:Bool?\n public var isGenericTypeDef:Bool?\n public var dataContract:MetadataDataContract?\n public var properties:[MetadataPropertyType]?\n public var attributes:[MetadataAttribute]?\n public var innerTypes:[MetadataTypeName]?\n public var enumNames:[String]?\n public var enumValues:[String]?\n public var enumMemberValues:[String]?\n public var enumDescriptions:[String]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class MetadataOperationType : Codable\n{\n public var request:MetadataType?\n public var response:MetadataType?\n public var actions:[String]?\n public var returnsVoid:Bool?\n public var method:String?\n public var returnType:MetadataTypeName?\n public var routes:[MetadataRoute]?\n public var dataModel:MetadataTypeName?\n public var viewModel:MetadataTypeName?\n public var requiresAuth:Bool?\n public var requiresApiKey:Bool?\n public var requiredRoles:[String]?\n public var requiresAnyRole:[String]?\n public var requiredPermissions:[String]?\n public var requiresAnyPermission:[String]?\n public var tags:[String]?\n public var ui:ApiUiInfo?\n\n required public init(){}\n}\n\npublic class MetadataDataMember : Codable\n{\n public var name:String?\n public var order:Int?\n public var isRequired:Bool?\n public var emitDefaultValue:Bool?\n\n required public init(){}\n}\n\npublic class MetadataAttribute : Codable\n{\n public var name:String?\n public var constructorArgs:[MetadataPropertyType]?\n public var args:[MetadataPropertyType]?\n\n required public init(){}\n}\n\npublic class InputInfo : Codable\n{\n public var id:String?\n public var name:String?\n public var type:String?\n public var value:String?\n public var placeholder:String?\n public var help:String?\n public var label:String?\n public var title:String?\n public var size:String?\n public var pattern:String?\n public var readOnly:Bool?\n public var required:Bool?\n public var disabled:Bool?\n public var autocomplete:String?\n public var autofocus:String?\n public var min:String?\n public var max:String?\n public var step:String?\n public var minLength:Int?\n public var maxLength:Int?\n public var accept:String?\n public var capture:String?\n public var multiple:Bool?\n public var allowableValues:[String]?\n public var allowableEntries:[KeyValuePair<String, String>]?\n public var options:String?\n public var ignore:Bool?\n public var css:FieldCss?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class FormatInfo : Codable\n{\n public var method:String?\n public var options:String?\n public var locale:String?\n\n required public init(){}\n}\n\npublic class RefInfo : Codable\n{\n public var model:String?\n public var selfId:String?\n public var refId:String?\n public var refLabel:String?\n public var queryApi:String?\n\n required public init(){}\n}\n\n// @DataContract\npublic class RequestSummary : Codable\n{\n // @DataMember(Order=1)\n public var name:String?\n\n // @DataMember(Order=2)\n public var totalRequests:Int?\n\n // @DataMember(Order=3)\n public var totalRequestLength:Int?\n\n // @DataMember(Order=4)\n public var minRequestLength:Int?\n\n // @DataMember(Order=5)\n public var maxRequestLength:Int?\n\n // @DataMember(Order=6)\n public var totalDuration:Double?\n\n // @DataMember(Order=7)\n public var minDuration:Double?\n\n // @DataMember(Order=8)\n public var maxDuration:Double?\n\n // @DataMember(Order=9)\n public var status:[Int:Int]?\n\n // @DataMember(Order=10)\n public var durations:[String:Int]?\n\n // @DataMember(Order=11)\n public var apis:[String:Int]?\n\n // @DataMember(Order=12)\n public var users:[String:Int]?\n\n // @DataMember(Order=13)\n public var ips:[String:Int]?\n\n // @DataMember(Order=14)\n public var apiKeys:[String:Int]?\n\n required public init(){}\n}\n\npublic class ApiCss : Codable\n{\n public var form:String?\n public var fieldset:String?\n public var field:String?\n\n required public init(){}\n}\n\npublic class AppTags : Codable\n{\n public var `default`:String?\n public var other:String?\n\n required public init(){}\n}\n\npublic class MetaAuthProvider : Codable\n{\n public var name:String?\n public var label:String?\n public var type:String?\n public var navItem:NavItem?\n public var icon:ImageInfo?\n public var formLayout:[InputInfo]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class IdentityAuthInfo : Codable\n{\n public var hasRefreshToken:Bool?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class KeyValuePair<TKey : Codable, TValue : Codable> : Codable\n{\n public var key:TKey?\n public var value:TValue?\n\n required public init(){}\n}\n\npublic class CommandInfo : Codable\n{\n public var name:String?\n public var tag:String?\n public var request:MetadataType?\n public var response:MetadataType?\n\n required public init(){}\n}\n\npublic class AutoQueryConvention : Codable\n{\n public var name:String?\n public var value:String?\n public var types:String?\n public var valueType:String?\n\n required public init(){}\n}\n\npublic class ScriptMethodType : Codable\n{\n public var name:String?\n public var paramNames:[String]?\n public var paramTypes:[String]?\n public var returnType:String?\n\n required public init(){}\n}\n\npublic class RequestLogsAnalytics : Codable\n{\n public var months:[String]?\n public var tabs:[String:String]?\n public var disableAnalytics:Bool?\n public var disableUserAnalytics:Bool?\n public var disableApiKeyAnalytics:Bool?\n\n required public init(){}\n}\n\npublic class FilesUploadLocation : Codable\n{\n public var name:String?\n public var readAccessRole:String?\n public var writeAccessRole:String?\n public var allowExtensions:[String]?\n public var allowOperations:String?\n public var maxFileCount:Int?\n public var minFileBytes:Int?\n public var maxFileBytes:Int?\n\n required public init(){}\n}\n\npublic class MediaRule : Codable\n{\n public var size:String?\n public var rule:String?\n public var applyTo:[String]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class DatabaseInfo : Codable\n{\n public var alias:String?\n public var name:String?\n public var schemas:[SchemaInfo]?\n\n required public init(){}\n}\n\npublic class MetadataTypeName : Codable\n{\n public var name:String?\n public var namespace:String?\n public var genericArgs:[String]?\n\n required public init(){}\n}\n\npublic class MetadataDataContract : Codable\n{\n public var name:String?\n public var namespace:String?\n\n required public init(){}\n}\n\npublic class MetadataRoute : Codable\n{\n public var path:String?\n public var verbs:String?\n public var notes:String?\n public var summary:String?\n\n required public init(){}\n}\n\npublic class ApiUiInfo : Codable\n{\n public var locodeCss:ApiCss?\n public var explorerCss:ApiCss?\n public var formLayout:[InputInfo]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class FieldCss : Codable\n{\n public var field:String?\n public var input:String?\n public var label:String?\n\n required public init(){}\n}\n\npublic class NavItem : Codable\n{\n public var label:String?\n public var href:String?\n public var exact:Bool?\n public var id:String?\n public var className:String?\n public var iconClass:String?\n public var iconSrc:String?\n public var show:String?\n public var hide:String?\n public var children:[NavItem]?\n public var meta:[String:String]?\n\n required public init(){}\n}\n\npublic class SchemaInfo : Codable\n{\n public var alias:String?\n public var name:String?\n public var tables:[String]?\n\n required public init(){}\n}\n\n\n | dataset_sample\swift\ServiceStack_ServiceStack\ServiceStack\tests\NorthwindAuto\wwwroot\dtos\dtos.swift | dtos.swift | Swift | 66,815 | 0.75 | 0.100293 | 0.149814 | react-lib | 50 | 2024-01-15T12:10:40.279517 | BSD-3-Clause | true | 378d42b2cc245895361df5843fb901c8 |
//===--- CreateObjects.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This is a simple test that creates thousands of C++ objects and does nothing\n// with them.\n\nimport TestsUtils\nimport CxxCreateObjects\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CreateObjects",\n runFunction: run_CreateObjects,\n tags: [.validation, .bridging, .cxxInterop])\n]\n\n@inline(never)\npublic func run_CreateObjects(_ n: Int) {\n for i in 0...(n * 10_000) {\n let x = Int32(i)\n let f = CxxLoadableIntWrapper(value: x)\n blackHole(f)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_cxx-source_CreateObjects.swift | cpp_apple_swift_benchmark_cxx-source_CreateObjects.swift | Swift | 991 | 0.95 | 0.090909 | 0.448276 | node-utils | 458 | 2024-05-09T13:57:34.199311 | GPL-3.0 | false | 24c68fed635d9d95242b0e324f816931 |
//===--- CxxSetToCollection.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2012 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This is a benchmark that tracks how quickly Swift can convert a C++ set\n// to a Swift collection.\n\nimport TestsUtils\nimport CxxStdlibPerformance\nimport Cxx\nimport CxxStdlib // FIXME(rdar://128520766): this import should be redundant\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CxxSetU32.to.Array",\n runFunction: run_CxxSetOfU32_to_Array,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeSetOnce),\n BenchmarkInfo(\n name: "CxxSetU32.to.Set",\n runFunction: run_CxxSetOfU32_to_Set,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeSetOnce),\n BenchmarkInfo(\n name: "CxxSetU32.forEach",\n runFunction: run_CxxSetOfU32_forEach,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeSetOnce),\n]\n\nfunc makeSetOnce() {\n initSet(setSize)\n}\n\nlet setSize = 1_000\n\n@inline(never)\npublic func run_CxxSetOfU32_to_Array(_ n: Int) {\n for _ in 0..<n {\n blackHole(Array(set))\n }\n}\n\n@inline(never)\npublic func run_CxxSetOfU32_to_Set(_ n: Int) {\n for _ in 0..<n {\n blackHole(Set(set))\n }\n}\n\n@inline(never)\npublic func run_CxxSetOfU32_forEach(_ n: Int) {\n for _ in 0..<n {\n set.forEach {\n blackHole($0)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_cxx-source_CxxSetToCollection.swift | cpp_apple_swift_benchmark_cxx-source_CxxSetToCollection.swift | Swift | 1,726 | 0.95 | 0.075758 | 0.224138 | awesome-app | 876 | 2023-11-03T13:23:31.532531 | BSD-3-Clause | false | 56d232deed7302a3fa3d3293fb18a153 |
//===--- CxxStringConversion.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport CxxStdlibPerformance\nimport CxxStdlib\n\nlet cxxStringSize = 1_000_000\nlet swiftStringSize = 1_000_000\n\nvar cxxString: std.string? = nil\nvar swiftString: String? = nil\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CxxStringConversion.swift.to.cxx",\n runFunction: run_swiftToCxx,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: {\n swiftString = String(repeating: "abc012", count: swiftStringSize / 6)\n }),\n BenchmarkInfo(\n name: "CxxStringConversion.cxx.to.swift",\n runFunction: run_cxxToSwift,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: {\n cxxString = std.string()\n for i in 0..<cxxStringSize {\n let char = std.string.value_type(65 + i % 10) // latin letters A-J\n cxxString!.push_back(char)\n }\n }),\n]\n\n@inline(never)\npublic func run_swiftToCxx(_ n: Int) {\n let str = swiftString!\n for _ in 0..<n {\n let x = std.string(str)\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_cxxToSwift(_ n: Int) {\n let str = cxxString!\n for _ in 0..<n {\n let x = String(str)\n blackHole(x)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_cxx-source_CxxStringConversion.swift | cpp_apple_swift_benchmark_cxx-source_CxxStringConversion.swift | Swift | 1,642 | 0.95 | 0.083333 | 0.203704 | awesome-app | 398 | 2024-03-25T13:05:57.849403 | MIT | false | a19d539877d58c5a64a52e252598efc0 |
//===--- CxxVectorSum.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2012 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This is a benchmark that tracks how quickly Swift can sum up a C++ vector\n// as compared to the C++ implementation of such sum.\n\nimport TestsUtils\nimport CxxStdlibPerformance\nimport Cxx\nimport CxxStdlib // FIXME(rdar://128520766): this import should be redundant\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CxxVecU32.sum.Cxx.rangedForLoop",\n runFunction: run_CxxVectorOfU32_Sum_Cxx_RangedForLoop,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeVectorOnce),\n BenchmarkInfo(\n name: "CxxVecU32.sum.Swift.forInLoop",\n runFunction: run_CxxVectorOfU32_Sum_Swift_ForInLoop,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeVectorOnce),\n BenchmarkInfo(\n name: "CxxVecU32.sum.Swift.iteratorLoop",\n runFunction: run_CxxVectorOfU32_Sum_Swift_RawIteratorLoop,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeVectorOnce),\n BenchmarkInfo(\n name: "CxxVecU32.sum.Swift.subscriptLoop",\n runFunction: run_CxxVectorOfU32_Sum_Swift_IndexAndSubscriptLoop,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeVectorOnce),\n BenchmarkInfo(\n name: "CxxVecU32.sum.Swift.reduce",\n runFunction: run_CxxVectorOfU32_Sum_Swift_Reduce,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: makeVectorOnce)\n]\n\nfunc makeVectorOnce() {\n initVector(vectorSize)\n}\n\n// FIXME: compare CxxVectorOfU32SumInCxx to CxxVectorOfU32SumInSwift and\n// establish an expected threshold of performance, which when exceeded should\n// fail the benchmark.\n\n// FIXME: Bump up to 50k and 10 once the sequence is faster.\nlet vectorSize = 25_000\nlet iterRepeatFactor = 7\n\n@inline(never)\npublic func run_CxxVectorOfU32_Sum_Cxx_RangedForLoop(_ n: Int) {\n let sum = testVector32Sum(vectorSize, n * iterRepeatFactor)\n blackHole(sum)\n}\n\n@inline(never)\npublic func run_CxxVectorOfU32_Sum_Swift_ForInLoop(_ n: Int) {\n let vectorOfU32 = makeVector32(vectorSize)\n var sum: UInt32 = 0\n for _ in 0..<(n * iterRepeatFactor) {\n for x in vectorOfU32 {\n sum = sum &+ x\n }\n }\n blackHole(sum)\n}\n\n// This function should have comparable performance to\n// `run_CxxVectorOfU32_Sum_Cxx_RangedForLoop`.\n@inline(never)\npublic func run_CxxVectorOfU32_Sum_Swift_RawIteratorLoop(_ n: Int) {\n let vectorOfU32 = makeVector32(vectorSize)\n var sum: UInt32 = 0\n for _ in 0..<(n * iterRepeatFactor) {\n var b = vectorOfU32.__beginUnsafe()\n let e = vectorOfU32.__endUnsafe()\n while b != e {\n sum = sum &+ b.pointee\n b = b.successor()\n }\n }\n blackHole(sum)\n}\n\n// Need to wait for https://github.com/apple/swift/issues/61499\n@inline(never)\npublic func run_CxxVectorOfU32_Sum_Swift_IndexAndSubscriptLoop(_ n: Int) {\n#if FIXED_61499\n let vectorOfU32 = makeVector32(vectorSize)\n var sum: UInt32 = 0\n for _ in 0..<(n * iterRepeatFactor) {\n for i in 0..<vectorOfU32.size() {\n sum = sum &+ vectorOfU32[i]\n }\n }\n blackHole(sum)\n#else\n run_CxxVectorOfU32_Sum_Swift_RawIteratorLoop(n)\n#endif\n}\n\n@inline(never)\npublic func run_CxxVectorOfU32_Sum_Swift_Reduce(_ n: Int) {\n let vectorOfU32 = makeVector32(vectorSize)\n var sum: UInt32 = 0\n for _ in 0..<(n * iterRepeatFactor) {\n sum = vectorOfU32.reduce(sum, &+)\n }\n blackHole(sum)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_cxx-source_CxxVectorSum.swift | cpp_apple_swift_benchmark_cxx-source_CxxVectorSum.swift | Swift | 3,811 | 0.95 | 0.099174 | 0.209091 | node-utils | 209 | 2025-01-12T20:57:40.811033 | GPL-3.0 | false | 8f8ddefdf618207e16ff2cb43f1b56dd |
// Subscripts.swift - Very brief description\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n// -----------------------------------------------------------------------------\n///\n/// This is a simple test that reads a non trivial C++ struct using an imported\n/// subscript thousands of times.\n///\n// -----------------------------------------------------------------------------\n\nimport TestsUtils\nimport CxxSubscripts\n\nvar vec : TwoDimensionalVector?\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "ReadAccessor",\n runFunction: run_ReadAccessor,\n tags: [.validation, .bridging, .cxxInterop],\n setUpFunction: {\n vec = initVector()\n })\n]\n\n@inline(never)\npublic func run_ReadAccessor(_ N: Int) {\n for _ in 0...N {\n for j in 0..<100 {\n let row = vec![j];\n for k in 0..<1_000 {\n let element = row[k];\n blackHole(element)\n }\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_cxx-source_ReadAccessor.swift | cpp_apple_swift_benchmark_cxx-source_ReadAccessor.swift | Swift | 1,198 | 0.95 | 0.113636 | 0.4 | node-utils | 111 | 2024-11-23T18:36:12.062194 | Apache-2.0 | false | 184655a8f3bb0cefa2d1e0c8458c56c7 |
//===--- Prims.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// The test implements Prim's algorithm for minimum spanning tree building.\n// http://en.wikipedia.org/wiki/Prim%27s_algorithm\n\n// This class implements array-based heap (priority queue).\n// It is used to store edges from nodes in spanning tree to nodes outside of it.\n// We are interested only in the edges with the smallest costs, so if there are\n// several edges pointing to the same node, we keep only one from them. Thus,\n// it is enough to record this node instead.\n// We maintain a map (node index in graph)->(node index in heap) to be able to\n// update the heap fast when we add a new node to the tree.\nimport TestsUtils\n\nclass PriorityQueue {\n final var heap: Array<EdgeCost>\n final var graphIndexToHeapIndexMap: Array<Int?>\n\n // Create heap for graph with NUM nodes.\n init(Num: Int) {\n heap = Array<EdgeCost>()\n graphIndexToHeapIndexMap = Array<Int?>(repeating:nil, count: Num)\n }\n\n func isEmpty() -> Bool {\n return heap.isEmpty\n }\n\n // Insert element N to heap, maintaining the heap property.\n func insert(_ n: EdgeCost) {\n let ind: Int = heap.count\n heap.append(n)\n graphIndexToHeapIndexMap[n.to] = heap.count - 1\n bubbleUp(ind)\n }\n\n // Insert element N if in's not in the heap, or update its cost if the new\n // value is less than the existing one.\n func insertOrUpdate(_ n: EdgeCost) {\n let id = n.to\n let c = n.cost\n if let ind = graphIndexToHeapIndexMap[id] {\n if heap[ind].cost <= c {\n // We don't need an edge with a bigger cost\n return\n }\n heap[ind].cost = c\n heap[ind].from = n.from\n bubbleUp(ind)\n } else {\n insert(n)\n }\n }\n\n // Restore heap property by moving element at index IND up.\n // This is needed after insertion, and after decreasing an element's cost.\n func bubbleUp(_ ind: Int) {\n var ind = ind\n let c = heap[ind].cost\n while (ind != 0) {\n let p = getParentIndex(ind)\n if heap[p].cost > c {\n swap(p, with: ind)\n ind = p\n } else {\n break\n }\n }\n }\n\n // Pop minimum element from heap and restore the heap property after that.\n func pop() -> EdgeCost? {\n if (heap.isEmpty) {\n return nil\n }\n swap(0, with:heap.count-1)\n let r = heap.removeLast()\n graphIndexToHeapIndexMap[r.to] = nil\n bubbleDown(0)\n return r\n }\n\n // Restore heap property by moving element at index IND down.\n // This is needed after removing an element, and after increasing an\n // element's cost.\n func bubbleDown(_ ind: Int) {\n var ind = ind\n let n = heap.count\n while (ind < n) {\n let l = getLeftChildIndex(ind)\n let r = getRightChildIndex(ind)\n if (l >= n) {\n break\n }\n var min: Int\n if (r < n && heap[r].cost < heap[l].cost) {\n min = r\n } else {\n min = l\n }\n if (heap[ind].cost <= heap[min].cost) {\n break\n }\n swap(ind, with: min)\n ind = min\n }\n }\n\n // Swaps elements I and J in the heap and correspondingly updates\n // graphIndexToHeapIndexMap.\n func swap(_ i: Int, with j : Int) {\n if (i == j) {\n return\n }\n (heap[i], heap[j]) = (heap[j], heap[i])\n let (i2, j2) = (heap[i].to, heap[j].to)\n (graphIndexToHeapIndexMap[i2], graphIndexToHeapIndexMap[j2]) =\n (graphIndexToHeapIndexMap[j2], graphIndexToHeapIndexMap[i2])\n }\n\n // Dumps the heap.\n func dump() {\n print("QUEUE")\n for nodeCost in heap {\n let to: Int = nodeCost.to\n let from: Int = nodeCost.from\n let cost: Double = nodeCost.cost\n print("(\(from)->\(to), \(cost))")\n }\n }\n\n func getLeftChildIndex(_ index : Int) -> Int {\n return index*2 + 1\n }\n func getRightChildIndex(_ index : Int) -> Int {\n return (index + 1)*2\n }\n func getParentIndex(_ childIndex : Int) -> Int {\n return (childIndex - 1)/2\n }\n}\n\nstruct GraphNode {\n var id: Int\n var adjList: Array<Int>\n\n init(i : Int) {\n id = i\n adjList = Array<Int>()\n }\n}\n\nstruct EdgeCost {\n var to: Int\n var cost: Double\n var from: Int\n}\n\nstruct Edge : Equatable {\n var start: Int\n var end: Int\n}\n\nfunc ==(lhs: Edge, rhs: Edge) -> Bool {\n return lhs.start == rhs.start && lhs.end == rhs.end\n}\n\nextension Edge : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(start)\n hasher.combine(end)\n }\n}\n\nfunc prims(_ graph : Array<GraphNode>, _ fun : (Int, Int) -> Double) -> Array<Int?> {\n var treeEdges = Array<Int?>(repeating:nil, count:graph.count)\n\n let queue = PriorityQueue(Num:graph.count)\n // Make the minimum spanning tree root its own parent for simplicity.\n queue.insert(EdgeCost(to: 0, cost: 0.0, from: 0))\n\n // Take an element with the smallest cost from the queue and add its\n // neighbors to the queue if their cost was updated\n while !queue.isEmpty() {\n // Add an edge with minimum cost to the spanning tree\n let e = queue.pop()!\n let newnode = e.to\n // Add record about the edge newnode->e.from to treeEdges\n treeEdges[newnode] = e.from\n\n // Check all adjacent nodes and add edges, ending outside the tree, to the\n // queue. If the queue already contains an edge to an adjacent node, we\n // replace existing one with the new one in case the new one costs less.\n for adjNodeIndex in graph[newnode].adjList {\n if treeEdges[adjNodeIndex] != nil {\n continue\n }\n let newcost = fun(newnode, graph[adjNodeIndex].id)\n queue.insertOrUpdate(EdgeCost(to: adjNodeIndex, cost: newcost, from: newnode))\n }\n }\n return treeEdges\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_multi-source_PrimsSplit_Prims.swift | cpp_apple_swift_benchmark_multi-source_PrimsSplit_Prims.swift | Swift | 6,011 | 0.95 | 0.117371 | 0.221053 | node-utils | 938 | 2024-09-05T22:47:28.634982 | Apache-2.0 | false | b153e09f7de660f90015c7a954024594 |
//===--- main.swift -------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "PrimsSplit",\n runFunction: run_PrimsSplit,\n tags: [.validation, .algorithm],\n legacyFactor: 5)\n]\n\n@inline(never)\npublic func run_PrimsSplit(_ n: Int) {\n for _ in 1...n {\n let nodes : [Int] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,\n 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,\n 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,\n 93, 94, 95, 96, 97, 98, 99 ]\n\n // Prim's algorithm is designed for undirected graphs.\n // Due to that, in our set all the edges are paired, i.e. for any\n // edge (start, end, C) there is also an edge (end, start, C).\n let edges : [(Int, Int, Double)] = [\n (26, 47, 921),\n (20, 25, 971),\n (92, 59, 250),\n (33, 55, 1391),\n (78, 39, 313),\n (7, 25, 637),\n (18, 19, 1817),\n (33, 41, 993),\n (64, 41, 926),\n (88, 86, 574),\n (93, 15, 1462),\n (86, 33, 1649),\n (37, 35, 841),\n (98, 51, 1160),\n (15, 30, 1125),\n (65, 78, 1052),\n (58, 12, 1273),\n (12, 17, 285),\n (45, 61, 1608),\n (75, 53, 545),\n (99, 48, 410),\n (97, 0, 1303),\n (48, 17, 1807),\n (1, 54, 1491),\n (15, 34, 807),\n (94, 98, 646),\n (12, 69, 136),\n (65, 11, 983),\n (63, 83, 1604),\n (78, 89, 1828),\n (61, 63, 845),\n (18, 36, 1626),\n (68, 52, 1324),\n (14, 50, 690),\n (3, 11, 943),\n (21, 68, 914),\n (19, 44, 1762),\n (85, 80, 270),\n (59, 92, 250),\n (86, 84, 1431),\n (19, 18, 1817),\n (52, 68, 1324),\n (16, 29, 1108),\n (36, 80, 395),\n (67, 18, 803),\n (63, 88, 1717),\n (68, 21, 914),\n (75, 82, 306),\n (49, 82, 1292),\n (73, 45, 1876),\n (89, 82, 409),\n (45, 47, 272),\n (22, 83, 597),\n (61, 12, 1791),\n (44, 68, 1229),\n (50, 51, 917),\n (14, 53, 355),\n (77, 41, 138),\n (54, 21, 1870),\n (93, 70, 1582),\n (76, 2, 1658),\n (83, 73, 1162),\n (6, 1, 482),\n (11, 65, 983),\n (81, 90, 1024),\n (19, 1, 970),\n (8, 58, 1131),\n (60, 42, 477),\n (86, 29, 258),\n (69, 59, 903),\n (34, 15, 807),\n (37, 2, 1451),\n (7, 73, 754),\n (47, 86, 184),\n (67, 17, 449),\n (18, 67, 803),\n (25, 4, 595),\n (3, 31, 1337),\n (64, 31, 1928),\n (9, 43, 237),\n (83, 63, 1604),\n (47, 45, 272),\n (86, 88, 574),\n (87, 74, 934),\n (98, 94, 646),\n (20, 1, 642),\n (26, 92, 1344),\n (18, 17, 565),\n (47, 11, 595),\n (10, 59, 1558),\n (2, 76, 1658),\n (77, 74, 1277),\n (42, 60, 477),\n (80, 36, 395),\n (35, 23, 589),\n (50, 37, 203),\n (6, 96, 481),\n (78, 65, 1052),\n (1, 52, 127),\n (65, 23, 1932),\n (46, 51, 213),\n (59, 89, 89),\n (15, 93, 1462),\n (69, 3, 1305),\n (17, 37, 1177),\n (30, 3, 193),\n (9, 15, 818),\n (75, 95, 977),\n (86, 47, 184),\n (10, 12, 1736),\n (80, 27, 1010),\n (12, 10, 1736),\n (86, 1, 1958),\n (60, 12, 1240),\n (43, 71, 683),\n (91, 65, 1519),\n (33, 86, 1649),\n (62, 26, 1773),\n (1, 13, 1187),\n (2, 10, 1018),\n (91, 29, 351),\n (69, 12, 136),\n (43, 9, 237),\n (29, 86, 258),\n (17, 48, 1807),\n (31, 64, 1928),\n (68, 61, 1936),\n (76, 38, 1724),\n (1, 6, 482),\n (53, 14, 355),\n (51, 50, 917),\n (54, 13, 815),\n (19, 29, 883),\n (35, 87, 974),\n (70, 96, 511),\n (23, 35, 589),\n (39, 69, 1588),\n (93, 73, 1093),\n (13, 73, 435),\n (5, 60, 1619),\n (42, 41, 1523),\n (66, 58, 1596),\n (1, 67, 431),\n (17, 67, 449),\n (30, 95, 906),\n (71, 43, 683),\n (5, 87, 190),\n (12, 78, 891),\n (30, 97, 402),\n (28, 17, 1131),\n (7, 97, 1356),\n (58, 66, 1596),\n (20, 37, 1294),\n (73, 76, 514),\n (54, 8, 613),\n (68, 35, 1252),\n (92, 32, 701),\n (3, 90, 652),\n (99, 46, 1576),\n (13, 54, 815),\n (20, 87, 1390),\n (36, 18, 1626),\n (51, 26, 1146),\n (2, 23, 581),\n (29, 7, 1558),\n (88, 59, 173),\n (17, 1, 1071),\n (37, 49, 1011),\n (18, 6, 696),\n (88, 33, 225),\n (58, 38, 802),\n (87, 50, 1744),\n (29, 91, 351),\n (6, 71, 1053),\n (45, 24, 1720),\n (65, 91, 1519),\n (37, 50, 203),\n (11, 3, 943),\n (72, 65, 1330),\n (45, 50, 339),\n (25, 20, 971),\n (15, 9, 818),\n (14, 54, 1353),\n (69, 95, 393),\n (8, 66, 1213),\n (52, 2, 1608),\n (50, 14, 690),\n (50, 45, 339),\n (1, 37, 1273),\n (45, 93, 1650),\n (39, 78, 313),\n (1, 86, 1958),\n (17, 28, 1131),\n (35, 33, 1667),\n (23, 2, 581),\n (51, 66, 245),\n (17, 54, 924),\n (41, 49, 1629),\n (60, 5, 1619),\n (56, 93, 1110),\n (96, 13, 461),\n (25, 7, 637),\n (11, 69, 370),\n (90, 3, 652),\n (39, 71, 1485),\n (65, 51, 1529),\n (20, 6, 1414),\n (80, 85, 270),\n (73, 83, 1162),\n (0, 97, 1303),\n (13, 33, 826),\n (29, 71, 1788),\n (33, 12, 461),\n (12, 58, 1273),\n (69, 39, 1588),\n (67, 75, 1504),\n (87, 20, 1390),\n (88, 97, 526),\n (33, 88, 225),\n (95, 69, 393),\n (2, 52, 1608),\n (5, 25, 719),\n (34, 78, 510),\n (53, 99, 1074),\n (33, 35, 1667),\n (57, 30, 361),\n (87, 58, 1574),\n (13, 90, 1030),\n (79, 74, 91),\n (4, 86, 1107),\n (64, 94, 1609),\n (11, 12, 167),\n (30, 45, 272),\n (47, 91, 561),\n (37, 17, 1177),\n (77, 49, 883),\n (88, 23, 1747),\n (70, 80, 995),\n (62, 77, 907),\n (18, 4, 371),\n (73, 93, 1093),\n (11, 47, 595),\n (44, 23, 1990),\n (20, 0, 512),\n (3, 69, 1305),\n (82, 3, 1815),\n (20, 88, 368),\n (44, 45, 364),\n (26, 51, 1146),\n (7, 65, 349),\n (71, 39, 1485),\n (56, 88, 1954),\n (94, 69, 1397),\n (12, 28, 544),\n (95, 75, 977),\n (32, 90, 789),\n (53, 1, 772),\n (54, 14, 1353),\n (49, 77, 883),\n (92, 26, 1344),\n (17, 18, 565),\n (97, 88, 526),\n (48, 80, 1203),\n (90, 32, 789),\n (71, 6, 1053),\n (87, 35, 974),\n (55, 90, 1808),\n (12, 61, 1791),\n (1, 96, 328),\n (63, 10, 1681),\n (76, 34, 871),\n (41, 64, 926),\n (42, 97, 482),\n (25, 5, 719),\n (23, 65, 1932),\n (54, 1, 1491),\n (28, 12, 544),\n (89, 10, 108),\n (27, 33, 143),\n (67, 1, 431),\n (32, 45, 52),\n (79, 33, 1871),\n (6, 55, 717),\n (10, 58, 459),\n (67, 39, 393),\n (10, 4, 1808),\n (96, 6, 481),\n (1, 19, 970),\n (97, 7, 1356),\n (29, 16, 1108),\n (1, 53, 772),\n (30, 15, 1125),\n (4, 6, 634),\n (6, 20, 1414),\n (88, 56, 1954),\n (87, 64, 1950),\n (34, 76, 871),\n (17, 12, 285),\n (55, 59, 321),\n (61, 68, 1936),\n (50, 87, 1744),\n (84, 44, 952),\n (41, 33, 993),\n (59, 18, 1352),\n (33, 27, 143),\n (38, 32, 1210),\n (55, 70, 1264),\n (38, 58, 802),\n (1, 20, 642),\n (73, 13, 435),\n (80, 48, 1203),\n (94, 64, 1609),\n (38, 28, 414),\n (73, 23, 1113),\n (78, 12, 891),\n (26, 62, 1773),\n (87, 43, 579),\n (53, 6, 95),\n (59, 95, 285),\n (88, 63, 1717),\n (17, 5, 633),\n (66, 8, 1213),\n (41, 42, 1523),\n (83, 22, 597),\n (95, 30, 906),\n (51, 65, 1529),\n (17, 49, 1727),\n (64, 87, 1950),\n (86, 4, 1107),\n (37, 98, 1102),\n (32, 92, 701),\n (60, 94, 198),\n (73, 98, 1749),\n (4, 18, 371),\n (96, 70, 511),\n (7, 29, 1558),\n (35, 37, 841),\n (27, 64, 384),\n (12, 33, 461),\n (36, 38, 529),\n (69, 16, 1183),\n (91, 47, 561),\n (85, 29, 1676),\n (3, 82, 1815),\n (69, 58, 1579),\n (93, 45, 1650),\n (97, 42, 482),\n (37, 1, 1273),\n (61, 4, 543),\n (96, 1, 328),\n (26, 0, 1993),\n (70, 64, 878),\n (3, 30, 193),\n (58, 69, 1579),\n (4, 25, 595),\n (31, 3, 1337),\n (55, 6, 717),\n (39, 67, 393),\n (78, 34, 510),\n (75, 67, 1504),\n (6, 53, 95),\n (51, 79, 175),\n (28, 91, 1040),\n (89, 78, 1828),\n (74, 93, 1587),\n (45, 32, 52),\n (10, 2, 1018),\n (49, 37, 1011),\n (63, 61, 845),\n (0, 20, 512),\n (1, 17, 1071),\n (99, 53, 1074),\n (37, 20, 1294),\n (10, 89, 108),\n (33, 92, 946),\n (23, 73, 1113),\n (23, 88, 1747),\n (49, 17, 1727),\n (88, 20, 368),\n (21, 54, 1870),\n (70, 93, 1582),\n (59, 88, 173),\n (32, 38, 1210),\n (89, 59, 89),\n (23, 44, 1990),\n (38, 76, 1724),\n (30, 57, 361),\n (94, 60, 198),\n (59, 10, 1558),\n (55, 64, 1996),\n (12, 11, 167),\n (36, 24, 1801),\n (97, 30, 402),\n (52, 1, 127),\n (58, 87, 1574),\n (54, 17, 924),\n (93, 74, 1587),\n (24, 36, 1801),\n (2, 37, 1451),\n (91, 28, 1040),\n (59, 55, 321),\n (69, 11, 370),\n (8, 54, 613),\n (29, 85, 1676),\n (44, 19, 1762),\n (74, 79, 91),\n (93, 56, 1110),\n (58, 10, 459),\n (41, 50, 1559),\n (66, 51, 245),\n (80, 19, 1838),\n (33, 79, 1871),\n (76, 73, 514),\n (98, 37, 1102),\n (45, 44, 364),\n (16, 69, 1183),\n (49, 41, 1629),\n (19, 80, 1838),\n (71, 57, 500),\n (6, 4, 634),\n (64, 27, 384),\n (84, 86, 1431),\n (5, 17, 633),\n (96, 88, 334),\n (87, 5, 190),\n (70, 21, 1619),\n (55, 33, 1391),\n (10, 63, 1681),\n (11, 62, 1339),\n (33, 13, 826),\n (64, 70, 878),\n (65, 72, 1330),\n (70, 55, 1264),\n (64, 55, 1996),\n (50, 41, 1559),\n (46, 99, 1576),\n (88, 96, 334),\n (51, 20, 868),\n (73, 7, 754),\n (80, 70, 995),\n (44, 84, 952),\n (29, 19, 883),\n (59, 69, 903),\n (57, 53, 1575),\n (90, 13, 1030),\n (28, 38, 414),\n (12, 60, 1240),\n (85, 58, 573),\n (90, 55, 1808),\n (4, 10, 1808),\n (68, 44, 1229),\n (92, 33, 946),\n (90, 81, 1024),\n (53, 75, 545),\n (45, 30, 272),\n (41, 77, 138),\n (21, 70, 1619),\n (45, 73, 1876),\n (35, 68, 1252),\n (13, 96, 461),\n (53, 57, 1575),\n (82, 89, 409),\n (28, 61, 449),\n (58, 61, 78),\n (27, 80, 1010),\n (61, 58, 78),\n (38, 36, 529),\n (80, 30, 397),\n (18, 59, 1352),\n (62, 11, 1339),\n (95, 59, 285),\n (51, 98, 1160),\n (6, 18, 696),\n (30, 80, 397),\n (69, 94, 1397),\n (58, 85, 573),\n (48, 99, 410),\n (51, 46, 213),\n (57, 71, 500),\n (91, 30, 104),\n (65, 7, 349),\n (79, 51, 175),\n (47, 26, 921),\n (4, 61, 543),\n (98, 73, 1749),\n (74, 77, 1277),\n (61, 28, 449),\n (58, 8, 1131),\n (61, 45, 1608),\n (74, 87, 934),\n (71, 29, 1788),\n (30, 91, 104),\n (13, 1, 1187),\n (0, 26, 1993),\n (82, 49, 1292),\n (43, 87, 579),\n (24, 45, 1720),\n (20, 51, 868),\n (77, 62, 907),\n (82, 75, 306),\n ]\n\n // Prepare graph and edge->cost map\n var graph = Array<GraphNode>()\n for n in nodes {\n graph.append(GraphNode(i: n))\n }\n var map = Dictionary<Edge, Double>()\n for tup in edges {\n map[Edge(start: tup.0, end: tup.1)] = tup.2\n graph[tup.0].adjList.append(tup.1)\n }\n\n // Find spanning tree\n let treeEdges = prims(graph, { (start: Int, end: Int) in\n return map[Edge(start: start, end: end)]!\n })\n\n // Compute its cost in order to check results\n var cost = 0.0\n for i in 1..<treeEdges.count {\n if let n = treeEdges[i] { cost += map[Edge(start: n, end: i)]! }\n }\n check(Int(cost) == 49324)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_multi-source_PrimsSplit_Prims_main.swift | cpp_apple_swift_benchmark_multi-source_PrimsSplit_Prims_main.swift | Swift | 12,749 | 0.95 | 0.015986 | 0.030576 | node-utils | 388 | 2024-09-10T23:11:20.456840 | BSD-3-Clause | false | f701754c9f209f5b7cb168181f48d9fd |
// swift-tools-version:5.9\n\nimport PackageDescription\nimport Foundation\n\nvar unsupportedTests: Set<String> = []\n#if !os(macOS) && !os(iOS) && !os(watchOS) && !os(tvOS)\nunsupportedTests.insert("ObjectiveCNoBridgingStubs")\nunsupportedTests.insert("ObjectiveCBridging")\nunsupportedTests.insert("ObjectiveCBridgingStubs")\n#endif\n\nunsupportedTests.insert("SimpleArraySpecialization")\n\n//===---\n// Single Source Libraries\n//\n\n/// Return the source files in subDirectory that we will translate into\n/// libraries. Each source library will be compiled as its own module.\nfunc getSingleSourceLibraries(subDirectory: String) -> [String] {\n let f = FileManager.`default`\n let dirURL = URL(fileURLWithPath: subDirectory)\n let fileURLs = try! f.contentsOfDirectory(at: dirURL,\n includingPropertiesForKeys: nil)\n return fileURLs.compactMap { (path: URL) -> String? in\n guard let lastDot = path.lastPathComponent.lastIndex(of: ".") else {\n return nil\n }\n let ext = String(path.lastPathComponent.suffix(from: lastDot))\n guard ext == ".swift" else { return nil }\n\n let name = String(path.lastPathComponent.prefix(upTo: lastDot))\n\n // Test names must have a single component.\n if name.contains(".") { return nil }\n\n if unsupportedTests.contains(name) {\n // We do not support this test.\n return nil\n }\n\n return name\n }\n}\n\nvar singleSourceLibraryDirs: [String] = []\nsingleSourceLibraryDirs.append("single-source")\n\nvar singleSourceLibraries: [String] = singleSourceLibraryDirs.flatMap {\n getSingleSourceLibraries(subDirectory: $0)\n}\n\nvar cxxSingleSourceLibraryDirs: [String] = ["cxx-source"]\nvar cxxSingleSourceLibraries: [String] = cxxSingleSourceLibraryDirs.flatMap {\n getSingleSourceLibraries(subDirectory: $0)\n}\n\n//===---\n// Multi Source Libraries\n//\n\nfunc getMultiSourceLibraries(subDirectory: String) -> [(String, String)] {\n let f = FileManager.`default`\n let dirURL = URL(string: subDirectory)!\n let subDirs = try! f.contentsOfDirectory(at: dirURL, includingPropertiesForKeys: nil)\n return subDirs.map { (subDirectory, $0.lastPathComponent) }\n}\n\nvar multiSourceLibraryDirs: [String] = []\nmultiSourceLibraryDirs.append("multi-source")\n\nvar multiSourceLibraries: [(parentSubDir: String, name: String)] = multiSourceLibraryDirs.flatMap {\n getMultiSourceLibraries(subDirectory: $0)\n}\n\n//===---\n// Products\n//\n\nvar products: [Product] = []\nproducts.append(.library(name: "TestsUtils", type: .static, targets: ["TestsUtils"]))\n//products.append(.library(name: "SimpleArray", type: .static, targets: ["SimpleArray"]))\nproducts.append(.library(name: "DriverUtils", type: .static, targets: ["DriverUtils"]))\n#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)\nproducts.append(.library(name: "ObjectiveCTests", type: .static, targets: ["ObjectiveCTests"]))\n#endif\nproducts.append(.executable(name: "SwiftBench", targets: ["SwiftBench"]))\n\nproducts += singleSourceLibraries.map { .library(name: $0, type: .static, targets: [$0]) }\nproducts += cxxSingleSourceLibraries.map { .library(name: $0, type: .static, targets: [$0]) }\nproducts += multiSourceLibraries.map {\n return .library(name: $0.name, type: .static, targets: [$0.name])\n}\n\n//===---\n// Targets\n//\n\nvar targets: [Target] = []\ntargets.append(.target(name: "TestsUtils", path: "utils", sources: ["TestsUtils.swift"]))\n// targets.append(.target(\n// name: "SimpleArray",\n// path: "utils",\n// sources: ["SimpleArray.swift"],\n// swiftSettings: [.unsafeFlags(["-Xfrontend",\n// "-enable-experimental-feature",\n// "LayoutPrespecialization"])]))\ntargets.append(.systemLibrary(name: "LibProc", path: "utils/LibProc"))\ntargets.append(\n .target(name: "DriverUtils",\n dependencies: [.target(name: "TestsUtils"), "LibProc"],\n path: "utils",\n sources: ["DriverUtils.swift", "ArgParse.swift"]))\n\nvar swiftBenchDeps: [Target.Dependency] = [.target(name: "TestsUtils")]\n#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)\nswiftBenchDeps.append(.target(name: "ObjectiveCTests"))\n#endif\nswiftBenchDeps.append(.target(name: "DriverUtils"))\nswiftBenchDeps += singleSourceLibraries.map { .target(name: $0) }\nswiftBenchDeps += cxxSingleSourceLibraries.map { .target(name: $0) }\nswiftBenchDeps += multiSourceLibraries.map { .target(name: $0.name) }\n\ntargets.append(\n .target(name: "SwiftBench",\n dependencies: swiftBenchDeps,\n path: "utils",\n sources: ["main.swift"],\n swiftSettings: [.interoperabilityMode(.Cxx),\n .unsafeFlags(["-I",\n "utils/CxxTests"])]))\n\n#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)\ntargets.append(\n .target(name: "ObjectiveCTests",\n path: "utils/ObjectiveCTests",\n publicHeadersPath: "."))\n#endif\n\nvar singleSourceDeps: [Target.Dependency] = [.target(name: "TestsUtils"), /* .target(name: "SimpleArray") */]\n#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)\nsingleSourceDeps.append(.target(name: "ObjectiveCTests"))\n#endif\n\ntargets += singleSourceLibraries.map { name in\n if name == "ObjectiveCNoBridgingStubs" {\n return .target(\n name: name,\n dependencies: singleSourceDeps,\n path: "single-source",\n sources: ["\(name).swift"],\n swiftSettings: [.unsafeFlags(["-Xfrontend",\n "-disable-swift-bridge-attr"])])\n }\n return .target(name: name,\n dependencies: singleSourceDeps,\n path: "single-source",\n sources: ["\(name).swift"])\n}\n\ntargets += cxxSingleSourceLibraries.map { name in\n return .target(\n name: name,\n dependencies: singleSourceDeps,\n path: "cxx-source",\n sources: ["\(name).swift"],\n swiftSettings: [.interoperabilityMode(.Cxx),\n .unsafeFlags(["-I",\n "utils/CxxTests",\n // FIXME: https://github.com/apple/swift/issues/61453\n "-Xfrontend", "-validate-tbd-against-ir=none"])])\n}\n\ntargets += multiSourceLibraries.map { lib in\n return .target(\n name: lib.name,\n dependencies: [\n .target(name: "TestsUtils")\n ],\n path: lib.parentSubDir)\n}\n\n//===---\n// Top Level Definition\n//\n\nlet p = Package(\n name: "swiftbench",\n products: products,\n targets: targets,\n swiftLanguageVersions: [.v4],\n cxxLanguageStandard: .cxx20\n)\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_Package.swift | cpp_apple_swift_benchmark_Package.swift | Swift | 6,356 | 0.95 | 0.051546 | 0.237805 | vue-tools | 783 | 2024-04-28T10:35:33.231316 | MIT | false | 44302418c38b17ab929806383c1ad14a |
//===--- Ackermann.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test is based on test Ackermann from utils/benchmark, with modifications\n// for performance measuring.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Ackermann2",\n runFunction: run_Ackermann,\n tags: [.algorithm])\n\nfunc _ackermann(_ m: Int, _ n : Int) -> Int {\n if (m == 0) { return n + 1 }\n if (n == 0) { return _ackermann(m - 1, 1) }\n return _ackermann(m - 1, _ackermann(m, n - 1))\n}\n\n@inline(never)\nfunc ackermann(_ m: Int, _ n : Int) -> Int {\n // This if prevents optimizer from computing return value of Ackermann(3,9)\n // at compile time.\n if getFalse() { return 0 }\n if (m == 0) { return n + 1 }\n if (n == 0) { return _ackermann(m - 1, 1) }\n return _ackermann(m - 1, _ackermann(m, n - 1))\n}\n\nlet ref_result = [5, 13, 29, 61, 125, 253, 509, 1021, 2045, 4093, 8189, 16381, 32765, 65533, 131069]\n\n@inline(never)\npublic func run_Ackermann(_ N: Int) {\n let (m, n) = (3, 6)\n var result = 0\n for _ in 1...N {\n result = ackermann(m, n)\n if result != ref_result[n] {\n break\n }\n }\n check(result == ref_result[n])\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Ackermann.swift | cpp_apple_swift_benchmark_single-source_Ackermann.swift | Swift | 1,597 | 0.95 | 0.211538 | 0.326087 | vue-tools | 103 | 2024-10-17T01:28:00.806433 | BSD-3-Clause | false | 9b77aca5e5cc099f4b884932a2cdb9e2 |
//===--- AngryPhonebook.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test is based on single-source/Phonebook, with\n// to test uppercase and lowercase ASCII string fast paths.\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.validation, .api, .String]\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "AngryPhonebook",\n runFunction: run_AngryPhonebook,\n tags: t,\n legacyFactor: 7),\n\n // Small String Workloads\n BenchmarkInfo(\n name: "AngryPhonebook.ASCII2.Small",\n runFunction: { angryPhonebook($0*10, ascii) },\n tags: t,\n setUpFunction: { blackHole(ascii) }),\n BenchmarkInfo(\n name: "AngryPhonebook.Strasse.Small",\n runFunction: { angryPhonebook($0, strasse) },\n tags: t,\n setUpFunction: { blackHole(strasse) }),\n BenchmarkInfo(\n name: "AngryPhonebook.Armenian.Small",\n runFunction: { angryPhonebook($0, armenian) },\n tags: t,\n setUpFunction: { blackHole(armenian) }),\n BenchmarkInfo(\n name: "AngryPhonebook.Cyrillic.Small",\n runFunction: { angryPhonebook($0, cyrillic) },\n tags: t,\n setUpFunction: { blackHole(cyrillic) }),\n\n // Regular String Workloads\n BenchmarkInfo(\n name: "AngryPhonebook.ASCII2",\n runFunction: { angryPhonebook($0*10, precomposed: longASCII) },\n tags: t,\n setUpFunction: { blackHole(longASCII) }),\n BenchmarkInfo(\n name: "AngryPhonebook.Strasse",\n runFunction: { angryPhonebook($0, precomposed: longStrasse) },\n tags: t,\n setUpFunction: { blackHole(longStrasse) }),\n BenchmarkInfo(\n name: "AngryPhonebook.Armenian",\n runFunction: { angryPhonebook($0, precomposed: longArmenian) },\n tags: t,\n setUpFunction: { blackHole(longArmenian) }),\n BenchmarkInfo(\n name: "AngryPhonebook.Cyrillic",\n runFunction: { angryPhonebook($0, precomposed: longCyrillic) },\n tags: t,\n setUpFunction: { blackHole(longCyrillic) })\n]\n\nlet words = [\n "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph",\n "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony",\n "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian",\n "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan",\n "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank"]\n\n@inline(never)\npublic func run_AngryPhonebook(_ n: Int) {\n // Permute the names.\n for _ in 1...n {\n for firstname in words {\n for lastname in words {\n _ = (firstname.uppercased(), lastname.lowercased())\n }\n }\n }\n}\n\n// Workloads for various scripts. Always 20 names for 400 pairings.\n// To keep the performance of various scripts roughly comparable, aim for\n// a total length of approximately 120 characters.\n// E.g.: `ascii.joined(separator: "").count == 124`\n// Every name should fit in 15-bytes UTF-8 encoded, to exercise the small\n// string optimization.\n// E.g.: `armenian.allSatisfy { $0._guts.isSmall } == true`\n\n// Workload Size Statistics\n// SMALL | UTF-8 | UTF-16 | REGULAR | UTF-8 | UTF-16\n// ---------|-------|--------|--------------|---------|--------\n// ascii | 124 B | 248 B | longASCII | 6158 B | 12316 B\n// strasse | 140 B | 240 B | longStrasse | 6798 B | 11996 B\n// armenian | 232 B | 232 B | longArmenian | 10478 B | 11676 B\n// cyrillic | 238 B | 238 B | longCyrillic | 10718 B | 11916 B\n\nlet ascii = Array(words.prefix(20))\n// Pathological case, uppercase: ß -> SS\nlet strasse = Array(repeating: "Straße", count: 20)\n\nlet armenian = [\n "Արմեն", "Աննա", "Հարութ", "Միքայել", "Մարիա", "Դավիթ", "Վարդան",\n "Նարինե", "Տիգրան", "Տաթևիկ", "Թագուհի", "Թամարա", "Ազնաուր", "Գրիգոր",\n "Կոմիտաս", "Հայկ", "Գառնիկ", "Վահրամ", "Վահագն", "Գևորգ"]\n\nlet cyrillic = [\n "Ульяна", "Аркадий", "Аня", "Даниил", "Дмитрий", "Эдуард", "Юрій", "Давид",\n "Анна", "Дмитрий", "Евгений", "Борис", "Ксения", "Артур", "Аполлон",\n "Соломон", "Николай", "Кристи", "Надежда", "Спартак"]\n\n/// Precompose the phonebook into one large string of comma separated names.\nfunc phonebook(_ names: [String]) -> String {\n names.map { firstName in\n names.map { lastName in\n firstName + " " + lastName\n }.joined(separator: ", ")\n }.joined(separator: ", ")\n}\n\nlet longASCII = phonebook(ascii)\nlet longStrasse = phonebook(strasse)\nlet longArmenian = phonebook(armenian)\nlet longCyrillic = phonebook(cyrillic)\n\n@inline(never)\npublic func angryPhonebook(_ n: Int, _ names: [String]) {\n assert(names.count == 20)\n // Permute the names.\n for _ in 1...n {\n for firstname in names {\n for lastname in names {\n blackHole((firstname.uppercased(), lastname.lowercased()))\n }\n }\n }\n}\n\n@inline(never)\npublic func angryPhonebook(_ n: Int, precomposed names: String) {\n for _ in 1...n {\n blackHole((names.uppercased(), names.lowercased()))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_AngryPhonebook.swift | cpp_apple_swift_benchmark_single-source_AngryPhonebook.swift | Swift | 5,447 | 0.95 | 0.078947 | 0.242647 | vue-tools | 172 | 2023-11-06T22:19:38.118174 | MIT | false | 2a7601561e178b1690d408a4f1a2af58 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark tests AnyHashable's initializer that needs to dynamically\n// upcast the instance to the type that introduces the Hashable\n// conformance.\n\nimport TestsUtils\n\n// 23% _swift_dynamicCast\n// 23% _swift_release_\n// 18% _swift_stdlib_makeAnyHashableUsingDefaultRepresentation\n// 11% _swift_stdlib_makeAnyHashableUpcastingToHashableBaseType\n// 16% _swift_retain_[n]\n// 5% swift_conformsToProtocol\npublic let benchmarks =\n BenchmarkInfo(\n name: "AnyHashableWithAClass",\n runFunction: run_AnyHashableWithAClass,\n tags: [.abstraction, .runtime, .cpubench],\n legacyFactor: 500\n )\n\nclass TestHashableBase : Hashable {\n var value: Int\n init(_ value: Int) {\n self.value = value\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n\n static func == (\n lhs: TestHashableBase,\n rhs: TestHashableBase\n ) -> Bool {\n return lhs.value == rhs.value\n }\n}\n\nclass TestHashableDerived1 : TestHashableBase {}\nclass TestHashableDerived2 : TestHashableDerived1 {}\nclass TestHashableDerived3 : TestHashableDerived2 {}\nclass TestHashableDerived4 : TestHashableDerived3 {}\nclass TestHashableDerived5 : TestHashableDerived4 {}\n\n@inline(never)\npublic func run_AnyHashableWithAClass(_ n: Int) {\n let c = TestHashableDerived5(10)\n for _ in 0...(n*1000) {\n _ = AnyHashable(c)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_AnyHashableWithAClass.swift | cpp_apple_swift_benchmark_single-source_AnyHashableWithAClass.swift | Swift | 1,843 | 0.95 | 0.142857 | 0.363636 | awesome-app | 924 | 2025-04-26T02:37:54.809999 | Apache-2.0 | false | a729712dfd6de968489e1e6ad693afac |
//===--- Array2D.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Array2D",\n runFunction: run_Array2D,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(inputArray) },\n tearDownFunction: { inputArray = nil },\n legacyFactor: 16)\n\nlet size = 256\n\nvar inputArray: [[Int]]! = {\n var a: [[Int]] = []\n a.reserveCapacity(size)\n for _ in 0 ..< size {\n a.append(Array(0 ..< size))\n }\n return a\n}()\n\n@inline(never)\nfunc modifyArray(_ a: inout [[Int]], _ n: Int) {\n for _ in 0..<n {\n for i in 0 ..< size {\n for y in 0 ..< size {\n a[i][y] = a[i][y] + 1\n a[i][y] = a[i][y] - 1\n }\n }\n }\n}\n\n@inline(never)\npublic func run_Array2D(_ n: Int) {\n modifyArray(&inputArray, n)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Array2D.swift | cpp_apple_swift_benchmark_single-source_Array2D.swift | Swift | 1,253 | 0.95 | 0.12 | 0.25 | vue-tools | 148 | 2024-06-23T05:09:52.031439 | Apache-2.0 | false | f8af7fb9eb3b7ec9d1cd62aea93f6e5e |
//===--- ArrayAppend.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks the performance of appending to an array.\n//\n// Note: Several benchmarks are marked .unstable until we have a way\n// of controlling malloc behavior from the benchmark driver.\n\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.validation, .api, .Array]\npublic let benchmarks = [\n BenchmarkInfo(name: "ArrayAppend", runFunction: run_ArrayAppend, tags: t + [.unstable], legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendArrayOfInt", runFunction: run_ArrayAppendArrayOfInt, tags: t,\n setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendAscii", runFunction: run_ArrayAppendAscii, tags: t, legacyFactor: 34),\n BenchmarkInfo(name: "ArrayAppendAsciiSubstring", runFunction: run_ArrayAppendAsciiSubstring, tags: t, legacyFactor: 36),\n BenchmarkInfo(name: "ArrayAppendFromGeneric", runFunction: run_ArrayAppendFromGeneric, tags: t,\n setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendGenericStructs", runFunction: run_ArrayAppendGenericStructs, tags: t,\n setUpFunction: { otherStructs = Array(repeating: S(x: 3, y: 4.2), count: 10_000) },\n tearDownFunction: { otherStructs = nil }, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendLatin1", runFunction: run_ArrayAppendLatin1, tags: t + [.unstable], legacyFactor: 34),\n BenchmarkInfo(name: "ArrayAppendLatin1Substring", runFunction: run_ArrayAppendLatin1Substring, tags: t, legacyFactor: 36),\n BenchmarkInfo(name: "ArrayAppendLazyMap", runFunction: run_ArrayAppendLazyMap, tags: t,\n setUpFunction: { blackHole(array) }, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendOptionals", runFunction: run_ArrayAppendOptionals, tags: t + [.unstable],\n setUpFunction: { otherOptionalOnes = Array(repeating: 1, count: 10_000) },\n tearDownFunction: { otherOptionalOnes = nil }, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendRepeatCol", runFunction: run_ArrayAppendRepeatCol, tags: t + [.unstable], legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendReserved", runFunction: run_ArrayAppendReserved, tags: t, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendSequence", runFunction: run_ArrayAppendSequence, tags: t, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendStrings", runFunction: run_ArrayAppendStrings, tags: t,\n setUpFunction: { otherStrings = stride(from: 0, to: 10_000, by: 1).map { "\($0)" } },\n tearDownFunction: { otherStrings = nil }, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendToFromGeneric", runFunction: run_ArrayAppendToFromGeneric, tags: t + [.unstable],\n setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendToGeneric", runFunction: run_ArrayAppendToGeneric, tags: t,\n setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayAppendUTF16", runFunction: run_ArrayAppendUTF16, tags: t + [.unstable], legacyFactor: 34),\n BenchmarkInfo(name: "ArrayAppendUTF16Substring", runFunction: run_ArrayAppendUTF16Substring, tags: t, legacyFactor: 36),\n BenchmarkInfo(name: "ArrayPlusEqualArrayOfInt", runFunction: run_ArrayPlusEqualArrayOfInt, tags: t + [.unstable],\n setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),\n BenchmarkInfo(name: "ArrayPlusEqualFiveElementCollection", runFunction: run_ArrayPlusEqualFiveElementCollection, tags: t + [.unstable], legacyFactor: 37),\n BenchmarkInfo(name: "ArrayPlusEqualSingleElementCollection", runFunction: run_ArrayPlusEqualSingleElementCollection, tags: t, legacyFactor: 47),\n BenchmarkInfo(name: "ArrayPlusEqualThreeElements", runFunction: run_ArrayPlusEqualThreeElements, tags: t, legacyFactor: 10),\n]\n\nvar otherOnes: [Int]!\nvar otherOptionalOnes: [Int?]!\nvar otherStrings: [String]!\nvar otherStructs: [S<Int, Double>]!\nlet array = Array(0..<10_000)\n\nfunc ones() { otherOnes = Array(repeating: 1, count: 10_000) }\nfunc releaseOnes() { otherOnes = nil }\n\n// Append single element\n@inline(never)\npublic func run_ArrayAppend(_ n: Int) {\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<40000 {\n nums.append(1)\n }\n }\n}\n\n// Append single element with reserve\n@inline(never)\npublic func run_ArrayAppendReserved(_ n: Int) {\n for _ in 0..<n {\n var nums = [Int]()\n nums.reserveCapacity(40000)\n for _ in 0..<40000 {\n nums.append(1)\n }\n }\n}\n\n// Append a sequence. Length of sequence unknown so\n// can't pre-reserve capacity.\n@inline(never)\npublic func run_ArrayAppendSequence(_ n: Int) {\n let seq = stride(from: 0, to: 10_000, by: 1)\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n nums.append(contentsOf: seq)\n }\n }\n}\n\n// Append another array. Length of sequence known so\n// can pre-reserve capacity.\n@inline(never)\npublic func run_ArrayAppendArrayOfInt(_ n: Int) {\n let other: [Int] = otherOnes\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n nums.append(contentsOf: other)\n }\n }\n}\n\n// Identical to run_ArrayAppendArrayOfInt\n// except +=, to check equally performant.\n@inline(never)\npublic func run_ArrayPlusEqualArrayOfInt(_ n: Int) {\n let other: [Int] = otherOnes\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n nums += other\n }\n }\n}\n\n// Append another array. Length of sequence known so\n// can pre-reserve capacity.\n@inline(never)\npublic func run_ArrayAppendStrings(_ n: Int) {\n let other: [String] = otherStrings\n\n for _ in 0..<n {\n var nums = [String]()\n // lower inner count due to string slowness\n for _ in 0..<4 {\n nums += other\n }\n }\n}\n\nstruct S<T,U> {\n var x: T\n var y: U\n}\n\n// Append another array. Length of sequence known so\n// can pre-reserve capacity.\n@inline(never)\npublic func run_ArrayAppendGenericStructs(_ n: Int) {\n let other: [S<Int, Double>] = otherStructs\n\n for _ in 0..<n {\n var nums = [S<Int,Double>]()\n for _ in 0..<8 {\n nums += other\n }\n }\n}\n\n// Append another array. Length of sequence known so\n// can pre-reserve capacity.\n@inline(never)\npublic func run_ArrayAppendOptionals(_ n: Int) {\n let other: [Int?] = otherOptionalOnes\n\n for _ in 0..<n {\n var nums = [Int?]()\n for _ in 0..<8 {\n nums += other\n }\n }\n}\n\n\n// Append a lazily-mapped array. Length of sequence known so\n// can pre-reserve capacity, but no optimization points used.\n@inline(never)\npublic func run_ArrayAppendLazyMap(_ n: Int) {\n let other = array.lazy.map { $0 * 2 }\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n nums += other\n }\n }\n}\n\n\n// Append a Repeat collection. Length of sequence known so\n// can pre-reserve capacity, but no optimization points used.\n@inline(never)\npublic func run_ArrayAppendRepeatCol(_ n: Int) {\n let other = repeatElement(1, count: 10_000)\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n nums += other\n }\n }\n}\n\n\n// Append an array as a generic sequence to another array\n@inline(never)\npublic func appendFromGeneric<\n S: Sequence\n>(array: inout [S.Element], sequence: S) {\n array.append(contentsOf: sequence)\n}\n\n@inline(never)\npublic func run_ArrayAppendFromGeneric(_ n: Int) {\n let other: [Int] = otherOnes\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n appendFromGeneric(array: &nums, sequence: other)\n }\n }\n}\n\n// Append an array to an array as a generic range replaceable collection.\n@inline(never)\npublic func appendToGeneric<\n R: RangeReplaceableCollection\n>(collection: inout R, array: [R.Element]) {\n collection.append(contentsOf: array)\n}\n\n@inline(never)\npublic func run_ArrayAppendToGeneric(_ n: Int) {\n let other: [Int] = otherOnes\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n appendToGeneric(collection: &nums, array: other)\n }\n }\n}\n\n// Append an array as a generic sequence to an array as a generic range\n// replaceable collection.\n@inline(never)\npublic func appendToFromGeneric<\n R: RangeReplaceableCollection, S: Sequence\n>(collection: inout R, sequence: S)\nwhere R.Element == S.Element {\n collection.append(contentsOf: sequence)\n}\n\n@inline(never)\npublic func run_ArrayAppendToFromGeneric(_ n: Int) {\n let other: [Int] = otherOnes\n\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<8 {\n appendToFromGeneric(collection: &nums, sequence: other)\n }\n }\n}\n\n// Append a single element array with the += operator\n@inline(never)\npublic func run_ArrayPlusEqualSingleElementCollection(_ n: Int) {\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<10_000 {\n nums += [1]\n }\n }\n}\n\n// Append a five element array with the += operator\n@inline(never)\npublic func run_ArrayPlusEqualFiveElementCollection(_ n: Int) {\n for _ in 0..<n {\n var nums = [Int]()\n for _ in 0..<10_000 {\n nums += [1, 2, 3, 4, 5]\n }\n }\n}\n\n@inline(never)\npublic func appendThreeElements(_ a: inout [Int]) {\n a += [1, 2, 3]\n}\n\n@inline(never)\npublic func run_ArrayPlusEqualThreeElements(_ n: Int) {\n for _ in 0..<(1_000 * n) {\n var a: [Int] = []\n appendThreeElements(&a)\n }\n}\n\n// Append the utf8 elements of an ascii string to a [UInt8]\n@inline(never)\npublic func run_ArrayAppendAscii(_ n: Int) {\n let s = "the quick brown fox jumps over the lazy dog!"\n for _ in 0..<n {\n var nums = [UInt8]()\n for _ in 0..<3_000 {\n nums += getString(s).utf8\n }\n }\n}\n\n// Append the utf8 elements of a latin1 string to a [UInt8]\n@inline(never)\npublic func run_ArrayAppendLatin1(_ n: Int) {\n let s = "the quick brown fox jumps over the lazy dog\u{00A1}"\n for _ in 0..<n {\n var nums = [UInt8]()\n for _ in 0..<3_000 {\n nums += getString(s).utf8\n }\n }\n}\n\n// Append the utf8 elements of an utf16 string to a [UInt8]\n@inline(never)\npublic func run_ArrayAppendUTF16(_ n: Int) {\n let s = "the quick brown 🦊 jumps over the lazy dog"\n for _ in 0..<n {\n var nums = [UInt8]()\n for _ in 0..<3_000 {\n nums += getString(s).utf8\n }\n }\n}\n\n// Append the utf8 elements of an ascii substring to a [UInt8]\n@inline(never)\npublic func run_ArrayAppendAsciiSubstring(_ n: Int) {\n let s = "the quick brown fox jumps over the lazy dog!"[...]\n for _ in 0..<n {\n var nums = [UInt8]()\n for _ in 0..<3_000 {\n nums += getSubstring(s).utf8\n }\n }\n}\n\n// Append the utf8 elements of a latin1 substring to a [UInt8]\n@inline(never)\npublic func run_ArrayAppendLatin1Substring(_ n: Int) {\n let s = "the quick brown fox jumps over the lazy dog\u{00A1}"[...]\n for _ in 0..<n {\n var nums = [UInt8]()\n for _ in 0..<3_000 {\n nums += getSubstring(s).utf8\n }\n }\n}\n\n// Append the utf8 elements of an utf16 substring to a [UInt8]\n@inline(never)\npublic func run_ArrayAppendUTF16Substring(_ n: Int) {\n let s = "the quick brown 🦊 jumps over the lazy dog"[...]\n for _ in 0..<n {\n var nums = [UInt8]()\n for _ in 0..<3_000 {\n nums += getSubstring(s).utf8\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayAppend.swift | cpp_apple_swift_benchmark_single-source_ArrayAppend.swift | Swift | 11,364 | 0.95 | 0.119048 | 0.138554 | node-utils | 823 | 2023-07-14T02:55:00.896774 | GPL-3.0 | false | 3a942ec5a25e177812eaf5fdba90b67c |
//===--- ArrayInClass.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\npublic let benchmarks = [\n BenchmarkInfo(\n name: "ArrayInClass",\n runFunction: run_ArrayInClass,\n tags: [.validation, .api, .Array],\n setUpFunction: { ac = ArrayContainer() },\n tearDownFunction: { ac = nil },\n legacyFactor: 5),\n BenchmarkInfo(name: "DistinctClassFieldAccesses",\n runFunction: run_DistinctClassFieldAccesses,\n tags: [.validation, .api, .Array],\n setUpFunction: { workload = ClassWithArrs(n: 10_000) },\n tearDownFunction: { workload = nil }),\n]\n\nvar ac: ArrayContainer!\n\nclass ArrayContainer {\n final var arr : [Int]\n\n init() {\n arr = [Int] (repeating: 0, count: 20_000)\n }\n\n func runLoop(_ n: Int) {\n for _ in 0 ..< n {\n for i in 0 ..< arr.count {\n arr[i] = arr[i] + 1\n }\n }\n }\n}\n\n@inline(never)\npublic func run_ArrayInClass(_ n: Int) {\n let a = ac!\n a.runLoop(n)\n}\n\nclass ClassWithArrs {\n var n: Int = 0\n var a: [Int]\n var b: [Int]\n\n init(n: Int) {\n self.n = n\n\n a = [Int](repeating: 0, count: n)\n b = [Int](repeating: 0, count: n)\n }\n\n func readArr() {\n for i in 0..<self.n {\n guard a[i] == b[i] else { fatalError("") }\n }\n }\n\n func writeArr() {\n for i in 0..<self.n {\n a[i] = i\n b[i] = i\n }\n }\n}\n\nvar workload: ClassWithArrs!\n\npublic func run_DistinctClassFieldAccesses(_ n: Int) {\n for _ in 1...n {\n workload.writeArr()\n workload.readArr()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayInClass.swift | cpp_apple_swift_benchmark_single-source_ArrayInClass.swift | Swift | 1,921 | 0.95 | 0.104651 | 0.150685 | python-kit | 829 | 2024-09-30T01:55:43.137462 | MIT | false | c58612789265af67ce14b1f5270ad487 |
//===--- ArrayLiteral.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of creating array from literal and array value\n// propagation.\n// It is reported to be slow: <rdar://problem/17297449>\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "ArrayLiteral2", runFunction: run_ArrayLiteral, tags: [.validation, .api, .Array]),\n BenchmarkInfo(name: "ArrayValueProp", runFunction: run_ArrayValueProp, tags: [.validation, .api, .Array]),\n BenchmarkInfo(name: "ArrayValueProp2", runFunction: run_ArrayValueProp2, tags: [.validation, .api, .Array]),\n BenchmarkInfo(name: "ArrayValueProp3", runFunction: run_ArrayValueProp3, tags: [.validation, .api, .Array]),\n BenchmarkInfo(name: "ArrayValueProp4", runFunction: run_ArrayValueProp4, tags: [.validation, .api, .Array]),\n]\n\n@inline(never)\nfunc makeArray() -> [Int] {\n return [1,2,3]\n}\n\n@inline(never)\npublic func run_ArrayLiteral(_ n: Int) {\n for _ in 1...10000*n {\n blackHole(makeArray())\n }\n}\n\n@inline(never)\nfunc addLiteralArray() -> Int {\n let arr = [1, 2, 3]\n return arr[0] + arr[1] + arr[2]\n}\n\n@inline(never)\npublic func run_ArrayValueProp(_ n: Int) {\n var res = 123\n for _ in 1...10000*n {\n res += addLiteralArray()\n res -= addLiteralArray()\n }\n check(res == 123)\n}\n\n\n@inline(never)\nfunc addLiteralArray2() -> Int {\n let arr = [1, 2, 3]\n var r = 0\n for elt in arr {\n r += elt\n }\n return r\n}\n\n@inline(never)\nfunc addLiteralArray3() -> Int {\n let arr = [1, 2, 3]\n var r = 0\n for i in 0..<arr.count {\n r += arr[i]\n }\n return r\n}\n\n@inline(never)\nfunc addLiteralArray4() -> Int {\n let arr = [1, 2, 3]\n var r = 0\n for i in 0..<3 {\n r += arr[i]\n }\n return r\n}\n\n@inline(never)\npublic func run_ArrayValueProp2(_ n: Int) {\n var res = 123\n for _ in 1...10000*n {\n res += addLiteralArray2()\n res -= addLiteralArray2()\n }\n check(res == 123)\n}\n\n@inline(never)\npublic func run_ArrayValueProp3(_ n: Int) {\n var res = 123\n for _ in 1...10000*n {\n res += addLiteralArray3()\n res -= addLiteralArray3()\n }\n check(res == 123)\n}\n\n@inline(never)\npublic func run_ArrayValueProp4(_ n: Int) {\n var res = 123\n for _ in 1...10000*n {\n res += addLiteralArray4()\n res -= addLiteralArray4()\n }\n check(res == 123)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayLiteral.swift | cpp_apple_swift_benchmark_single-source_ArrayLiteral.swift | Swift | 2,706 | 0.95 | 0.088496 | 0.14 | python-kit | 710 | 2024-02-18T19:37:24.544489 | Apache-2.0 | false | d73687ff266fdb981d6abc3cd574c139 |
//===--- ArrayOfGenericPOD.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark tests creation and destruction of arrays of enum and\n// generic type bound to trivial types. It should take the same time as\n// ArrayOfPOD. (In practice, it takes a little longer to construct\n// the optional arrays).\n//\n// For comparison, we always create three arrays of 200,000 words.\n// An integer enum takes two words.\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n // Renamed benchmark to "2" when IUO test was removed, which\n // effectively changed what we're benchmarking here.\n name: "ArrayOfGenericPOD2",\n runFunction: run_ArrayOfGenericPOD,\n tags: [.validation, .api, .Array]),\n\n // Initialize an array of generic POD from a slice.\n // This takes a unique path through stdlib customization points.\n BenchmarkInfo(\n name: "ArrayInitFromSlice",\n runFunction: run_initFromSlice,\n tags: [.validation, .api, .Array], setUpFunction: createArrayOfPOD)\n]\n\nclass RefArray<T> {\n var array: [T]\n\n init(_ i:T) {\n array = [T](repeating: i, count: 100000)\n }\n}\n\n// Check the performance of destroying an array of enums (optional) where the\n// enum has a single payload of trivial type. Destroying the\n// elements should be a nop.\n@inline(never)\nfunc genEnumArray() {\n blackHole(RefArray<Int?>(3))\n // should be a nop\n}\n\n// Check the performance of destroying an array of structs where the\n// struct has multiple fields of trivial type. Destroying the\n// elements should be a nop.\nstruct S<T> {\n var x: T\n var y: T\n}\n@inline(never)\nfunc genStructArray() {\n blackHole(RefArray<S<Int>>(S(x:3, y:4)))\n // should be a nop\n}\n\n@inline(never)\npublic func run_ArrayOfGenericPOD(_ n: Int) {\n for _ in 0..<n {\n genEnumArray()\n genStructArray()\n }\n}\n\n// --- ArrayInitFromSlice\n\nlet globalArray = Array<UInt8>(repeating: 0, count: 4096)\n\nfunc createArrayOfPOD() {\n blackHole(globalArray)\n}\n\n@inline(never)\n@_optimize(none)\nfunc copyElements<S: Sequence>(_ contents: S) -> [UInt8]\n where S.Iterator.Element == UInt8\n{\n return [UInt8](contents)\n}\n\n@inline(never)\npublic func run_initFromSlice(_ n: Int) {\n for _ in 0..<n {\n for _ in 0..<1000 {\n // Slice off at least one element so the array buffer can't be reused.\n blackHole(copyElements(globalArray[0..<4095]))\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayOfGenericPOD.swift | cpp_apple_swift_benchmark_single-source_ArrayOfGenericPOD.swift | Swift | 2,777 | 0.95 | 0.059406 | 0.367816 | node-utils | 114 | 2023-10-21T20:37:13.665740 | Apache-2.0 | false | b37f50a71a977c7637718e58e3cebc35 |
//===--- ArrayOfGenericRef.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark tests creation and destruction of an array of enum\n// and generic type bound to nontrivial types.\n//\n// For comparison, we always create three arrays of 1,000 words.\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ArrayOfGenericRef",\n runFunction: run_ArrayOfGenericRef,\n tags: [.validation, .api, .Array],\n legacyFactor: 10)\n\nprotocol Constructible {\n associatedtype Element\n init(e:Element)\n}\nclass ConstructibleArray<T:Constructible> {\n var array: [T]\n\n init(_ e:T.Element) {\n array = [T]()\n array.reserveCapacity(1_000)\n for _ in 0...1_000 {\n array.append(T(e:e))\n }\n }\n}\n\nclass GenericRef<T> : Constructible {\n typealias Element=T\n var x: T\n required init(e:T) { self.x = e }\n}\n\n// Reference to a POD class.\n@inline(never)\nfunc genPODRefArray() {\n blackHole(ConstructibleArray<GenericRef<Int>>(3))\n // should be a nop\n}\n\nclass Dummy {}\n\n// Reference to a reference. The nested reference is shared across elements.\n@inline(never)\nfunc genCommonRefArray() {\n let d = Dummy()\n blackHole(ConstructibleArray<GenericRef<Dummy>>(d))\n // should be a nop\n}\n\n// Reuse the same enum value for each element.\nclass RefArray<T> {\n var array: [T]\n\n init(_ i:T, count:Int = 1_000) {\n array = [T](repeating: i, count: count)\n }\n}\n\n// enum holding a reference.\n@inline(never)\nfunc genRefEnumArray() {\n let d = Dummy()\n blackHole(RefArray<Dummy?>(d))\n // should be a nop\n}\n\nstruct GenericVal<T> : Constructible {\n typealias Element=T\n var x: T\n init(e:T) { self.x = e }\n}\n\n// Struct holding a reference.\n@inline(never)\nfunc genRefStructArray() {\n let d = Dummy()\n blackHole(ConstructibleArray<GenericVal<Dummy>>(d))\n // should be a nop\n}\n\n@inline(never)\npublic func run_ArrayOfGenericRef(_ n: Int) {\n for _ in 0..<n {\n genPODRefArray()\n genCommonRefArray()\n genRefEnumArray()\n genRefStructArray()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayOfGenericRef.swift | cpp_apple_swift_benchmark_single-source_ArrayOfGenericRef.swift | Swift | 2,418 | 0.95 | 0.095238 | 0.266667 | react-lib | 674 | 2023-12-28T11:20:22.237911 | MIT | false | 41de47a16888f40026338d82174879e8 |
//===--- ArrayOfPOD.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark tests creation and destruction of an array of\n// trivial static type. It is meant to be a baseline for comparison against\n// ArrayOfGenericPOD.\n//\n// For comparison, we always create three arrays of 200,000 words.\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ArrayOfPOD",\n runFunction: run_ArrayOfPOD,\n tags: [.validation, .api, .Array])\n\nclass RefArray<T> {\n var array : [T]\n\n init(_ i:T, count:Int = 100_000) {\n array = [T](repeating: i, count: count)\n }\n}\n\n@inline(never)\nfunc genIntArray() {\n blackHole(RefArray<Int>(3, count:200_000))\n // should be a nop\n}\n\nenum PODEnum {\n case Some(Int)\n\n init(i:Int) { self = .Some(i) }\n}\n\n@inline(never)\nfunc genEnumArray() {\n blackHole(RefArray<PODEnum>(PODEnum.Some(3)))\n // should be a nop\n}\n\nstruct S {\n var x: Int\n var y: Int\n}\n@inline(never)\nfunc genStructArray() {\n blackHole(RefArray<S>(S(x:3, y:4)))\n // should be a nop\n}\n\n@inline(never)\npublic func run_ArrayOfPOD(_ n: Int) {\n for _ in 0..<n {\n genIntArray()\n genEnumArray()\n genStructArray()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayOfPOD.swift | cpp_apple_swift_benchmark_single-source_ArrayOfPOD.swift | Swift | 1,598 | 0.95 | 0.071429 | 0.322034 | vue-tools | 269 | 2023-12-04T07:10:22.499107 | Apache-2.0 | false | 73d0e9cebb30db5498d3ebf2b4c9a943 |
//===--- ArrayOfRef.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark tests creation and destruction of an array of\n// references. It is meant to be a baseline for comparison against\n// ArrayOfGenericRef.\n//\n// For comparison, we always create four arrays of 1,000 words.\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ArrayOfRef",\n runFunction: run_ArrayOfRef,\n tags: [.validation, .api, .Array],\n legacyFactor: 10)\n\nprotocol Constructible {\n associatedtype Element\n init(e:Element)\n}\nclass ConstructibleArray<T:Constructible> {\n var array : [T]\n\n init(_ e:T.Element) {\n array = [T]()\n array.reserveCapacity(1_000)\n for _ in 0...1_000 {\n array.append(T(e:e))\n }\n }\n}\n\n// Reference to a POD class.\nclass POD : Constructible {\n typealias Element=Int\n var x: Int\n required init(e:Int) { self.x = e }\n}\n\n@inline(never)\nfunc genPODRefArray() {\n blackHole(ConstructibleArray<POD>(3))\n // should be a nop\n}\n\nclass Dummy {}\n\n// Reference to a reference. The nested reference is shared across elements.\nclass CommonRef : Constructible {\n typealias Element=Dummy\n var d: Dummy\n required init(e:Dummy) { self.d = e }\n}\n\n@inline(never)\nfunc genCommonRefArray() {\n let d = Dummy()\n blackHole(ConstructibleArray<CommonRef>(d))\n // should be a nop\n}\n\nenum RefEnum {\n case None\n case Some(Dummy)\n}\n\n// Reuse the same enum value for each element.\nclass RefArray<T> {\n var array : [T]\n\n init(_ i:T, count:Int = 1_000) {\n array = [T](repeating: i, count: count)\n }\n}\n\n@inline(never)\nfunc genRefEnumArray() {\n let e = RefEnum.Some(Dummy())\n blackHole(RefArray<RefEnum>(e))\n // should be a nop\n}\n\n// Struct holding a reference.\nstruct S : Constructible {\n typealias Element=Dummy\n var d: Dummy\n init(e:Dummy) { self.d = e }\n}\n\n@inline(never)\nfunc genRefStructArray() {\n let d = Dummy()\n blackHole(ConstructibleArray<S>(d))\n // should be a nop\n}\n\n@inline(never)\npublic func run_ArrayOfRef(_ n: Int) {\n for _ in 0..<n {\n genPODRefArray()\n genCommonRefArray()\n genRefEnumArray()\n genRefStructArray()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayOfRef.swift | cpp_apple_swift_benchmark_single-source_ArrayOfRef.swift | Swift | 2,548 | 0.95 | 0.103448 | 0.242424 | vue-tools | 739 | 2024-04-13T18:48:43.268073 | Apache-2.0 | false | a4d69b3a626466fade8918fa67a155bd |
// This test checks the performance of removeAll\n// on a non-uniquely referenced array.\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "Array.removeAll.keepingCapacity.Int",\n runFunction: run_ArrayRemoveAll_Class,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(inputArray_Class) }\n ),\n BenchmarkInfo(\n name: "Array.removeAll.keepingCapacity.Object",\n runFunction: run_ArrayRemoveAll_Int,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(inputArray_Int) }\n )\n]\n\nclass Slow {\n public var num: Int\n\n init(num: Int) {\n self.num = num\n }\n}\n\nlet inputArray_Int: [Int] = Array(0..<500_000)\nlet inputArray_Class: [Slow] = (0..<50_000).map(Slow.init(num:))\n\n@inline(never)\nfunc removeAll<T>(_ arr: [T]) -> [T] {\n var copy = arr\n copy.removeAll(keepingCapacity: true)\n return copy\n}\n\n@inline(never)\nfunc run_ArrayRemoveAll_Class(_ n: Int) {\n var copy = removeAll(inputArray_Class);\n for _ in 1..<n {\n copy = removeAll(inputArray_Class)\n }\n check(copy.capacity == inputArray_Class.capacity)\n}\n\n@inline(never)\nfunc run_ArrayRemoveAll_Int(_ n: Int) {\n var copy = removeAll(inputArray_Int);\n for _ in 1..<n {\n copy = removeAll(inputArray_Int)\n }\n check(copy.capacity == inputArray_Int.capacity)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArrayRemoveAll.swift | cpp_apple_swift_benchmark_single-source_ArrayRemoveAll.swift | Swift | 1,288 | 0.95 | 0.054545 | 0.042553 | python-kit | 768 | 2023-08-21T14:27:29.149863 | Apache-2.0 | false | fec5ee4784f8c76359efaf0f72d1968d |
//===--- ArraySetElement.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// 33% isUniquelyReferenced\n// 15% swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native\n// 18% swift_isUniquelyReferencedOrPinned_nonNull_native\npublic let benchmarks =\n BenchmarkInfo(\n name: "ArraySetElement",\n runFunction: run_ArraySetElement,\n tags: [.runtime, .cpubench]\n )\n\n// This is an effort to defeat isUniquelyReferenced optimization. Ideally\n// microbenchmarks list this should be written in C.\n@inline(never)\nfunc storeArrayElement(_ array: inout [Int], _ i: Int) {\n array[i] = i\n}\n\npublic func run_ArraySetElement(_ n: Int) {\n var array = [Int](repeating: 0, count: 10000)\n for _ in 0..<10*n {\n for i in 0..<array.count {\n storeArrayElement(&array, i)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArraySetElement.swift | cpp_apple_swift_benchmark_single-source_ArraySetElement.swift | Swift | 1,249 | 0.95 | 0.102564 | 0.457143 | awesome-app | 600 | 2024-01-28T17:10:18.121668 | GPL-3.0 | false | 0c1dbba3b3d575afd4047fe13f0b94d8 |
//===--- ArraySubscript.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks the performance of modifying an array element.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ArraySubscript",\n runFunction: run_ArraySubscript,\n tags: [.validation, .api, .Array],\n legacyFactor: 4)\n\n@inline(never)\npublic func run_ArraySubscript(_ n: Int) {\n var lfsr = LFSR()\n\n let numArrays = 50\n let numArrayElements = 100\n\n func bound(_ x: Int) -> Int { return min(x, numArrayElements-1) }\n\n for _ in 1...n {\n var arrays = [[Int]](repeating: [], count: numArrays)\n for i in 0..<numArrays {\n for _ in 0..<numArrayElements {\n arrays[i].append(Int(truncatingIfNeeded: lfsr.next()))\n }\n }\n\n // Do a max up the diagonal.\n for i in 1..<numArrays {\n arrays[i][bound(i)] =\n max(arrays[i-1][bound(i-1)], arrays[i][bound(i)])\n }\n check(arrays[0][0] <= arrays[numArrays-1][bound(numArrays-1)])\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ArraySubscript.swift | cpp_apple_swift_benchmark_single-source_ArraySubscript.swift | Swift | 1,421 | 0.95 | 0.12766 | 0.325 | react-lib | 194 | 2024-09-12T04:54:07.650297 | BSD-3-Clause | false | 36057bd320f655bf5c4e42abef417bfc |
//===--- AsyncTree.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Dispatch\n\npublic var benchmarks: [BenchmarkInfo] {\n guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) else {\n return []\n }\n return [\n BenchmarkInfo(\n name: "AsyncTree.100",\n runFunction: run_AsyncTree(treeSize: 100),\n tags: [.concurrency]\n ),\n BenchmarkInfo(\n name: "AsyncTree.5000",\n runFunction: run_AsyncTree(treeSize: 5000),\n tags: [.concurrency]\n )\n ]\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nprivate actor MyActor {\n let g: DispatchGroup\n\n init(_ g: DispatchGroup) {\n self.g = g\n }\n\n func test(_ n: Int) {\n let L = n / 2\n let R = n - 1 - L\n\n if L > 0 {\n Task {\n self.test(L)\n }\n }\n\n if R > 0 {\n Task {\n self.test(R)\n }\n }\n\n g.leave()\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nprivate func run_AsyncTree(treeSize: Int) -> (Int) -> Void {\n return { n in\n for _ in 0..<n {\n let g = DispatchGroup()\n for _ in 0..<treeSize {\n g.enter()\n }\n let actor = MyActor(g)\n Task {\n await actor.test(treeSize)\n }\n g.wait()\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_AsyncTree.swift | cpp_apple_swift_benchmark_single-source_AsyncTree.swift | Swift | 1,674 | 0.95 | 0.077922 | 0.161765 | react-lib | 49 | 2023-10-29T23:43:38.282437 | Apache-2.0 | false | 2e2304d089fb7737be454ede728886e6 |
//===--- BinaryFloatingPointConversionFromBinaryInteger.swift -------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of generic binary floating-point conversion from\n// a binary integer.\n\nimport TestsUtils\n\n#if swift(>=4.2)\npublic let benchmarks = [\n BenchmarkInfo(\n name: "BinaryFloatingPointConversionFromBinaryInteger",\n runFunction: run_BinaryFloatingPointConversionFromBinaryInteger,\n tags: [.validation, .algorithm]\n ),\n]\n#else\npublic let benchmarks: [BenchmarkInfo] = []\n#endif\n\nstruct MockBinaryInteger<T : BinaryInteger> {\n var _value: T\n\n init(_ value: T) {\n _value = value\n }\n}\n\nextension MockBinaryInteger : CustomStringConvertible {\n var description: String {\n return _value.description\n }\n}\n\nextension MockBinaryInteger : ExpressibleByIntegerLiteral {\n init(integerLiteral value: T.IntegerLiteralType) {\n _value = T(integerLiteral: value)\n }\n}\n\nextension MockBinaryInteger : Comparable {\n static func < (lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) -> Bool {\n return lhs._value < rhs._value\n }\n\n static func == (\n lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>\n ) -> Bool {\n return lhs._value == rhs._value\n }\n}\n\nextension MockBinaryInteger : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(_value)\n }\n}\n\nextension MockBinaryInteger : BinaryInteger {\n static var isSigned: Bool {\n return T.isSigned\n }\n\n init<Source>(_ source: Source) where Source : BinaryFloatingPoint {\n _value = T(source)\n }\n\n init?<Source>(exactly source: Source) where Source : BinaryFloatingPoint {\n guard let result = T(exactly: source) else { return nil }\n _value = result\n }\n\n init<Source>(_ source: Source) where Source : BinaryInteger {\n _value = T(source)\n }\n\n init?<Source>(exactly source: Source) where Source : BinaryInteger {\n guard let result = T(exactly: source) else { return nil }\n _value = result\n }\n\n init<Source>(truncatingIfNeeded source: Source) where Source : BinaryInteger {\n _value = T(truncatingIfNeeded: source)\n }\n\n init<Source>(clamping source: Source) where Source : BinaryInteger {\n _value = T(clamping: source)\n }\n\n var magnitude: MockBinaryInteger<T.Magnitude> {\n return MockBinaryInteger<T.Magnitude>(_value.magnitude)\n }\n\n var words: T.Words {\n return _value.words\n }\n\n var bitWidth: Int {\n return _value.bitWidth\n }\n\n var trailingZeroBitCount: Int {\n return _value.trailingZeroBitCount\n }\n\n func isMultiple(of other: MockBinaryInteger<T>) -> Bool {\n return _value.isMultiple(of: other._value)\n }\n\n static func + (\n lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>\n ) -> MockBinaryInteger<T> {\n return MockBinaryInteger(lhs._value + rhs._value)\n }\n\n static func += (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value += rhs._value\n }\n\n static func - (\n lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>\n ) -> MockBinaryInteger<T> {\n return MockBinaryInteger(lhs._value - rhs._value)\n }\n\n static func -= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value -= rhs._value\n }\n\n static func * (\n lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>\n ) -> MockBinaryInteger<T> {\n return MockBinaryInteger(lhs._value * rhs._value)\n }\n\n static func *= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value *= rhs._value\n }\n\n static func / (\n lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>\n ) -> MockBinaryInteger<T> {\n return MockBinaryInteger(lhs._value / rhs._value)\n }\n\n static func /= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value /= rhs._value\n }\n\n static func % (\n lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>\n ) -> MockBinaryInteger<T> {\n return MockBinaryInteger(lhs._value % rhs._value)\n }\n\n static func %= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value %= rhs._value\n }\n\n static func &= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value &= rhs._value\n }\n\n static func |= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value |= rhs._value\n }\n\n static func ^= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) {\n lhs._value ^= rhs._value\n }\n\n static prefix func ~ (x: MockBinaryInteger<T>) -> MockBinaryInteger<T> {\n return MockBinaryInteger(~x._value)\n }\n\n static func >>= <RHS>(\n lhs: inout MockBinaryInteger<T>, rhs: RHS\n ) where RHS : BinaryInteger {\n lhs._value >>= rhs\n }\n\n static func <<= <RHS>(\n lhs: inout MockBinaryInteger<T>, rhs: RHS\n ) where RHS : BinaryInteger {\n lhs._value <<= rhs\n }\n}\n\n#if swift(>=4.2)\n\n@inline(never)\npublic func run_BinaryFloatingPointConversionFromBinaryInteger(_ n: Int) {\n var xs = [Double]()\n xs.reserveCapacity(n)\n for _ in 1...n {\n var x = 0 as Double\n for i in 0..<2000 {\n x += Double._convert(from: MockBinaryInteger(getInt(i))).value\n }\n xs.append(x)\n }\n check(xs[getInt(0)] == 1999000)\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_BinaryFloatingPointConversionFromBinaryInteger.swift | cpp_apple_swift_benchmark_single-source_BinaryFloatingPointConversionFromBinaryInteger.swift | Swift | 5,475 | 0.95 | 0.028037 | 0.104046 | node-utils | 247 | 2024-08-20T14:14:24.013449 | MIT | false | 830fef0e4c2d36166ba90a82800b6d6b |
//===--- BinaryFloatingPointProperties.swift ------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "BinaryFloatingPointPropertiesBinade",\n runFunction: run_BinaryFloatingPointPropertiesBinade,\n tags: [.validation, .algorithm]\n ),\n BenchmarkInfo(\n name: "BinaryFloatingPointPropertiesNextUp",\n runFunction: run_BinaryFloatingPointPropertiesNextUp,\n tags: [.validation, .algorithm]\n ),\n BenchmarkInfo(\n name: "BinaryFloatingPointPropertiesUlp",\n runFunction: run_BinaryFloatingPointPropertiesUlp,\n tags: [.validation, .algorithm]\n )\n]\n\n@inline(never)\npublic func run_BinaryFloatingPointPropertiesBinade(_ n: Int) {\n var xs = [Double]()\n xs.reserveCapacity(n)\n for _ in 1...n {\n var x = 0 as Double\n for i in 0..<10000 {\n x += Double(getInt(i)).binade\n }\n xs.append(x)\n }\n check(xs[getInt(0)] == 37180757)\n}\n\n@inline(never)\npublic func run_BinaryFloatingPointPropertiesNextUp(_ n: Int) {\n var xs = [Int]()\n xs.reserveCapacity(n)\n for _ in 1...n {\n var x = 0 as Int\n for i in 0..<10000 {\n x += Int(Double(getInt(i)).nextUp)\n }\n xs.append(x)\n }\n check(xs[getInt(0)] == 49995000)\n}\n\n@inline(never)\npublic func run_BinaryFloatingPointPropertiesUlp(_ n: Int) {\n var xs = [Int]()\n xs.reserveCapacity(n)\n for _ in 1...n {\n var x = 0 as Int\n for i in 0..<10000 {\n x += Int(Double(getInt(i)).ulp)\n }\n xs.append(x)\n }\n check(xs[getInt(0)] == 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_BinaryFloatingPointProperties.swift | cpp_apple_swift_benchmark_single-source_BinaryFloatingPointProperties.swift | Swift | 1,922 | 0.95 | 0.109589 | 0.161765 | vue-tools | 926 | 2025-01-10T02:20:27.284836 | Apache-2.0 | false | 77fa49d536398437a604656f6f0e1518 |
//===--- BitCount.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of Swift bit count.\n// and mask operator.\n// rdar://problem/22151678\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "BitCount",\n runFunction: run_BitCount,\n tags: [.validation, .algorithm])\n\nfunc countBitSet(_ num: Int) -> Int {\n let bits = MemoryLayout<Int>.size * 8\n var cnt: Int = 0\n var mask: Int = 1\n for _ in 0...bits {\n if num & mask != 0 {\n cnt += 1\n }\n mask <<= 1\n }\n return cnt\n}\n\n@inline(never)\npublic func run_BitCount(_ n: Int) {\n var sum = 0\n for _ in 1...1000*n {\n // Check some results.\n sum = sum &+ countBitSet(getInt(1))\n &+ countBitSet(getInt(2))\n &+ countBitSet(getInt(2457))\n }\n check(sum == 8 * 1000 * n)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_BitCount.swift | cpp_apple_swift_benchmark_single-source_BitCount.swift | Swift | 1,267 | 0.95 | 0.106383 | 0.348837 | python-kit | 651 | 2023-11-07T14:59:30.550560 | MIT | false | 2567f75cab26735491f11de2b72da139 |
//===--- Breadcrumbs.swift ------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// Tests the performance of String's memoized UTF-8 to UTF-16 index conversion\n// breadcrumbs. These are used to speed up range- and positional access through\n// conventional NSString APIs.\n\npublic let benchmarks: [BenchmarkInfo] = [\n UTF16ToIdx(workload: longASCIIWorkload, count: 5_000).info,\n UTF16ToIdx(workload: longMixedWorkload, count: 5_000).info,\n IdxToUTF16(workload: longASCIIWorkload, count: 5_000).info,\n IdxToUTF16(workload: longMixedWorkload, count: 5_000).info,\n\n UTF16ToIdxRange(workload: longASCIIWorkload, count: 1_000).info,\n UTF16ToIdxRange(workload: longMixedWorkload, count: 1_000).info,\n IdxToUTF16Range(workload: longASCIIWorkload, count: 1_000).info,\n IdxToUTF16Range(workload: longMixedWorkload, count: 1_000).info,\n\n CopyUTF16CodeUnits(workload: asciiWorkload, count: 500).info,\n CopyUTF16CodeUnits(workload: mixedWorkload, count: 500).info,\n CopyUTF16CodeUnits(workload: longMixedWorkload, count: 50).info,\n \n CopyAllUTF16CodeUnits(workload: asciiWorkload, count: 1_000).info,\n CopyAllUTF16CodeUnits(workload: mixedWorkload, count: 100).info,\n CopyAllUTF16CodeUnits(workload: longASCIIWorkload, count: 7).info,\n CopyAllUTF16CodeUnits(workload: longMixedWorkload, count: 1).info,\n\n MutatedUTF16ToIdx(workload: asciiWorkload, count: 50).info,\n MutatedUTF16ToIdx(workload: mixedWorkload, count: 50).info,\n MutatedIdxToUTF16(workload: asciiWorkload, count: 50).info,\n MutatedIdxToUTF16(workload: mixedWorkload, count: 50).info,\n]\n\nextension String {\n func forceNativeCopy() -> String {\n var result = String()\n result.reserveCapacity(64)\n result.append(self)\n return result\n }\n}\n\nextension Collection {\n /// Returns a randomly ordered array of random non-overlapping index ranges\n /// that cover this collection entirely.\n ///\n /// Note: some of the returned ranges may be empty.\n func randomIndexRanges<R: RandomNumberGenerator>(\n count: Int,\n using generator: inout R\n ) -> [Range<Index>] {\n // Load indices into a buffer to prevent quadratic performance with\n // forward-only collections. FIXME: Eliminate this if Self conforms to RAC.\n let indices = Array(self.indices)\n var cuts: [Index] = (0 ..< count - 1).map { _ in\n indices.randomElement(using: &generator)!\n }\n cuts.append(self.startIndex)\n cuts.append(self.endIndex)\n cuts.sort()\n let ranges = (0 ..< count).map { cuts[$0] ..< cuts[$0 + 1] }\n return ranges.shuffled(using: &generator)\n }\n}\n\nstruct Workload {\n let name: String\n let string: String\n}\n\nclass BenchmarkBase {\n let name: String\n let workload: Workload\n\n var inputString: String = ""\n\n init(name: String, workload: Workload) {\n self.name = name\n self.workload = workload\n }\n\n var label: String {\n return "\(name).\(workload.name)"\n }\n\n func setUp() {\n self.inputString = workload.string.forceNativeCopy()\n }\n\n func tearDown() {\n self.inputString = ""\n }\n\n func run(iterations: Int) {\n fatalError("unimplemented abstract method")\n }\n\n var info: BenchmarkInfo {\n return BenchmarkInfo(\n name: self.label,\n runFunction: self.run(iterations:),\n tags: [.validation, .api, .String],\n setUpFunction: self.setUp,\n tearDownFunction: self.tearDown)\n }\n}\n\n//==============================================================================\n// Workloads\n//==============================================================================\n\nlet asciiBase = #"""\n * Debugger support. Swift has a `-g` command line switch that turns on\n debug info for the compiled output. Using the standard lldb debugger\n this will allow single-stepping through Swift programs, printing\n backtraces, and navigating through stack frames; all in sync with\n the corresponding Swift source code. An unmodified lldb cannot\n inspect any variables.\n\n Example session:\n\n ```\n $ echo 'println("Hello World")' >hello.swift\n $ swift hello.swift -c -g -o hello.o\n $ ld hello.o "-dynamic" "-arch" "x86_64" "-macosx_version_min" "10.9.0" \\n -framework Foundation lib/swift/libswift_stdlib_core.dylib \\n lib/swift/libswift_stdlib_posix.dylib -lSystem -o hello\n $ lldb hello\n Current executable set to 'hello' (x86_64).\n (lldb) b top_level_code\n Breakpoint 1: where = hello`top_level_code + 26 at hello.swift:1, addre...\n (lldb) r\n Process 38592 launched: 'hello' (x86_64)\n Process 38592 stopped\n * thread #1: tid = 0x1599fb, 0x0000000100000f2a hello`top_level_code + ...\n frame #0: 0x0000000100000f2a hello`top_level_code + 26 at hello.shi...\n -> 1 println("Hello World")\n (lldb) bt\n * thread #1: tid = 0x1599fb, 0x0000000100000f2a hello`top_level_code + ...\n frame #0: 0x0000000100000f2a hello`top_level_code + 26 at hello.shi...\n frame #1: 0x0000000100000f5c hello`main + 28\n frame #2: 0x00007fff918605fd libdyld.dylib`start + 1\n frame #3: 0x00007fff918605fd libdyld.dylib`start + 1\n ```\n\n Also try `s`, `n`, `up`, `down`.\n\n * `nil` can now be used without explicit casting. Previously, `nil` had\n type `NSObject`, so one would have to write (e.g.) `nil as! NSArray`\n to create a `nil` `NSArray`. Now, `nil` picks up the type of its\n context.\n\n * `POSIX.EnvironmentVariables` and `swift.CommandLineArguments` global variables\n were merged into a `swift.Process` variable. Now you can access command line\n arguments with `Process.arguments`. In order to access environment variables\n add `import POSIX` and use `Process.environmentVariables`.\n\n func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> {\n let lowerbound = _toUTF16Offset(indices.lowerBound)\n let length = self.utf16.distance(\n from: indices.lowerBound, to: indices.upperBound)\n return Range(\n uncheckedBounds: (lower: lowerbound, upper: lowerbound + length))\n }\n 0 swift 0x00000001036b5f58 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 40\n 1 swift 0x00000001036b50f8 llvm::sys::RunSignalHandlers() + 248\n 2 swift 0x00000001036b6572 SignalHandler(int) + 258\n 3 libsystem_platform.dylib 0x00007fff64010b5d _sigtramp + 29\n 4 libsystem_platform.dylib 0x0000000100000000 _sigtramp + 2617177280\n 5 libswiftCore.dylib 0x0000000107b5d135 $sSh8_VariantV7element2atxSh5IndexVyx_G_tF + 613\n 6 libswiftCore.dylib 0x0000000107c51449 $sShyxSh5IndexVyx_Gcig + 9\n 7 libswiftCore.dylib 0x00000001059d60be $sShyxSh5IndexVyx_Gcig + 4258811006\n 8 swift 0x000000010078801d llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) + 381\n 9 swift 0x000000010078b0a4 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1268\n 10 swift 0x00000001000e048c REPLEnvironment::executeSwiftSource(llvm::StringRef, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&) + 1532\n 11 swift 0x00000001000dbbd3 swift::runREPL(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, bool) + 1443\n 12 swift 0x00000001000b5341 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 2865\n 13 swift 0x00000001000b38f4 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 3028\n 14 swift 0x000000010006ca44 main + 660\n 15 libdyld.dylib 0x00007fff63e293f1 start + 1\n 16 libdyld.dylib 0x0000000000000008 start + 2619173912\n Illegal instruction: 4\n\n """#\nlet asciiWorkload = Workload(\n name: "ASCII",\n string: asciiBase)\nlet longASCIIWorkload = Workload(\n name: "longASCII",\n string: String(repeating: asciiBase, count: 100))\n\nlet mixedBase = """\n siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig\n 👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿\n siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig\n 👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿the quick brown fox👍🏿👍🏾👍🏽👍🏼👍🏻🇲🇽🇨🇦🇺🇸👨👨👦👦👩👩👧👧👍\n siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig\n 今回のアップデートでSwiftに大幅な改良が施され、安定していてしかも直感的に使うことができるAppleプラットフォーム向けプログラミング言語になりました。\n Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭\n Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。\n siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig\n 이번 업데이트에서는 강력하면서도 직관적인 Apple 플랫폼용 프로그래밍 언어인 Swift를 완벽히 개선하였습니다.\n Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭\n в чащах юга жил-был цитрус? да, но фальшивый экземпляр\n siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig\n \u{201c}Hello\u{2010}world\u{2026}\u{201d}\n \u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d}\n Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭\n\n """\nlet mixedWorkload = Workload(\n name: "Mixed",\n string: mixedBase)\nlet longMixedWorkload = Workload(\n name: "longMixed",\n string: String(repeating: mixedBase, count: 100))\n\n\n//==============================================================================\n// Benchmarks\n//==============================================================================\n\n/// Convert `count` random UTF-16 offsets into String indices.\nclass UTF16ToIdx: BenchmarkBase {\n let count: Int\n var inputOffsets: [Int] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(name: "Breadcrumbs.UTF16ToIdx", workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var rng = SplitMix64(seed: 42)\n let range = 0 ..< inputString.utf16.count\n inputOffsets = Array(range.shuffled(using: &rng).prefix(count))\n }\n\n override func tearDown() {\n super.tearDown()\n inputOffsets = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n for _ in 0 ..< iterations {\n for offset in inputOffsets {\n blackHole(inputString._toUTF16Index(offset))\n }\n }\n }\n}\n\n/// Convert `count` random String indices into UTF-16 offsets.\nclass IdxToUTF16: BenchmarkBase {\n let count: Int\n var inputIndices: [String.Index] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(name: "Breadcrumbs.IdxToUTF16", workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var rng = SplitMix64(seed: 42)\n inputIndices = Array(inputString.indices.shuffled(using: &rng).prefix(count))\n }\n\n override func tearDown() {\n super.tearDown()\n inputIndices = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n for _ in 0 ..< iterations {\n for index in inputIndices {\n blackHole(inputString._toUTF16Offset(index))\n }\n }\n }\n}\n\n/// Split a string into `count` random slices and convert their UTF-16 offsets\n/// into String index ranges.\nclass UTF16ToIdxRange: BenchmarkBase {\n let count: Int\n var inputOffsets: [Range<Int>] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(name: "Breadcrumbs.UTF16ToIdxRange", workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var rng = SplitMix64(seed: 42)\n inputOffsets = (\n 0 ..< inputString.utf16.count\n ).randomIndexRanges(count: count, using: &rng)\n }\n\n override func tearDown() {\n super.tearDown()\n inputOffsets = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n for _ in 0 ..< iterations {\n for range in inputOffsets {\n blackHole(inputString._toUTF16Indices(range))\n }\n }\n }\n}\n\n/// Split a string into `count` random slices and convert their index ranges\n/// into UTF-16 offset pairs.\nclass IdxToUTF16Range: BenchmarkBase {\n let count: Int\n var inputIndices: [Range<String.Index>] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(name: "Breadcrumbs.IdxToUTF16Range", workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var rng = SplitMix64(seed: 42)\n inputIndices = self.inputString.randomIndexRanges(count: count, using: &rng)\n }\n\n override func tearDown() {\n super.tearDown()\n inputIndices = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n for _ in 0 ..< iterations {\n for range in inputIndices {\n blackHole(inputString._toUTF16Offsets(range))\n }\n }\n }\n}\n\n\nclass CopyUTF16CodeUnits: BenchmarkBase {\n let count: Int\n var inputIndices: [Range<Int>] = []\n var outputBuffer: [UInt16] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(name: "Breadcrumbs.CopyUTF16CodeUnits", workload: workload)\n }\n \n init(name: String, workload: Workload, count: Int) {\n self.count = count\n super.init(name: name, workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var rng = SplitMix64(seed: 42)\n inputIndices = (\n 0 ..< inputString.utf16.count\n ).randomIndexRanges(count: count, using: &rng)\n outputBuffer = Array(repeating: 0, count: inputString.utf16.count)\n }\n\n override func tearDown() {\n super.tearDown()\n inputIndices = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n outputBuffer.withUnsafeMutableBufferPointer { buffer in\n for _ in 0 ..< iterations {\n for range in inputIndices {\n inputString._copyUTF16CodeUnits(\n into: UnsafeMutableBufferPointer(rebasing: buffer[range]),\n range: range)\n }\n }\n }\n }\n}\n\nclass CopyAllUTF16CodeUnits : CopyUTF16CodeUnits {\n override init(workload: Workload, count: Int) {\n super.init(\n name: "Breadcrumbs.CopyAllUTF16CodeUnits",\n workload: workload,\n count: count\n )\n }\n \n override func setUp() {\n super.setUp()\n inputIndices = Array(repeating: 0 ..< inputString.utf16.count, count: count)\n }\n}\n\n/// This is like `UTF16ToIdx` but appends to the string after every index\n/// conversion. In effect, this tests breadcrumb creation performance.\nclass MutatedUTF16ToIdx: BenchmarkBase {\n let count: Int\n var inputOffsets: [Int] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(\n name: "Breadcrumbs.MutatedUTF16ToIdx",\n workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var generator = SplitMix64(seed: 42)\n let range = 0 ..< inputString.utf16.count\n inputOffsets = Array(range.shuffled(using: &generator).prefix(count))\n }\n\n override func tearDown() {\n super.tearDown()\n inputOffsets = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n var flag = true\n for _ in 0 ..< iterations {\n var string = inputString\n for offset in inputOffsets {\n blackHole(string._toUTF16Index(offset))\n if flag {\n string.append(" ")\n } else {\n string.removeLast()\n }\n flag.toggle()\n }\n }\n }\n}\n\n\n/// This is like `IdxToUTF16` but appends to the string after every index\n/// conversion. In effect, this tests breadcrumb creation performance.\nclass MutatedIdxToUTF16: BenchmarkBase {\n let count: Int\n var inputIndices: [String.Index] = []\n\n init(workload: Workload, count: Int) {\n self.count = count\n super.init(\n name: "Breadcrumbs.MutatedIdxToUTF16",\n workload: workload)\n }\n\n override func setUp() {\n super.setUp()\n var rng = SplitMix64(seed: 42)\n inputIndices = Array(inputString.indices.shuffled(using: &rng).prefix(count))\n }\n\n override func tearDown() {\n super.tearDown()\n inputIndices = []\n }\n\n @inline(never)\n override func run(iterations: Int) {\n var flag = true\n for _ in 0 ..< iterations {\n var string = inputString\n for index in inputIndices {\n blackHole(string._toUTF16Offset(index))\n if flag {\n string.append(" ")\n flag = false\n } else {\n string.removeLast()\n flag = true\n }\n }\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Breadcrumbs.swift | cpp_apple_swift_benchmark_single-source_Breadcrumbs.swift | Swift | 17,840 | 0.95 | 0.061144 | 0.094037 | vue-tools | 407 | 2024-03-30T18:08:06.169673 | BSD-3-Clause | false | 19561e42bc07051b46b3e9dfb69e7e0c |
//===--- BucketSort.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// This benchmark demonstrates the benefits of ExistentialSpecializer\n// optimization pass. It's a generic version of the classic BucketSort algorithm\n// adapted from an original implementation from the Swift Algorithm Club.\n// See https://en.wikipedia.org/wiki/Bucket_sort and\n// https://github.com/raywenderlich/swift-algorithm-club/tree/master/Bucket%20Sort\n//\n// It sorts an array of generic `SortableItem`s. If the type of `sortingAlgo`\n// is not known to the call site at line 89, the `sort` method can not be\n// specialized to integer array sorting, which will lead to a huge performance\n// loss. Since `SortingAlgorithm` and `InsertionSort` are declared to be\n// `public` and the lines 88-90 can not be inlined in `bucketSort` (due to\n// inlining heuristic limitations), compiler without ExistentialSpecializer\n// optimization can not achieve this feat. With ExistentialSpecializer which\n// enables generic specialization recursively in a call chain, we're able to\n// specialize line 89 for `InsertionSort` on integers.\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "BucketSort",\n runFunction: run_BucketSort,\n tags: [.validation, .algorithm],\n setUpFunction: { blackHole(buckets) }\n )\n\npublic protocol IntegerConvertible {\n func convertToInt() -> Int\n}\n\nextension Int: IntegerConvertible, SortableItem {\n public func convertToInt() -> Int {\n return self\n }\n}\n\npublic protocol SortableItem: IntegerConvertible, Comparable { }\n\npublic protocol SortingAlgorithm {\n func sort<T: SortableItem>(_ items: [T]) -> [T]\n}\n\npublic struct InsertionSort: SortingAlgorithm {\n public func sort<T: SortableItem>(_ items: [T]) -> [T] {\n var sortedItems = items\n for i in 0 ..< sortedItems.count {\n var j = i\n while j > 0 && sortedItems[j-1] > sortedItems[j] {\n let temp = sortedItems[j-1]\n sortedItems[j-1] = sortedItems[j]\n sortedItems[j] = temp\n j -= 1\n }\n }\n return sortedItems\n }\n}\n\nfunc distribute<T>(_ item: T, bucketArray: inout [Bucket<T>]) {\n let val = item.convertToInt()\n let capacity = bucketArray.first!.capacity\n let index = val / capacity\n bucketArray[index].add(item)\n}\n\nstruct Bucket<T: SortableItem> {\n var items: [T]\n let capacity: Int\n init(capacity: Int) {\n self.capacity = capacity\n items = [T]()\n }\n mutating func add(_ item: T) {\n if items.count < capacity {\n items.append(item)\n }\n }\n func sort(_ sortingAlgo: SortingAlgorithm) -> [T] {\n return sortingAlgo.sort(items)\n }\n}\n\nfunc bucketSort<T>(\n _ items: [T], sortingAlgorithm: SortingAlgorithm, bucketArray: [Bucket<T>]\n) -> [T] {\n var copyBucketArray = bucketArray\n for item in items {\n distribute(item, bucketArray: ©BucketArray)\n }\n var sortedArray = [T]()\n for bucket in copyBucketArray {\n sortedArray += bucket.sort(sortingAlgorithm)\n }\n return sortedArray\n}\n\nfunc isAscending(_ a: [Int]) -> Bool {\n return zip(a, a.dropFirst()).allSatisfy(<=)\n}\n\nlet items: [Int] = {\n var g = SplitMix64(seed: 42)\n return (0..<10_000).map {_ in Int.random(in: 0..<1000, using: &g) }\n}()\n\nlet buckets: [Bucket<Int>] = {\n let bucketCount = 10\n let maxValue = items.max()!.convertToInt()\n let maxCapacity = Int(\n (Double(maxValue + 1) / Double(bucketCount)).rounded(.up))\n return (0..<bucketCount).map { _ in Bucket<Int>(capacity: maxCapacity) }\n}()\n\n@inline(never)\nfunc run_BucketSort(_ n : Int) {\n for _ in 0..<n {\n let sortedArray = bucketSort(\n items, sortingAlgorithm: InsertionSort(), bucketArray: buckets)\n check(isAscending(sortedArray))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_BucketSort.swift | cpp_apple_swift_benchmark_single-source_BucketSort.swift | Swift | 4,178 | 0.95 | 0.068182 | 0.220339 | python-kit | 499 | 2024-07-22T02:48:32.464057 | GPL-3.0 | false | 604e9a4d7d91979d6aafe53ed295e2dd |
//===--- BufferFill.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "BufferFillFromSlice",\n runFunction: bufferFillFromSliceExecute,\n tags: [.validation, .api],\n setUpFunction: bufferFillFromSliceSetup,\n tearDownFunction: bufferFillFromSliceTeardown),\n BenchmarkInfo(name: "RawBufferCopyBytes",\n runFunction: rawBufferCopyBytesExecute,\n tags: [.validation, .api],\n setUpFunction: rawBufferCopyBytesSetup,\n tearDownFunction: rawBufferCopyBytesTeardown),\n BenchmarkInfo(name: "RawBufferInitializeMemory",\n runFunction: rawBufferInitializeMemoryExecute,\n tags: [.validation, .api],\n setUpFunction: rawBufferInitializeMemorySetup,\n tearDownFunction: rawBufferInitializeMemoryTeardown),\n BenchmarkInfo(name: "RawBuffer.copyContents",\n runFunction: rawBufferCopyContentsExecute,\n tags: [.validation, .api],\n setUpFunction: rawBufferCopyContentsSetup,\n tearDownFunction: rawBufferCopyContentsTeardown),\n]\n\nlet c = 100_000\nlet a = Array(0..<c)\nvar b: UnsafeMutableBufferPointer<Int> = .init(start: nil, count: 0)\nvar r = Int.zero\n\npublic func bufferFillFromSliceSetup() {\n assert(b.baseAddress == nil)\n b = .allocate(capacity: c)\n r = a.indices.randomElement()!\n}\n\npublic func bufferFillFromSliceTeardown() {\n b.deallocate()\n b = .init(start: nil, count: 0)\n}\n\n@inline(never)\npublic func bufferFillFromSliceExecute(n: Int) {\n // Measure performance when filling an UnsafeBuffer from a Slice\n // of a Collection that supports `withContiguousStorageIfAvailable`\n // See: https://github.com/apple/swift/issues/56846\n\n for _ in 0..<n {\n let slice = Slice(base: a, bounds: a.indices)\n var (iterator, copied) = b.initialize(from: slice)\n blackHole(b)\n check(copied == a.count && iterator.next() == nil)\n }\n\n check(a[r] == b[r])\n}\n\nvar ra: [UInt8] = []\nvar rb = UnsafeMutableRawBufferPointer(start: nil, count: 0)\n\npublic func rawBufferCopyBytesSetup() {\n assert(rb.baseAddress == nil)\n ra = a.withUnsafeBytes(Array.init)\n r = ra.indices.randomElement()!\n rb = .allocate(byteCount: ra.count, alignment: 1)\n}\n\npublic func rawBufferCopyBytesTeardown() {\n rb.deallocate()\n rb = .init(start: nil, count: 0)\n ra = []\n}\n\n@inline(never)\npublic func rawBufferCopyBytesExecute(n: Int) {\n // Measure performance when copying bytes into an UnsafeRawBuffer\n // from a Collection that supports `withContiguousStorageIfAvailable`\n // See: https://github.com/apple/swift/issues/57233\n\n for _ in 0..<n {\n rb.copyBytes(from: ra)\n blackHole(rb)\n }\n\n check(ra[r] == rb[r])\n}\n\npublic func rawBufferInitializeMemorySetup() {\n assert(rb.baseAddress == nil)\n rb = .allocate(byteCount: a.count * MemoryLayout<Int>.stride, alignment: 1)\n r = a.indices.randomElement()!\n}\n\npublic func rawBufferInitializeMemoryTeardown() {\n rb.deallocate()\n rb = .init(start: nil, count: 0)\n}\n\n@inline(never)\npublic func rawBufferInitializeMemoryExecute(n: Int) {\n // Measure performance when initializing an UnsafeRawBuffer\n // from a Collection that supports `withContiguousStorageIfAvailable`\n // See: https://github.com/apple/swift/issues/57324\n\n for _ in 0..<n {\n var (iterator, initialized) = rb.initializeMemory(as: Int.self, from: a)\n blackHole(rb)\n check(initialized.count == a.count && iterator.next() == nil)\n }\n\n let offset = rb.baseAddress!.advanced(by: r*MemoryLayout<Int>.stride)\n let value = offset.load(as: Int.self)\n check(value == a[r])\n}\n\nvar r8: UnsafeRawBufferPointer = .init(start: nil, count: 0)\nvar b8: UnsafeMutableBufferPointer<UInt8> = .init(start: nil, count: 0)\n\npublic func rawBufferCopyContentsSetup() {\n assert(r8.baseAddress == nil)\n let count = a.count * MemoryLayout<Int>.stride\n let rb = UnsafeMutableRawBufferPointer.allocate(\n byteCount: count, \n alignment: MemoryLayout<Int>.alignment)\n a.withUnsafeBytes {\n rb.copyMemory(from: $0)\n }\n r8 = UnsafeRawBufferPointer(rb)\n assert(b8.baseAddress == nil)\n b8 = .allocate(capacity: rb.count)\n r = rb.indices.randomElement()!\n}\n\npublic func rawBufferCopyContentsTeardown() {\n r8.deallocate()\n r8 = .init(start: nil, count: 0)\n b8.deallocate()\n b8 = .init(start: nil, count: 0)\n}\n\n@inline(never)\npublic func rawBufferCopyContentsExecute(n: Int) {\n // Measure performance of copying bytes from an\n // `UnsafeRawBufferPointer` to an `UnsafeMutableBufferPointer<UInt8>`.\n // See: https://github.com/apple/swift/issues/52050\n\n for _ in 0..<n {\n var (iterator, initialized) = b8.initialize(from: r8)\n blackHole(b8)\n check(initialized == r8.count && iterator.next() == nil)\n }\n\n check(b8[r] == r8[r])\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_BufferFill.swift | cpp_apple_swift_benchmark_single-source_BufferFill.swift | Swift | 5,277 | 0.95 | 0.036145 | 0.163121 | awesome-app | 319 | 2025-02-03T06:28:01.961366 | Apache-2.0 | false | f8f00a7ef34a9233e3ba5b0446b4284c |
//===--- BufferFind.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic var benchmarks: [BenchmarkInfo] = [\n // size 1000, alignment 0\n BenchmarkInfo(\n name: "RawBuffer.1000.findFirst",\n runFunction: run_BufferFindFirst,\n tags: [.validation, .api],\n setUpFunction: buffer1000Setup,\n tearDownFunction: bufferTeardown\n ),\n BenchmarkInfo(\n name: "RawBuffer.1000.findLast",\n runFunction: run_BufferFindLast,\n tags: [.validation, .api],\n setUpFunction: buffer1000Setup,\n tearDownFunction: bufferTeardown\n ),\n // size 128, alignment 0\n BenchmarkInfo(\n name: "RawBuffer.128.findFirst",\n runFunction: run_BufferFindFirst,\n tags: [.validation, .api, .skip],\n setUpFunction: buffer128Setup,\n tearDownFunction: bufferTeardown\n ),\n BenchmarkInfo(\n name: "RawBuffer.128.findLast",\n runFunction: run_BufferFindLast,\n tags: [.validation, .api],\n setUpFunction: buffer128Setup,\n tearDownFunction: bufferTeardown\n ),\n // size 39, alignment 0\n BenchmarkInfo(\n name: "RawBuffer.39.findFirst",\n runFunction: run_BufferFindFirst,\n tags: [.validation, .api],\n setUpFunction: buffer39Setup,\n tearDownFunction: bufferTeardown\n ),\n BenchmarkInfo(\n name: "RawBuffer.39.findLast",\n runFunction: run_BufferFindLast,\n tags: [.validation, .api],\n setUpFunction: buffer39Setup,\n tearDownFunction: bufferTeardown\n ),\n // size 7, alignment 0\n BenchmarkInfo(\n name: "RawBuffer.7.findFirst",\n runFunction: run_BufferFindFirst,\n tags: [.validation, .api],\n setUpFunction: buffer7Setup,\n tearDownFunction: bufferTeardown\n ),\n BenchmarkInfo(\n name: "RawBuffer.7.findLast",\n runFunction: run_BufferFindLast,\n tags: [.validation, .api],\n setUpFunction: buffer7Setup,\n tearDownFunction: bufferTeardown\n )\n]\n\nvar buffer: UnsafeMutableRawBufferPointer = .init(start: nil, count: 0)\n\nfunc buffer1000Setup() {\n bufferSetup(size: 1000, alignment: 0)\n}\n\nfunc buffer128Setup() {\n bufferSetup(size: 128, alignment: 0)\n}\n\nfunc buffer39Setup() {\n bufferSetup(size: 39, alignment: 0)\n}\n\nfunc buffer7Setup() {\n bufferSetup(size: 7, alignment: 0)\n}\n\nfunc bufferTeardown() {\n buffer.deallocate()\n buffer = .init(start: nil, count: 0)\n}\n\nfunc bufferSetup(size: Int, alignment: Int) {\n buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: size, alignment: alignment)\n buffer.initializeMemory(as: UInt8.self, repeating: UInt8.min)\n buffer[size / 2] = UInt8.max\n}\n\n@inline(never)\npublic func run_BufferFindFirst(n: Int) {\n var offset = 0\n for _ in 0 ..< n * 10_000 {\n if let index = buffer.firstIndex(of: UInt8.max) {\n offset += index\n }\n }\n blackHole(offset)\n}\n\n@inline(never)\npublic func run_BufferFindLast(n: Int) {\n var offset = 0\n for _ in 0 ..< n * 10_000 {\n if let index = buffer.lastIndex(of: UInt8.max) {\n offset += index\n }\n }\n blackHole(offset)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_BufferFind.swift | cpp_apple_swift_benchmark_single-source_BufferFind.swift | Swift | 3,345 | 0.95 | 0.047244 | 0.12931 | vue-tools | 311 | 2024-07-31T06:55:53.718409 | Apache-2.0 | false | fc0cfb576134ab983914a54c4a591f9f |
//===--- ByteSwap.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of Swift byte swap.\n// rdar://problem/22151907\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ByteSwap",\n runFunction: run_ByteSwap,\n tags: [.validation, .algorithm])\n\n// a naive O(n) implementation of byteswap.\n@inline(never)\nfunc byteswap_n(_ a: UInt64) -> UInt64 {\n return ((a & 0x00000000000000FF) &<< 56) |\n ((a & 0x000000000000FF00) &<< 40) |\n ((a & 0x0000000000FF0000) &<< 24) |\n ((a & 0x00000000FF000000) &<< 8) |\n ((a & 0x000000FF00000000) &>> 8) |\n ((a & 0x0000FF0000000000) &>> 24) |\n ((a & 0x00FF000000000000) &>> 40) |\n ((a & 0xFF00000000000000) &>> 56)\n}\n\n// a O(logn) implementation of byteswap.\n@inline(never)\nfunc byteswap_logn(_ a: UInt64) -> UInt64 {\n var a = a\n a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32\n a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16\n a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8\n return a\n}\n\n@inline(never)\npublic func run_ByteSwap(_ n: Int) {\n var s: UInt64 = 0\n for _ in 1...10000*n {\n // Check some results.\n let x : UInt64 = UInt64(getInt(0))\n s = s &+ byteswap_logn(byteswap_n(x &+ 2457))\n &+ byteswap_logn(byteswap_n(x &+ 9129))\n &+ byteswap_logn(byteswap_n(x &+ 3333))\n }\n check(s == (2457 &+ 9129 &+ 3333) &* 10000 &* n)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ByteSwap.swift | cpp_apple_swift_benchmark_single-source_ByteSwap.swift | Swift | 1,917 | 0.95 | 0.051724 | 0.307692 | python-kit | 262 | 2024-05-28T21:41:53.790613 | MIT | false | 3c091a9f8ffc0dee361b273790379db8 |
//===--- Calculator.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Calculator",\n runFunction: run_Calculator,\n tags: [.validation])\n\n@inline(never)\nfunc my_atoi_impl(_ input : String) -> Int {\n switch input {\n case "0": return 0\n case "1": return 1\n case "2": return 2\n case "3": return 3\n case "4": return 4\n case "5": return 5\n case "6": return 6\n case "7": return 7\n case "8": return 8\n case "9": return 9\n default: return 0\n }\n}\n\n@inline(never)\npublic func run_Calculator(_ n: Int) {\n var c = 0\n for _ in 1...n*800 {\n c += my_atoi_impl(identity("1"))\n c += my_atoi_impl(identity("2"))\n c += my_atoi_impl(identity("3"))\n c += my_atoi_impl(identity("4"))\n c += my_atoi_impl(identity("5"))\n c += my_atoi_impl(identity("6"))\n c += my_atoi_impl(identity("7"))\n c += my_atoi_impl(identity("8"))\n c += my_atoi_impl(identity("9"))\n c += my_atoi_impl(identity("10"))\n c -= 45\n }\n check(c == 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Calculator.swift | cpp_apple_swift_benchmark_single-source_Calculator.swift | Swift | 1,515 | 0.95 | 0.072727 | 0.215686 | node-utils | 247 | 2024-12-08T22:31:22.074116 | Apache-2.0 | false | 957b781c22bba88b43e1c7e7cb22a32a |
//===--- CaptureProp.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "CaptureProp",\n runFunction: run_CaptureProp,\n tags: [.validation, .api, .refcount],\n legacyFactor: 10)\n\nfunc sum(_ x:Int, y:Int) -> Int {\n return x + y\n}\n\n@inline(never)\nfunc benchCaptureProp<S : Sequence\n>(\n _ s: S, _ f: (S.Element, S.Element) -> S.Element) -> S.Element {\n\n var it = s.makeIterator()\n let initial = it.next()!\n return IteratorSequence(it).reduce(initial, f)\n}\n\npublic func run_CaptureProp(_ n: Int) {\n let a = 1...10_000\n for _ in 1...10*n {\n _ = benchCaptureProp(a, sum)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CaptureProp.swift | cpp_apple_swift_benchmark_single-source_CaptureProp.swift | Swift | 1,106 | 0.95 | 0.073171 | 0.314286 | vue-tools | 563 | 2024-05-07T00:54:52.163995 | BSD-3-Clause | false | 178dad9beba4049dd5584018acbc8c5f |
//===--- ChaCha.swift -----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n/// This benchmark tests two things:\n///\n/// 1. Swift's ability to optimise low-level bit twiddling code.\n/// 2. Swift's ability to optimise generic code when using contiguous data structures.\n///\n/// In principle initializing ChaCha20's state and then xoring the keystream with the\n/// plaintext should be able to be vectorised.\nenum ChaCha20 { }\n\nextension ChaCha20 {\n @inline(never)\n public static func encrypt<Key: Collection, Nonce: Collection, Bytes: MutableCollection>(bytes: inout Bytes, key: Key, nonce: Nonce, initialCounter: UInt32 = 0) where Bytes.Element == UInt8, Key.Element == UInt8, Nonce.Element == UInt8 {\n var baseState = ChaChaState(key: key, nonce: nonce, counter: initialCounter)\n var index = bytes.startIndex\n\n while index < bytes.endIndex {\n let keyStream = baseState.block()\n keyStream.xorBytes(bytes: &bytes, at: &index)\n baseState.incrementCounter()\n }\n }\n}\n\n\ntypealias BackingState = (UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32)\n\nstruct ChaChaState {\n /// The ChaCha20 algorithm has 16 32-bit integer numbers as its state.\n /// They are traditionally laid out as a matrix: we do the same.\n var _state: BackingState\n\n /// Create a ChaChaState.\n ///\n /// The inputs to ChaCha20 are:\n ///\n /// - A 256-bit key, treated as a concatenation of eight 32-bit little-\n /// endian integers.\n /// - A 96-bit nonce, treated as a concatenation of three 32-bit little-\n /// endian integers.\n /// - A 32-bit block count parameter, treated as a 32-bit little-endian\n /// integer.\n init<Key: Collection, Nonce: Collection>(key: Key, nonce: Nonce, counter: UInt32) where Key.Element == UInt8, Nonce.Element == UInt8 {\n guard key.count == 32 && nonce.count == 12 else {\n fatalError("Invalid key or nonce length.")\n }\n\n // The ChaCha20 state is initialized as follows:\n //\n // - The first four words (0-3) are constants: 0x61707865, 0x3320646e,\n // 0x79622d32, 0x6b206574.\n self._state.0 = 0x61707865\n self._state.1 = 0x3320646e\n self._state.2 = 0x79622d32\n self._state.3 = 0x6b206574\n\n // - The next eight words (4-11) are taken from the 256-bit key by\n // reading the bytes in little-endian order, in 4-byte chunks.\n //\n // We force unwrap here because we have already preconditioned on the length.\n var keyIterator = CollectionOf32BitLittleEndianIntegers(key).makeIterator()\n self._state.4 = keyIterator.next()!\n self._state.5 = keyIterator.next()!\n self._state.6 = keyIterator.next()!\n self._state.7 = keyIterator.next()!\n self._state.8 = keyIterator.next()!\n self._state.9 = keyIterator.next()!\n self._state.10 = keyIterator.next()!\n self._state.11 = keyIterator.next()!\n\n\n // - Word 12 is a block counter. Since each block is 64-byte, a 32-bit\n // word is enough for 256 gigabytes of data.\n self._state.12 = counter\n\n // - Words 13-15 are a nonce, which should not be repeated for the same\n // key. The 13th word is the first 32 bits of the input nonce taken\n // as a little-endian integer, while the 15th word is the last 32\n // bits.\n //\n // Again, we forcibly unwrap these bytes.\n var nonceIterator = CollectionOf32BitLittleEndianIntegers(nonce).makeIterator()\n self._state.13 = nonceIterator.next()!\n self._state.14 = nonceIterator.next()!\n self._state.15 = nonceIterator.next()!\n }\n\n /// As a performance enhancement, it is often useful to be able to increment the counter portion directly. This avoids the\n /// expensive construction cost of the ChaCha state for each next sequence of bytes of the keystream.\n mutating func incrementCounter() {\n self._state.12 &+= 1\n }\n\n\n private mutating func add(_ otherState: ChaChaState) {\n self._state.0 &+= otherState._state.0\n self._state.1 &+= otherState._state.1\n self._state.2 &+= otherState._state.2\n self._state.3 &+= otherState._state.3\n self._state.4 &+= otherState._state.4\n self._state.5 &+= otherState._state.5\n self._state.6 &+= otherState._state.6\n self._state.7 &+= otherState._state.7\n self._state.8 &+= otherState._state.8\n self._state.9 &+= otherState._state.9\n self._state.10 &+= otherState._state.10\n self._state.11 &+= otherState._state.11\n self._state.12 &+= otherState._state.12\n self._state.13 &+= otherState._state.13\n self._state.14 &+= otherState._state.14\n self._state.15 &+= otherState._state.15\n }\n\n private mutating func columnRound() {\n // The column round:\n //\n // 1. QUARTERROUND ( 0, 4, 8,12)\n // 2. QUARTERROUND ( 1, 5, 9,13)\n // 3. QUARTERROUND ( 2, 6,10,14)\n // 4. QUARTERROUND ( 3, 7,11,15)\n ChaChaState.quarterRound(a: &self._state.0, b: &self._state.4, c: &self._state.8, d: &self._state.12)\n ChaChaState.quarterRound(a: &self._state.1, b: &self._state.5, c: &self._state.9, d: &self._state.13)\n ChaChaState.quarterRound(a: &self._state.2, b: &self._state.6, c: &self._state.10, d: &self._state.14)\n ChaChaState.quarterRound(a: &self._state.3, b: &self._state.7, c: &self._state.11, d: &self._state.15)\n }\n\n private mutating func diagonalRound() {\n // The diagonal round:\n //\n // 5. QUARTERROUND ( 0, 5,10,15)\n // 6. QUARTERROUND ( 1, 6,11,12)\n // 7. QUARTERROUND ( 2, 7, 8,13)\n // 8. QUARTERROUND ( 3, 4, 9,14)\n ChaChaState.quarterRound(a: &self._state.0, b: &self._state.5, c: &self._state.10, d: &self._state.15)\n ChaChaState.quarterRound(a: &self._state.1, b: &self._state.6, c: &self._state.11, d: &self._state.12)\n ChaChaState.quarterRound(a: &self._state.2, b: &self._state.7, c: &self._state.8, d: &self._state.13)\n ChaChaState.quarterRound(a: &self._state.3, b: &self._state.4, c: &self._state.9, d: &self._state.14)\n }\n}\n\nextension ChaChaState {\n static func quarterRound(a: inout UInt32, b: inout UInt32, c: inout UInt32, d: inout UInt32) {\n // The ChaCha quarter round. This is almost identical to the definition from RFC 7539\n // except that we use &+= instead of += because overflow modulo 32 is expected.\n a &+= b; d ^= a; d <<<= 16\n c &+= d; b ^= c; b <<<= 12\n a &+= b; d ^= a; d <<<= 8\n c &+= d; b ^= c; b <<<= 7\n }\n}\n\nextension ChaChaState {\n func block() -> ChaChaKeystreamBlock {\n var stateCopy = self // We need this copy. This is cheaper than initializing twice.\n\n // The ChaCha20 block runs 10 double rounds (a total of 20 rounds), made of one column and\n // one diagonal round.\n for _ in 0..<10 {\n stateCopy.columnRound()\n stateCopy.diagonalRound()\n }\n\n // We add the original input words to the output words.\n stateCopy.add(self)\n\n return ChaChaKeystreamBlock(stateCopy)\n }\n}\n\n\n/// The result of running the ChaCha block function on a given set of ChaCha state.\n///\n/// This result has a distinct set of behaviours compared to the ChaChaState object, so we give it a different\n/// (and more constrained) type.\nstruct ChaChaKeystreamBlock {\n var _state: BackingState\n\n init(_ state: ChaChaState) {\n self._state = state._state\n }\n\n /// A nice thing we can do with a ChaCha keystream block is xor it with some bytes.\n ///\n /// This helper function exists because we want a hook to do fast, in-place encryption of bytes.\n func xorBytes<Bytes: MutableCollection>(bytes: inout Bytes, at index: inout Bytes.Index) where Bytes.Element == UInt8 {\n // This is a naive implementation of this loop but I'm interested in testing the Swift compiler's ability\n // to optimise this. If we have a programmatic way to roll up this loop I'd love to hear it!\n self._state.0.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.1.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.2.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.3.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.4.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.5.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.6.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.7.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.8.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.9.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.10.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.11.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.12.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.13.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.14.xorLittleEndianBytes(bytes: &bytes, at: &index)\n if index == bytes.endIndex { return }\n self._state.15.xorLittleEndianBytes(bytes: &bytes, at: &index)\n }\n}\n\n\ninfix operator <<<: BitwiseShiftPrecedence\n\ninfix operator <<<=: AssignmentPrecedence\n\n\nextension FixedWidthInteger {\n func leftRotate(_ distance: Int) -> Self {\n return (self << distance) | (self >> (Self.bitWidth - distance))\n }\n\n mutating func rotatedLeft(_ distance: Int) {\n self = self.leftRotate(distance)\n }\n\n static func <<<(lhs: Self, rhs: Int) -> Self {\n return lhs.leftRotate(rhs)\n }\n\n static func <<<=(lhs: inout Self, rhs: Int) {\n lhs.rotatedLeft(rhs)\n }\n}\n\n\nstruct CollectionOf32BitLittleEndianIntegers<BaseCollection: Collection> where BaseCollection.Element == UInt8 {\n var baseCollection: BaseCollection\n\n init(_ baseCollection: BaseCollection) {\n precondition(baseCollection.count % 4 == 0)\n self.baseCollection = baseCollection\n }\n}\n\nextension CollectionOf32BitLittleEndianIntegers: Collection {\n typealias Element = UInt32\n\n struct Index {\n var baseIndex: BaseCollection.Index\n\n init(_ baseIndex: BaseCollection.Index) {\n self.baseIndex = baseIndex\n }\n }\n\n var startIndex: Index {\n return Index(self.baseCollection.startIndex)\n }\n\n var endIndex: Index {\n return Index(self.baseCollection.endIndex)\n }\n\n func index(after index: Index) -> Index {\n return Index(self.baseCollection.index(index.baseIndex, offsetBy: 4))\n }\n\n subscript(_ index: Index) -> UInt32 {\n var baseIndex = index.baseIndex\n var result = UInt32(0)\n\n for shift in stride(from: 0, through: 24, by: 8) {\n result |= UInt32(self.baseCollection[baseIndex]) << shift\n self.baseCollection.formIndex(after: &baseIndex)\n }\n\n return result\n }\n}\n\nextension CollectionOf32BitLittleEndianIntegers.Index: Equatable {\n static func ==(lhs: Self, rhs: Self) -> Bool {\n return lhs.baseIndex == rhs.baseIndex\n }\n}\n\nextension CollectionOf32BitLittleEndianIntegers.Index: Comparable {\n static func <(lhs: Self, rhs: Self) -> Bool {\n return lhs.baseIndex < rhs.baseIndex\n }\n\n static func <=(lhs: Self, rhs: Self) -> Bool {\n return lhs.baseIndex <= rhs.baseIndex\n }\n\n static func >(lhs: Self, rhs: Self) -> Bool {\n return lhs.baseIndex > rhs.baseIndex\n }\n\n static func >=(lhs: Self, rhs: Self) -> Bool {\n return lhs.baseIndex >= rhs.baseIndex\n }\n}\n\n\nextension UInt32 {\n /// Performs an xor operation on up to 4 bytes of the mutable collection.\n func xorLittleEndianBytes<Bytes: MutableCollection>(bytes: inout Bytes, at index: inout Bytes.Index) where Bytes.Element == UInt8 {\n var loopCount = 0\n while index < bytes.endIndex && loopCount < 4 {\n bytes[index] ^= UInt8((self >> (loopCount * 8)) & UInt32(0xFF))\n bytes.formIndex(after: &index)\n loopCount += 1\n }\n }\n}\n\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "ChaCha",\n runFunction: run_ChaCha,\n tags: [.runtime, .cpubench]),\n]\n\n@inline(never)\nfunc checkResult(_ plaintext: [UInt8]) {\n check(plaintext.first! == 6 && plaintext.last! == 254)\n var hash: UInt64 = 0\n for byte in plaintext {\n // rotate\n hash = (hash &<< 8) | (hash &>> (64 - 8))\n hash ^= UInt64(byte)\n }\n check(hash == 0xa1bcdb217d8d14e4)\n}\n\n@inline(never)\npublic func run_ChaCha(_ n: Int) {\n let key = Array(repeating: UInt8(1), count: 32)\n let nonce = Array(repeating: UInt8(2), count: 12)\n\n var checkedtext = Array(repeating: UInt8(0), count: 1024)\n ChaCha20.encrypt(bytes: &checkedtext, key: key, nonce: nonce)\n checkResult(checkedtext)\n\n var plaintext = Array(repeating: UInt8(0), count: 30720) // Chosen for CI runtime\n for _ in 1...n {\n ChaCha20.encrypt(bytes: &plaintext, key: key, nonce: nonce)\n blackHole(plaintext.first!)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ChaCha.swift | cpp_apple_swift_benchmark_single-source_ChaCha.swift | Swift | 14,406 | 0.95 | 0.079156 | 0.238245 | python-kit | 591 | 2024-01-18T12:08:25.463878 | Apache-2.0 | false | 3d957c6080f92fbd26519b63941cf549 |
import TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "ChainedFilterMap", runFunction: run_ChainedFilterMap,\n tags: [.algorithm], setUpFunction: { blackHole(first100k) },\n legacyFactor: 9),\n BenchmarkInfo(name: "FatCompactMap", runFunction: run_FatCompactMap,\n tags: [.algorithm], setUpFunction: { blackHole(first100k) },\n legacyFactor: 10)\n]\n\npublic let first100k = Array(0...100_000-1)\n\n@inline(never)\npublic func run_ChainedFilterMap(_ n: Int) {\n var result = 0\n for _ in 1...n {\n let numbers = first100k.lazy\n .filter { $0 % 3 == 0 }\n .map { $0 * 2 }\n .filter { $0 % 8 == 0 }\n .map { $0 / 2 + 1}\n result = numbers.reduce(into: 0) { $0 += $1 }\n }\n\n check(result == 416691666)\n}\n\n@inline(never)\npublic func run_FatCompactMap(_ n: Int) {\n var result = 0\n for _ in 1...n {\n let numbers = first100k.lazy\n .compactMap { (x: Int) -> Int? in\n if x % 3 != 0 { return nil }\n let y = x * 2\n if y % 8 != 0 { return nil }\n let z = y / 2 + 1\n return z\n }\n result = numbers.reduce(into: 0) { $0 += $1 }\n }\n check(result == 416691666)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ChainedFilterMap.swift | cpp_apple_swift_benchmark_single-source_ChainedFilterMap.swift | Swift | 1,136 | 0.85 | 0.090909 | 0 | node-utils | 652 | 2024-10-11T14:49:42.965415 | GPL-3.0 | false | ed56d3ab99319651091cbee0aec3da6f |
//===--- CharacterLiteralsLarge.swift -------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test tests the performance of Characters initialized from literals\n// which don't fit into the small (63-bit) representation and need to allocate\n// and retain a StringBuffer.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "CharacterLiteralsLarge",\n runFunction: run_CharacterLiteralsLarge,\n tags: [.validation, .api, .String])\n\n@inline(never)\nfunc makeCharacter_UTF8Length9() -> Character {\n return "a\u{0300}\u{0301}\u{0302}\u{0303}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length10() -> Character {\n return "\u{00a9}\u{0300}\u{0301}\u{0302}\u{0303}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length11() -> Character {\n return "a\u{0300}\u{0301}\u{0302}\u{0303}\u{0304}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length12() -> Character {\n return "\u{00a9}\u{0300}\u{0301}\u{0302}\u{0303}\u{0304}"\n}\n\npublic func run_CharacterLiteralsLarge(_ n: Int) {\n for _ in 0...10000 * n {\n _ = makeCharacter_UTF8Length9()\n _ = makeCharacter_UTF8Length10()\n _ = makeCharacter_UTF8Length11()\n _ = makeCharacter_UTF8Length12()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CharacterLiteralsLarge.swift | cpp_apple_swift_benchmark_single-source_CharacterLiteralsLarge.swift | Swift | 1,594 | 0.95 | 0.058824 | 0.318182 | python-kit | 413 | 2024-12-18T01:29:38.521595 | GPL-3.0 | false | 11a04a5c2ca196c1bc60bb8b27ae0cc1 |
//===--- CharacterLiteralsSmall.swift -------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test tests the performance of Characters initialized from literals that\n// fit within the small (63 bits or fewer) representation and can be\n// represented as a packed integer.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "CharacterLiteralsSmall",\n runFunction: run_CharacterLiteralsSmall,\n tags: [.validation, .api, .String])\n\n@inline(never)\nfunc makeCharacter_UTF8Length1() -> Character {\n return "a"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length2() -> Character {\n return "\u{00a9}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length3() -> Character {\n return "a\u{0300}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length4() -> Character {\n return "\u{00a9}\u{0300}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length5() -> Character {\n return "a\u{0300}\u{0301}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length6() -> Character {\n return "\u{00a9}\u{0300}\u{0301}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length7() -> Character {\n return "a\u{0300}\u{0301}\u{0302}"\n}\n\n@inline(never)\nfunc makeCharacter_UTF8Length8() -> Character {\n return "\u{00a9}\u{0300}\u{0301}\u{0302}"\n}\n\n@inline(never)\nfunc makeLiterals() {\n blackHole(makeCharacter_UTF8Length1())\n blackHole(makeCharacter_UTF8Length2())\n blackHole(makeCharacter_UTF8Length3())\n blackHole(makeCharacter_UTF8Length4())\n blackHole(makeCharacter_UTF8Length5())\n blackHole(makeCharacter_UTF8Length6())\n blackHole(makeCharacter_UTF8Length7())\n blackHole(makeCharacter_UTF8Length8())\n}\n\npublic func run_CharacterLiteralsSmall(_ n: Int) {\n for _ in 0...10000 * n {\n makeLiterals()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CharacterLiteralsSmall.swift | cpp_apple_swift_benchmark_single-source_CharacterLiteralsSmall.swift | Swift | 2,114 | 0.95 | 0.0375 | 0.205882 | node-utils | 56 | 2024-03-29T09:02:18.725479 | MIT | false | 7d433379b457bf6431333ae444b455c2 |
//===--- CharacterProperties.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to CharacterProperties.swift.gyb\n// and run scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\nimport Foundation\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CharacterPropertiesFetch",\n runFunction: run_CharacterPropertiesFetch,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload) },\n legacyFactor: 10),\n\n BenchmarkInfo(\n name: "CharacterPropertiesStashed",\n runFunction: run_CharacterPropertiesStashed,\n tags: [.validation, .api, .String],\n setUpFunction: { setupStash() },\n legacyFactor: 10),\n\n BenchmarkInfo(\n name: "CharacterPropertiesStashedMemo",\n runFunction: run_CharacterPropertiesStashedMemo,\n tags: [.validation, .api, .String],\n setUpFunction: { setupMemo() },\n legacyFactor: 10),\n\n BenchmarkInfo(\n name: "CharacterPropertiesPrecomputed",\n runFunction: run_CharacterPropertiesPrecomputed,\n tags: [.validation, .api, .String],\n setUpFunction: { setupPrecomputed() },\n legacyFactor: 10),\n]\n\nextension Character {\n var firstScalar: UnicodeScalar { return unicodeScalars.first! }\n}\n\n\n// Fetch the CharacterSet for every call\nfunc isAlphanumeric(_ c: Character) -> Bool {\n return CharacterSet.alphanumerics.contains(c.firstScalar)\n}\nfunc isCapitalized(_ c: Character) -> Bool {\n return CharacterSet.capitalizedLetters.contains(c.firstScalar)\n}\nfunc isControl(_ c: Character) -> Bool {\n return CharacterSet.controlCharacters.contains(c.firstScalar)\n}\nfunc isDecimal(_ c: Character) -> Bool {\n return CharacterSet.decimalDigits.contains(c.firstScalar)\n}\nfunc isLetter(_ c: Character) -> Bool {\n return CharacterSet.letters.contains(c.firstScalar)\n}\nfunc isLowercase(_ c: Character) -> Bool {\n return CharacterSet.lowercaseLetters.contains(c.firstScalar)\n}\nfunc isUppercase(_ c: Character) -> Bool {\n return CharacterSet.uppercaseLetters.contains(c.firstScalar)\n}\nfunc isNewline(_ c: Character) -> Bool {\n return CharacterSet.newlines.contains(c.firstScalar)\n}\nfunc isWhitespace(_ c: Character) -> Bool {\n return CharacterSet.whitespaces.contains(c.firstScalar)\n}\nfunc isPunctuation(_ c: Character) -> Bool {\n return CharacterSet.punctuationCharacters.contains(c.firstScalar)\n}\n\n// Stash the set\nlet alphanumerics = CharacterSet.alphanumerics\nfunc isAlphanumericStashed(_ c: Character) -> Bool {\n return alphanumerics.contains(c.firstScalar)\n}\nlet capitalizedLetters = CharacterSet.capitalizedLetters\nfunc isCapitalizedStashed(_ c: Character) -> Bool {\n return capitalizedLetters.contains(c.firstScalar)\n}\nlet controlCharacters = CharacterSet.controlCharacters\nfunc isControlStashed(_ c: Character) -> Bool {\n return controlCharacters.contains(c.firstScalar)\n}\nlet decimalDigits = CharacterSet.decimalDigits\nfunc isDecimalStashed(_ c: Character) -> Bool {\n return decimalDigits.contains(c.firstScalar)\n}\nlet letters = CharacterSet.letters\nfunc isLetterStashed(_ c: Character) -> Bool {\n return letters.contains(c.firstScalar)\n}\nlet lowercaseLetters = CharacterSet.lowercaseLetters\nfunc isLowercaseStashed(_ c: Character) -> Bool {\n return lowercaseLetters.contains(c.firstScalar)\n}\nlet uppercaseLetters = CharacterSet.uppercaseLetters\nfunc isUppercaseStashed(_ c: Character) -> Bool {\n return uppercaseLetters.contains(c.firstScalar)\n}\nlet newlines = CharacterSet.newlines\nfunc isNewlineStashed(_ c: Character) -> Bool {\n return newlines.contains(c.firstScalar)\n}\nlet whitespaces = CharacterSet.whitespaces\nfunc isWhitespaceStashed(_ c: Character) -> Bool {\n return whitespaces.contains(c.firstScalar)\n}\nlet punctuationCharacters = CharacterSet.punctuationCharacters\nfunc isPunctuationStashed(_ c: Character) -> Bool {\n return punctuationCharacters.contains(c.firstScalar)\n}\n\nfunc setupStash() {\n blackHole(workload)\n blackHole(alphanumerics)\n blackHole(capitalizedLetters)\n blackHole(controlCharacters)\n blackHole(decimalDigits)\n blackHole(letters)\n blackHole(lowercaseLetters)\n blackHole(uppercaseLetters)\n blackHole(newlines)\n blackHole(whitespaces)\n blackHole(punctuationCharacters)\n}\n\n// Memoize the stashed set\nvar alphanumericsMemo = Set<UInt32>()\nfunc isAlphanumericStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if alphanumericsMemo.contains(scalar.value) { return true }\n if alphanumerics.contains(scalar) {\n alphanumericsMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar capitalizedLettersMemo = Set<UInt32>()\nfunc isCapitalizedStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if capitalizedLettersMemo.contains(scalar.value) { return true }\n if capitalizedLetters.contains(scalar) {\n capitalizedLettersMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar controlCharactersMemo = Set<UInt32>()\nfunc isControlStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if controlCharactersMemo.contains(scalar.value) { return true }\n if controlCharacters.contains(scalar) {\n controlCharactersMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar decimalDigitsMemo = Set<UInt32>()\nfunc isDecimalStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if decimalDigitsMemo.contains(scalar.value) { return true }\n if decimalDigits.contains(scalar) {\n decimalDigitsMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar lettersMemo = Set<UInt32>()\nfunc isLetterStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if lettersMemo.contains(scalar.value) { return true }\n if letters.contains(scalar) {\n lettersMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar lowercaseLettersMemo = Set<UInt32>()\nfunc isLowercaseStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if lowercaseLettersMemo.contains(scalar.value) { return true }\n if lowercaseLetters.contains(scalar) {\n lowercaseLettersMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar uppercaseLettersMemo = Set<UInt32>()\nfunc isUppercaseStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if uppercaseLettersMemo.contains(scalar.value) { return true }\n if uppercaseLetters.contains(scalar) {\n uppercaseLettersMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar newlinesMemo = Set<UInt32>()\nfunc isNewlineStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if newlinesMemo.contains(scalar.value) { return true }\n if newlines.contains(scalar) {\n newlinesMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar whitespacesMemo = Set<UInt32>()\nfunc isWhitespaceStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if whitespacesMemo.contains(scalar.value) { return true }\n if whitespaces.contains(scalar) {\n whitespacesMemo.insert(scalar.value)\n return true\n }\n return false\n}\nvar punctuationCharactersMemo = Set<UInt32>()\nfunc isPunctuationStashedMemo(_ c: Character) -> Bool {\n let scalar = c.firstScalar\n if punctuationCharactersMemo.contains(scalar.value) { return true }\n if punctuationCharacters.contains(scalar) {\n punctuationCharactersMemo.insert(scalar.value)\n return true\n }\n return false\n}\n\nfunc setupMemo() {\n blackHole(workload)\n blackHole(alphanumericsMemo)\n blackHole(capitalizedLettersMemo)\n blackHole(controlCharactersMemo)\n blackHole(decimalDigitsMemo)\n blackHole(lettersMemo)\n blackHole(lowercaseLettersMemo)\n blackHole(uppercaseLettersMemo)\n blackHole(newlinesMemo)\n blackHole(whitespacesMemo)\n blackHole(punctuationCharactersMemo)\n}\n\n// Precompute whole scalar set\nfunc precompute(_ charSet: CharacterSet, capacity: Int) -> Set<UInt32> {\n var result = Set<UInt32>(minimumCapacity: capacity)\n for plane in 0...0x10 {\n guard charSet.hasMember(inPlane: UInt8(plane)) else { continue }\n let offset = plane &* 0x1_0000\n for codePoint in 0...0xFFFF {\n guard let scalar = UnicodeScalar(codePoint &+ offset) else { continue }\n if charSet.contains(scalar) {\n result.insert(scalar.value)\n }\n }\n }\n return result\n}\nvar alphanumericsPrecomputed: Set<UInt32> =\n precompute(alphanumerics, capacity: 122647)\nfunc isAlphanumericPrecomputed(_ c: Character) -> Bool {\n return alphanumericsPrecomputed.contains(c.firstScalar.value)\n}\nvar capitalizedLettersPrecomputed: Set<UInt32> =\n precompute(capitalizedLetters, capacity: 31)\nfunc isCapitalizedPrecomputed(_ c: Character) -> Bool {\n return capitalizedLettersPrecomputed.contains(c.firstScalar.value)\n}\nvar controlCharactersPrecomputed: Set<UInt32> =\n precompute(controlCharacters, capacity: 24951)\nfunc isControlPrecomputed(_ c: Character) -> Bool {\n return controlCharactersPrecomputed.contains(c.firstScalar.value)\n}\nvar decimalDigitsPrecomputed: Set<UInt32> =\n precompute(decimalDigits, capacity: 590)\nfunc isDecimalPrecomputed(_ c: Character) -> Bool {\n return decimalDigitsPrecomputed.contains(c.firstScalar.value)\n}\nvar lettersPrecomputed: Set<UInt32> =\n precompute(letters, capacity: 121145)\nfunc isLetterPrecomputed(_ c: Character) -> Bool {\n return lettersPrecomputed.contains(c.firstScalar.value)\n}\nvar lowercaseLettersPrecomputed: Set<UInt32> =\n precompute(lowercaseLetters, capacity: 2063)\nfunc isLowercasePrecomputed(_ c: Character) -> Bool {\n return lowercaseLettersPrecomputed.contains(c.firstScalar.value)\n}\nvar uppercaseLettersPrecomputed: Set<UInt32> =\n precompute(uppercaseLetters, capacity: 1733)\nfunc isUppercasePrecomputed(_ c: Character) -> Bool {\n return uppercaseLettersPrecomputed.contains(c.firstScalar.value)\n}\nvar newlinesPrecomputed: Set<UInt32> =\n precompute(newlines, capacity: 7)\nfunc isNewlinePrecomputed(_ c: Character) -> Bool {\n return newlinesPrecomputed.contains(c.firstScalar.value)\n}\nvar whitespacesPrecomputed: Set<UInt32> =\n precompute(whitespaces, capacity: 19)\nfunc isWhitespacePrecomputed(_ c: Character) -> Bool {\n return whitespacesPrecomputed.contains(c.firstScalar.value)\n}\nvar punctuationCharactersPrecomputed: Set<UInt32> =\n precompute(punctuationCharacters, capacity: 770)\nfunc isPunctuationPrecomputed(_ c: Character) -> Bool {\n return punctuationCharactersPrecomputed.contains(c.firstScalar.value)\n}\n\nfunc setupPrecomputed() {\n blackHole(workload)\n blackHole(alphanumericsPrecomputed)\n blackHole(capitalizedLettersPrecomputed)\n blackHole(controlCharactersPrecomputed)\n blackHole(decimalDigitsPrecomputed)\n blackHole(lettersPrecomputed)\n blackHole(lowercaseLettersPrecomputed)\n blackHole(uppercaseLettersPrecomputed)\n blackHole(newlinesPrecomputed)\n blackHole(whitespacesPrecomputed)\n blackHole(punctuationCharactersPrecomputed)\n}\n\n// Compute on the fly\n//\n// TODO: If UnicodeScalars ever exposes category, etc., implement the others!\nfunc isNewlineComputed(_ c: Character) -> Bool {\n switch c.firstScalar.value {\n case 0x000A...0x000D: return true\n case 0x0085: return true\n case 0x2028...0x2029: return true\n default: return false\n }\n}\n\nlet workload = """\n the quick brown 🦊 jumped over the lazy 🐶.\n в чащах юга жил-был цитрус? да, но фальшивый экземпляр\n 𓀀𓀤𓁓𓁲𓃔𓃗𓃀𓃁𓃂𓃃𓆌𓆍𓆎𓆏𓆐𓆑𓆒𓆲𓁿\n 🝁ꃕ躍‾∾📦⺨\n 👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿\n Lorem ipsum something something something...\n"""\n\n@inline(never)\npublic func run_CharacterPropertiesFetch(_ n: Int) {\n for _ in 1...n {\n for c in workload {\n blackHole(isAlphanumeric(c))\n blackHole(isCapitalized(c))\n blackHole(isControl(c))\n blackHole(isDecimal(c))\n blackHole(isLetter(c))\n blackHole(isLowercase(c))\n blackHole(isUppercase(c))\n blackHole(isNewline(c))\n blackHole(isWhitespace(c))\n blackHole(isPunctuation(c))\n }\n }\n}\n\n@inline(never)\npublic func run_CharacterPropertiesStashed(_ n: Int) {\n for _ in 1...n {\n for c in workload {\n blackHole(isAlphanumericStashed(c))\n blackHole(isCapitalizedStashed(c))\n blackHole(isControlStashed(c))\n blackHole(isDecimalStashed(c))\n blackHole(isLetterStashed(c))\n blackHole(isLowercaseStashed(c))\n blackHole(isUppercaseStashed(c))\n blackHole(isNewlineStashed(c))\n blackHole(isWhitespaceStashed(c))\n blackHole(isPunctuationStashed(c))\n }\n }\n}\n\n@inline(never)\npublic func run_CharacterPropertiesStashedMemo(_ n: Int) {\n for _ in 1...n {\n for c in workload {\n blackHole(isAlphanumericStashedMemo(c))\n blackHole(isCapitalizedStashedMemo(c))\n blackHole(isControlStashedMemo(c))\n blackHole(isDecimalStashedMemo(c))\n blackHole(isLetterStashedMemo(c))\n blackHole(isLowercaseStashedMemo(c))\n blackHole(isUppercaseStashedMemo(c))\n blackHole(isNewlineStashedMemo(c))\n blackHole(isWhitespaceStashedMemo(c))\n blackHole(isPunctuationStashedMemo(c))\n }\n }\n}\n\n@inline(never)\npublic func run_CharacterPropertiesPrecomputed(_ n: Int) {\n for _ in 1...n {\n for c in workload {\n blackHole(isAlphanumericPrecomputed(c))\n blackHole(isCapitalizedPrecomputed(c))\n blackHole(isControlPrecomputed(c))\n blackHole(isDecimalPrecomputed(c))\n blackHole(isLetterPrecomputed(c))\n blackHole(isLowercasePrecomputed(c))\n blackHole(isUppercasePrecomputed(c))\n blackHole(isNewlinePrecomputed(c))\n blackHole(isWhitespacePrecomputed(c))\n blackHole(isPunctuationPrecomputed(c))\n }\n }\n}\n\n\n\n// TODO: run_CharacterPropertiesComputed\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CharacterProperties.swift | cpp_apple_swift_benchmark_single-source_CharacterProperties.swift | Swift | 14,444 | 0.95 | 0.079545 | 0.06506 | react-lib | 620 | 2023-10-02T21:11:56.524630 | Apache-2.0 | false | de4e88d1fa353fe414e82e5280bbdace |
//===--- StringEdits.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic var benchmarks: [BenchmarkInfo] {\n guard #available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *) else {\n return []\n }\n return [\n BenchmarkInfo(\n name: "CharacterRecognizer.mixed",\n runFunction: { n in\n run(string: mixedString, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(mixedString) }),\n BenchmarkInfo(\n name: "CharacterRecognizer.ascii",\n runFunction: { n in\n run(string: asciiString, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(asciiString) }),\n ]\n}\n\nlet mixedString = #"""\n The powerful programming language that is also easy to learn.\n 손쉽게 학습할 수 있는 강력한 프로그래밍 언어.\n 🪙 A 🥞 short 🍰 piece 🫘 of 🌰 text 👨👨👧👧 with 👨👩👦 some 🚶🏽 emoji 🇺🇸🇨🇦 characters 🧈\n some🔩times 🛺 placed 🎣 in 🥌 the 🆘 mid🔀dle 🇦🇶or🏁 around 🏳️🌈 a 🍇 w🍑o🥒r🥨d\n Unicode is such fun!\n U̷n̷i̷c̷o̴d̴e̷ ̶i̸s̷ ̸s̵u̵c̸h̷ ̸f̵u̷n̴!̵\n U̴̡̲͋̾n̵̻̳͌ì̶̠̕c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́ ̴̟͎͐̈i̴̦̓s̴̜̱͘ ̶̲̮̚s̶̙̞͘u̵͕̯̎̽c̵̛͕̜̓h̶̘̍̽ ̸̜̞̿f̵̤̽ṷ̴͇̎͘ń̷͓̒!̷͍̾̚\n U̷̢̢̧̨̼̬̰̪͓̞̠͔̗̼̙͕͕̭̻̗̮̮̥̣͉̫͉̬̲̺͍̺͊̂ͅ\#\n n̶̨̢̨̯͓̹̝̲̣̖̞̼̺̬̤̝̊̌́̑̋̋͜͝ͅ\#\n ḭ̸̦̺̺͉̳͎́͑\#\n c̵̛̘̥̮̙̥̟̘̝͙̤̮͉͔̭̺̺̅̀̽̒̽̏̊̆͒͌̂͌̌̓̈́̐̔̿̂͑͠͝͝ͅ\#\n ö̶̱̠̱̤̙͚͖̳̜̰̹̖̣̻͎͉̞̫̬̯͕̝͔̝̟̘͔̙̪̭̲́̆̂͑̌͂̉̀̓́̏̎̋͗͛͆̌̽͌̄̎̚͝͝͝͝ͅ\#\n d̶̨̨̡̡͙̟͉̱̗̝͙͍̮͍̘̮͔͑\#\n e̶̢͕̦̜͔̘̘̝͈̪̖̺̥̺̹͉͎͈̫̯̯̻͑͑̿̽͂̀̽͋́̎̈́̈̿͆̿̒̈́̽̔̇͐͛̀̓͆̏̾̀̌̈́̆̽̕ͅ\n """#\n\nlet _asciiString = #"""\n Swift is a high-performance system programming language. It has a clean\n and modern syntax, offers seamless access to existing C and Objective-C code\n and frameworks, and is memory safe by default.\n\n Although inspired by Objective-C and many other languages, Swift is not itself\n a C-derived language. As a complete and independent language, Swift packages\n core features like flow control, data structures, and functions, with\n high-level constructs like objects, protocols, closures, and generics. Swift\n embraces modules, eliminating the need for headers and the code duplication\n they entail.\n\n Swift toolchains are created using the script\n [build-toolchain](https://github.com/apple/swift/blob/main/utils/build-toolchain).\n This script is used by swift.org's CI to produce snapshots and can allow for\n one to locally reproduce such builds for development or distribution purposes.\n A typical invocation looks like the following:\n\n ```\n $ ./swift/utils/build-toolchain $BUNDLE_PREFIX\n ```\n\n where ``$BUNDLE_PREFIX`` is a string that will be prepended to the build date\n to give the bundle identifier of the toolchain's ``Info.plist``. For instance,\n if ``$BUNDLE_PREFIX`` was ``com.example``, the toolchain produced will have\n the bundle identifier ``com.example.YYYYMMDD``. It will be created in the\n directory you run the script with a filename of the form:\n ``swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz``.\n """#\nlet asciiString = String(repeating: _asciiString, count: 10)\n\n@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)\nfunc run(string: String, n: Int) {\n var state = Unicode._CharacterRecognizer()\n var c = 0\n for _ in 0 ..< n {\n for scalar in string.unicodeScalars {\n if state.hasBreak(before: scalar) {\n c += 1\n }\n }\n }\n blackHole(c)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CharacterRecognizer.swift | cpp_apple_swift_benchmark_single-source_CharacterRecognizer.swift | Swift | 4,234 | 0.95 | 0.092784 | 0.125 | vue-tools | 275 | 2023-07-13T22:17:27.933000 | BSD-3-Clause | false | 538b07b5b45ce2cb119e25f3ed4cc6e3 |
//===--- Chars.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test tests the performance of ASCII Character comparison.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Chars2",\n runFunction: run_Chars,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(alphabetInput) },\n legacyFactor: 50)\n\nlet alphabetInput: [Character] = [\n "A", "B", "C", "D", "E", "F", "G",\n "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",\n "S", "T", "U",\n "V", "W", "X", "Y", "Z", "/", "f", "Z", "z", "6", "7", "C", "j", "f", "9",\n "g", "g", "I", "J", "K", "c", "x", "i", ".",\n "2", "a", "t", "i", "o", "e", "q", "n", "X", "Y", "Z", "?", "m", "Z", ","\n ]\n\n@inline(never)\npublic func run_Chars(_ n: Int) {\n // Permute some characters.\n let alphabet: [Character] = alphabetInput\n\n for _ in 0..<n {\n for firstChar in alphabet {\n for lastChar in alphabet {\n blackHole(firstChar < lastChar)\n blackHole(firstChar == lastChar)\n blackHole(firstChar > lastChar)\n blackHole(firstChar <= lastChar)\n blackHole(firstChar >= lastChar)\n }\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Chars.swift | cpp_apple_swift_benchmark_single-source_Chars.swift | Swift | 1,602 | 0.95 | 0.102041 | 0.295455 | react-lib | 494 | 2025-03-09T22:21:36.651198 | MIT | false | a0cd337bbee9a3b79eae355ed5b8cfe3 |
//===--- ClassArrayGetter.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ClassArrayGetter2",\n runFunction: run_ClassArrayGetter,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(inputArray) },\n tearDownFunction: { inputArray = nil },\n legacyFactor: 10)\n\nclass Box {\n var v: Int\n init(v: Int) { self.v = v }\n}\n\n@inline(never)\nfunc sumArray(_ a: [Box]) -> Int {\n var s = 0\n for i in 0..<a.count {\n s += a[i].v\n }\n return s\n}\n\nvar inputArray: [Box]! = {\n let aSize = 10_000\n var a: [Box] = []\n a.reserveCapacity(aSize)\n for i in 1...aSize {\n a.append(Box(v:i))\n }\n return a\n}()\n\npublic func run_ClassArrayGetter(_ n: Int) {\n let a: [Box] = inputArray\n for _ in 1...n {\n _ = sumArray(a)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ClassArrayGetter.swift | cpp_apple_swift_benchmark_single-source_ClassArrayGetter.swift | Swift | 1,260 | 0.95 | 0.113208 | 0.234043 | python-kit | 627 | 2024-07-23T06:18:25.506603 | MIT | false | f2622db29ec4022e9e1f59c29813f23f |
// Combos benchmark\n//\n// Description: Generates every combination of every element in two sequences\n// Source: https://gist.github.com/airspeedswift/34251f2ddb1b038c5d88\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Combos",\n runFunction: run_Combos,\n tags: [.validation, .abstraction]\n )\n\n@inline(never)\npublic func run_Combos(_ n: Int) {\n let firstRef = [Character("A"), Character("0")]\n let lastRef = [Character("J"), Character("9")]\n var combos = [[Character]]()\n\n for _ in 1...10*n {\n combos = combinations("ABCDEFGHIJ", "0123456789").map {\n return [$0] + [$1]\n }\n\n if combos.first! != firstRef || combos.last! != lastRef {\n break\n }\n }\n\n check(combos.first! == firstRef && combos.last! == lastRef)\n}\n\nfunc combinations\n<First: Sequence, Second: Collection>\n(_ first: First, _ second: Second)\n-> AnyIterator<(First.Element, Second.Element)> {\n var first_gen = first.makeIterator()\n var second_gen = second.makeIterator()\n var current_first = first_gen.next()\n return AnyIterator {\n // check if there's more of first to consume\n if let this_first = current_first {\n // if so, is there more of this go-around\n // of second to consume?\n if let this_second = second_gen.next() {\n return (this_first, this_second)\n }\n // if second used up, reset it\n else {\n // go back to the beginning of second\n second_gen = second.makeIterator()\n // and take the first element of it\n let next_second = second_gen.next()\n // was there a first element?\n if let this_second = next_second {\n // move on to the next element of first\n current_first = first_gen.next()\n // is there such an element?\n if let this_first = current_first {\n return (this_first, this_second)\n }\n // if not, we've reached the end of\n // the first sequence\n else {\n // so we've finished\n return nil\n }\n }\n // if not, second is empty\n else {\n // so we need to guard against\n // infinite looping in that case\n return nil\n }\n }\n }\n // if not, we've reached the end of\n // the first sequence\n else {\n // so we've finished\n return nil\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Combos.swift | cpp_apple_swift_benchmark_single-source_Combos.swift | Swift | 2,344 | 0.95 | 0.141176 | 0.282051 | vue-tools | 659 | 2024-07-01T23:09:43.155717 | GPL-3.0 | false | 0f460fd6d3b1c9cd95adfab49eef5956 |
//===--- CountAlgo.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CountAlgoArray",\n runFunction: run_CountAlgoArray,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "CountAlgoString",\n runFunction: run_CountAlgoString,\n tags: [.validation, .api],\n legacyFactor: 5),\n]\n\n@inline(never)\npublic func run_CountAlgoArray(_ N: Int) {\n for _ in 1...10*N {\n CheckResults(numbers.count(where: { $0 & 4095 == 0 }) == 25)\n }\n}\n\n@inline(never)\npublic func run_CountAlgoString(_ N: Int) {\n let vowels = Set("aeiou")\n for _ in 1...N {\n CheckResults(text.count(where: vowels.contains) == 2014)\n }\n}\n\nlet numbers = Array(0..<100_000)\n\nlet text = """\n Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus\n dictum tellus placerat ultrices. Proin mauris risus, eleifend a elit ut,\n semper consectetur nibh. Nulla ultricies est a vehicula rhoncus. Morbi\n sollicitudin efficitur est a hendrerit. Interdum et malesuada fames ac ante\n ipsum primis in faucibus. Lorem ipsum dolor sit amet, consectetur\n adipiscing elit. Nulla facilisi. Sed euismod sagittis laoreet. Ut elementum\n tempus ultrices. Donec convallis mauris at faucibus maximus.\n Nullam in nunc sit amet ante tristique elementum quis ut eros. Fusce\n dignissim, ante at efficitur dapibus, ex massa convallis nibh, et venenatis\n leo leo sit amet nisl. Lorem ipsum dolor sit amet, consectetur adipiscing\n elit. Quisque sed mi eu mi rutrum accumsan vel non massa. Nunc condimentum,\n arcu eget interdum hendrerit, ipsum mi pretium felis, ut mollis erat metus\n non est. Donec eu sapien id urna lobortis eleifend et eu ipsum. Mauris\n purus dolor, consequat ac nulla a, vehicula sollicitudin nulla.\n Phasellus a congue diam. Curabitur sed orci at sem laoreet facilisis eget\n quis est. Pellentesque habitant morbi tristique senectus et netus et\n malesuada fames ac turpis egestas. Maecenas justo tellus, efficitur id\n velit at, mollis pellentesque mi. Vivamus maximus nibh et ipsum porttitor\n facilisis. Curabitur cursus lobortis erat. Sed vitae eros et dolor feugiat\n consequat. In ac massa in odio gravida dignissim. Praesent aliquam gravida\n ullamcorper.\n Etiam feugiat sit amet odio sed tincidunt. Duis dolor odio, posuere at\n pretium sed, dignissim eu diam. Aenean eu convallis orci, vitae finibus\n erat. Aliquam nec mollis tellus. Morbi luctus sed quam et vestibulum.\n Praesent id diam tempus, consectetur tortor vel, auctor orci. Aliquam\n congue ex eu sagittis sodales. Suspendisse non convallis nulla. Praesent\n elementum semper augue, et fringilla risus ullamcorper id. Fusce eu lorem\n sit amet augue fermentum tincidunt. In aliquam libero sit amet dui rhoncus,\n ac scelerisque sem porttitor. Cras venenatis, nisi quis ullamcorper\n dapibus, odio dolor rutrum magna, vel pellentesque sem lectus in tellus.\n Proin faucibus leo iaculis nulla egestas molestie.\n Phasellus vitae tortor vitae erat elementum feugiat vel vel enim. Phasellus\n fringilla lacus sed venenatis dapibus. Phasellus sagittis vel neque ut\n varius. Proin aliquam, lectus sit amet auctor finibus, lorem libero\n pellentesque turpis, ac condimentum augue felis sit amet sem. Pellentesque\n pharetra nisl nec est congue, in posuere felis maximus. In ut nulla\n sodales, pharetra neque et, venenatis dui. Mauris imperdiet, arcu vel\n hendrerit vehicula, elit massa consectetur purus, eu blandit nunc orci sit\n amet turpis. Vestibulum ultricies id lorem id maximus. Pellentesque\n feugiat, lacus et aliquet consequat, mi leo vehicula justo, dapibus dictum\n mi quam convallis magna. Quisque id pulvinar dui, consequat gravida nisl.\n Nam nec justo venenatis, tincidunt enim a, iaculis odio. Maecenas eget\n lorem posuere, euismod nisl vel, pulvinar ex. Maecenas vitae risus ipsum.\n Proin congue sem ante, sit amet sagittis odio mattis sit amet. Nullam et\n nisi nulla.\n Donec vel hendrerit metus. Praesent quis finibus erat. Aliquam erat\n volutpat. Fusce sit amet ultricies tellus, vitae dictum dolor. Morbi auctor\n dolor vel ligula pretium aliquam. Aenean lobortis vel magna vel ultricies.\n Aenean porta urna vitae ornare porta. Quisque pretium dui diam, quis\n iaculis odio venenatis non. Maecenas at lacus et ligula tincidunt feugiat\n eu vel ipsum. Proin fermentum elit et quam tempus, eget pulvinar nisl\n pharetra.\n Mauris sodales tempus erat in lobortis. Duis vitae lacinia sapien.\n Pellentesque vitae massa eget orci sodales aliquet. Orci varius natoque\n penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce\n nisi arcu, egestas vel consectetur eu, auctor et metus. In ultricies ligula\n felis, vitae pellentesque dolor tempor ac. Praesent mi magna, ultrices ut\n ultrices vel, sollicitudin a leo.\n Nam porta, nisi in scelerisque consequat, leo lacus accumsan massa,\n venenatis faucibus tellus quam eget tellus. Curabitur pulvinar, tellus ac\n facilisis consectetur, lacus lacus venenatis est, eu pretium orci augue\n gravida nunc. Aenean odio tellus, facilisis et finibus id, varius vitae\n diam. Aenean at suscipit sem. Suspendisse porta neque at nibh semper, sit\n amet suscipit libero egestas. Donec commodo vitae justo vitae laoreet.\n Suspendisse dignissim erat id ante maximus porta. Curabitur hendrerit\n maximus odio, et maximus felis malesuada eu. Integer dapibus finibus diam,\n quis convallis metus bibendum non.\n In vel vulputate nisi, non lacinia nunc. Nullam vitae ligula finibus,\n varius arcu in, pellentesque ipsum. Morbi vel velit tincidunt quam cursus\n lacinia non in neque. Suspendisse id feugiat nibh. Vestibulum egestas eu\n leo viverra fringilla. Curabitur ultrices sollicitudin libero, non sagittis\n felis consectetur id. Aenean non metus eget leo ornare porta sed in metus.\n Nullam quis fermentum sapien, sit amet sodales mi. Maecenas nec purus urna.\n Phasellus condimentum enim nec magna convallis, eu lacinia libero\n scelerisque. Suspendisse justo libero, maximus in auctor id, euismod quis\n risus. Nam eget augue diam. Ut id risus pulvinar elit consectetur varius.\n Aliquam tincidunt tortor pretium feugiat tempor. Nunc nec feugiat ex.\n Ut pulvinar augue eget pharetra vehicula. Phasellus malesuada tempor sem,\n ut tincidunt velit convallis in. Vivamus luctus libero vitae massa tempus,\n id elementum urna iaculis. Sed eleifend quis purus quis convallis. In\n rhoncus interdum mollis. Pellentesque dictum euismod felis, eget lacinia\n elit blandit vel. Praesent elit velit, pharetra a sodales in, cursus vitae\n tortor. In vitae scelerisque tellus.\n """\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CountAlgo.swift | cpp_apple_swift_benchmark_single-source_CountAlgo.swift | Swift | 7,214 | 0.95 | 0.031496 | 0.090164 | python-kit | 466 | 2025-01-22T14:43:34.568172 | Apache-2.0 | false | 7e1e81183c3041176bda5952e454a045 |
//===--- COWArrayGuaranteedParameterOverhead.swift ------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// This test makes sure that even though we have +0 arguments by default that we\n// can properly convert +0 -> +1 to avoid extra COW copies.\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "COWArrayGuaranteedParameterOverhead",\n runFunction: run_COWArrayGuaranteedParameterOverhead,\n tags: [.regression, .abstraction, .refcount],\n legacyFactor: 50\n )\n\n@inline(never)\nfunc caller() {\n let x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n blackHole(callee(x))\n}\n\n@inline(never)\nfunc callee(_ x: [Int]) -> [Int] {\n var y = x\n // This should not copy.\n y[2] = 27\n return y\n}\n\n@inline(never)\npublic func run_COWArrayGuaranteedParameterOverhead(_ n: Int) {\n for _ in 0..<n*400 {\n caller()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_COWArrayGuaranteedParameterOverhead.swift | cpp_apple_swift_benchmark_single-source_COWArrayGuaranteedParameterOverhead.swift | Swift | 1,248 | 0.95 | 0.066667 | 0.358974 | react-lib | 8 | 2025-05-10T20:42:45.645454 | BSD-3-Clause | false | cf080595e529802d6c7bcc571eb3aeeb |
// COWTree benchmark\n//\n// Description: Copy-On-Write behaviour for a struct\n// Source: https://gist.github.com/airspeedswift/71f15d1eb866be9e5ac7\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "COWTree",\n runFunction: run_COWTree,\n tags: [.validation, .abstraction, .String],\n legacyFactor: 20\n ),\n]\n\n@inline(never)\npublic func run_COWTree(_ n: Int) {\n var tree1 = Tree<String>()\n var tree2 = Tree<String>()\n var tree3 = Tree<String>()\n\n for _ in 1...50*n {\n tree1 = Tree<String>()\n tree1.insert("Emily")\n tree2 = tree1\n tree1.insert("Gordon")\n tree3 = tree2\n tree3.insert("Spencer")\n\n if !checkRef(tree1, tree2, tree3) {\n break\n }\n }\n\n check(checkRef(tree1, tree2, tree3))\n}\n\n@inline(never)\nfunc checkRef(_ t1: Tree<String>, _ t2: Tree<String>,\n _ t3: Tree<String>) -> Bool {\n if !(t1.contains("Emily") && t1.contains("Gordon") &&\n !t1.contains("Spencer")) {\n return false\n }\n if !(t2.contains("Emily") && !t2.contains("Gordon") &&\n !t2.contains("Spencer")) {\n return false\n }\n if !(t3.contains("Emily") && !t3.contains("Gordon") &&\n t3.contains("Spencer")) {\n return false\n }\n return true\n}\n\n// ideally we would define this inside the tree struct\nprivate class _Node<T: Comparable> {\n var _value: T\n var _left: _Node<T>? = nil\n var _right: _Node<T>? = nil\n\n init(value: T) { _value = value }\n}\n\npublic struct Tree<T: Comparable> {\n // this makes things a bit more pleasant later\n fileprivate typealias Node = _Node<T>\n\n fileprivate var _root: Node? = nil\n\n public init() { }\n\n // constructor from a sequence\n public init<S: Sequence>(_ seq: S) where S.Element == T {\n var g = seq.makeIterator()\n while let x = g.next() {\n self.insert(x)\n }\n }\n\n private mutating func ensureUnique() {\n if !isKnownUniquelyReferenced(&_root) {\n // inefficiently...\n self = Tree<T>(self)\n }\n }\n\n public mutating func insert(_ value: T) {\n ensureUnique()\n _root = insert(_root, value)\n }\n\n private mutating func insert(_ node: Node?, _ value: T) -> Node? {\n switch node {\n case .none:\n return Node(value: value)\n case let .some(node) where value < node._value:\n node._left = insert(node._left, value)\n return node\n case let .some(node):\n node._right = insert(node._right, value)\n return node\n }\n }\n\n public func contains(_ value: T) -> Bool {\n return contains(_root, value)\n }\n\n private func contains(_ node: Node?, _ value: T) -> Bool {\n switch node {\n case .none:\n return false\n case let .some(node) where node._value == value:\n return true\n case let .some(node):\n return contains(value < node._value ? node._left : node._right,\n value)\n }\n }\n}\n\nextension Tree: Sequence {\n public typealias Iterator = AnyIterator<T>\n\n public func makeIterator() -> Iterator {\n var stack: [Node] = []\n var current: Node? = _root\n return AnyIterator {\n // stack-based technique for inorder traversal\n // without recursion\n while true {\n if let node = current {\n stack.append(node)\n current = node._left\n }\n else if !stack.isEmpty {\n let pop = stack.removeLast()\n current = pop._right\n return pop._value\n }\n else {\n return nil\n }\n }\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_COWTree.swift | cpp_apple_swift_benchmark_single-source_COWTree.swift | Swift | 3,371 | 0.95 | 0.100671 | 0.077519 | node-utils | 718 | 2024-07-24T17:45:48.396341 | Apache-2.0 | false | 20b65946fe71dbaaf1f4475009a08242 |
//===--- CString.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n#if canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif os(Windows)\nimport MSVCRT\n#else\nimport Darwin\n#endif\n\npublic let benchmarks = [\n BenchmarkInfo(name: "CStringLongAscii", runFunction: run_CStringLongAscii, tags: [.validation, .api, .String, .bridging]),\n BenchmarkInfo(name: "CStringLongNonAscii", runFunction: run_CStringLongNonAscii, tags: [.validation, .api, .String, .bridging]),\n BenchmarkInfo(name: "CStringShortAscii", runFunction: run_CStringShortAscii, tags: [.validation, .api, .String, .bridging], legacyFactor: 10),\n BenchmarkInfo(name: "StringWithCString2", runFunction: run_StringWithCString, tags: [.validation, .api, .String, .bridging],\n setUpFunction: { blackHole(repeatedStr) }, tearDownFunction: { repeatedStr = nil })\n]\n\nlet ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."\nlet japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"\n\nvar repeatedStr: String! = String(repeating: "x", count: 5 * (1 << 16))\n\n@inline(never)\npublic func run_StringWithCString(_ n: Int) {\n let str: String = repeatedStr\n for _ in 0 ..< n {\n str.withCString { blackHole($0) }\n }\n}\n\n@inline(never)\npublic func run_CStringLongAscii(_ n: Int) {\n var res = 0\n for _ in 1...n*500 {\n // static string to c -> from c to String -> implicit conversion\n res &= strlen(ascii.withCString(String.init(cString:)))\n }\n check(res == 0)\n}\n\n@inline(never)\npublic func run_CStringLongNonAscii(_ n: Int) {\n var res = 0\n for _ in 1...n*500 {\n res &= strlen(japanese.withCString(String.init(cString:)))\n }\n check(res == 0)\n}\n\n\nlet input = ["-237392", "293715", "126809", "333779", "-362824", "144198",\n "-394973", "-163669", "-7236", "376965", "-400783", "-118670",\n "454728", "-38915", "136285", "-448481", "-499684", "68298",\n "382671", "105432", "-38385", "39422", "-267849", "-439886",\n "292690", "87017", "404692", "27692", "486408", "336482",\n "-67850", "56414", "-340902", "-391782", "414778", "-494338",\n "-413017", "-377452", "-300681", "170194", "428941", "-291665",\n "89331", "329496", "-364449", "272843", "-10688", "142542",\n "-417439", "167337", "96598", "-264104", "-186029", "98480",\n "-316727", "483808", "300149", "-405877", "-98938", "283685",\n "-247856", "-46975", "346060", "160085",]\nlet reference = 517492\n\n@inline(never)\npublic func run_CStringShortAscii(_ n: Int) {\n\n func doOneIter(_ arr: [String]) -> Int {\n var r = 0\n for n in arr {\n r += Int(atoi(n))\n }\n if r < 0 {\n r = -r\n }\n return r\n }\n\n var res = Int.max\n for _ in 1...10*n {\n let strings = input.map {\n $0.withCString(String.init(cString:))\n }\n res = res & doOneIter(strings)\n }\n check(res == reference)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CString.swift | cpp_apple_swift_benchmark_single-source_CString.swift | Swift | 3,962 | 0.95 | 0.11 | 0.193182 | python-kit | 294 | 2024-10-17T23:13:28.310082 | MIT | false | 43c4e1b0acb4046cf73d9553c99b65a9 |
import TestsUtils\npublic let benchmarks = [\n BenchmarkInfo(\n name: "CSVParsing.Char",\n runFunction: run_CSVParsing_characters,\n tags: [.miniapplication, .api, .String],\n setUpFunction: { buildWorkload() }),\n BenchmarkInfo(\n name: "CSVParsing.Scalar",\n runFunction: run_CSVParsing_scalars,\n tags: [.miniapplication, .api, .String],\n setUpFunction: { buildWorkload() }),\n BenchmarkInfo(\n name: "CSVParsing.UTF16",\n runFunction: run_CSVParsing_utf16,\n tags: [.miniapplication, .api, .String],\n setUpFunction: { buildWorkload() }),\n BenchmarkInfo(\n name: "CSVParsing.UTF8",\n runFunction: run_CSVParsing_utf8,\n tags: [.miniapplication, .api, .String],\n setUpFunction: { buildWorkload() }),\n BenchmarkInfo(\n name: "CSVParsingAlt2",\n runFunction: run_CSVParsingAlt,\n tags: [.miniapplication, .api, .String],\n setUpFunction: { buildWorkload() },\n legacyFactor: 11),\n BenchmarkInfo(\n name: "CSVParsingAltIndices2",\n runFunction: run_CSVParsingAltIndices,\n tags: [.miniapplication, .api, .String],\n setUpFunction: { buildWorkload() },\n legacyFactor: 11),\n]\n\n// Convenience\nextension Collection where Self == Self.SubSequence {\n mutating func remove(upTo index: Index) {\n self = suffix(from: index)\n }\n\n mutating func remove(upToAndIncluding index: Index) {\n self = suffix(from: self.index(after: index))\n }\n}\n\nstruct ParseError: Error {\n var message: String\n}\n\nprotocol StringView: Collection where Element: Equatable, SubSequence == Self {\n init()\n mutating func append(_ other: Self)\n}\nextension StringView {\n mutating func removeAll() { self = Self() }\n}\nextension StringView where Self: RangeReplaceableCollection {\n mutating func append(_ other: Self) {\n self += other\n }\n}\n\nextension Substring: StringView {}\nextension Substring.UnicodeScalarView: StringView {}\nextension Substring.UTF8View: StringView {\n init() { self = Substring().utf8 }\n\n // We're hoping for only whole-scalar operations\n mutating func append(_ other: Substring.UTF8View) {\n self = (Substring(self) + Substring(other)).utf8\n }\n}\nextension Substring.UTF16View: StringView {\n init() { self = Substring().utf16 }\n\n // We're hoping for only whole-scalar operations\n mutating func append(_ other: Substring.UTF16View) {\n self = (Substring(self) + Substring(other)).utf16\n }\n}\n\nlet comma = ",".utf16.first!\nlet newline = "\n".utf16.first!\nlet carriageReturn = "\n".utf16.first!\nlet quote = "\"".utf16.first!\n\n@inline(__always) // ... and always specialize\nfunc parseCSV<View: StringView, State>(\n _ remainder: inout View,\n initialState: State,\n quote: View.Element,\n comma: View.Element,\n newline: View.Element,\n carriageReturn: View.Element,\n processField: (inout State, Int, View) -> ()\n) throws -> State {\n // Helper to parse a quoted field\n @inline(__always) // ... and always specialize\n func parseQuotedField(_ remainder: inout View) throws -> View {\n var result: View = View()\n\n while !remainder.isEmpty {\n guard let nextQuoteIndex = remainder.firstIndex(of: quote) else {\n throw ParseError(message: "Expected a closing \"")\n }\n\n // Append until the next quote\n result.append(remainder[nextQuoteIndex...nextQuoteIndex])\n result.append(remainder.prefix(upTo: nextQuoteIndex))\n remainder.remove(upToAndIncluding: nextQuoteIndex)\n\n guard let peek = remainder.first else {\n // End of the string\n return result\n }\n\n switch peek {\n case quote: // two quotes after each other is an escaped quote\n result.append(remainder[...remainder.startIndex])\n remainder.removeFirst()\n case comma: // field ending\n remainder.removeFirst()\n result.append(result[...result.startIndex])\n return result\n default:\n throw ParseError(message: "Expected closing quote to end a field")\n }\n }\n\n throw ParseError(message: "Expected a closing quote")\n }\n\n // Helper to parse a field\n @inline(__always) // ... and always specialize\n func parseField(_ remainder: inout View) throws -> View? {\n guard let start = remainder.first else { return nil }\n switch start {\n case quote:\n remainder.removeFirst() // remove the first quote\n return try parseQuotedField(&remainder)\n case newline:\n return nil\n default:\n // This is the most common case and should ideally be super fast...\n var index = remainder.startIndex\n while index < remainder.endIndex {\n switch remainder[index] {\n case comma:\n defer { remainder.remove(upToAndIncluding: index) }\n return remainder.prefix(upTo: index)\n case newline:\n let result = remainder.prefix(upTo: index)\n remainder.remove(upTo: index)\n return result\n case quote:\n throw ParseError(message: "Quotes can only surround the whole field")\n default:\n remainder.formIndex(after: &index)\n }\n }\n let result = remainder\n remainder.removeAll()\n return result\n }\n }\n\n // Helper to parse a line\n @inline(__always) // ... and always specialize\n func parseLine(\n _ remainder: inout View,\n result: inout State,\n processField: (inout State, Int, View) -> ()\n ) throws -> Bool {\n var fieldNumber = 0\n\n while let field = try parseField(&remainder) {\n processField(&result, fieldNumber, field)\n fieldNumber += 1\n }\n\n if !remainder.isEmpty {\n let next = remainder[remainder.startIndex]\n guard next == carriageReturn || next == newline else {\n throw ParseError(message: "Expected a newline or CR, got \(next)")\n }\n\n while let x = remainder.first, x == carriageReturn || x == newline {\n remainder.removeFirst()\n }\n }\n\n return !remainder.isEmpty && fieldNumber > 0\n }\n\n var state = initialState\n while try parseLine(\n &remainder, result: &state, processField: processField\n ) {}\n return state\n}\n\n// More concrete convenience\n@inline(__always) // ... and always specialize\nfunc parseCSV<State>(\n _ remainder: inout Substring,\n initialState: State,\n processField: (inout State, Int, Substring) -> ()\n) throws -> State {\n return try parseCSV(\n &remainder,\n initialState: initialState,\n quote: "\"",\n comma: ",",\n newline: "\n",\n carriageReturn: "\r\n",\n processField: processField)\n}\n@inline(__always) // ... and always specialize\nfunc parseCSV<State>(\n _ remainder: inout Substring.UnicodeScalarView,\n initialState: State,\n processField: (inout State, Int, Substring.UnicodeScalarView) -> ()\n) throws -> State {\n return try parseCSV(\n &remainder,\n initialState: initialState,\n quote: "\"".unicodeScalars.first!,\n comma: ",".unicodeScalars.first!,\n newline: "\n".unicodeScalars.first!,\n carriageReturn: "\r\n".unicodeScalars.first!,\n processField: processField)\n}\n@inline(__always) // ... and always specialize\nfunc parseCSV<State>(\n _ remainder: inout Substring.UTF16View,\n initialState: State,\n processField: (inout State, Int, Substring.UTF16View) -> ()\n) throws -> State {\n return try parseCSV(\n &remainder,\n initialState: initialState,\n quote: "\"".utf16.first!,\n comma: ",".utf16.first!,\n newline: "\n".utf16.first!,\n carriageReturn: "\r\n".utf16.first!,\n processField: processField)\n}\n@inline(__always) // ... and always specialize\nfunc parseCSV<State>(\n _ remainder: inout Substring.UTF8View,\n initialState: State,\n processField: (inout State, Int, Substring.UTF8View) -> ()\n) throws -> State {\n return try parseCSV(\n &remainder,\n initialState: initialState,\n quote: "\"".utf8.first!,\n comma: ",".utf8.first!,\n newline: "\n".utf8.first!,\n carriageReturn: "\r\n".utf8.first!,\n processField: processField)\n}\n\nextension String {\n func parseAlt() -> [[String]] {\n var result: [[String]] = [[]]\n var currentField = "".unicodeScalars\n var inQuotes = false\n func flush() {\n result[result.endIndex-1].append(String(currentField))\n currentField.removeAll()\n }\n for c in self.unicodeScalars {\n switch (c, inQuotes) {\n case (",", false):\n flush()\n case ("\n", false):\n flush()\n result.append([])\n case ("\"", _):\n inQuotes = !inQuotes\n currentField.append(c)\n default:\n currentField.append(c)\n }\n }\n flush()\n return result\n }\n func parseAltIndices() -> [[Substring]] {\n var result: [[Substring]] = [[]]\n var fieldStart = self.startIndex\n var inQuotes = false\n func flush(endingAt end: Index) {\n result[result.endIndex-1].append(self[fieldStart..<end])\n }\n for i in self.unicodeScalars.indices {\n switch (self.unicodeScalars[i], inQuotes) {\n case (",", false):\n flush(endingAt: i)\n fieldStart = self.unicodeScalars.index(after: i)\n case ("\n", false):\n flush(endingAt: i)\n fieldStart = self.unicodeScalars.index(after: i)\n result.append([])\n case ("\"", _):\n inQuotes = !inQuotes\n default:\n continue\n }\n }\n flush(endingAt: endIndex)\n return result\n }\n}\n\nlet workloadBase = """\n Heading1,Heading2,Heading3,Heading4,Heading5,Heading6,Heading7\n FirstEntry,"secondentry",third,fourth,fifth,sixth,seventh\n zéro,un,deux,trois,quatre,cinq,six\n pagh,wa',cha',wej,IoS,vagh,jav\n ᬦᬸᬮ᭄,ᬲᬶᬓᬶ,ᬤᬸᬯ,ᬢᭂᬮᬸ,ᬧᬧᬢ᭄,ᬮᬶᬫᬾ,ᬦᭂᬦᭂᬫ᭄\n unu,du,tri,kvar,kvin,ses,sep\n "quoted","f""ield","with a comma ',' in it","and some \n for good measure", five, six, seven\n 𐌏𐌉𐌍𐌏,𐌃𐌏,𐌕𐌓𐌉,𐌐𐌄𐌕𐌏𐌓,𐌐𐌄𐌌𐌐𐌄,𐌔𐌖𐌄𐌊𐌏𐌔,𐌔𐌄𐌗𐌕𐌀𐌌\n zero,un,duo.tres.quantro,cinque,sex\n nolla,yksi,kaksi,kolme,neljä,viisi,kuusi\n really long field, because otherwise, small string opt,imizations may trivial,ize the copies that, were trying to also, measure here!!!!\n нула,једин,два,три,четыри,петь,шесть\n 一,二,三,四,五,六,七\n saquui,ta'lo,tso'i,nvgi,hisgi,sudali,galiquogi\n\n """\n\nlet targetRowNumber = 50\nlet repeatCount = targetRowNumber / workloadBase.split(separator: "\n").count\nlet workload = String(\n repeatElement(workloadBase, count: repeatCount).joined().dropLast())\n\npublic func buildWorkload() {\n let contents = workload\n // Validate that all the parsers produce the same results.\n let alt: [[String]] = contents.parseAlt()\n let altIndices: [[String]] = contents.parseAltIndices().map {\n $0.map { String($0) }\n }\n check(alt.elementsEqual(altIndices))\n\n var remainder = workload[...]\n\n let parseResult: [[String]] = try! parseCSV(&remainder, initialState: []) {\n (res: inout [[String]], num, substr) in\n let field = String(substr)\n if num == 0 {\n res.append([field])\n } else {\n res[res.endIndex-1].append(field)\n }\n }\n check(alt.elementsEqual(parseResult))\n}\n\n@inline(never)\npublic func run_CSVParsing_characters(_ n: Int) {\n let contents = workload\n for _ in 0..<n {\n var remainder = contents[...]\n let result = try! parseCSV(&remainder, initialState: 0) {\n (result: inout Int, _, substr) in\n result += 1\n blackHole(substr)\n }\n blackHole(result)\n }\n}\n\n@inline(never)\npublic func run_CSVParsing_scalars(_ n: Int) {\n let contents = workload.unicodeScalars\n for _ in 0..<n {\n var remainder = contents[...]\n let result = try! parseCSV(&remainder, initialState: 0) {\n (result: inout Int, _, substr) in\n result += 1\n blackHole(substr)\n }\n blackHole(result)\n }\n}\n\n@inline(never)\npublic func run_CSVParsing_utf16(_ n: Int) {\n let contents = workload.utf16\n for _ in 0..<n {\n var remainder = contents[...]\n let result = try! parseCSV(&remainder, initialState: 0) {\n (result: inout Int, _, substr) in\n result += 1\n blackHole(substr)\n }\n blackHole(result)\n }\n}\n\n@inline(never)\npublic func run_CSVParsing_utf8(_ n: Int) {\n let contents = workload.utf8\n for _ in 0..<n {\n var remainder = contents[...]\n let result = try! parseCSV(&remainder, initialState: 0) {\n (result: inout Int, _, substr) in\n result += 1\n blackHole(substr)\n }\n blackHole(result)\n }\n}\n\n\n@inline(never)\npublic func run_CSVParsingAlt(_ n: Int) {\n let contents = workload\n for _ in 0..<n {\n blackHole(contents.parseAlt())\n }\n}\n\n@inline(never)\npublic func run_CSVParsingAltIndices(_ n: Int) {\n let contents = workload\n for _ in 0..<n {\n blackHole(contents.parseAltIndices())\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_CSVParsing.swift | cpp_apple_swift_benchmark_single-source_CSVParsing.swift | Swift | 12,531 | 0.95 | 0.080092 | 0.0275 | python-kit | 651 | 2025-04-05T07:00:39.069659 | Apache-2.0 | false | 56c8c81c25f2a59a4539090d1f65d8d5 |
//===--- DataBenchmarks.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n\nlet d: [BenchmarkCategory] = [.validation, .api, .Data, .cpubench]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "DataCreateEmpty",\n runFunction: { for _ in 0..<$0*10_000 { blackHole(Data()) } },\n tags: d, legacyFactor: 10),\n BenchmarkInfo(name: "DataCreateSmall",\n runFunction: { for _ in 0..<$0*10_000 { blackHole(sampleData(.small)) } },\n tags: d, legacyFactor: 10),\n BenchmarkInfo(name: "DataCreateMedium",\n runFunction: { for _ in 0..<$0*100 { blackHole(sampleData(.medium)) } },\n tags: d, legacyFactor: 100),\n\n BenchmarkInfo(name: "DataCreateEmptyArray",\n runFunction: { for _ in 0..<$0*2_000 { blackHole(Data([])) } }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "DataCreateSmallArray",\n runFunction: { for _ in 0..<$0*2_000 { blackHole(Data(\n [0, 1, 2, 3, 4, 5, 6])) } }, tags: d, legacyFactor: 50),\n BenchmarkInfo(name: "DataCreateMediumArray",\n runFunction: { for _ in 0..<$0*500 { blackHole(Data([\n 0, 1, 2, 3, 4, 5, 6,\n 0, 1, 2, 3, 4, 5, 6,\n 0, 1, 2, 3, 4, 5, 6,\n 0, 1, 2, 3, 4, 5, 6,\n ])) } }, tags: d, legacyFactor: 20),\n\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count", runFunction: {\n _init($0*100, sequence: Bytes(count: 809, exact: true)) }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count0", runFunction: {\n _init($0*100, sequence: Bytes(count: 809, exact: false)) }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count.I", runFunction: {\n for _ in 0..<$0*100 {\n blackHole(Data(Bytes(count: 809, exact: true))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count0.I", runFunction: {\n for _ in 0..<$0*100 {\n blackHole(Data(Bytes(count: 809, exact: false))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.2047B.Count.I", runFunction: {\n for _ in 0..<$0*50 {\n blackHole(Data(Bytes(count: 2047, exact: true))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.2047B.Count0.I", runFunction: {\n for _ in 0..<$0*50 {\n blackHole(Data(Bytes(count: 2047, exact: false))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.2049B.Count.I", runFunction: {\n for _ in 0..<$0*50 {\n blackHole(Data(Bytes(count: 2049, exact: true))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.2049B.Count0.I", runFunction: {\n for _ in 0..<$0*50 {\n blackHole(Data(Bytes(count: 2049, exact: false))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.511B.Count.I", runFunction: {\n for _ in 0..<$0*150 {\n blackHole(Data(Bytes(count: 511, exact: true))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.511B.Count0.I", runFunction: {\n for _ in 0..<$0*150 {\n blackHole(Data(Bytes(count: 511, exact: false))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.513B.Count.I", runFunction: {\n for _ in 0..<$0*150 {\n blackHole(Data(Bytes(count: 513, exact: true))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.513B.Count0.I", runFunction: {\n for _ in 0..<$0*150 {\n blackHole(Data(Bytes(count: 513, exact: false))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count", runFunction: {\n _init($0, sequence: Bytes(count: 2<<15, exact: true)) }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count0", runFunction: {\n _init($0, sequence: Bytes(count: 2<<15, exact: false)) }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count.I", runFunction: {\n for _ in 0..<$0 {\n blackHole(Data(Bytes(count: 2<<15, exact: true))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count0.I", runFunction: {\n for _ in 0..<$0 {\n blackHole(Data(Bytes(count: 2<<15, exact: false))) } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count.RE", runFunction: {\n _init($0*100, sequence: repeatElement(UInt8(0xA0), count: 809)) }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count0.RE", runFunction: {\n _init($0*100, sequence: Count0(repeatElement(UInt8(0xA0), count: 809))) },\n tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count.RE.I", runFunction: {\n for _ in 0..<$0*100 {\n blackHole(Data(repeatElement(UInt8(0xA0), count: 809)))\n } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.809B.Count0.RE.I", runFunction: {\n for _ in 0..<$0*100 {\n blackHole(Data(Count0(repeatElement(UInt8(0xA0), count: 809))))\n } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count.RE", runFunction: {\n _init($0, sequence: repeatElement(UInt8(0xA0), count: 2<<15)) }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count0.RE", runFunction: {\n _init($0, sequence: Count0(repeatElement(UInt8(0xA0), count: 2<<15))) },\n tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count.RE.I", runFunction: {\n for _ in 0..<$0 {\n blackHole(Data(repeatElement(UInt8(0xA0), count: 2<<15)))\n } }, tags: d),\n BenchmarkInfo(name: "Data.init.Sequence.64kB.Count0.RE.I", runFunction: {\n for _ in 0..<$0 {\n blackHole(Data(Count0(repeatElement(UInt8(0xA0), count: 2<<15))))\n } }, tags: d),\n\n BenchmarkInfo(name: "DataSubscriptSmall",\n runFunction: { let data = small\n for _ in 0..<$0*10_000 { blackHole(data[1]) } }, tags: d),\n BenchmarkInfo(name: "DataSubscriptMedium",\n runFunction: { let data = medium\n for _ in 0..<$0*10_000 { blackHole(data[521]) } }, tags: d),\n\n BenchmarkInfo(name: "DataCountSmall",\n runFunction: { count($0*10_000, data: small) }, tags: d),\n BenchmarkInfo(name: "DataCountMedium",\n runFunction: { count($0*10_000, data: medium) }, tags: d),\n\n BenchmarkInfo(name: "DataSetCountSmall",\n runFunction: { setCount($0*10_000, data: small, extra: 3) }, tags: d),\n BenchmarkInfo(name: "DataSetCountMedium",\n runFunction: { setCount($0*1_000, data: medium, extra: 100) }, tags: d,\n legacyFactor: 10),\n\n BenchmarkInfo(name: "DataAccessBytesSmall",\n runFunction: { withUnsafeBytes($0*10_000, data: small) }, tags: d),\n BenchmarkInfo(name: "DataAccessBytesMedium",\n runFunction: { withUnsafeBytes($0*10_000, data: medium) }, tags: d),\n\n BenchmarkInfo(name: "DataMutateBytesSmall",\n runFunction: { withUnsafeMutableBytes($0*500, data: small) }, tags: d,\n legacyFactor: 20),\n BenchmarkInfo(name: "DataMutateBytesMedium",\n runFunction: { withUnsafeMutableBytes($0*500, data: medium) }, tags: d,\n legacyFactor: 20),\n\n BenchmarkInfo(name: "DataCopyBytesSmall",\n runFunction: { copyBytes($0*10_000, data: small) }, tags: d),\n BenchmarkInfo(name: "DataCopyBytesMedium",\n runFunction: { copyBytes($0*5_000, data: medium) }, tags: d,\n legacyFactor: 2),\n\n BenchmarkInfo(name: "DataAppendBytesSmall",\n runFunction: { append($0*10_000, bytes: 3, to: small) }, tags: d),\n BenchmarkInfo(name: "DataAppendBytesMedium",\n runFunction: { append($0*500, bytes: 809, to: medium) }, tags: d,\n legacyFactor: 20),\n\n BenchmarkInfo(name: "DataAppendArray",\n runFunction: { append($0*100, array: array809, to: medium) }, tags: d,\n legacyFactor: 100),\n\n BenchmarkInfo(name: "DataReset",\n runFunction: { resetBytes($0*100, in: 431..<809, data: medium) },\n tags: d, legacyFactor: 100),\n\n BenchmarkInfo(name: "DataReplaceSmall", runFunction: {\n replace($0*100, data: medium, subrange:431..<809, with: small) },\n tags: d, legacyFactor: 100),\n BenchmarkInfo(name: "DataReplaceMedium", runFunction: {\n replace($0*100, data: medium, subrange:431..<809, with: medium) },\n tags: d, legacyFactor: 100),\n BenchmarkInfo(name: "DataReplaceLarge", runFunction: {\n replace($0*100, data: medium, subrange:431..<809, with: large) },\n tags: d, legacyFactor: 100),\n\n BenchmarkInfo(name: "DataReplaceSmallBuffer", runFunction: {\n replaceBuffer($0*100, data: medium, subrange:431..<809, with: small) },\n tags: d, legacyFactor: 100),\n BenchmarkInfo(name: "DataReplaceMediumBuffer", runFunction: {\n replaceBuffer($0*100, data: medium, subrange:431..<809, with: medium) },\n tags: d, legacyFactor: 100),\n BenchmarkInfo(name: "DataReplaceLargeBuffer", runFunction: {\n replaceBuffer($0*100, data: medium, subrange:431..<809, with: large) },\n tags: d + [.skip]),\n // Large buffer replacement is too dependent on the system state\n // to produce a meaningful benchmark score. 30% variation is common.\n\n BenchmarkInfo(name: "DataAppendSequence",\n runFunction: { append($0*100, sequenceLength: 809, to: medium) },\n tags: d, legacyFactor: 100),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count", runFunction: {\n append($0*100, sequence: Bytes(count: 809, exact: true), to: medium) },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count0", runFunction: {\n append($0*100, sequence: Bytes(count: 809, exact: false) , to: medium) },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count.I",\n runFunction: { for _ in 1...$0*100 { var copy = medium\n copy.append(contentsOf: Bytes(count: 809, exact: true)) } }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count0.I",\n runFunction: { for _ in 1...$0*100 { var copy = medium\n copy.append(contentsOf: Bytes(count: 809, exact: false)) } }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count", runFunction: {\n append($0, sequence: Bytes(count: 2<<15, exact: true), to: medium) },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count0", runFunction: {\n append($0, sequence: Bytes(count: 2<<15, exact: false), to: medium) },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count.I", runFunction: {\n for _ in 1...$0 { var copy = medium\n copy.append(contentsOf: Bytes(count: 2<<15, exact: true)) } }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count0.I", runFunction: {\n for _ in 1...$0 { var copy = medium\n copy.append(contentsOf: Bytes(count: 2<<15, exact: false)) } }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count.RE.I", runFunction: {\n for _ in 1...$0*100 { var copy = medium\n copy.append(contentsOf: repeatElement(UInt8(0xA0), count: 809)) } },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count0.RE.I", runFunction: {\n for _ in 1...$0*100 { var copy = medium\n copy.append(contentsOf: Count0(repeatElement(UInt8(0xA0), count: 809))) } },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count.RE", runFunction: {\n append($0*100, sequence: repeatElement(UInt8(0xA0), count: 809),\n to: medium) }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.809B.Count0.RE", runFunction: {\n append($0*100, sequence: Count0(repeatElement(UInt8(0xA0), count: 809)),\n to: medium) }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count.RE.I", runFunction: {\n for _ in 1...$0 { var copy = medium\n copy.append(contentsOf: repeatElement(UInt8(0xA0), count: 2<<15)) } },\n tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count0.RE.I", runFunction: {\n for _ in 1...$0 { var copy = medium\n copy.append(contentsOf: Count0(repeatElement(UInt8(0xA0), count: 2<<15))) }\n }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count.RE", runFunction: {\n append($0, sequence: repeatElement(UInt8(0xA0), count: 2<<15),\n to: medium) }, tags: d),\n BenchmarkInfo(name: "Data.append.Sequence.64kB.Count0.RE", runFunction: {\n append($0, sequence: Count0(repeatElement(UInt8(0xA0), count: 2<<15)),\n to: medium) }, tags: d),\n\n BenchmarkInfo(name: "DataAppendDataSmallToSmall",\n runFunction: { append($0*500, data: small, to: small) }, tags: d,\n legacyFactor: 20),\n BenchmarkInfo(name: "DataAppendDataSmallToMedium",\n runFunction: { append($0*500, data: small, to: medium) }, tags: d,\n legacyFactor: 20),\n BenchmarkInfo(name: "DataAppendDataSmallToLarge",\n runFunction: { append($0*50, data: small, to: large) }, tags: d,\n legacyFactor: 200),\n BenchmarkInfo(name: "DataAppendDataMediumToSmall",\n runFunction: { append($0*500, data: medium, to: small) }, tags: d,\n legacyFactor: 20),\n BenchmarkInfo(name: "DataAppendDataMediumToMedium",\n runFunction: { append($0*500, data: medium, to: medium) }, tags: d,\n legacyFactor: 20),\n BenchmarkInfo(name: "DataAppendDataMediumToLarge",\n runFunction: { append($0*50, data: medium, to: large) }, tags: d,\n legacyFactor: 200),\n BenchmarkInfo(name: "DataAppendDataLargeToSmall",\n runFunction: { append($0*50, data: large, to: small) }, tags: d,\n legacyFactor: 200),\n BenchmarkInfo(name: "DataAppendDataLargeToMedium",\n runFunction: { append($0*50, data: large, to: medium) }, tags: d,\n legacyFactor: 200),\n BenchmarkInfo(name: "DataAppendDataLargeToLarge",\n runFunction: { append($0*50, data: large, to: large) }, tags: d + [.unstable],\n legacyFactor: 200),\n\n BenchmarkInfo(name: "DataToStringEmpty",\n runFunction: { string($0*200, from: emptyData) }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "DataToStringSmall",\n runFunction: { string($0*200, from: smallData) }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "DataToStringMedium",\n runFunction: { string($0*200, from: mediumData) }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "DataToStringLargeUnicode",\n runFunction: { string($0*200, from: largeUnicodeData) }, tags: d,\n legacyFactor: 50),\n\n BenchmarkInfo(name: "StringToDataEmpty",\n runFunction: { dataFromUTF8View($0*200, from: emptyString) }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "StringToDataSmall",\n runFunction: { dataFromUTF8View($0*200, from: smallString) }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "StringToDataMedium",\n runFunction: { dataFromUTF8View($0*200, from: mediumString) }, tags: d,\n legacyFactor: 50),\n BenchmarkInfo(name: "StringToDataLargeUnicode",\n runFunction: { dataFromUTF8View($0*200, from: largeUnicodeString) }, tags: d,\n legacyFactor: 50),\n\n BenchmarkInfo(name: "String.data.Empty",\n runFunction: { dataUsingUTF8Encoding($0*200, from: emptyString) }, tags: d),\n BenchmarkInfo(name: "String.data.Small",\n runFunction: { dataUsingUTF8Encoding($0*200, from: smallString) }, tags: d),\n BenchmarkInfo(name: "String.data.Medium",\n runFunction: { dataUsingUTF8Encoding($0*200, from: mediumString) }, tags: d),\n BenchmarkInfo(name: "String.data.LargeUnicode",\n runFunction: { dataUsingUTF8Encoding($0*200, from: largeUnicodeString) }, tags: d),\n\n BenchmarkInfo(name: "Data.hash.Empty",\n runFunction: { hash($0*10_000, data: Data()) }, tags: d),\n BenchmarkInfo(name: "Data.hash.Small",\n runFunction: { hash($0*10_000, data: small) }, tags: d),\n BenchmarkInfo(name: "Data.hash.Medium",\n runFunction: { hash($0*1_000, data: medium) }, tags: d),\n]\n\nlet emptyString = ""\nlet smallString = "\r\n"\nlet mediumString = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"\nlet largeUnicodeString = \n "Swiftに大幅な改良が施され、𓀀𓀁𓀂𓀃, 🇺🇸🇨🇦🇲🇽" + mediumString\nlet emptyData = Data()\nlet smallData = Data(smallString.utf8)\nlet mediumData = Data(mediumString.utf8)\nlet largeUnicodeData = Data(largeUnicodeString.utf8)\n\nlet small = sampleData(.small)\nlet medium = sampleData(.medium)\nlet large = sampleData(.large)\n\nlet array809 = byteArray(size: 809)\n\nstruct Count0<S: Sequence> : Sequence {\n let base: S\n init (_ base:S) { self.base = base }\n func makeIterator() -> S.Iterator { return base.makeIterator() }\n var underestimatedCount: Int { return 0 }\n}\n\nstruct Bytes: Sequence, IteratorProtocol {\n let count: Int\n let exact: Bool\n var i: Int = 0\n init(count: Int, exact: Bool) {\n self.count = count\n self.exact = exact\n }\n mutating func next() -> UInt8? {\n defer { i = i &+ 1 }\n return (i < count) ? UInt8(truncatingIfNeeded: i) : nil\n }\n var underestimatedCount: Int {\n return exact ? count : 0\n }\n}\n\nenum SampleKind {\n case small\n case medium\n case large\n case veryLarge\n case immutableBacking\n}\n\nfunc byteArray(size: Int) -> [UInt8] {\n var bytes = [UInt8](repeating: 0, count: size)\n bytes.withUnsafeMutableBufferPointer { buffer in\n for i in buffer.indices {\n buffer[i] = UInt8(truncatingIfNeeded: i)\n }\n }\n return bytes\n}\n\nfunc sampleData(size: Int) -> Data {\n var data = Data(count: size)\n data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> () in\n for i in 0..<size {\n bytes[i] = UInt8(truncatingIfNeeded: i)\n }\n }\n return data\n}\n\nfunc sampleBridgedNSData() -> Data {\n let count = 1033\n let data = NSData(bytes: byteArray(size: count), length: count)\n return Data(referencing: data)\n}\n\nfunc sampleData(_ type: SampleKind) -> Data {\n switch type {\n case .small: return sampleData(size: 11)\n case .medium: return sampleData(size: 1033)\n case .large: return sampleData(size: 40980)\n case .veryLarge: return sampleData(size: 1024 * 1024 * 1024 + 128)\n case .immutableBacking: return sampleBridgedNSData()\n }\n\n}\n\n@inline(never)\nfunc withUnsafeBytes(_ n: Int, data: Data) {\n for _ in 1...n {\n data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) in\n blackHole(ptr.pointee)\n }\n }\n}\n\n@inline(never)\nfunc withUnsafeMutableBytes(_ n: Int, data: Data) {\n for _ in 1...n {\n var copy = data\n copy.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in\n // Mutate a byte\n ptr.pointee = 42\n }\n }\n}\n\n@inline(never)\nfunc copyBytes(_ n: Int, data: Data) {\n let amount = data.count\n let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: amount)\n defer { buffer.deallocate() }\n for _ in 1...n {\n data.copyBytes(to: buffer, from: 0..<amount)\n }\n}\n\n@inline(never)\nfunc append(_ n: Int, bytes count: Int, to data: Data) {\n let bytes = malloc(count).assumingMemoryBound(to: UInt8.self)\n defer { free(bytes) }\n for _ in 1...n {\n var copy = data\n copy.append(bytes, count: count)\n }\n}\n\n@inline(never)\nfunc append(_ n: Int, array bytes: [UInt8], to data: Data) {\n for _ in 1...n {\n var copy = data\n copy.append(contentsOf: bytes)\n }\n}\n\n@inline(never)\nfunc append(_ n: Int, sequenceLength: Int, to data: Data) {\n let bytes = repeatElement(UInt8(0xA0), count: sequenceLength)\n for _ in 1...n {\n var copy = data\n copy.append(contentsOf: bytes)\n }\n}\n\n@inline(never)\nfunc append<S: Sequence>(_ n: Int, sequence: S, to data: Data)\nwhere S.Element == UInt8 {\n for _ in 1...n {\n var copy = data\n copy.append(contentsOf: sequence)\n }\n}\n\n@inline(never)\nfunc _init<S: Sequence>(_ n: Int, sequence: S) where S.Element == UInt8 {\n for _ in 1...n {\n blackHole(Data(sequence))\n }\n}\n\n@inline(never)\nfunc resetBytes(_ n: Int, in range: Range<Data.Index>, data: Data) {\n for _ in 1...n {\n var copy = data\n copy.resetBytes(in: range)\n }\n}\n\n@inline(never)\nfunc replace(\n _ n: Int,\n data: Data,\n subrange range: Range<Data.Index>,\n with replacement: Data\n) {\n for _ in 1...n {\n var copy = data\n copy.replaceSubrange(range, with: replacement)\n }\n}\n\n@inline(never)\nfunc replaceBuffer(\n _ n: Int,\n data: Data,\n subrange range: Range<Data.Index>,\n with replacement: Data\n) {\n replacement.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in\n let buffer = UnsafeBufferPointer(start: bytes, count: replacement.count)\n\n for _ in 1...n {\n var copy = data\n copy.replaceSubrange(range, with: buffer)\n }\n }\n}\n\n@inline(never)\nfunc append(_ n: Int, data: Data, to target: Data) {\n var copy: Data\n for _ in 1...n {\n copy = target\n copy.append(data)\n }\n}\n\n@inline(never)\npublic func count(_ n: Int, data: Data) {\n for _ in 1...n {\n blackHole(data.count)\n }\n}\n\n@inline(never)\npublic func setCount(_ n: Int, data: Data, extra: Int) {\n var copy = data\n let count = data.count + extra\n let orig = data.count\n for _ in 1...n {\n copy.count = count\n copy.count = orig\n }\n}\n\n@inline(never)\npublic func string(_ n: Int, from data: Data) {\n for _ in 1...n {\n blackHole(String(decoding: data, as: UTF8.self))\n }\n}\n\n@inline(never)\npublic func dataFromUTF8View(_ n: Int, from string: String) {\n for _ in 1...n {\n blackHole(Data(string.utf8))\n }\n}\n\n@inline(never)\npublic func dataUsingUTF8Encoding(_ n: Int, from string: String) {\n for _ in 1...n {\n autoreleasepool { blackHole(string.data(using: .utf8)) }\n }\n}\n\n@inline(never)\npublic func hash(_ n: Int, data: Data) {\n var hasher = Hasher()\n for _ in 0 ..< n {\n hasher.combine(data)\n }\n\n let _ = hasher.finalize()\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DataBenchmarks.swift | cpp_apple_swift_benchmark_single-source_DataBenchmarks.swift | Swift | 20,942 | 0.95 | 0.097345 | 0.027344 | vue-tools | 924 | 2024-05-08T18:33:34.560295 | MIT | false | f068b03f14e5c1b363703164963b299f |
//===--- DeadArray.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// rdar://problem/20980377\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "DeadArray",\n runFunction: run_DeadArray,\n tags: [.regression, .unstable],\n legacyFactor: 200\n )\n\n@inline(__always)\nfunc debug(_ m:String) {}\n\nprivate var count = 0\n\n@inline(never)\nfunc bar() { count += 1 }\n\n@inline(never)\nfunc runLoop(_ var1: Int, var2: Int) {\n for _ in 0..<500 {\n debug("Var1: \(var1) Var2: \(var2)")\n bar()\n }\n}\n\n@inline(never)\npublic func run_DeadArray(_ n: Int) {\n for _ in 1...n {\n count = 0\n runLoop(0, var2: 0)\n }\n check(count == 500)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DeadArray.swift | cpp_apple_swift_benchmark_single-source_DeadArray.swift | Swift | 1,106 | 0.95 | 0.085106 | 0.3 | node-utils | 622 | 2025-03-10T14:33:49.977532 | MIT | false | 0a69b4cbf9d577d9421b2913cc8daa2b |
//===--- DevirtualizeProtocolComposition.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "DevirtualizeProtocolComposition", runFunction: run_DevirtualizeProtocolComposition, tags: [.validation, .api]),\n]\n\nprotocol Pingable { func ping() -> Int; func pong() -> Int}\n\npublic class Game<T> {\n func length() -> Int { return 10 }\n}\n\npublic class PingPong: Game<String> { }\n\nextension PingPong : Pingable {\n func ping() -> Int { return 1 }\n func pong() -> Int { return 2 }\n}\n\nfunc playGame<T>(_ x: Game<T> & Pingable) -> Int {\n var sum = 0\n for _ in 0..<x.length() {\n sum += x.ping() + x.pong()\n }\n return sum\n}\n\n@inline(never)\npublic func run_DevirtualizeProtocolComposition(n: Int) {\n for _ in 0..<n * 20_000 {\n blackHole(playGame(PingPong()))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DevirtualizeProtocolComposition.swift | cpp_apple_swift_benchmark_single-source_DevirtualizeProtocolComposition.swift | Swift | 1,273 | 0.95 | 0.133333 | 0.297297 | react-lib | 811 | 2023-09-22T08:20:45.036072 | MIT | false | b527ee07e72af3293fa6b7e5d780a26a |
//===--- DictionaryBridge.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// benchmark to test the performance of bridging an NSDictionary to a\n// Swift.Dictionary.\n\nimport Foundation\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "DictionaryBridge",\n runFunction: run_DictionaryBridge,\n tags: [.validation, .api, .Dictionary, .bridging])\n\n#if _runtime(_ObjC)\nclass Thing : NSObject {\n\n required override init() {\n let c = type(of: self).col()\n check(c!.count == 10)\n }\n\n private class func col() -> [String : AnyObject]? {\n let dict = NSMutableDictionary()\n dict.setValue(1, forKey: "one")\n dict.setValue(2, forKey: "two")\n dict.setValue(3, forKey: "three")\n dict.setValue(4, forKey: "four")\n dict.setValue(5, forKey: "five")\n dict.setValue(6, forKey: "six")\n dict.setValue(7, forKey: "seven")\n dict.setValue(8, forKey: "eight")\n dict.setValue(9, forKey: "nine")\n dict.setValue(10, forKey: "ten")\n\n return NSDictionary(dictionary: dict) as? [String: AnyObject]\n }\n\n class func mk() -> Thing {\n return self.init()\n }\n}\n\nclass Stuff {\n var c: Thing = Thing.mk()\n init() {\n\n }\n}\n#endif\n\n@inline(never)\npublic func run_DictionaryBridge(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 1...100*n {\n autoreleasepool {\n _ = Stuff()\n }\n }\n#endif\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryBridge.swift | cpp_apple_swift_benchmark_single-source_DictionaryBridge.swift | Swift | 1,786 | 0.95 | 0.126761 | 0.283333 | node-utils | 45 | 2023-10-31T00:27:40.740607 | Apache-2.0 | false | 2c5942bb3db7c27b96e2b10d8de401ef |
//===--- DictionaryBridgeToObjC.swift -------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Performance benchmark for common operations on Dictionary values bridged to\n// NSDictionary.\nimport TestsUtils\n#if _runtime(_ObjC)\nimport Foundation\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DictionaryBridgeToObjC_Bridge",\n runFunction: run_DictionaryBridgeToObjC_BridgeToObjC,\n tags: [.validation, .api, .Dictionary, .bridging]),\n BenchmarkInfo(\n name: "DictionaryBridgeToObjC_Access",\n runFunction: run_DictionaryBridgeToObjC_Access,\n tags: [.validation, .api, .Dictionary, .bridging]),\n BenchmarkInfo(\n name: "DictionaryBridgeToObjC_BulkAccess",\n runFunction: run_DictionaryBridgeToObjC_BulkAccess,\n tags: [.validation, .api, .Dictionary, .bridging])\n]\n\nlet numbers: [String: Int] = [\n "one": 1,\n "two": 2,\n "three": 3,\n "four": 4,\n "five": 5,\n "six": 6,\n "seven": 7,\n "eight": 8,\n "nine": 9,\n "ten": 10,\n "eleven": 11,\n "twelve": 12,\n "thirteen": 13,\n "fourteen": 14,\n "fifteen": 15,\n "sixteen": 16,\n "seventeen": 17,\n "eighteen": 18,\n "nineteen": 19,\n "twenty": 20\n]\n\n@inline(never)\npublic func run_DictionaryBridgeToObjC_BridgeToObjC(_ n: Int) {\n for _ in 1 ... 100 * n {\n blackHole(numbers as NSDictionary)\n }\n}\n\n@inline(never)\npublic func run_DictionaryBridgeToObjC_Access(_ n: Int) {\n let d = numbers as NSDictionary\n blackHole(d.object(forKey: "one")) // Force bridging of contents\n for _ in 1 ... 100 * n {\n for key in numbers.keys {\n check(identity(d).object(forKey: key) != nil)\n }\n }\n}\n\n@inline(never)\npublic func run_DictionaryBridgeToObjC_BulkAccess(_ n: Int) {\n let d = numbers as NSDictionary\n for _ in 1 ... 100 * n {\n let d2 = NSDictionary(dictionary: identity(d))\n check(d2.count == d.count)\n }\n}\n\n#else // !_runtime(ObjC)\npublic let benchmarks: [BenchmarkInfo] = []\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryBridgeToObjC.swift | cpp_apple_swift_benchmark_single-source_DictionaryBridgeToObjC.swift | Swift | 2,306 | 0.95 | 0.093023 | 0.202532 | react-lib | 450 | 2024-12-25T06:28:45.535186 | GPL-3.0 | false | 918fc73c365d146c364bbeb767cd85a3 |
//===--- DictionaryCompactMapValues.swift ---------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\nlet size = 100\nlet oddNumbers = stride(from: 1, to: size, by: 2)\nlet smallOddNumMap: [Int: Int?] =\n Dictionary(uniqueKeysWithValues: zip(oddNumbers, oddNumbers))\nlet compactOddNums: [Int: Int] =\n Dictionary(uniqueKeysWithValues: zip(oddNumbers, oddNumbers))\nlet oddStringMap: [Int: String] = Dictionary(uniqueKeysWithValues:\n (1...size).lazy.map { ($0, $0 % 2 == 0 ? "dummy" : "\($0)") })\n\nlet t: [BenchmarkCategory] = [.validation, .api, .Dictionary]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "DictionaryCompactMapValuesOfNilValue",\n runFunction: compactMapValues, tags: t,\n setUpFunction: { blackHole(smallOddNumMap); blackHole(compactOddNums)},\n legacyFactor: 50),\n BenchmarkInfo(name: "DictionaryCompactMapValuesOfCastValue",\n runFunction: compactMapValuesInt, tags: t,\n setUpFunction: { blackHole(oddStringMap); blackHole(compactOddNums)},\n legacyFactor: 54),\n]\n\nfunc compactMapValues(n: Int) {\n for _ in 1...20*n {\n check(smallOddNumMap.compactMapValues({$0}) == compactOddNums)\n }\n}\n\nfunc compactMapValuesInt(n: Int) {\n for _ in 1...20*n {\n check(oddStringMap.compactMapValues(Int.init) == compactOddNums)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryCompactMapValues.swift | cpp_apple_swift_benchmark_single-source_DictionaryCompactMapValues.swift | Swift | 1,696 | 0.95 | 0.085106 | 0.268293 | awesome-app | 277 | 2024-06-12T11:51:17.680881 | Apache-2.0 | false | a5027449e72b23c500b6ed04dbdc0edf |
//===--- DictionaryCopy.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark checks for quadratic behavior while copying elements in hash\n// order between Dictionaries of decreasing capacity\n//\n// https://github.com/apple/swift/issues/45856\n\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.validation, .api, .Dictionary]\n\n// We run the test at a spread of sizes between 1*x and 2*x, because the\n// quadratic behavior only happens at certain load factors.\n\npublic let benchmarks = [\n BenchmarkInfo(name:"Dict.CopyKeyValue.16k",\n runFunction: copyKeyValue, tags: t, setUpFunction: { dict(16_000) }),\n BenchmarkInfo(name:"Dict.CopyKeyValue.20k",\n runFunction: copyKeyValue, tags: t, setUpFunction: { dict(20_000) }),\n BenchmarkInfo(name:"Dict.CopyKeyValue.24k",\n runFunction: copyKeyValue, tags: t, setUpFunction: { dict(24_000) }),\n BenchmarkInfo(name:"Dict.CopyKeyValue.28k",\n runFunction: copyKeyValue, tags: t, setUpFunction: { dict(28_000) }),\n\n BenchmarkInfo(name:"Dict.FilterAllMatch.16k",\n runFunction: filterAllMatch, tags: t, setUpFunction: { dict(16_000) }),\n BenchmarkInfo(name:"Dict.FilterAllMatch.20k",\n runFunction: filterAllMatch, tags: t, setUpFunction: { dict(20_000) }),\n BenchmarkInfo(name:"Dict.FilterAllMatch.24k",\n runFunction: filterAllMatch, tags: t, setUpFunction: { dict(24_000) }),\n BenchmarkInfo(name:"Dict.FilterAllMatch.28k",\n runFunction: filterAllMatch, tags: t, setUpFunction: { dict(28_000) }),\n]\n\nvar dict: [Int: Int]?\n\nfunc dict(_ size: Int) {\n dict = Dictionary(uniqueKeysWithValues: zip(1...size, 1...size))\n}\n\n@inline(never)\nfunc copyKeyValue(n: Int) {\n for _ in 1...n {\n var copy = [Int: Int]()\n for (key, value) in dict! {\n copy[key] = value\n }\n check(copy.count == dict!.count)\n }\n}\n\n// Filter with a predicate returning true is essentially the same loop as the\n// one in copyKeyValue above.\n@inline(never)\nfunc filterAllMatch(n: Int) {\n for _ in 1...n {\n let copy = dict!.filter { _ in true }\n check(copy.count == dict!.count)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryCopy.swift | cpp_apple_swift_benchmark_single-source_DictionaryCopy.swift | Swift | 2,496 | 0.95 | 0.1 | 0.316667 | python-kit | 822 | 2025-03-02T02:25:14.056310 | MIT | false | c875b92af273b19a5a5ddfc33b7fd06b |
//===--- DictionaryGroup.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "DictionaryGroup",\n runFunction: run_DictionaryGroup,\n tags: [.validation, .api, .Dictionary]),\n BenchmarkInfo(name: "DictionaryGroupOfObjects",\n runFunction: run_DictionaryGroupOfObjects,\n tags: [.validation, .api, .Dictionary],\n setUpFunction: { blackHole(inputObjects) },\n tearDownFunction: { inputObjects = nil },\n legacyFactor: 9\n ),\n]\n\n@inline(never)\npublic func run_DictionaryGroup(_ n: Int) {\n for _ in 1...n {\n let dict = Dictionary(grouping: 0..<10_000, by: { $0 % 10 })\n check(dict.count == 10)\n check(dict[0]!.count == 1_000)\n }\n}\n\nclass Box<T : Hashable> : Hashable {\n var value: T\n\n init(_ v: T) {\n value = v\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n\n static func ==(lhs: Box, rhs: Box) -> Bool {\n return lhs.value == rhs.value\n }\n}\n\nvar inputObjects: [Box<Int>]! = (0..<1_000).lazy.map { Box($0) }\n\n@inline(never)\npublic func run_DictionaryGroupOfObjects(_ n: Int) {\n let objects: [Box<Int>] = inputObjects\n for _ in 1...n {\n let dict = Dictionary(grouping: objects, by: { Box($0.value % 10) })\n check(dict.count == 10)\n check(dict[Box(0)]!.count == 100)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryGroup.swift | cpp_apple_swift_benchmark_single-source_DictionaryGroup.swift | Swift | 1,753 | 0.95 | 0.079365 | 0.203704 | python-kit | 376 | 2025-07-07T23:58:11.089265 | MIT | false | 84a4b5096608f60631131dfbb746de4a |
//===--- DictionaryKeysContains.swift -------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark checks if keys.contains(key) is executed in O(1)\n// even when wrapping a NSDictionary\nimport TestsUtils\nimport Foundation\n\n#if _runtime(_ObjC)\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DictionaryKeysContainsNative",\n runFunction: run_DictionaryKeysContains,\n tags: [.validation, .api, .Dictionary],\n setUpFunction: setupNativeDictionary,\n tearDownFunction: teardownDictionary,\n unsupportedPlatforms: [.linux]),\n BenchmarkInfo(\n name: "DictionaryKeysContainsCocoa",\n runFunction: run_DictionaryKeysContains,\n tags: [.validation, .api, .Dictionary],\n setUpFunction: setupBridgedDictionary,\n tearDownFunction: teardownDictionary),\n]\n#else\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DictionaryKeysContainsNative",\n runFunction: run_DictionaryKeysContains,\n tags: [.validation, .api, .Dictionary],\n setUpFunction: setupNativeDictionary,\n tearDownFunction: teardownDictionary,\n unsupportedPlatforms: [.linux]),\n]\n#endif\n\nprivate var dictionary: [NSString: NSString]!\n\nprivate func setupNativeDictionary() {\n#if os(Linux)\n fatalError("Unsupported benchmark")\n#else\n let keyValuePair: (Int) -> (NSString, NSString) = {\n let n = "\($0)" as NSString; return (n, n)\n }\n dictionary = [NSString: NSString](uniqueKeysWithValues:\n (1...10_000).lazy.map(keyValuePair))\n#endif\n}\n\n#if _runtime(_ObjC)\nprivate func setupBridgedDictionary() {\n setupNativeDictionary()\n dictionary = (NSDictionary(dictionary: dictionary) as! [NSString: NSString])\n}\n#endif\n\nprivate func teardownDictionary() {\n dictionary = nil\n}\n\n@inline(never)\npublic func run_DictionaryKeysContains(_ n: Int) {\n#if os(Linux)\n fatalError("Unsupported benchmark")\n#else\n for _ in 0..<(n * 100) {\n check(dictionary.keys.contains("42"))\n check(!dictionary.keys.contains("-1"))\n }\n#endif\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryKeysContains.swift | cpp_apple_swift_benchmark_single-source_DictionaryKeysContains.swift | Swift | 2,362 | 0.95 | 0.098765 | 0.324324 | vue-tools | 980 | 2025-06-26T01:20:02.304640 | Apache-2.0 | false | a6d79e25e523d037a8f5c655526ab17c |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// This benchmark tests the performance of Dictionary<AnyHashable, Any> with\n// small ASCII String keys. Untyped NSDictionary values get imported as this\n// type, so it occurs relatively often in practice.\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DictionaryOfAnyHashableStrings_insert",\n runFunction: run_DictionaryOfAnyHashableStrings_insert,\n tags: [.abstraction, .runtime, .cpubench],\n setUpFunction: { keys = buildKeys(50) },\n legacyFactor: 14\n ),\n BenchmarkInfo(\n name: "DictionaryOfAnyHashableStrings_lookup",\n runFunction: run_DictionaryOfAnyHashableStrings_lookup,\n tags: [.abstraction, .runtime, .cpubench],\n setUpFunction: { keys = buildKeys(50); workload = buildWorkload() },\n legacyFactor: 24\n ),\n]\n\nvar keys: [String] = []\nvar workload: [AnyHashable: Any] = [:]\n\nfunc buildKeys(_ size: Int) -> [String] {\n var result: [String] = []\n let keyPrefixes = ["font", "bgcolor", "fgcolor", "blink", "marquee"]\n for key in keyPrefixes {\n for i in 0 ..< size {\n result.append(key + "\(i)")\n }\n }\n return result\n}\n\nfunc buildWorkload() -> [AnyHashable: Any] {\n precondition(keys.count > 0)\n var result: [AnyHashable: Any] = [:]\n var i = 0\n for key in keys {\n result[key] = i\n i += 1\n }\n return result\n}\n\n\n@inline(never)\npublic func run_DictionaryOfAnyHashableStrings_insert(_ n: Int) {\n precondition(keys.count > 0)\n for _ in 1...n {\n blackHole(buildWorkload())\n }\n}\n\n@inline(never)\npublic func run_DictionaryOfAnyHashableStrings_lookup(_ n: Int) {\n precondition(workload.count > 0)\n precondition(keys.count > 0)\n for _ in 1...n {\n for i in 0 ..< keys.count {\n let key = keys[i]\n check((workload[key] as! Int) == i)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryOfAnyHashableStrings.swift | cpp_apple_swift_benchmark_single-source_DictionaryOfAnyHashableStrings.swift | Swift | 2,263 | 0.95 | 0.1 | 0.197183 | python-kit | 198 | 2024-04-30T23:30:05.214726 | BSD-3-Clause | false | b150e7dd36d2425d0d8cbdb20c7da677 |
//===--- DictionaryRemove.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Dictionary element removal benchmark\n// rdar://problem/19804127\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.validation, .api, .Dictionary]\n\nlet size = 100\nlet numberMap = Dictionary(uniqueKeysWithValues: zip(1...size, 1...size))\nlet boxedNums = (1...size).lazy.map { Box($0) }\nlet boxedNumMap = Dictionary(uniqueKeysWithValues: zip(boxedNums, boxedNums))\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DictionaryRemove",\n runFunction: remove,\n tags: t,\n setUpFunction: { blackHole(numberMap) },\n legacyFactor: 10),\n BenchmarkInfo(\n name: "DictionaryRemoveOfObjects",\n runFunction: removeObjects,\n tags: t,\n setUpFunction: { blackHole(boxedNumMap) },\n legacyFactor: 100),\n\n BenchmarkInfo(\n name: "DictionaryFilter",\n runFunction: filter,\n tags: t,\n setUpFunction: { blackHole(numberMap) },\n legacyFactor: 1),\n\n BenchmarkInfo(\n name: "DictionaryFilterOfObjects",\n runFunction: filterObjects,\n tags: t,\n setUpFunction: { blackHole(boxedNumMap) },\n legacyFactor: 1),\n]\n\nclass Box<T : Hashable> : Hashable {\n var value: T\n\n init(_ v: T) {\n value = v\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n\n static func ==(lhs: Box, rhs: Box) -> Bool {\n return lhs.value == rhs.value\n }\n}\n\nfunc remove(n: Int) {\n for _ in 1...100*n {\n var dict = numberMap\n for i in 1...size { dict.removeValue(forKey: i) }\n check(dict.isEmpty)\n }\n}\n\nfunc removeObjects(n: Int) {\n for _ in 1...10*n {\n var dict = boxedNumMap\n for i in 1...size { dict.removeValue(forKey: Box(i)) }\n check(dict.isEmpty)\n }\n}\n\nfunc filter(n: Int) {\n for _ in 1...1000*n {\n let dict = numberMap\n let result = dict.filter {key, value in value % 2 == 0}\n check(result.count == size/2)\n }\n}\n\nfunc filterObjects(n: Int) {\n for _ in 1...1000*n {\n let dict = boxedNumMap\n let result = dict.filter {key, value in value.value % 2 == 0}\n check(result.count == size/2)\n }\n} | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionaryRemove.swift | cpp_apple_swift_benchmark_single-source_DictionaryRemove.swift | Swift | 2,492 | 0.95 | 0.091837 | 0.152941 | node-utils | 555 | 2025-01-20T01:54:24.026328 | GPL-3.0 | false | cbf02a8c00b4c841c7969a7b0eac89d9 |
//===--- DictionarySubscriptDefault.swift ---------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "DictionarySubscriptDefaultMutation",\n runFunction: run_DictionarySubscriptDefaultMutation,\n tags: [.validation, .api, .Dictionary]),\n BenchmarkInfo(name: "DictionarySubscriptDefaultMutationArray",\n runFunction: run_DictionarySubscriptDefaultMutationArray,\n tags: [.validation, .api, .Dictionary]),\n BenchmarkInfo(name: "DictionarySubscriptDefaultMutationOfObjects",\n runFunction: run_DictionarySubscriptDefaultMutationOfObjects,\n tags: [.validation, .api, .Dictionary], legacyFactor: 20),\n BenchmarkInfo(name: "DictionarySubscriptDefaultMutationArrayOfObjects",\n runFunction:\n run_DictionarySubscriptDefaultMutationArrayOfObjects,\n tags: [.validation, .api, .Dictionary], legacyFactor: 20),\n]\n\n@inline(never)\npublic func run_DictionarySubscriptDefaultMutation(_ n: Int) {\n for _ in 1...n {\n\n var dict = [Int: Int]()\n\n for i in 0..<10_000 {\n dict[i % 100, default: 0] += 1\n }\n\n check(dict.count == 100)\n check(dict[0]! == 100)\n }\n}\n\n@inline(never)\npublic func run_DictionarySubscriptDefaultMutationArray(_ n: Int) {\n for _ in 1...n {\n\n var dict = [Int: [Int]]()\n\n for i in 0..<10_000 {\n dict[i % 100, default: []].append(i)\n }\n\n check(dict.count == 100)\n check(dict[0]!.count == 100)\n }\n}\n\n// Hack to workaround the fact that if we attempt to increment the Box's value\n// from the subscript, the compiler will just call the subscript's getter (and\n// therefore not insert the instance) as it's dealing with a reference type.\n// By using a mutating method in a protocol extension, the compiler is forced to\n// treat this an actual mutation, so cannot call the getter.\nprotocol P {\n associatedtype T\n var value: T { get set }\n}\n\nextension P {\n mutating func mutateValue(_ mutations: (inout T) -> Void) {\n mutations(&value)\n }\n}\n\nclass Box<T : Hashable> : Hashable, P {\n var value: T\n\n init(_ v: T) {\n value = v\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n\n static func ==(lhs: Box, rhs: Box) -> Bool {\n return lhs.value == rhs.value\n }\n}\n\n@inline(never)\npublic func run_DictionarySubscriptDefaultMutationOfObjects(_ n: Int) {\n for _ in 1...n {\n\n var dict = [Box<Int>: Box<Int>]()\n\n for i in 0..<500 {\n dict[Box(i % 5), default: Box(0)].mutateValue { $0 += 1 }\n }\n\n check(dict.count == 5)\n check(dict[Box(0)]!.value == 100)\n }\n}\n\n@inline(never)\npublic func run_DictionarySubscriptDefaultMutationArrayOfObjects(_ n: Int) {\n for _ in 1...n {\n\n var dict = [Box<Int>: [Box<Int>]]()\n\n for i in 0..<500 {\n dict[Box(i % 5), default: []].append(Box(i))\n }\n\n check(dict.count == 5)\n check(dict[Box(0)]!.count == 100)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionarySubscriptDefault.swift | cpp_apple_swift_benchmark_single-source_DictionarySubscriptDefault.swift | Swift | 3,376 | 0.95 | 0.099174 | 0.164948 | python-kit | 606 | 2024-04-21T04:06:01.213654 | Apache-2.0 | false | 6f55031f26958cd31e33066193bc14ee |
//===--- DictionarySwap.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Dictionary element swapping benchmark\n// rdar://problem/19804127\nimport TestsUtils\n\nlet size = 100\nlet numberMap = Dictionary(uniqueKeysWithValues: zip(1...size, 1...size))\nlet boxedNums = (1...size).lazy.map { Box($0) }\nlet boxedNumMap = Dictionary(uniqueKeysWithValues: zip(boxedNums, boxedNums))\n\nlet t: [BenchmarkCategory] = [.validation, .api, .Dictionary, .cpubench]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "DictionarySwap",\n runFunction: swap, tags: t, legacyFactor: 4),\n BenchmarkInfo(name: "DictionarySwapOfObjects",\n runFunction: swapObjects, tags: t, legacyFactor: 40),\n BenchmarkInfo(name: "DictionarySwapAt",\n runFunction: swapAt, tags: t, legacyFactor: 4),\n BenchmarkInfo(name: "DictionarySwapAtOfObjects",\n runFunction: swapAtObjects, tags: t, legacyFactor: 11),\n]\n\n// Return true if correctly swapped, false otherwise\nfunc swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {\n return swapped && (p25 == 75 && p75 == 25) ||\n !swapped && (p25 == 25 && p75 == 75)\n}\n\nclass Box<T : Hashable> : Hashable {\n var value: T\n\n init(_ v: T) {\n value = v\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n\n static func ==(lhs: Box, rhs: Box) -> Bool {\n return lhs.value == rhs.value\n }\n}\n\nfunc swap(n: Int) {\n var dict = numberMap\n var swapped = false\n for _ in 1...2500*n {\n (dict[25], dict[75]) = (dict[75]!, dict[25]!)\n swapped = !swapped\n check(swappedCorrectly(swapped, dict[25]!, dict[75]!))\n }\n}\n\nfunc swapObjects(n: Int) {\n var dict = boxedNumMap\n var swapped = false\n for _ in 1...250*n {\n let b1 = Box(25)\n let b2 = Box(75)\n (dict[b1], dict[b2]) = (dict[b2]!, dict[b1]!)\n swapped = !swapped\n check(swappedCorrectly(swapped,\n dict[Box(25)]!.value, dict[Box(75)]!.value))\n }\n}\n\nfunc swapAt(n: Int) {\n var dict = numberMap\n var swapped = false\n for _ in 1...2500*n {\n let i25 = dict.index(forKey: 25)!\n let i75 = dict.index(forKey: 75)!\n dict.values.swapAt(i25, i75)\n swapped = !swapped\n check(swappedCorrectly(swapped, dict[25]!, dict[75]!))\n }\n}\n\nfunc swapAtObjects(n: Int) {\n var dict = boxedNumMap\n var swapped = false\n for _ in 1...1000*n {\n let i25 = dict.index(forKey: Box(25))!\n let i75 = dict.index(forKey: Box(75))!\n dict.values.swapAt(i25, i75)\n swapped = !swapped\n check(swappedCorrectly(swapped,\n dict[Box(25)]!.value, dict[Box(75)]!.value))\n}}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictionarySwap.swift | cpp_apple_swift_benchmark_single-source_DictionarySwap.swift | Swift | 2,966 | 0.95 | 0.078431 | 0.157303 | vue-tools | 279 | 2024-02-11T04:03:04.139977 | BSD-3-Clause | false | 096ee4cf21267d9c575733c03706edb5 |
// DictOfArraysToArrayOfDicts benchmark\n//\n// Description: Convert a dictionary of [key: [values]] to an array of\n// dictionaries [[key: value]] using zipWith.\n// Source: https://gist.github.com/airspeedswift/3675952127ee775551b0\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DictOfArraysToArrayOfDicts",\n runFunction: run_DictOfArraysToArrayOfDicts,\n tags: [.algorithm, .Dictionary]\n ),\n]\n\n@inline(never)\npublic func run_DictOfArraysToArrayOfDicts(_ n: Int) {\n let returnedFromServer = [\n "title": ["abc", "def", "ghi"],\n "time": ["1234", "5678", "0123"],\n "content": ["qwerty", "asdfg", "zxcvb"],\n ]\n var pairs: [[(String, String)]] = []\n var inverted: [[(String, String)]] = []\n var arrayOfDicts: [[String: String]] = [[:]]\n\n for _ in 1...100*n {\n pairs = returnedFromServer.map {\n (key, value) in value.map { (key, $0) }\n }\n inverted = zipWith(pairs[0], pairs[1], pairs[2]) {\n [$0] + [$1] + [$2]\n }\n arrayOfDicts = inverted\n .map { $0.map { (key: $0.0, value: $0.1) } }\n .map { Dictionary($0) }\n\n if !(arrayOfDicts.count == 3) {\n break\n }\n }\n\n check(arrayOfDicts.count == 3)\n}\n\n// Given [\n// "title" : ["abc", "def"],\n// "time" : ["1234", "5678", "0123"],\n// "content":["qwerty", "asdfg", "zxcvb"]\n// ]\n//\n// how do you get to this:\n//\n// [\n// ["title" : "abc",\n// "time" : "1234",\n// "content": "qwerty"],\n// ["title" : "def",\n// "time" : "5678",\n// "content": "asdfg"],\n// ["title" : "ghi",\n// "time" : "0123",\n// "content": "zxcvb"]]\n\npublic func zip3 <\n A: Sequence,B: Sequence,C: Sequence\n> (_ a: A, _ b: B, _ c: C) -> ZipSequence3<A, B, C> {\n return ZipSequence3(a, b, c)\n}\n\n// Sequence of tuples created from values from three other sequences\npublic struct ZipSequence3<A: Sequence,B: Sequence,C: Sequence> {\n private var a: A\n private var b: B\n private var c: C\n\n public init (_ a: A, _ b: B, _ c: C) {\n self.a = a\n self.b = b\n self.c = c\n } \n}\n\nextension ZipSequence3 {\n public struct Iterator {\n private var a: A.Iterator\n private var b: B.Iterator\n private var c: C.Iterator\n\n public init(_ a: A, _ b: B, _ c: C) {\n self.a = a.makeIterator()\n self.b = b.makeIterator()\n self.c = c.makeIterator()\n }\n }\n}\n\nextension ZipSequence3.Iterator: IteratorProtocol {\n public typealias Element = (A.Element,B.Element,C.Element)\n \n public mutating func next() -> Element? {\n switch (a.next(), b.next(), c.next()) {\n case let (aValue?, bValue?, cValue?):\n return (aValue, bValue, cValue)\n default:\n return nil\n }\n }\n}\n\nextension ZipSequence3: Sequence {\n public typealias Element = (A.Element,B.Element,C.Element)\n public typealias SubSequence = AnySequence<Element>\n\n public func makeIterator() -> Iterator {\n return Iterator(a, b, c)\n }\n}\n\n// Iterator that creates tuples of values from three other generators\nfunc zipWith<\n A: Sequence, B: Sequence, C: Sequence, T\n>(\n _ a: A, _ b: B, _ c: C, \n _ combine: (A.Element,B.Element,C.Element) -> T\n) -> [T] {\n return zip3(a,b,c).map(combine)\n}\n\nextension Dictionary {\n // Construct from an arbitrary sequence with elements of the tupe\n // `(Key,Value)`\n init<S: Sequence> (_ seq: S) where S.Iterator.Element == Element {\n self.init()\n self.merge(seq)\n }\n\n // Merge a sequence of `(Key,Value)` tuples into the dictionary\n mutating func merge<S: Sequence> (_ seq: S) where S.Element == Element {\n var gen = seq.makeIterator()\n while let (k, v) = gen.next() {\n self[k] = v\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DictOfArraysToArrayOfDicts.swift | cpp_apple_swift_benchmark_single-source_DictOfArraysToArrayOfDicts.swift | Swift | 3,566 | 0.95 | 0.047945 | 0.220472 | python-kit | 772 | 2024-09-29T07:15:11.291470 | MIT | false | ad23871c5f83dadd065b59783a94aa6c |
//===--- Differentiation.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if canImport(_Differentiation)\n\nimport TestsUtils\nimport _Differentiation\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DifferentiationIdentity",\n runFunction: run_DifferentiationIdentity,\n tags: [.regression, .differentiation]\n ),\n BenchmarkInfo(\n name: "DifferentiationSquare",\n runFunction: run_DifferentiationSquare,\n tags: [.regression, .differentiation]\n ),\n BenchmarkInfo(\n name: "DifferentiationArraySum",\n runFunction: run_DifferentiationArraySum,\n tags: [.regression, .differentiation],\n setUpFunction: { blackHole(onesArray) }\n ),\n]\n\n@inline(never)\npublic func run_DifferentiationIdentity(n: Int) {\n func f(_ x: Float) -> Float {\n x\n }\n for _ in 0..<1000*n {\n blackHole(valueWithGradient(at: 1, of: f))\n }\n}\n\n@inline(never)\npublic func run_DifferentiationSquare(n: Int) {\n func f(_ x: Float) -> Float {\n x * x\n }\n for _ in 0..<1000*n {\n blackHole(valueWithGradient(at: 1, of: f))\n }\n}\n\nlet onesArray: [Float] = Array(repeating: 1, count: 50)\n\n@inline(never)\npublic func run_DifferentiationArraySum(n: Int) {\n func sum(_ array: [Float]) -> Float {\n var result: Float = 0\n for i in withoutDerivative(at: 0..<array.count) {\n result += array[i]\n }\n return result\n }\n for _ in 0..<n {\n blackHole(valueWithGradient(at: onesArray, of: sum))\n }\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Differentiation.swift | cpp_apple_swift_benchmark_single-source_Differentiation.swift | Swift | 1,863 | 0.95 | 0.09589 | 0.2 | node-utils | 436 | 2024-02-17T03:33:42.964389 | MIT | false | 277e419ae0dc27c0f819ad31a175adf7 |
//===--- Diffing.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.api]\npublic let benchmarks = [\n BenchmarkInfo(\n name: "Diffing.Same",\n runFunction: { diff($0, from: longPangram, to: longPangram) },\n tags: t,\n setUpFunction: { blackHole(longPangram) }),\n BenchmarkInfo(\n name: "Diffing.PangramToAlphabet",\n runFunction: { diff($0, from: longPangram, to: alphabets) },\n tags: t,\n setUpFunction: { blackHole((longPangram, alphabets)) }),\n BenchmarkInfo(\n name: "Diffing.Pangrams",\n runFunction: { diff($0, from:typingPangram, to: longPangram) },\n tags: t,\n setUpFunction: { blackHole((longPangram, typingPangram)) }),\n BenchmarkInfo(\n name: "Diffing.ReversedAlphabets",\n runFunction: { diff($0, from:alphabets, to: alphabetsReversed) },\n tags: t,\n setUpFunction: { blackHole((alphabets, alphabetsReversed)) }),\n BenchmarkInfo(\n name: "Diffing.ReversedLorem",\n runFunction: { diff($0, from: loremIpsum, to: loremReversed) },\n tags: t,\n setUpFunction: { blackHole((loremIpsum, loremReversed)) }),\n BenchmarkInfo(\n name: "Diffing.Disparate",\n runFunction: { diff($0, from: numbersAndSymbols, to: alphabets) },\n tags: t,\n setUpFunction: { blackHole((numbersAndSymbols, alphabets)) }),\n BenchmarkInfo(\n name: "Diffing.Similar",\n runFunction: { diff($0, from: unabridgedLorem, to: loremIpsum) },\n tags: t,\n setUpFunction: { blackHole((unabridgedLorem, loremIpsum)) }),\n]\n\nlet numbersAndSymbols = Array("0123456789`~!@#$%^&*()+=_-\"'?/<,>.\\{}'")\nlet alphabets = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")\nlet alphabetsReversed = Array(alphabets.reversed())\nlet longPangram = Array("This pangram contains four As, one B, two Cs, one D, thirty Es, six Fs, five Gs, seven Hs, eleven Is, one J, one K, two Ls, two Ms, eighteen Ns, fifteen Os, two Ps, one Q, five Rs, twenty-seven Ss, eighteen Ts, two Us, seven Vs, eight Ws, two Xs, three Ys, & one Z")\nlet typingPangram = Array("The quick brown fox jumps over the lazy dog")\nlet loremIpsum = Array("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")\nlet unabridgedLorem = Array("Lorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non-numquam [do] eius modi tempora inci[di]dunt, ut labore et dolore magnam aliqua.")\nlet loremReversed = Array(loremIpsum.reversed())\n\n@inline(never) func diff(_ n: Int, from older: [Character], to newer: [Character]) {\n if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {\n for _ in 1...n {\n blackHole(newer.difference(from: older))\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Diffing.swift | cpp_apple_swift_benchmark_single-source_Diffing.swift | Swift | 3,145 | 0.95 | 0.057971 | 0.169231 | react-lib | 276 | 2024-04-26T05:57:03.085769 | GPL-3.0 | false | 1899942deaebcb412e2b1df8e88e60c3 |
//===--- DiffingMyers.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// The DiffingMyers test benchmarks Swift's performance running the algorithm\n// described in Myers (1986). The Diffing benchmark tracks the performance\n// of `Collection.difference(from:to:)`.\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Diffing.Myers.Similar",\n runFunction: run_Myers,\n tags: [.algorithm],\n setUpFunction: { blackHole((loremIpsum, unabridgedLorem)) })\n\n\nlet loremIpsum = Array("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")\nlet unabridgedLorem = Array("Lorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non-numquam [do] eius modi tempora inci[di]dunt, ut labore et dolore magnam aliqua.")\n\n@inline(never)\npublic func run_Myers(n: Int) {\n if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {\n for _ in 1...n {\n blackHole(myers(from: unabridgedLorem, to: loremIpsum, using: ==))\n }\n }\n}\n\n// _V is a rudimentary type made to represent the rows of the triangular matrix type used by the Myer's algorithm\n//\n// This type is basically an array that only supports indexes in the set `stride(from: -d, through: d, by: 2)` where `d` is the depth of this row in the matrix\n// `d` is always known at allocation-time, and is used to preallocate the structure.\nfileprivate struct _V {\n\n private var a: [Int]\n\n // The way negative indexes are implemented is by interleaving them in the empty slots between the valid positive indexes\n @inline(__always) private static func transform(_ index: Int) -> Int {\n // -3, -1, 1, 3 -> 3, 1, 0, 2 -> 0...3\n // -2, 0, 2 -> 2, 0, 1 -> 0...2\n return (index <= 0 ? -index : index &- 1)\n }\n\n init(maxIndex largest: Int) {\n a = [Int](repeating: 0, count: largest + 1)\n }\n\n subscript(index: Int) -> Int {\n get {\n return a[_V.transform(index)]\n }\n set(newValue) {\n a[_V.transform(index)] = newValue\n }\n }\n}\n\n@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)\nfileprivate func myers<C,D>(\n from old: C, to new: D,\n using cmp: (C.Element, D.Element) -> Bool\n) -> CollectionDifference<C.Element>\n where\n C : BidirectionalCollection,\n D : BidirectionalCollection,\n C.Element == D.Element\n{\n\n // Core implementation of the algorithm described at http://www.xmailserver.org/diff2.pdf\n // Variable names match those used in the paper as closely as possible\n func _descent(from a: UnsafeBufferPointer<C.Element>, to b: UnsafeBufferPointer<D.Element>) -> [_V] {\n let n = a.count\n let m = b.count\n let max = n + m\n\n var result = [_V]()\n var v = _V(maxIndex: 1)\n v[1] = 0\n\n var x = 0\n var y = 0\n iterator: for d in 0...max {\n let prev_v = v\n result.append(v)\n v = _V(maxIndex: d)\n\n // The code in this loop is _very_ hot—the loop bounds increases in terms\n // of the iterator of the outer loop!\n for k in stride(from: -d, through: d, by: 2) {\n if k == -d {\n x = prev_v[k &+ 1]\n } else {\n let km = prev_v[k &- 1]\n\n if k != d {\n let kp = prev_v[k &+ 1]\n if km < kp {\n x = kp\n } else {\n x = km &+ 1\n }\n } else {\n x = km &+ 1\n }\n }\n y = x &- k\n\n while x < n && y < m {\n if !cmp(a[x], b[y]) {\n break;\n }\n x &+= 1\n y &+= 1\n }\n\n v[k] = x\n\n if x >= n && y >= m {\n break iterator\n }\n }\n if x >= n && y >= m {\n break\n }\n }\n\n return result\n }\n\n // Backtrack through the trace generated by the Myers descent to produce the changes that make up the diff\n func _formChanges(\n from a: UnsafeBufferPointer<C.Element>,\n to b: UnsafeBufferPointer<C.Element>,\n using trace: [_V]\n ) -> [CollectionDifference<C.Element>.Change] {\n var changes = [CollectionDifference<C.Element>.Change]()\n\n var x = a.count\n var y = b.count\n for d in stride(from: trace.count &- 1, to: 0, by: -1) {\n let v = trace[d]\n let k = x &- y\n let prev_k = (k == -d || (k != d && v[k &- 1] < v[k &+ 1])) ? k &+ 1 : k &- 1\n let prev_x = v[prev_k]\n let prev_y = prev_x &- prev_k\n\n while x > prev_x && y > prev_y {\n // No change at this position.\n x &-= 1\n y &-= 1\n }\n\n assert((x == prev_x && y > prev_y) || (y == prev_y && x > prev_x))\n if y != prev_y {\n changes.append(.insert(offset: prev_y, element: b[prev_y], associatedWith: nil))\n } else {\n changes.append(.remove(offset: prev_x, element: a[prev_x], associatedWith: nil))\n }\n\n x = prev_x\n y = prev_y\n }\n\n return changes\n }\n\n /* Splatting the collections into contiguous storage has two advantages:\n *\n * 1) Subscript access is much faster\n * 2) Subscript index becomes Int, matching the iterator types in the algorithm\n *\n * Combined, these effects dramatically improves performance when\n * collections differ significantly, without unduly degrading runtime when\n * the parameters are very similar.\n *\n * In terms of memory use, the linear cost of creating a ContiguousArray (when\n * necessary) is significantly less than the worst-case n² memory use of the\n * descent algorithm.\n */\n func _withContiguousStorage<C : Collection, R>(\n for values: C,\n _ body: (UnsafeBufferPointer<C.Element>) throws -> R\n ) rethrows -> R {\n if let result = try values.withContiguousStorageIfAvailable(body) { return result }\n let array = ContiguousArray(values)\n return try array.withUnsafeBufferPointer(body)\n }\n\n return _withContiguousStorage(for: old) { a in\n return _withContiguousStorage(for: new) { b in\n return CollectionDifference(_formChanges(from: a, to: b, using:_descent(from: a, to: b)))!\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DiffingMyers.swift | cpp_apple_swift_benchmark_single-source_DiffingMyers.swift | Swift | 6,388 | 0.95 | 0.107843 | 0.228571 | python-kit | 39 | 2024-01-23T22:15:22.018354 | Apache-2.0 | false | 0dfd72876f67a93d339860ac76f93543 |
//===--- DropFirst.swift --------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to DropFirst.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\nlet sequenceCount = 4096\nlet dropCount = 1024\nlet suffixCount = sequenceCount - dropCount\nlet sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2\nlet array: [Int] = Array(0..<sequenceCount)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DropFirstCountableRange",\n runFunction: run_DropFirstCountableRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstSequence",\n runFunction: run_DropFirstSequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnySequence",\n runFunction: run_DropFirstAnySequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnySeqCntRange",\n runFunction: run_DropFirstAnySeqCntRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnySeqCRangeIter",\n runFunction: run_DropFirstAnySeqCRangeIter,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnyCollection",\n runFunction: run_DropFirstAnyCollection,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstArray",\n runFunction: run_DropFirstArray,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n BenchmarkInfo(\n name: "DropFirstCountableRangeLazy",\n runFunction: run_DropFirstCountableRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstSequenceLazy",\n runFunction: run_DropFirstSequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnySequenceLazy",\n runFunction: run_DropFirstAnySequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnySeqCntRangeLazy",\n runFunction: run_DropFirstAnySeqCntRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnySeqCRangeIterLazy",\n runFunction: run_DropFirstAnySeqCRangeIterLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstAnyCollectionLazy",\n runFunction: run_DropFirstAnyCollectionLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropFirstArrayLazy",\n runFunction: run_DropFirstArrayLazy,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n]\n\n@inline(never)\npublic func run_DropFirstCountableRange(_ n: Int) {\n let s = 0..<sequenceCount\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstSequence(_ n: Int) {\n let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnySequence(_ n: Int) {\n let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnySeqCntRange(_ n: Int) {\n let s = AnySequence(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnySeqCRangeIter(_ n: Int) {\n let s = AnySequence((0..<sequenceCount).makeIterator())\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnyCollection(_ n: Int) {\n let s = AnyCollection(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstArray(_ n: Int) {\n let s = array\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstCountableRangeLazy(_ n: Int) {\n let s = (0..<sequenceCount).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstSequenceLazy(_ n: Int) {\n let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnySequenceLazy(_ n: Int) {\n let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnySeqCntRangeLazy(_ n: Int) {\n let s = (AnySequence(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnySeqCRangeIterLazy(_ n: Int) {\n let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstAnyCollectionLazy(_ n: Int) {\n let s = (AnyCollection(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropFirstArrayLazy(_ n: Int) {\n let s = (array).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropFirst(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DropFirst.swift | cpp_apple_swift_benchmark_single-source_DropFirst.swift | Swift | 6,938 | 0.95 | 0.122449 | 0.079498 | vue-tools | 219 | 2024-11-06T12:58:14.318231 | Apache-2.0 | false | c53a1ec2a6b411f5c9471a2493c4ddb4 |
//===--- DropLast.swift ---------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to DropLast.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\nlet sequenceCount = 4096\nlet prefixCount = 1024\nlet dropCount = sequenceCount - prefixCount\nlet sumCount = prefixCount * (prefixCount - 1) / 2\nlet array: [Int] = Array(0..<sequenceCount)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DropLastCountableRange",\n runFunction: run_DropLastCountableRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastSequence",\n runFunction: run_DropLastSequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnySequence",\n runFunction: run_DropLastAnySequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnySeqCntRange",\n runFunction: run_DropLastAnySeqCntRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnySeqCRangeIter",\n runFunction: run_DropLastAnySeqCRangeIter,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnyCollection",\n runFunction: run_DropLastAnyCollection,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastArray",\n runFunction: run_DropLastArray,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n BenchmarkInfo(\n name: "DropLastCountableRangeLazy",\n runFunction: run_DropLastCountableRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastSequenceLazy",\n runFunction: run_DropLastSequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnySequenceLazy",\n runFunction: run_DropLastAnySequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnySeqCntRangeLazy",\n runFunction: run_DropLastAnySeqCntRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnySeqCRangeIterLazy",\n runFunction: run_DropLastAnySeqCRangeIterLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastAnyCollectionLazy",\n runFunction: run_DropLastAnyCollectionLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropLastArrayLazy",\n runFunction: run_DropLastArrayLazy,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n]\n\n@inline(never)\npublic func run_DropLastCountableRange(_ n: Int) {\n let s = 0..<sequenceCount\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastSequence(_ n: Int) {\n let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnySequence(_ n: Int) {\n let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnySeqCntRange(_ n: Int) {\n let s = AnySequence(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnySeqCRangeIter(_ n: Int) {\n let s = AnySequence((0..<sequenceCount).makeIterator())\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnyCollection(_ n: Int) {\n let s = AnyCollection(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastArray(_ n: Int) {\n let s = array\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastCountableRangeLazy(_ n: Int) {\n let s = (0..<sequenceCount).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastSequenceLazy(_ n: Int) {\n let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnySequenceLazy(_ n: Int) {\n let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnySeqCntRangeLazy(_ n: Int) {\n let s = (AnySequence(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnySeqCRangeIterLazy(_ n: Int) {\n let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastAnyCollectionLazy(_ n: Int) {\n let s = (AnyCollection(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropLastArrayLazy(_ n: Int) {\n let s = (array).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.dropLast(dropCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DropLast.swift | cpp_apple_swift_benchmark_single-source_DropLast.swift | Swift | 6,863 | 0.95 | 0.122449 | 0.079498 | node-utils | 239 | 2024-06-10T06:35:12.055414 | BSD-3-Clause | false | 3f70c51e3437aeeb89cbf397e056f08d |
//===--- DropWhile.swift --------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to DropWhile.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\nlet sequenceCount = 4096\nlet dropCount = 1024\nlet suffixCount = sequenceCount - dropCount\nlet sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2\nlet array: [Int] = Array(0..<sequenceCount)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "DropWhileCountableRange",\n runFunction: run_DropWhileCountableRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileSequence",\n runFunction: run_DropWhileSequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnySequence",\n runFunction: run_DropWhileAnySequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnySeqCntRange",\n runFunction: run_DropWhileAnySeqCntRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnySeqCRangeIter",\n runFunction: run_DropWhileAnySeqCRangeIter,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnyCollection",\n runFunction: run_DropWhileAnyCollection,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileArray",\n runFunction: run_DropWhileArray,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n BenchmarkInfo(\n name: "DropWhileCountableRangeLazy",\n runFunction: run_DropWhileCountableRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileSequenceLazy",\n runFunction: run_DropWhileSequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnySequenceLazy",\n runFunction: run_DropWhileAnySequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnySeqCntRangeLazy",\n runFunction: run_DropWhileAnySeqCntRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnySeqCRangeIterLazy",\n runFunction: run_DropWhileAnySeqCRangeIterLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileAnyCollectionLazy",\n runFunction: run_DropWhileAnyCollectionLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "DropWhileArrayLazy",\n runFunction: run_DropWhileArrayLazy,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n]\n\n@inline(never)\npublic func run_DropWhileCountableRange(_ n: Int) {\n let s = 0..<sequenceCount\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileSequence(_ n: Int) {\n let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnySequence(_ n: Int) {\n let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnySeqCntRange(_ n: Int) {\n let s = AnySequence(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnySeqCRangeIter(_ n: Int) {\n let s = AnySequence((0..<sequenceCount).makeIterator())\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnyCollection(_ n: Int) {\n let s = AnyCollection(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileArray(_ n: Int) {\n let s = array\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileCountableRangeLazy(_ n: Int) {\n let s = (0..<sequenceCount).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileSequenceLazy(_ n: Int) {\n let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnySequenceLazy(_ n: Int) {\n let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnySeqCntRangeLazy(_ n: Int) {\n let s = (AnySequence(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnySeqCRangeIterLazy(_ n: Int) {\n let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileAnyCollectionLazy(_ n: Int) {\n let s = (AnyCollection(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_DropWhileArrayLazy(_ n: Int) {\n let s = (array).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.drop(while: {$0 < dropCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_DropWhile.swift | cpp_apple_swift_benchmark_single-source_DropWhile.swift | Swift | 7,078 | 0.95 | 0.179592 | 0.079498 | vue-tools | 889 | 2024-01-13T11:18:12.932491 | GPL-3.0 | false | 9170377710652df3ae76551c3aa17831 |
//===--- ErrorHandling.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ErrorHandling",\n runFunction: run_ErrorHandling,\n tags: [.validation, .exceptions],\n legacyFactor: 10)\n\nenum PizzaError : Error {\n case Pepperoni, Olives, Anchovy\n}\n\n@inline(never)\nfunc doSomething() throws -> String {\n var sb = "pi"\n for str in ["z","z","a","?","?","?"] {\n sb += str\n if sb == "pizza" {\n throw PizzaError.Anchovy\n }\n }\n return sb\n}\n\n@inline(never)\npublic func run_ErrorHandling(_ n: Int) {\n for _ in 1...500*n {\n do {\n _ = try doSomething()\n } catch _ {\n\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ErrorHandling.swift | cpp_apple_swift_benchmark_single-source_ErrorHandling.swift | Swift | 1,116 | 0.95 | 0.148936 | 0.268293 | python-kit | 272 | 2023-10-20T17:57:57.021379 | GPL-3.0 | false | c6aaaf615182f6c612496d7e5b341d11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.