Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
c4ec80e
Keep C# size balanced trees within the AVL height bound
konard Nov 29, 2026
61c18c6
Keep C++ size balanced trees within the AVL height bound
konard Nov 29, 2026
67713ca
Release size balanced tree fix and test C# on pull requests
konard Nov 29, 2026
c334df5
Address Codacy findings in the size balanced tree fix
konard Nov 29, 2026
6743b4b
Maintain C# recursionless attach paths by the direction of the attach
konard Nov 29, 2026
3bfeb22
Maintain C++ recursionless attach paths by the direction of the attach
konard Nov 29, 2026
f864a23
Remove unreachable empty-root guard from recursive Maintain
konard Nov 29, 2026
1295c97
Undo path size changes when an AVL attach or detach fails
konard Nov 29, 2026
f630e3d
Test rotations, edge cases and lists to reach full C# coverage
konard Nov 29, 2026
5fbdb8d
Test C++ rotations, edge cases and lists like the C# tests
konard Nov 29, 2026
d9b0f1d
Benchmark attach and detach of all three trees in C# and C++
konard Nov 29, 2026
d6c4dbf
Fetch Platform.Interfaces, GTest and benchmark in CMake when no packa…
konard Nov 29, 2026
f92756e
Pack the C++ headers with the .NET SDK and check the package by compi…
konard Nov 29, 2026
1ddebf6
Keep the exceptions in tree validation mode and build C# with it on r…
konard Nov 29, 2026
3b9755e
Run the C++ tests on every compiler with sanitizers, validation and c…
konard Nov 29, 2026
4fa848e
Require full C# coverage and self-validating trees before a C# release
konard Nov 29, 2026
d4afb7a
Run the C# and C++ benchmarks on request
konard Nov 29, 2026
edd6814
Lint, audit and scan the repository like linksplatform/Interfaces
konard Nov 29, 2026
fcd4619
Let the trees pay nothing for being inspected
konard Nov 29, 2026
21cc382
Make the shell scripts executable
konard Nov 29, 2026
ad3539c
Exclude the CodeQL queries that report the C++ unity builds
konard Nov 29, 2026
b13c278
Let the documentation jobs build the README and the comments of the t…
konard Nov 29, 2026
bb17f45
Resolve the C# sources from the repository root in the PDF preamble test
konard Nov 29, 2026
1ad28a5
Validate the documentation pages that DocFX writes for this library
konard Nov 29, 2026
caba0d1
Link the README to the API documentation PDF and the namespace pages
konard Nov 29, 2026
2555c3e
Resolve the Codacy findings of the pull request
konard Nov 29, 2026
fc26de0
Resolve the remaining Codacy findings
konard Nov 29, 2026
5e7db26
Expose the tree internals to inheritors and let the AVL tree reuse it…
konard Nov 29, 2026
f2173e0
Split the test trees into plain trees and inspectable inheritors
konard Nov 29, 2026
7ebf8c6
Benchmark tree lookup and all four doubly linked lists in C#
konard Nov 29, 2026
7491365
Benchmark tree lookup, storage and all four lists in C++ and count al…
konard Nov 29, 2026
b0f9e55
Benchmark the storage of every tree and list in C#
konard Nov 29, 2026
562163a
Prove that trees hold as many nodes as their element type can count a…
konard Nov 29, 2026
5b9344f
Render the benchmark results into README and document memory and limits
konard Nov 29, 2026
ebebbec
Ship the README with the benchmark results in both NuGet packages
konard Nov 29, 2026
47bd4ee
TEMPORARY: run the benchmarks on push to measure the README results
konard Nov 29, 2026
77f2bd2
Count the nothrow allocations so AddressSanitizer sees matching new a…
konard Nov 29, 2026
71f9964
Show the measured benchmark results in README and choose structures b…
konard Nov 29, 2026
bac2d1a
Run the benchmarks only on request again
konard Nov 29, 2026
37e9bc3
Count found nodes without a filtering branch in the search benchmark
konard Nov 29, 2026
65c7d8f
Name the StringBuilder parameters stringBuilder instead of sb
konard Nov 29, 2026
d31361c
Wrap README prose at 80 columns and lint it with markdownlint
konard Nov 29, 2026
343b01f
Make RotationDetector a class so its state is not copied
konard Nov 29, 2026
feaf05a
Return roots from the benchmark helpers and document the ref root API
konard Nov 29, 2026
2b85fd2
Keep the balancing helpers and path buffers of the trees private
konard Nov 29, 2026
19164d8
Add an experiment that runs SonarC# on the library as Codacy does
konard Nov 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/codeql/codeql-config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Collections.Methods CodeQL config

