diff --git a/dev/stackdiff/Package.swift b/dev/stackdiff/Package.swift new file mode 100644 index 000000000..eed82fb21 --- /dev/null +++ b/dev/stackdiff/Package.swift @@ -0,0 +1,46 @@ +// swift-tools-version: 6.1 +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import PackageDescription + +let package = Package( + name: "stackdiff", + // Required for Regex support + platforms: [.macOS(.v13)], + dependencies: [ + .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.5.0") + ], + targets: [ + .executableTarget( + name: "stackdiff", + dependencies: [ + .target(name: "Stacks"), + .product( + name: "ArgumentParser", + package: "swift-argument-parser" + ), + ] + ), + .target( + name: "Stacks" + ), + .testTarget( + name: "StacksTests", + dependencies: [ + .target(name: "Stacks") + ] + ), + ] +) diff --git a/dev/stackdiff/Sources/Stacks/AggregateStacks.swift b/dev/stackdiff/Sources/Stacks/AggregateStacks.swift new file mode 100644 index 000000000..8e270c2bc --- /dev/null +++ b/dev/stackdiff/Sources/Stacks/AggregateStacks.swift @@ -0,0 +1,119 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +/// A collection of weighted stacks aggregated by their partial stacks. +/// +/// Effectively a wrapper aound `[PartialStack: [WeightedStack]]` with a few helpers. +public struct AggregateStacks { + private var storage: [PartialStack: [WeightedStack]] + + public init() { + self.storage = [:] + } + + /// The set of all partial stacks under which weighted stacks have been aggregated. + public var partialStacks: Set { + Set(self.storage.keys) + } + + /// The net allocations of all aggregated stacks. + public var netAllocations: Int { + self.storage.values.reduce(0) { partial, stackAllocs in + partial + stackAllocs.netAllocations + } + } + + /// Adds a weighted stack under the given partial stack. + public mutating func groupWeightedStack(_ stack: WeightedStack, by partial: PartialStack) { + self.storage[partial, default: []].append(stack) + } + + /// Regroups a set of stack from under one partial stack to another. + public mutating func regroupStacks(from source: PartialStack, to destination: PartialStack) { + guard let stacks = self.removeWeightedStacks(groupedUnder: source) else { + return + } + + self.storage[destination, default: []].append(contentsOf: stacks) + } + + /// Removes all weighted stacks which are grouped under the given partial stack. + @discardableResult + public mutating func removeWeightedStacks(groupedUnder partial: PartialStack) -> [WeightedStack]? { + self.storage.removeValue(forKey: partial) + } + + /// Returns the net allocations of all stacks grouped under the given partial stack. + public func netAllocations(groupedBy stack: PartialStack) -> Int { + self.storage[stack]?.netAllocations ?? 0 + } + + /// Returns all weighted stacks grouped under the given partial stack. + public func weightedStacks(groupedBy stack: PartialStack) -> [WeightedStack] { + self.storage[stack, default: []] + } + + /// Returns a new aggregate only containing pairs which return true for the given predidate. + public func filter( + isIncluded: ((key: PartialStack, value: [WeightedStack])) -> Bool + ) -> AggregateStacks { + var other = AggregateStacks() + other.storage = self.storage.filter(isIncluded) + return other + } + + /// Removes all pairs which return true for the given predicate. + public mutating func removeAll( + where predicate: ((key: PartialStack, value: [WeightedStack])) -> Bool + ) { + for (stack, stackAllocs) in self.storage { + if predicate((stack, stackAllocs)) { + self.storage.removeValue(forKey: stack) + } + } + } + + /// Returns a list of key-values pairs sorted by the given comparator. + public func sorted( + by comparator: ( + (key: PartialStack, value: [WeightedStack]), + (key: PartialStack, value: [WeightedStack]) + ) -> Bool + ) -> [(key: PartialStack, value: [WeightedStack])] { + self.storage.sorted(by: comparator) + } +} + +extension AggregateStacks { + public mutating func subtract(_ other: AggregateStacks) { + for (partialStack, weightedStacks) in other.storage { + for var weightedStack in weightedStacks { + weightedStack.allocations = -weightedStack.allocations + self.groupWeightedStack(weightedStack, by: partialStack) + } + } + } + + public func subtracting(_ other: AggregateStacks) -> AggregateStacks { + var copy = self + copy.subtract(other) + return copy + } +} + +extension [WeightedStack] { + public var netAllocations: Int { + self.reduce(0) { $0 + $1.allocations } + } +} diff --git a/dev/stackdiff/Sources/Stacks/Parsing/HeaptrackParser.swift b/dev/stackdiff/Sources/Stacks/Parsing/HeaptrackParser.swift new file mode 100644 index 000000000..3cdb7a36b --- /dev/null +++ b/dev/stackdiff/Sources/Stacks/Parsing/HeaptrackParser.swift @@ -0,0 +1,138 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation + +/// Parses output from `heaptrack analyze`. +public struct HeaptrackParser: StackParser { + private let regex = /^(\d+) calls with/ + private var state: ParseState + private var stacks: [WeightedStack] + + private init() { + self.stacks = [] + self.state = .parsingHeader + } + + private enum ParseResult { + case needsNextLine + case parsedStack(Stack, Int) + } + + private enum ParseState { + case parsingHeader + case parsingStack(ParsingStackState) + } + + private struct ParsingStackState { + var count: Int + var lines: [String] + + init(count: Int) { + self.count = count + self.lines = [] + } + + private static var prefixesToIgnore: [String] { + [" in", " at", " 0x"] + } + + mutating func parse(_ line: String) -> (ParseState, ParseResult) { + if Self.prefixesToIgnore.contains(where: { line.contains($0) }) { + return (.parsingStack(self), .needsNextLine) + } else if line.starts(with: " ") { + self.lines.append(line.trimmingCharacters(in: .whitespacesAndNewlines)) + return (.parsingStack(self), .needsNextLine) + } else { + return (.parsingHeader, .parsedStack(Stack(self.lines), self.count)) + } + } + } + + /// Parses input which looks roughly like the following: + /// + /// ``` + /// reading file "heaptrack.simple-handshake.b.gz" - please wait, this might take some time... + /// Debuggee command was: ./.build/release/simple-handshake + /// finished reading file, now analyzing data: + /// + /// MOST CALLS TO ALLOCATION FUNCTIONS + /// 488867 calls to allocation functions with 28.16K peak consumption from + /// CNIOBoringSSL_OPENSSL_malloc + /// at Sources/CNIOBoringSSL/crypto/mem.cc:249 + /// in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + /// 3000 calls with 80B peak consumption from: + /// CNIOBoringSSL_OPENSSL_zalloc + /// at Sources/CNIOBoringSSL/crypto/mem.cc:266 + /// in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + /// CNIOBoringSSL_ASN1_item_ex_new + /// at Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc:153 + /// ... + /// __libc_start_main + /// in /lib/aarch64-linux-gnu/libc.so.6 + /// 3000 calls with 96B peak consumption from: + /// CNIOBoringSSL_ASN1_STRING_type_new + /// at Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc:329 + /// in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + /// ASN1_primitive_new(ASN1_VALUE_st**, ASN1_ITEM_st const*) + /// ... + /// ``` + private mutating func parse(lines: some Sequence) -> [WeightedStack] { + for line in lines { + loop: while true { + switch self.parseNextState(line) { + case .parsedStack(let stack, let count): + self.stacks.append(WeightedStack(stack: stack, allocations: count)) + + case .needsNextLine: + break loop + } + } + } + + return self.stacks + } + + private mutating func parseNextState(_ line: String) -> ParseResult { + switch self.state { + case .parsingHeader: + return self.parseHeader(line) + + case .parsingStack(var state): + let (state, result) = state.parse(line) + self.state = state + return result + } + } + + private mutating func parseHeader(_ line: String) -> ParseResult { + if let match = line.firstMatch(of: self.regex) { + // At the start of a stack. + guard let count = Int(match.1) else { + fatalError("Failed to convert '\(match.1)' to an Int") + } + + self.state = .parsingStack(ParsingStackState(count: count)) + } + + return .needsNextLine + } +} + +extension HeaptrackParser { + public static func parse(lines: some Sequence) -> [WeightedStack] { + var parser = Self() + return parser.parse(lines: lines) + } +} diff --git a/dev/stackdiff/Sources/Stacks/Parsing/StackParser.swift b/dev/stackdiff/Sources/Stacks/Parsing/StackParser.swift new file mode 100644 index 000000000..414dec74f --- /dev/null +++ b/dev/stackdiff/Sources/Stacks/Parsing/StackParser.swift @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +public protocol StackParser { + static func parse(lines: some Sequence) throws -> [WeightedStack] +} + +public protocol StackProtocol { + var lines: [String] { get } +} + +extension StackProtocol { + /// Returns a stack with at most `maxLength` lines from the start of the current stack. + public func prefix(_ maxLength: Int) -> PartialStack { + PartialStack(self.lines.prefix(max(0, maxLength))) + } + + /// Returns a stack with at most `maxLength` lines from the end of the current stack. + public func suffix(_ maxLength: Int) -> PartialStack { + PartialStack(self.lines.suffix(max(0, maxLength))) + } +} + +/// The lines of a full stack trace. +public struct Stack: Hashable, StackProtocol { + public var lines: [String] + + public init(_ lines: [String]) { + self.lines = lines + } + + public init(_ weighted: WeightedStack) { + self = weighted.stack + } +} + +/// The lines of a possibly incomplete stack trace. +public struct PartialStack: Hashable, StackProtocol { + public var lines: [String] + + public init(_ lines: some Sequence) { + self.lines = Array(lines) + } +} + +/// A stack with an associated number of allocations +public struct WeightedStack: Hashable, StackProtocol { + public var stack: Stack + public var allocations: Int + + public var lines: [String] { + self.stack.lines + } + + public init(lines: [String], allocations: Int) { + self.init(stack: Stack(lines), allocations: allocations) + } + + public init(stack: Stack, allocations: Int) { + self.stack = stack + self.allocations = allocations + } +} diff --git a/dev/stackdiff/Sources/Stacks/Similarity.swift b/dev/stackdiff/Sources/Stacks/Similarity.swift new file mode 100644 index 000000000..e65d3d746 --- /dev/null +++ b/dev/stackdiff/Sources/Stacks/Similarity.swift @@ -0,0 +1,64 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +public enum Similarity { + /// Returns the Levenshtein distance between two strings and their similarity score. + /// + /// See also: https://en.wikipedia.org/wiki/Levenshtein_distance + /// + /// The score is normalized to 0...1, with 1 indicting an exact match. Scores are calculated + /// as `1 - levenshtein(a, b) / max(length(a), length(b))`. + public static func levenshtein(_ a: String, _ b: String) -> (distance: Int, similarity: Double) { + Self.levenshtein(Array(a.utf8), Array(b.utf8)) + } + + private static func levenshtein( + _ a: [UInt8], + _ b: [UInt8] + ) -> (distance: Int, similarity: Double) { + if a.isEmpty, b.isEmpty { + // Perfect match. + return (0, 1.0) + } else if a.isEmpty { + // A is empty, B isn't. Distance is length of B. + return (b.count, 0.0) + } else if b.isEmpty { + // B is empty, A isn't. Distance is length of A. + return (a.count, 0.0) + } + + var distance = Array(0...b.count) + + for rowIndex in 1...a.count { + var previous = distance[0] + distance[0] = rowIndex + + for colIndex in 1...b.count { + let temp = distance[colIndex] + + if a[rowIndex - 1] == b[colIndex - 1] { + distance[colIndex] = previous + } else { + distance[colIndex] = 1 + min(distance[colIndex - 1], previous, distance[colIndex]) + } + + previous = temp + } + } + + let editDistance = distance[b.count] + let similarity = 1 - (Double(editDistance) / Double(max(a.count, b.count))) + return (editDistance, similarity) + } +} diff --git a/dev/stackdiff/Sources/stackdiff/Stackdiff.swift b/dev/stackdiff/Sources/stackdiff/Stackdiff.swift new file mode 100644 index 000000000..3251aa3d3 --- /dev/null +++ b/dev/stackdiff/Sources/stackdiff/Stackdiff.swift @@ -0,0 +1,21 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import ArgumentParser + +@main +struct Stackdiff: ParsableCommand { + func run() { + } +} diff --git a/dev/stackdiff/Tests/StacksTests/AggregateStackTests.swift b/dev/stackdiff/Tests/StacksTests/AggregateStackTests.swift new file mode 100644 index 000000000..dc960d8c2 --- /dev/null +++ b/dev/stackdiff/Tests/StacksTests/AggregateStackTests.swift @@ -0,0 +1,131 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Stacks +import Testing + +struct AggregateStackTests { + @Test + func netAllocations() { + var aggregate = AggregateStacks() + #expect(aggregate.netAllocations == 0) + + aggregate.groupWeightedStack( + WeightedStack(lines: ["a"], allocations: 100), + by: PartialStack(["a"]) + ) + + #expect(aggregate.netAllocations == 100) + + aggregate.groupWeightedStack( + WeightedStack(lines: ["a"], allocations: -10), + by: PartialStack(["a"]) + ) + + #expect(aggregate.netAllocations == 90) + } + + @Test + func groupWeightedStack() { + var aggregate = AggregateStacks() + + let partial = PartialStack(["a"]) + let weighted = ["a", "b", "c"].map { line in + WeightedStack(lines: ["a"] + [line], allocations: 10) + } + + for weightedStack in weighted { + aggregate.groupWeightedStack(weightedStack, by: partial) + } + + aggregate.groupWeightedStack( + WeightedStack(lines: [], allocations: 0), + by: PartialStack(["b"]) + ) + + #expect(aggregate.netAllocations(groupedBy: partial) == 30) + + let grouped = aggregate.weightedStacks(groupedBy: partial) + #expect(grouped == weighted) + } + + @Test + func removeWeightedStacks() { + var aggregate = AggregateStacks() + let partial = PartialStack(["a"]) + + // Nothing to remove. + #expect(aggregate.removeWeightedStacks(groupedUnder: partial) == nil) + + // Add then remove. + let weighted = WeightedStack(lines: ["a"], allocations: 100) + aggregate.groupWeightedStack(weighted, by: partial) + #expect(aggregate.removeWeightedStacks(groupedUnder: partial) == [weighted]) + } + + @Test + func filter() { + var aggregate = AggregateStacks() + + let partialA = PartialStack(["a"]) + let partialB = PartialStack(["b"]) + aggregate.groupWeightedStack(WeightedStack(lines: ["a"], allocations: 10), by: partialA) + aggregate.groupWeightedStack(WeightedStack(lines: ["b"], allocations: -10), by: partialB) + #expect(aggregate.netAllocations == 0) + + let filtered = aggregate.filter { $0.key.lines == ["a"] } + #expect(filtered.netAllocations == 10) + } + + @Test + func removeAll() { + var aggregate = AggregateStacks() + + let partialA = PartialStack(["a"]) + let partialB = PartialStack(["b"]) + aggregate.groupWeightedStack(WeightedStack(lines: ["a"], allocations: 10), by: partialA) + aggregate.groupWeightedStack(WeightedStack(lines: ["b"], allocations: -10), by: partialB) + #expect(aggregate.netAllocations == 0) + + aggregate.removeAll { $0.key.lines == ["a"] } + #expect(aggregate.netAllocations == -10) + } + + @Test + func subtract() { + let weighted = WeightedStack(lines: [], allocations: 10) + + var aggregateA = AggregateStacks() + aggregateA.groupWeightedStack(weighted, by: PartialStack(["m"])) + aggregateA.groupWeightedStack(weighted, by: PartialStack(["n"])) + + var aggregateB = AggregateStacks() + aggregateB.groupWeightedStack(weighted, by: PartialStack(["m"])) + aggregateB.groupWeightedStack(weighted, by: PartialStack(["o"])) + + let diff = aggregateA.subtracting(aggregateB) + + // m=10 in A and B + #expect(diff.netAllocations(groupedBy: PartialStack(["m"])) == 0) + #expect(diff.weightedStacks(groupedBy: PartialStack(["m"])).count == 2) + + // n=10 in A and not present in B + #expect(diff.netAllocations(groupedBy: PartialStack(["n"])) == 10) + #expect(diff.weightedStacks(groupedBy: PartialStack(["n"])).count == 1) + + // o=10 in B and not present in A + #expect(diff.netAllocations(groupedBy: PartialStack(["o"])) == -10) + #expect(diff.weightedStacks(groupedBy: PartialStack(["o"])).count == 1) + } +} diff --git a/dev/stackdiff/Tests/StacksTests/HeaptrackParserTests.swift b/dev/stackdiff/Tests/StacksTests/HeaptrackParserTests.swift new file mode 100644 index 000000000..9c313af33 --- /dev/null +++ b/dev/stackdiff/Tests/StacksTests/HeaptrackParserTests.swift @@ -0,0 +1,118 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Stacks +import Testing + +struct HeaptrackParserTests { + @Test + func parsing() throws { + // Real input but modified to be a lot shorter. + let input = """ + reading file "heaptrack.simple-handshake.a.gz" - please wait, this might take some time... + Debuggee command was: ./.build/release/simple-handshake + finished reading file, now analyzing data: + + MOST CALLS TO ALLOCATION FUNCTIONS + 488872 calls to allocation functions with 28.16K peak consumption from + CNIOBoringSSL_OPENSSL_malloc + at Sources/CNIOBoringSSL/crypto/mem.cc:249 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + 3000 calls with 80B peak consumption from: + CNIOBoringSSL_OPENSSL_zalloc + at Sources/CNIOBoringSSL/crypto/mem.cc:266 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + CNIOBoringSSL_ASN1_item_ex_new + at Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc:153 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + ASN1_template_new(ASN1_VALUE_st**, ASN1_TEMPLATE_st const*) + at Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc:236 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + CNIOBoringSSL_ASN1_item_ex_new + at Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc:161 + asn1_item_ex_d2i(ASN1_VALUE_st**, unsigned char const**, long, ASN1_ITEM_st const*, int, int, char, crypto_buffer_st*, int) + at Sources/CNIOBoringSSL/crypto/asn1/tasn_dec.cc:378 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + static simple_handshake.SimpleHandshake.$main() throws -> () + at //:40 + simple_handshake_main + at /code/Sources/simple-handshake/SimpleHandshake.swift:0 + 0xffff935b73fa + in /lib/aarch64-linux-gnu/libc.so.6 + __libc_start_main + in /lib/aarch64-linux-gnu/libc.so.6 + 2000 calls with 96B peak consumption from: + CNIOBoringSSL_ASN1_STRING_type_new + at Sources/CNIOBoringSSL/crypto/asn1/asn1_lib.cc:329 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + ASN1_primitive_new(ASN1_VALUE_st**, ASN1_ITEM_st const*) + at Sources/CNIOBoringSSL/crypto/asn1/tasn_new.cc:294 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + static simple_handshake.SimpleHandshake.main() throws -> () + at /code/Sources/simple-handshake/SimpleHandshake.swift:43 + in /code/.build/aarch64-unknown-linux-gnu/release/simple-handshake + static simple_handshake.SimpleHandshake.$main() throws -> () + at //:40 + simple_handshake_main + at /code/Sources/simple-handshake/SimpleHandshake.swift:0 + 0xffff935b73fa + in /lib/aarch64-linux-gnu/libc.so.6 + __libc_start_main + in /lib/aarch64-linux-gnu/libc.so.6 + + + total runtime: 0.44s. + calls to allocation functions: 638104 (1440415/s) + temporary memory allocations: 56039 (126498/s) + peak heap memory consumption: 190.22K + peak RSS (including heaptrack overhead): 21.92M + total memory leaked: 5.54K + """ + + let lines = input.split(separator: "\n").map { String($0) } + let stacks = HeaptrackParser.parse(lines: lines) + + try #require(stacks.count == 2) + + let stack0 = stacks[0] + let expected0 = WeightedStack( + lines: [ + "CNIOBoringSSL_OPENSSL_zalloc", + "CNIOBoringSSL_ASN1_item_ex_new", + "ASN1_template_new(ASN1_VALUE_st**, ASN1_TEMPLATE_st const*)", + "CNIOBoringSSL_ASN1_item_ex_new", + "asn1_item_ex_d2i(ASN1_VALUE_st**, unsigned char const**, long, ASN1_ITEM_st const*, int, int, char, crypto_buffer_st*, int)", + "static simple_handshake.SimpleHandshake.$main() throws -> ()", + "simple_handshake_main", + "__libc_start_main", + ], + allocations: 3000 + ) + #expect(stack0 == expected0) + + let stack1 = stacks[1] + let expected1 = WeightedStack( + lines: [ + "CNIOBoringSSL_ASN1_STRING_type_new", + "ASN1_primitive_new(ASN1_VALUE_st**, ASN1_ITEM_st const*)", + "static simple_handshake.SimpleHandshake.main() throws -> ()", + "static simple_handshake.SimpleHandshake.$main() throws -> ()", + "simple_handshake_main", + "__libc_start_main", + ], + allocations: 2000 + ) + #expect(stack1 == expected1) + } +} diff --git a/dev/stackdiff/Tests/StacksTests/SimilarityTests.swift b/dev/stackdiff/Tests/StacksTests/SimilarityTests.swift new file mode 100644 index 000000000..8777aa48b --- /dev/null +++ b/dev/stackdiff/Tests/StacksTests/SimilarityTests.swift @@ -0,0 +1,55 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Stacks +import Testing + +struct SimilarityTests { + @Test(arguments: ["", "foo", "Foo"]) + func perfectMatch(_ input: String) { + let (distance, score) = Similarity.levenshtein(input, input) + #expect(distance == 0) + #expect(score == 1) + } + + @Test(arguments: [("", "a"), ("a", ""), ("a", "b"), ("A", "a")]) + func maxDistance(_ lhs: String, _ rhs: String) { + let (distance, score) = Similarity.levenshtein(lhs, rhs) + #expect(distance == 1) + #expect(score == 0) + } + + @Test + func kittenSitting() { + let (distance, _) = Similarity.levenshtein("kitten", "sitting") + // k -> s + // e -> i + // +g + #expect(distance == 3) + } + + @Test + func similarityScore() { + let (distance, similarity) = Similarity.levenshtein("aa", "bbaa") + // +b + // +b + #expect(distance == 2) + // = 1 - lev(aa, bbaa) / max(len(aa), len(bbaa)) + // = 1 - (2) / max(2, 4) + // = 1 - 2 / 4 + // = 1 - 0.5 + // = 0.5 + #expect(similarity == 0.5) + } +}