# Both excluded queries only report the way the C++ tests and benchmarks are
# built, not defects. Every other query of the security-extended and
# security-and-quality suites still runs.
query-filters:
# The C++ tests and benchmarks are unity builds: AllTests.cpp and
# AllBenchmarks.cpp include the other .cpp files of their directory, as in
# every linksplatform C++ library, so each is one translation unit.
- exclude:
id: cpp/include-non-header
# Without a build (build-mode: none) the Google Test and Google Benchmark
# headers, which CMake fetches at configure time, are missing, so CodeQL
# cannot tell that benchmark::State is a type and reads the function
# template "void AttachAndDetach(benchmark::State& state)" as a static
# variable initialized with "benchmark::State & state".
- exclude:
id: cpp/unused-static-variable
9 changes: 9 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,13 @@ updates:
directory: "/"
schedule:
interval: daily
cooldown:
default-days: 7
open-pull-requests-limit: 10
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: weekly
cooldown:
default-days: 7
open-pull-requests-limit: 10
125 changes: 125 additions & 0 deletions .github/scripts/check-cpp-nuget-package.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#!/usr/bin/env bash
# Consume the packed C++ NuGet package the way a project does, so a package
# that packs but cannot be used fails before it is published. Adapted from
# link-foundation/cpp-ai-driven-development-pipeline-template
# (scripts/check-nuget-package.sh): push it to a local folder feed, let
# `dotnet restore` extract it through <PackageDownload> (which skips the TFM
# check that a native package fails in an SDK-style project), check the MSBuild
# targets and headers, then compile a program against the restored headers.
#
# Usage: check-cpp-nuget-package.sh <package.nupkg>
# Environment:
# CXX C++20 compiler for the consumer program (default: c++)
# VERBOSE=1 or RUNNER_DEBUG=1 traces every command (off by default)
set -euo pipefail

if [ "${VERBOSE:-}" = 1 ] || [ "${RUNNER_DEBUG:-}" = 1 ]; then
set -x
fi

package="${1:?Usage: check-cpp-nuget-package.sh <package.nupkg>}"
package="$(cd "$(dirname "$package")" && pwd)/$(basename "$package")"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

# <id>.<version>.nupkg; the version is the last three dot-separated fields.
name="$(basename "$package" .nupkg)"
version="$(printf '%s\n' "$name" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+([-+].*)?$')"
id="${name%."$version"}"

# Native dependencies of the package, as "id version" lines. PackageDownload
# does not restore dependencies, so each one is downloaded from nuget.org.
dependencies="$(unzip -p "$package" "$id.nuspec" | grep -oE '<dependency id="[^"]+" version="[^"]+"' | sed -E 's/<dependency id="([^"]+)" version="([^"]+)"/\1 \2/' || true)"

mkdir -p "$work/feed" "$work/project"
dotnet nuget push "$package" --source "$work/feed"
downloads="<PackageDownload Include=\"$id\" Version=\"[$version]\" />"
while read -r dependency_id dependency_version; do
[ -n "$dependency_id" ] || continue
downloads+="<PackageDownload Include=\"$dependency_id\" Version=\"[$dependency_version]\" />"
done <<< "$dependencies"
cat > "$work/project/check.csproj" <<XML
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><TargetFramework>netstandard2.0</TargetFramework><DisableImplicitNuGetFallbackFolder>true</DisableImplicitNuGetFallbackFolder><DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences></PropertyGroup>
<ItemGroup>$downloads</ItemGroup>
</Project>
XML
# The package under test comes only from the local feed; its dependencies only from nuget.org.
cat > "$work/project/nuget.config" <<XML
<configuration>
<packageSources><clear /><add key="local" value="$work/feed" /><add key="nuget.org" value="https://api.nuget.org/v3/index.json" /></packageSources>
<packageSourceMapping>
<packageSource key="local"><package pattern="$id" /></packageSource>
<packageSource key="nuget.org"><package pattern="*" /></packageSource>
</packageSourceMapping>
</configuration>
XML
dotnet restore "$work/project/check.csproj" --packages "$work/packages"

lowercase() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }
extracted="$work/packages/$(lowercase "$id")/$version"
include_flags=(-I "$extracted/lib/native/include")
while read -r dependency_id dependency_version; do
[ -n "$dependency_id" ] || continue
include_flags+=(-I "$work/packages/$(lowercase "$dependency_id")/$dependency_version/lib/native/include")
done <<< "$dependencies"
# nuget.org shows README.md, which carries the benchmark results.
if ! grep -q '<!-- benchmarks:start -->' "$extracted/README.md" 2>/dev/null; then
echo "::error title=C++ NuGet package unusable::README.md with the benchmark results is missing"
exit 1
fi
if [ ! -f "$extracted/build/native/$id.targets" ]; then
echo "::error title=C++ NuGet package unusable::build/native/$id.targets is missing"
exit 1
fi
if ! grep -q 'lib\\native\\include' "$extracted/build/native/$id.targets"; then
echo "::error title=C++ NuGet package unusable::build/native/$id.targets does not add lib/native/include to the include path"
exit 1
fi

# The nuspec tells users to include Platform.Collections.Methods.h only, so it
# has to pull in every header it needs from the package and its dependencies.
# The consumer builds a small size balanced tree with the restored headers.
cat > "$work/consumer.cpp" <<'CPP'
#include <cstdint>
#include <Platform.Collections.Methods.h>

using namespace Platform::Collections::Methods::Trees;

struct Tree : SizeBalancedTreeMethods<Tree, std::uint32_t>
{
struct Node { std::uint32_t Left, Right, Size; } Nodes[8]{};
std::uint32_t Root = 0;
std::uint32_t* GetLeftReference(std::uint32_t node) { return &Nodes[node].Left; }
std::uint32_t* GetRightReference(std::uint32_t node) { return &Nodes[node].Right; }
std::uint32_t GetLeft(std::uint32_t node) { return Nodes[node].Left; }
std::uint32_t GetRight(std::uint32_t node) { return Nodes[node].Right; }
std::uint32_t GetSize(std::uint32_t node) { return Nodes[node].Size; }
void SetLeft(std::uint32_t node, std::uint32_t left) { Nodes[node].Left = left; }
void SetRight(std::uint32_t node, std::uint32_t right) { Nodes[node].Right = right; }
void SetSize(std::uint32_t node, std::uint32_t size) { Nodes[node].Size = size; }
bool FirstIsToTheLeftOfSecond(std::uint32_t first, std::uint32_t second) { return first < second; }
bool FirstIsToTheRightOfSecond(std::uint32_t first, std::uint32_t second) { return first > second; }
void ClearNode(std::uint32_t node) { Nodes[node] = {}; }
};

int main()
{
Tree tree;
for (std::uint32_t node = 1; node < 8; node++)
{
tree.Attach(&tree.Root, node);
}
// 1..7 attached in ascending order form the perfect tree of height 3 rooted at 4.
return tree.Root == 4 && tree.GetSize(tree.Root) == 7 ? 0 : 1;
}
CPP
if ! "${CXX:-c++}" -std=c++20 "${include_flags[@]}" -o "$work/consumer" "$work/consumer.cpp"; then
echo "::error title=C++ NuGet package unusable::A program that includes Platform.Collections.Methods.h from the restored package does not compile"
exit 1
fi
if ! "$work/consumer"; then
echo "::error title=C++ NuGet package unusable::A size balanced tree built with the restored headers has a wrong shape"
exit 1
fi
echo "NuGet restore and use of $id $version: OK"
67 changes: 67 additions & 0 deletions .github/scripts/check-cpp-nuget-package.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env node

import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { copyFileSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { after, before, test } from "node:test";

// Packs the real package once, then checks it and broken copies of it with
// the real dotnet client and compiler, so this needs the .NET SDK, zip and c++.
const script = new URL("./check-cpp-nuget-package.sh", import.meta.url).pathname;
const packScript = new URL("./pack-cpp-nuget.mjs", import.meta.url).pathname;
const missing = ["dotnet", "zip", "c++"].filter(
(tool) => spawnSync("bash", ["-c", `command -v ${tool}`]).status !== 0,
);
const options = { skip: missing.length > 0 && `${missing.join(", ")} not installed`, timeout: 300_000 };

let directory;
let packed;
before(() => {
if (missing.length > 0) {
return;
}
directory = mkdtempSync(path.join(tmpdir(), "check-cpp-nuget-"));
const pack = spawnSync("node", [packScript, path.join(directory, "packed")], { encoding: "utf8" });
assert.equal(pack.status, 0, pack.stdout + pack.stderr);
const name = readdirSync(path.join(directory, "packed")).find((file) => file.endsWith(".nupkg"));
packed = path.join(directory, "packed", name);
});
after(() => directory && rmSync(directory, { recursive: true, force: true }));

// Copies the package into its own folder, deletes `entries` from it and checks it.
const checkWithout = (label, entries) => {
const copy = path.join(directory, label, path.basename(packed));
spawnSync("mkdir", ["-p", path.dirname(copy)]);
copyFileSync(packed, copy);
if (entries.length > 0) {
const zip = spawnSync("zip", ["-q", "-d", copy, ...entries], { encoding: "utf8" });
assert.equal(zip.status, 0, zip.stderr);
}
return spawnSync("bash", [script, copy], { encoding: "utf8" });
};

test("restores and compiles against the packed package", options, () => {
const result = checkWithout("complete", []);
assert.equal(result.status, 0, result.stdout + result.stderr);
assert.match(result.stdout, /NuGet restore and use of Platform\.Collections\.Methods\.TemplateLibrary .*: OK/);
});

test("fails when the README with the benchmark results is missing", options, () => {
const result = checkWithout("no-readme", ["README.md"]);
assert.notEqual(result.status, 0);
assert.match(result.stdout, /README\.md with the benchmark results is missing/);
});

test("fails when the MSBuild targets are missing", options, () => {
const result = checkWithout("no-targets", ["build/native/*"]);
assert.notEqual(result.status, 0);
assert.match(result.stdout, /::error title=C\+\+ NuGet package unusable::build\/native\/.*\.targets is missing/);
});

test("fails when a header that Platform.Collections.Methods.h includes is missing", options, () => {
const result = checkWithout("no-header", ["lib/native/include/Trees/SizeBalancedTreeMethods.h"]);
assert.notEqual(result.status, 0);
assert.match(result.stdout, /does not compile/);
});
122 changes: 122 additions & 0 deletions .github/scripts/check-csharp-coverage.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
#!/usr/bin/env node

/**
* Require full line coverage of the library by the C# tests.
*
* Reads the Cobertura reports that coverlet writes for
* `dotnet test --collect "XPlat Code Coverage"` and fails with the file and
* line of every library line that no test executed. Only the package named
* by --package (default: Platform.Collections.Methods) is checked, so test
* and benchmark code does not count.
*
* Usage: node check-csharp-coverage.mjs [--package <name>] [--verbose] <coverage.cobertura.xml>...
* `--verbose`, VERBOSE=1 or RUNNER_DEBUG=1 prints the coverage of every file.
* Writes a Markdown summary to GITHUB_STEP_SUMMARY when it is set. File names
* are reported relative to GITHUB_WORKSPACE (or the current directory), so
* the annotations point at the repository files.
*/

import { appendFileSync, readFileSync } from "node:fs";
import { isAbsolute, join, relative } from "node:path";

const attribute = (element, name) => new RegExp(`\\b${name}="([^"]*)"`).exec(element)?.[1];

// Line hits of every class of the package: Map<file, Map<line, hits>>.
// Hits of the same line in several classes (e.g. nested or partial classes,
// or several reports) are summed, so a line counts as covered if any run hit it.
export const collectLines = (reports, packageName, files = new Map(), root = undefined) => {
let found = false;
for (const report of reports) {
// coverlet writes class file names relative to the single <source> directory.
const source = /<source>([^<]*)<\/source>/.exec(report)?.[1];
const resolve = (file) => {
const path = source && !isAbsolute(file) ? join(source, file) : file;
return root && isAbsolute(path) ? relative(root, path) : path;
};
const packagePattern = /<package\b[^>]*>[\s\S]*?<\/package>/g;
for (const [packageSource] of report.matchAll(packagePattern)) {
if (attribute(packageSource.slice(0, packageSource.indexOf(">")), "name") !== packageName) {
continue;
}
found = true;
for (const [classSource] of packageSource.matchAll(/<class\b[^>]*>[\s\S]*?<\/class>/g)) {
const file = resolve(attribute(classSource.slice(0, classSource.indexOf(">")), "filename"));
const lines = files.get(file) ?? new Map();
files.set(file, lines);
// Method bodies repeat the class lines; the class level list is enough.
const classLines = classSource.slice(classSource.lastIndexOf("</methods>") + 1);
for (const [line] of classLines.matchAll(/<line\b[^>]*>/g)) {
const number = Number(attribute(line, "number"));
lines.set(number, (lines.get(number) ?? 0) + Number(attribute(line, "hits")));
}
}
}
}
if (!found) {
throw new Error(`No coverage report contains the package ${packageName}`);
}
return files;
};

export const summarize = (files) => {
const summary = [...files].map(([file, lines]) => {
const missed = [...lines].filter(([, hits]) => hits === 0).map(([number]) => number).sort((a, b) => a - b);
return { file, total: lines.size, missed };
});
summary.sort((a, b) => a.file.localeCompare(b.file));
const total = summary.reduce((sum, { total: lines }) => sum + lines, 0);
const missed = summary.reduce((sum, file) => sum + file.missed.length, 0);
return { files: summary, total, covered: total - missed };
};

const percent = ({ total, covered }) => (total === 0 ? 100 : (100 * covered) / total).toFixed(2);

export const run = (args = process.argv.slice(2), environment = process.env) => {
let verbose = environment.VERBOSE === "1" || environment.RUNNER_DEBUG === "1";
let packageName = "Platform.Collections.Methods";
const paths = [];
for (let index = 0; index < args.length; index++) {
if (args[index] === "--verbose") {
verbose = true;
} else if (args[index] === "--package") {
packageName = args[++index];
} else {
paths.push(args[index]);
}
}
if (paths.length === 0 || !packageName) {
console.error("Usage: node check-csharp-coverage.mjs [--package <name>] [--verbose] <coverage.cobertura.xml>...");
return 2;
}

let result;
try {
const reports = paths.map((path) => readFileSync(path, "utf8"));
result = summarize(collectLines(reports, packageName, new Map(), environment.GITHUB_WORKSPACE || process.cwd()));
} catch (error) {
console.error(`::error title=C# coverage check failed::${error.message}`);
return 1;
}

const rows = result.files.map((file) => `| ${file.file} | ${percent({ total: file.total, covered: file.total - file.missed.length })}% | ${file.missed.join(", ")} |`);
if (verbose) {
console.log(rows.join("\n"));
}
if (environment.GITHUB_STEP_SUMMARY) {
appendFileSync(
environment.GITHUB_STEP_SUMMARY,
[`### C# line coverage of ${packageName}: ${percent(result)}%`, "", "| File | Lines | Missed lines |", "| --- | --- | --- |", ...rows, ""].join("\n"),
);
}
for (const file of result.files) {
for (const line of file.missed) {
console.error(`::error file=${file.file},line=${line},title=Line not covered::No C# test executes this line.`);
}
}
console.log(`${packageName}: ${result.covered} of ${result.total} lines covered (${percent(result)}%).`);
return result.covered === result.total ? 0 : 1;
};

if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
process.exitCode = run();
}
Loading
Loading