From c4ec80e9f904b161338c6138bbf267750a916218 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 08:01:35 +0000 Subject: [PATCH 01/46] Keep C# size balanced trees within the AVL height bound Restore Chen's size balanced tree algorithm: Maintain after every attach (removing the skip-every-second-attach threshold) and after every detach. The recursionless variant is the same algorithm with explicit stacks, so both build trees of identical shape. Trees built by older versions are rebuilt once with Day-Stout-Warren when an operation passes more nodes than any size balanced tree of that size can have. Refs #115, linksplatform/Data.Doublets#577 --- .../IInspectableTree.cs | 17 + .../RecursionlessSizeBalancedTree.cs | 8 +- .../SizeBalancedTree.cs | 8 +- .../SizedAndThreadedAVLBalancedTree.cs | 8 +- .../TreeBalanceTests.cs | 350 +++++++++++++ .../RecursionlessSizeBalancedTreeMethods.cs | 476 +++++++++++------- .../Trees/SizeBalancedTreeMethods.cs | 249 +++++---- .../Trees/SizedBinaryTreeMethodsBase.cs | 103 ++++ 8 files changed, 929 insertions(+), 290 deletions(-) create mode 100644 csharp/Platform.Collections.Methods.Tests/IInspectableTree.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs diff --git a/csharp/Platform.Collections.Methods.Tests/IInspectableTree.cs b/csharp/Platform.Collections.Methods.Tests/IInspectableTree.cs new file mode 100644 index 0000000..8aefa31 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/IInspectableTree.cs @@ -0,0 +1,17 @@ +using System.Numerics; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Read-only view of a test tree that balance checks use to walk its shape. + /// Представление тестового дерева только для чтения, используемое проверками балансировки для обхода его формы. + /// + public interface IInspectableTree where TElement : IUnsignedNumber + { + TElement LeftOf(TElement node); + + TElement RightOf(TElement node); + + TElement SizeOf(TElement node); + } +} diff --git a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs index 670ddb1..fc0e174 100644 --- a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs @@ -8,7 +8,7 @@ namespace Platform.Collections.Methods.Tests { - public class RecursionlessSizeBalancedTree : RecursionlessSizeBalancedTreeMethods where TElement: IUnsignedNumber, IComparisonOperators + public class RecursionlessSizeBalancedTree : RecursionlessSizeBalancedTreeMethods, IInspectableTree where TElement: IUnsignedNumber, IComparisonOperators { private struct TreeElement { @@ -23,6 +23,12 @@ private struct TreeElement public TElement Count => GetSizeOrZero(Root); + public TElement LeftOf(TElement node) => GetLeftOrDefault(node); + + public TElement RightOf(TElement node) => GetRightOrDefault(node); + + public TElement SizeOf(TElement node) => GetSizeOrZero(node); + public RecursionlessSizeBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); public TElement Allocate() diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs index 6b55e9f..4ac8686 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs @@ -8,7 +8,7 @@ namespace Platform.Collections.Methods.Tests { - public class SizeBalancedTree : SizeBalancedTreeMethods where TElement: IUnsignedNumber, IComparisonOperators + public class SizeBalancedTree : SizeBalancedTreeMethods, IInspectableTree where TElement: IUnsignedNumber, IComparisonOperators { private struct TreeElement { @@ -23,6 +23,12 @@ private struct TreeElement public TElement Count => GetSizeOrZero(Root); + public TElement LeftOf(TElement node) => GetLeftOrDefault(node); + + public TElement RightOf(TElement node) => GetRightOrDefault(node); + + public TElement SizeOf(TElement node) => GetSizeOrZero(node); + public SizeBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); public TElement Allocate() diff --git a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs index 9b50487..dd6978c 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs @@ -8,7 +8,7 @@ namespace Platform.Collections.Methods.Tests { - public class SizedAndThreadedAVLBalancedTree : SizedAndThreadedAVLBalancedTreeMethods where TElement: IUnsignedNumber, IComparisonOperators + public class SizedAndThreadedAVLBalancedTree : SizedAndThreadedAVLBalancedTreeMethods, IInspectableTree where TElement: IUnsignedNumber, IComparisonOperators { private struct TreeElement { @@ -26,6 +26,12 @@ private struct TreeElement public TElement Count => GetSizeOrZero(Root); + public TElement LeftOf(TElement node) => GetLeftOrDefault(node); + + public TElement RightOf(TElement node) => GetRightOrDefault(node); + + public TElement SizeOf(TElement node) => GetSizeOrZero(node); + public SizedAndThreadedAVLBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); public TElement Allocate() diff --git a/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs b/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs new file mode 100644 index 0000000..85d8f77 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Platform.Collections.Methods.Trees; +using Xunit; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Checks that every tree keeps a near-optimal height for workloads that used to degenerate size-balanced trees. + /// Проверяет, что каждое дерево сохраняет близкую к оптимальной высоту на нагрузках, которые раньше вырождали деревья, сбалансированные по размеру. + /// + public static class TreeBalanceTests + { + private const int N = 2048; + + public static IEnumerable Trees => new[] { new object[] { "SizeBalancedTree" }, new object[] { "RecursionlessSizeBalancedTree" }, new object[] { "SizedAndThreadedAVLBalancedTree" } }; + + public static IEnumerable TreesAndWorkloads => + from tree in Trees + from workload in new[] { "Ascending", "Descending", "Random", "InterleavedHotAndCold", "InterleavedHotAndColdMirrored", "AlternatingEnds" } + select new object[] { tree[0], workload }; + + [Theory] + [MemberData(nameof(TreesAndWorkloads))] + public static void AttachKeepsHeightNearOptimal(string treeName, string workload) + { + var tree = Create(treeName, (2 * N) + 2); + foreach (var key in Keys(workload)) + { + tree.Attach(key); + AssertBalanced(tree, treeName); + } + } + + [Theory] + [MemberData(nameof(Trees))] + public static void DetachKeepsHeightNearOptimal(string treeName) + { + var tree = Create(treeName, N + 2); + for (uint key = 1; key <= N; key++) + { + tree.Attach(key); + } + // Removing one whole side shifts all the weight to the other side of the root. + for (uint key = 1; key <= N - 8; key++) + { + tree.Detach(key); + AssertBalanced(tree, treeName); + } + } + + [Theory] + [MemberData(nameof(Trees))] + public static void RandomChurnKeepsHeightNearOptimal(string treeName) + { + var tree = Create(treeName, N + 2); + var random = new System.Random(577); + var present = new List(); + var absent = Enumerable.Range(1, N).Select(i => (uint)i).ToList(); + for (var step = 0; step < 8 * N; step++) + { + // Bias towards growth in the first half and towards shrinking in the second half. + var grow = present.Count == 0 || (absent.Count > 0 && random.Next(4) < (step < 4 * N ? 3 : 1)); + var source = grow ? absent : present; + var index = random.Next(source.Count); + var key = source[index]; + source[index] = source[^1]; + source.RemoveAt(source.Count - 1); + if (grow) + { + tree.Attach(key); + present.Add(key); + } + else + { + tree.Detach(key); + absent.Add(key); + } + AssertBalanced(tree, treeName); + } + } + + [Fact] + public static void RecursiveAndRecursionlessTreesHaveTheSameShape() + { + var recursive = Create("SizeBalancedTree", N + 2); + var recursionless = Create("RecursionlessSizeBalancedTree", N + 2); + var random = new System.Random(592); + var present = new HashSet(); + for (var step = 0; step < 8 * N; step++) + { + var key = (uint)random.Next(1, N + 1); + if (present.Remove(key)) + { + recursive.Detach(key); + recursionless.Detach(key); + } + else + { + present.Add(key); + recursive.Attach(key); + recursionless.Attach(key); + } + if (step % 64 == 0) + { + Assert.Equal(recursive.Shape(), recursionless.Shape()); + } + } + Assert.Equal(recursive.Shape(), recursionless.Shape()); + } + + public static IEnumerable SizeBalancedTreesAndOperations => + from tree in new[] { "SizeBalancedTree", "RecursionlessSizeBalancedTree" } + from attach in new[] { true, false } + select new object[] { tree, attach }; + + /// + /// A tree built by other code (here a path of right children, as older versions could build) is rebuilt by the first operation that finds a too long path. + /// Дерево, построенное другим кодом (здесь путь из правых потомков, как могли строить старые версии), перестраивается первой операцией, нашедшей слишком длинный путь. + /// + [Theory] + [MemberData(nameof(SizeBalancedTreesAndOperations))] + public static void TreesBuiltByOtherCodeAreRebuilt(string treeName, bool attach) + { + for (uint count = 1; count <= 200; count++) + { + var tree = treeName == "SizeBalancedTree" + ? new TestTree(new ChainedSizeBalancedTree(count), t => ref t.Root) + : (ITestTree)new TestTree(new ChainedRecursionlessSizeBalancedTree(count), t => ref t.Root); + if (attach) + { + tree.Attach(count + 1); + } + else + { + tree.Detach(count); + } + var expected = attach ? count + 1 : count - 1; + Assert.Equal((int)expected, tree.Count); + AssertBalanced(tree, treeName); + for (uint key = 1; key <= expected; key++) + { + Assert.True(tree.Contains(key)); + } + } + } + + private sealed class ChainedSizeBalancedTree : SizeBalancedTree + { + public ChainedSizeBalancedTree(uint count) : base((int)count + 2) => Root = BuildChain(count, Allocate, SetLeft, SetRight, SetSize); + } + + private sealed class ChainedRecursionlessSizeBalancedTree : RecursionlessSizeBalancedTree + { + public ChainedRecursionlessSizeBalancedTree(uint count) : base((int)count + 2) => Root = BuildChain(count, Allocate, SetLeft, SetRight, SetSize); + } + + private static uint BuildChain(uint count, Func allocate, Action setLeft, Action setRight, Action setSize) + { + for (uint node = 1; node <= count; node++) + { + Assert.Equal(node, allocate()); + setLeft(node, 0); + setRight(node, node < count ? node + 1 : 0); + setSize(node, count - node + 1); + } + return 1; + } + + private static IEnumerable Keys(string workload) + { + switch (workload) + { + case "Ascending": + for (uint i = 1; i <= N; i++) yield return i; + break; + case "Descending": + for (uint i = N; i >= 1; i--) yield return i; + break; + case "Random": + var random = new System.Random(577); + foreach (var key in Enumerable.Range(1, N).OrderBy(_ => random.Next())) yield return (uint)key; + break; + case "InterleavedHotAndCold": + // The pattern of issue linksplatform/Data.Doublets#577: links that share one source + // ("hot" keys in one narrow range) are created alternately with unrelated links ("cold" keys). + for (uint i = 1; i <= N; i++) + { + yield return i; + yield return N + i; + } + break; + case "InterleavedHotAndColdMirrored": + for (uint i = N; i >= 1; i--) + { + yield return N + i; + yield return i; + } + break; + case "AlternatingEnds": + for (uint i = 1; i <= N; i++) + { + yield return i; + yield return (2 * N) + 1 - i; + } + break; + default: + throw new ArgumentOutOfRangeException(nameof(workload)); + } + } + + private static void AssertBalanced(ITestTree tree, string treeName) + { + var count = tree.Count; + var height = tree.Height; + var limit = MaximumHeight(count); + Assert.True(height <= limit, $"{treeName}: height {height} exceeds {limit} for {count} nodes."); + if (treeName != "SizedAndThreadedAVLBalancedTree") + { + tree.AssertSizeBalanced(); + } + } + + /// + /// The largest number of levels that an AVL tree or a size balanced tree with the specified number of nodes can have. + /// Наибольшее число уровней, которое может иметь АВЛ-дерево или дерево, сбалансированное по размеру, с указанным числом узлов. + /// + /// + /// The sparsest tree of each kind with h levels has m(h) = m(h - 1) + m(h - 2) + 1 nodes, where m(1) = 1 and m(2) = 2, + /// so both kinds are at most about 1.44 * log2(n) levels high. + /// + public static int MaximumHeight(int count) + { + var height = 0; + long previous = 0, current = 1; // m(0) = 0, m(1) = 1 + while (current <= count) + { + height++; + (previous, current) = (current, current + previous + 1); + } + return height; + } + + private static ITestTree Create(string treeName, int capacity) => treeName switch + { + "SizeBalancedTree" => new TestTree>(new SizeBalancedTree(capacity), t => ref t.Root), + "RecursionlessSizeBalancedTree" => new TestTree>(new RecursionlessSizeBalancedTree(capacity), t => ref t.Root), + "SizedAndThreadedAVLBalancedTree" => new TestTree>(new SizedAndThreadedAVLBalancedTree(capacity), t => ref t.Root), + _ => throw new ArgumentOutOfRangeException(nameof(treeName)), + }; + + private interface ITestTree + { + int Count { get; } + + int Height { get; } + + void Attach(uint key); + + void Detach(uint key); + + void AssertSizeBalanced(); + + bool Contains(uint key); + + /// The root followed by the left child, the right child and the size of every node. + string Shape(); + } + + private delegate ref uint RootReference(TTree tree); + + private sealed class TestTree : ITestTree where TTree : SizedBinaryTreeMethodsBase, IInspectableTree + { + private readonly TTree _tree; + private readonly RootReference _root; + + public TestTree(TTree tree, RootReference root) => (_tree, _root) = (tree, root); + + public int Count => (int)_tree.SizeOf(_root(_tree)); + + public int Height => HeightOf(_root(_tree)); + + public void Attach(uint key) => _tree.Attach(ref _root(_tree), key); + + public void Detach(uint key) => _tree.Detach(ref _root(_tree), key); + + public void AssertSizeBalanced() => AssertSizeBalanced(_root(_tree)); + + public bool Contains(uint key) => _tree.Contains(key, _root(_tree)); + + public string Shape() + { + var root = _root(_tree); + var shape = new System.Text.StringBuilder().Append(root).Append(';'); + for (uint node = 1; node <= N; node++) + { + shape.Append(_tree.LeftOf(node)).Append(',').Append(_tree.RightOf(node)).Append(',').Append(_tree.SizeOf(node)).Append(';'); + } + return shape.ToString(); + } + + private int HeightOf(uint node) + { + // Iterative breadth-first walk, so that a degenerate tree cannot overflow the stack. + var height = 0; + var level = new List(); + if (node != 0) + { + level.Add(node); + } + while (level.Count > 0) + { + height++; + var next = new List(); + foreach (var current in level) + { + var left = _tree.LeftOf(current); + var right = _tree.RightOf(current); + if (left != 0) next.Add(left); + if (right != 0) next.Add(right); + } + level = next; + } + return height; + } + + private void AssertSizeBalanced(uint root) + { + var stack = new Stack(); + if (root != 0) + { + stack.Push(root); + } + while (stack.Count > 0) + { + var node = stack.Pop(); + var left = _tree.LeftOf(node); + var right = _tree.RightOf(node); + Assert.Equal(_tree.SizeOf(left) + _tree.SizeOf(right) + 1, _tree.SizeOf(node)); + // Size balanced tree properties (Chen, 2007): each subtree is at least as large as both subtrees of its sibling. + Assert.True(_tree.SizeOf(left) >= _tree.SizeOf(_tree.LeftOf(right)) && _tree.SizeOf(left) >= _tree.SizeOf(_tree.RightOf(right)), $"Node {node} breaks the size balanced tree property on its left side."); + Assert.True(_tree.SizeOf(right) >= _tree.SizeOf(_tree.LeftOf(left)) && _tree.SizeOf(right) >= _tree.SizeOf(_tree.RightOf(left)), $"Node {node} breaks the size balanced tree property on its right side."); + if (left != 0) stack.Push(left); + if (right != 0) stack.Push(right); + } + } + } + } +} diff --git a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs index 2abf386..993e45f 100644 --- a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs @@ -1,3 +1,4 @@ +using System; using System.Numerics; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member @@ -6,224 +7,343 @@ namespace Platform.Collections.Methods.Trees { /// /// - /// Represents the recursionless size balanced tree methods. + /// Represents the size balanced tree methods that do not use recursion. + /// + /// + /// Представляет методы дерева, сбалансированного по размеру, не использующие рекурсию. /// - /// /// + /// + /// + /// The algorithm is the same as in and builds the same trees. + /// The path from the root and the pending Maintain steps are kept in explicit stacks instead of the call stack. + /// + /// + /// A position in the tree is stored as its parent and the side of the parent, because a rotation replaces the node at a position but not the position itself. + /// The root position has no parent. + /// + /// + /// A tree built by other code, for example by older versions of this class, is rebuilt once when an operation finds a path + /// longer than allows. + /// + /// + /// The stacks belong to the instance, so one instance must not be used by several threads at once. + /// + /// /// + /// public abstract class RecursionlessSizeBalancedTreeMethods : SizedBinaryTreeMethodsBase where TElement: IUnsignedNumber, IComparisonOperators { + /// + /// A position in the tree and the side to check there. + /// Позиция в дереве и сторона, которую нужно там проверить. + /// + /// + /// The parent of the position, or zero for the root position. + /// Родитель позиции или ноль для позиции корня. + /// + /// + /// Whether the position is the left child of the parent. + /// Является ли позиция левым потомком родителя. + /// + /// + /// Whether the left side of the subtree at the position may have become too heavy; otherwise the right side. + /// Могла ли левая сторона поддерева в этой позиции стать слишком тяжёлой; иначе правая сторона. + /// + private readonly record struct Step(TElement Parent, bool IsLeft, bool LeftMayBeHeavy); + + private Step[] _path = new Step[64]; + private int _pathLength; + private Step[] _maintenance = new Step[64]; + /// /// - /// Attaches the core using the specified root. + /// Attaches the node to the subtree with the specified root and restores the size balanced tree properties on the way back up. + /// + /// + /// Присоединяет узел к поддереву с указанным корнем и восстанавливает свойства дерева, сбалансированного по размеру, на обратном пути. /// - /// /// /// - /// The root. - /// + /// The reference to the root of the subtree. + /// Ссылка на корень поддерева. /// /// - /// The node. - /// + /// The node to attach. + /// Присоединяемый узел. /// protected override void AttachCore(ref TElement root, TElement node) { - while (true) + var size = GetSizeOrZero(root); + _pathLength = 0; + var parent = TElement.Zero; + var isLeft = false; + ref TElement current = ref root; + while (current != TElement.Zero) { - ref var left = ref GetLeftReference(root); - var leftSize = GetSizeOrZero(left); - ref var right = ref GetRightReference(root); - var rightSize = GetSizeOrZero(right); - if (FirstIsToTheLeftOfSecond(node, root)) // node.Key less than root.Key - { - if (left == TElement.Zero) - { - IncrementSize(root); - SetSize(node, TElement.One); - left = node; - return; - } - if (FirstIsToTheLeftOfSecond(node, left)) // node.Key less than left.Key - { - if ((leftSize + TElement.One) > rightSize) - { - RightRotate(ref root); - } - else - { - IncrementSize(root); - root = ref left; - } - } - else // node.Key greater than left.Key - { - var leftRightSize = GetSizeOrZero(GetRight(left)); - if ((leftRightSize + TElement.One) > rightSize) - { - if (leftRightSize == TElement.Zero && rightSize == TElement.Zero) - { - SetLeft(node, left); - SetRight(node, root); - SetSize(node, (leftSize+ TElement.CreateTruncating(2))); // TElement.CreateTruncating(2) (2) - node the size of root and a node itself - SetLeft(root, TElement.Zero); - SetSize(root, TElement.One); - root = node; - return; - } - LeftRotate(ref left); - RightRotate(ref root); - } - else - { - IncrementSize(root); - root = ref left; - } - } - } - else // node.Key greater than root.Key - { - if (right == TElement.Zero) - { - IncrementSize(root); - SetSize(node, TElement.One); - right = node; - return; - } - if (FirstIsToTheRightOfSecond(node, right)) // node.Key greater than right.Key - { - if ((rightSize + TElement.One) > leftSize) - { - LeftRotate(ref root); - } - else - { - IncrementSize(root); - root = ref right; - } - } - else // node.Key less than right.Key - { - var rightLeftSize = GetSizeOrZero(GetLeft(right)); - if ((rightLeftSize + TElement.One) > leftSize) - { - if (rightLeftSize == TElement.Zero && leftSize == TElement.Zero) - { - SetLeft(node, root); - SetRight(node, right); - SetSize(node, (rightSize + TElement.CreateTruncating(2))); // TElement.CreateTruncating(2) (2) - node the size of root and a node itself - SetRight(root, TElement.Zero); - SetSize(root, TElement.One); - root = node; - return; - } - RightRotate(ref right); - LeftRotate(ref root); - } - else - { - IncrementSize(root); - root = ref right; - } - } - } + IncrementSize(current); + var goLeft = FirstIsToTheLeftOfSecond(node, current); + // The subtree that grows may become too heavy. + PushPath(new Step(parent, isLeft, goLeft)); + parent = current; + isLeft = goLeft; + current = ref goLeft ? ref GetLeftReference(current) : ref GetRightReference(current); } + SetSize(node, TElement.One); + current = node; + var passed = _pathLength; + MaintainPath(ref root, 0); + RebuildIfDeeperThanBalanced(ref root, passed, size); } /// /// - /// Detaches the core using the specified root. + /// Detaches the node from the subtree with the specified root and restores the size balanced tree properties on the way back up. + /// + /// + /// Отсоединяет узел от поддерева с указанным корнем и восстанавливает свойства дерева, сбалансированного по размеру, на обратном пути. /// - /// /// /// - /// The root. - /// + /// The reference to the root of the subtree. + /// Ссылка на корень поддерева. /// /// - /// The node. - /// + /// The node to detach. + /// Отсоединяемый узел. /// + /// + /// The node is not in the tree, or another node has the same key. + /// Узла нет в дереве, или другой узел имеет такой же ключ. + /// protected override void DetachCore(ref TElement root, TElement node) { + var size = GetSizeOrZero(root); + _pathLength = 0; + var parent = TElement.Zero; + var isLeft = false; while (true) { - ref var left = ref GetLeftReference(root); - var leftSize = GetSizeOrZero(left); - ref var right = ref GetRightReference(root); - var rightSize = GetSizeOrZero(right); - if (FirstIsToTheLeftOfSecond(node, root)) // node.Key less than root.Key + var current = Position(ref root, parent, isLeft); + if (current == TElement.Zero) { - var decrementedLeftSize = leftSize - TElement.One; - if ((GetSizeOrZero(GetRightOrDefault(right))) > decrementedLeftSize) - { - LeftRotate(ref root); - } - else if ((GetSizeOrZero(GetLeftOrDefault(right))) > decrementedLeftSize) - { - RightRotate(ref right); - LeftRotate(ref root); - } - else - { - DecrementSize(root); - root = ref left; - } + throw new InvalidOperationException($"The node {node} is not in the tree."); } - else if (FirstIsToTheRightOfSecond(node, root)) // node.Key greater than root.Key + bool goLeft; + if (FirstIsToTheLeftOfSecond(node, current)) { - var decrementedRightSize = rightSize - TElement.One; - if ((GetSizeOrZero(GetLeftOrDefault(left))) > decrementedRightSize) - { - RightRotate(ref root); - } - else if ((GetSizeOrZero(GetRightOrDefault(left))) > decrementedRightSize) - { - LeftRotate(ref left); - RightRotate(ref root); - } - else - { - DecrementSize(root); - root = ref right; - } + goLeft = true; } - else // key equals to root.Key + else if (FirstIsToTheRightOfSecond(node, current)) { - if (leftSize > TElement.Zero && rightSize > TElement.Zero) - { - TElement replacement; - if ((leftSize) > rightSize) - { - replacement = GetRightest(left); - DetachCore(ref left, replacement); - } - else - { - replacement = GetLeftest(right); - DetachCore(ref right, replacement); - } - SetLeft(replacement, left); - SetRight(replacement, right); - SetSize(replacement, (leftSize + rightSize)); - root = replacement; - } - else if (leftSize > TElement.Zero) - { - root = left; - } - else if (rightSize > TElement.Zero) - { - root = right; - } - else + goLeft = false; + } + else if (current != node) + { + throw new InvalidOperationException("Duplicate link found in the tree."); + } + else + { + break; + } + // The other subtree may become too heavy when this one shrinks. + PushPath(new Step(parent, isLeft, !goLeft)); + parent = current; + isLeft = goLeft; + } + // Sizes are decremented only after the node is found, so a failed search leaves the tree intact. + for (var i = 0; i < _pathLength; i++) + { + DecrementSize(Position(ref root, _path[i].Parent, _path[i].IsLeft)); + } + var ancestors = _pathLength; + // The node itself and, if it has two children, its replacement. + var passed = ancestors + 1; + var left = GetLeft(node); + var right = GetRight(node); + if (left != TElement.Zero && right != TElement.Zero) + { + // Replace the node with its neighbour from the larger subtree, so that the smaller subtree does not shrink. + var fromLeft = GetSize(left) > GetSize(right); + var replacementParent = node; + var replacementIsLeft = fromLeft; + var replacement = fromLeft ? left : right; + while (true) + { + var next = fromLeft ? GetRight(replacement) : GetLeft(replacement); + if (next == TElement.Zero) { - root = TElement.Zero; + break; } - ClearNode(node); - return; + DecrementSize(replacement); + PushPath(new Step(replacementParent, replacementIsLeft, fromLeft)); + replacementParent = replacement; + replacementIsLeft = !fromLeft; + replacement = next; + } + passed = _pathLength + 2; + Position(ref root, replacementParent, replacementIsLeft) = fromLeft ? GetLeft(replacement) : GetRight(replacement); + MaintainPath(ref root, ancestors); + SetLeft(replacement, GetLeft(node)); + SetRight(replacement, GetRight(node)); + SetSize(replacement, GetSize(node) - TElement.One); + Position(ref root, parent, isLeft) = replacement; + ClearNode(node); + Maintain(ref root, new Step(parent, isLeft, !fromLeft)); + } + else + { + Position(ref root, parent, isLeft) = left != TElement.Zero ? left : right; + ClearNode(node); + } + MaintainPath(ref root, 0); + RebuildIfDeeperThanBalanced(ref root, passed, size); + } + + /// + /// + /// Rebuilds the tree if the path of an operation passed more nodes than any size balanced tree of the size before the operation has levels. + /// Only trees built by other code, for example by older versions of this class, have such paths. + /// + /// + /// Перестраивает дерево, если путь операции прошёл больше узлов, чем уровней в любом дереве, сбалансированном по размеру, с размером до операции. + /// Такие пути есть только у деревьев, построенных другим кодом, например старыми версиями этого класса. + /// + /// + private void RebuildIfDeeperThanBalanced(ref TElement root, int passed, TElement size) + { + if (passed > GetMaximumBalancedHeight(size)) + { + RebuildComplete(ref root); + } + } + + /// + /// Returns the reference to the specified position: the root reference or the child reference of the parent. + /// Возвращает ссылку на указанную позицию: ссылку на корень или ссылку на потомка родителя. + /// + private ref TElement Position(ref TElement root, TElement parent, bool isLeft) + { + if (parent == TElement.Zero) + { + return ref root; + } + return ref isLeft ? ref GetLeftReference(parent) : ref GetRightReference(parent); + } + + private void PushPath(Step step) + { + if (_pathLength == _path.Length) + { + Array.Resize(ref _path, _path.Length * 2); + } + _path[_pathLength++] = step; + } + + /// + /// Maintains the positions of the path from the deepest one up to (but not including) the specified path length. + /// Поддерживает позиции пути, начиная с самой глубокой и до указанной длины пути (не включая её). + /// + private void MaintainPath(ref TElement root, int length) + { + while (_pathLength > length) + { + Maintain(ref root, _path[--_pathLength]); + } + } + + /// + /// + /// Restores the size balanced tree properties at the position (Maintain in the paper). + /// The pending steps run in the same order as the recursive calls of . + /// + /// + /// Восстанавливает свойства дерева, сбалансированного по размеру, в позиции (Maintain в статье). + /// Отложенные шаги выполняются в том же порядке, что и рекурсивные вызовы в . + /// + /// + private void Maintain(ref TElement root, Step step) + { + var count = 0; + _maintenance[count++] = step; + while (count > 0) + { + step = _maintenance[--count]; + ref var position = ref Position(ref root, step.Parent, step.IsLeft); + if (!Rotate(ref position, step.LeftMayBeHeavy)) + { + continue; + } + if (count + 4 > _maintenance.Length) + { + Array.Resize(ref _maintenance, _maintenance.Length * 2); } + var top = position; + // Pushed in reverse order: maintain the left child, then the right child, then the position for each side. + _maintenance[count++] = step with { LeftMayBeHeavy = true }; + _maintenance[count++] = step with { LeftMayBeHeavy = false }; + _maintenance[count++] = new Step(top, false, false); + _maintenance[count++] = new Step(top, true, true); + } + } + + /// + /// Rotates the subtree at the position if the specified side is too heavy. + /// Поворачивает поддерево в позиции, если указанная сторона слишком тяжёлая. + /// + /// + /// Whether the subtree was rotated. + /// Было ли поддерево повёрнуто. + /// + private bool Rotate(ref TElement root, bool leftMayBeHeavy) + { + if (root == TElement.Zero) + { + return false; + } + if (leftMayBeHeavy) + { + var left = GetLeft(root); + if (left == TElement.Zero) + { + return false; + } + var rightSize = GetSizeOrZero(GetRight(root)); + var leftLeft = GetLeft(left); + if (leftLeft != TElement.Zero && GetSize(leftLeft) > rightSize) + { + RightRotate(ref root); + return true; + } + var leftRight = GetRight(left); + if (leftRight != TElement.Zero && GetSize(leftRight) > rightSize) + { + LeftRotate(ref GetLeftReference(root)); + RightRotate(ref root); + return true; + } + return false; + } + var right = GetRight(root); + if (right == TElement.Zero) + { + return false; + } + var leftSize = GetSizeOrZero(GetLeft(root)); + var rightRight = GetRight(right); + if (rightRight != TElement.Zero && GetSize(rightRight) > leftSize) + { + LeftRotate(ref root); + return true; + } + var rightLeft = GetLeft(right); + if (rightLeft != TElement.Zero && GetSize(rightLeft) > leftSize) + { + RightRotate(ref GetRightReference(root)); + LeftRotate(ref root); + return true; } + return false; } } } diff --git a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs index 8253647..8c41731 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs @@ -7,155 +7,182 @@ namespace Platform.Collections.Methods.Trees { /// /// - /// Represents the size balanced tree methods. + /// Represents the size balanced tree methods (Chen Qifeng, "Size Balanced Tree", 2007). + /// + /// + /// Представляет методы дерева, сбалансированного по размеру (Чэнь Цифэн, «Size Balanced Tree», 2007). /// - /// /// + /// + /// + /// Every node t keeps the size balanced tree properties: each child subtree of t is at least as large as both subtrees of its sibling, + /// size(t.left) ≥ size(t.right.left), size(t.right.right) and size(t.right) ≥ size(t.left.left), size(t.left.right). + /// Such a tree with n nodes is at most about 1.44 · log2(n) levels high, the same bound as an AVL tree. + /// Only subtree sizes are used for balancing. + /// + /// + /// Every attach and every detach restores the properties with Maintain on each node of the changed path, from the bottom up. + /// Maintain checks one side of a node with two size comparisons and rotates only when that side became too heavy. + /// The amortized number of rotations per operation is constant. + /// + /// /// + /// public abstract class SizeBalancedTreeMethods : SizedBinaryTreeMethodsBase where TElement: IUnsignedNumber, IComparisonOperators { - protected int attachCount = 0; - const int maintainThreashold = 1; - - protected override void BeforeAttach() - { - attachCount++; - } - /// /// - /// Attaches the core using the specified root. + /// Attaches the node to the subtree with the specified root and restores the size balanced tree properties on the way back up. + /// + /// + /// Присоединяет узел к поддереву с указанным корнем и восстанавливает свойства дерева, сбалансированного по размеру, на обратном пути. /// - /// /// /// - /// The root. - /// + /// The reference to the root of the subtree. + /// Ссылка на корень поддерева. /// /// - /// The node. - /// + /// The node to attach. + /// Присоединяемый узел. /// protected override void AttachCore(ref TElement root, TElement node) + { + var size = GetSizeOrZero(root); + if (AttachCounting(ref root, node) > GetMaximumBalancedHeight(size)) + { + // The path was longer than in any size balanced tree, so the tree was built by other code. + RebuildComplete(ref root); + } + } + + /// The number of nodes of the tree that the path passed before the node was attached. + private int AttachCounting(ref TElement root, TElement node) { if (root == TElement.Zero) { + SetSize(node, TElement.One); root = node; - IncrementSize(root); + return 0; } - else + IncrementSize(root); + int passed; + if (FirstIsToTheLeftOfSecond(node, root)) { - IncrementSize(root); - if (FirstIsToTheLeftOfSecond(node, root)) - { - AttachCore(ref GetLeftReference(root), node); - if (attachCount > maintainThreashold) - { - LeftMaintain(ref root); - } - } - else - { - AttachCore(ref GetRightReference(root), node); - if (attachCount > maintainThreashold) - { - RightMaintain(ref root); - } - } + passed = AttachCounting(ref GetLeftReference(root), node); + LeftMaintain(ref root); } - } - - protected override void AfterAttach() - { - if (attachCount > maintainThreashold) + else { - attachCount = 0; + passed = AttachCounting(ref GetRightReference(root), node); + RightMaintain(ref root); } + return passed + 1; } /// /// - /// Detaches the core using the specified root. + /// Detaches the node from the subtree with the specified root and restores the size balanced tree properties on the way back up. + /// + /// + /// Отсоединяет узел от поддерева с указанным корнем и восстанавливает свойства дерева, сбалансированного по размеру, на обратном пути. /// - /// /// /// - /// The root. - /// + /// The reference to the root of the subtree. + /// Ссылка на корень поддерева. /// - /// + /// /// The node to detach. - /// + /// Отсоединяемый узел. /// /// - /// Duplicate link found in the tree. - /// + /// The node is not in the tree, or another node has the same key. + /// Узла нет в дереве, или другой узел имеет такой же ключ. /// - protected override void DetachCore(ref TElement root, TElement nodeToDetach) + protected override void DetachCore(ref TElement root, TElement node) { - ref var currentNode = ref root; - ref var parent = ref root; - var replacementNode = TElement.Zero; - while (currentNode != nodeToDetach) - { - DecrementSize(currentNode); - if (FirstIsToTheLeftOfSecond(nodeToDetach, currentNode)) - { - parent = ref currentNode; - currentNode = ref GetLeftReference(currentNode); - } - else if (FirstIsToTheRightOfSecond(nodeToDetach, currentNode)) - { - parent = ref currentNode; - currentNode = ref GetRightReference(currentNode); - } - else - { - throw new InvalidOperationException("Duplicate link found in the tree."); - } - } - var nodeToDetachLeft = GetLeft(nodeToDetach); - var node = GetRight(nodeToDetach); - if (nodeToDetachLeft != TElement.Zero && node != TElement.Zero) + var size = GetSizeOrZero(root); + if (DetachCounting(ref root, node) > GetMaximumBalancedHeight(size)) { - var leftestNode = GetLeftest(node); - DetachCore(ref GetRightReference(nodeToDetach), leftestNode); - SetLeft(leftestNode, nodeToDetachLeft); - node = GetRight(nodeToDetach); - if (node != TElement.Zero) - { - SetRight(leftestNode, node); - SetSize(leftestNode, ((GetSize(nodeToDetachLeft) + GetSize(node))) + TElement.One); - } - else - { - SetSize(leftestNode, (GetSize(nodeToDetachLeft)) + TElement.One); - } - replacementNode = leftestNode; + // The path was longer than in any size balanced tree, so the tree was built by other code. + RebuildComplete(ref root); } - else if (nodeToDetachLeft != TElement.Zero) + } + + /// The number of nodes that the paths to the node and to its replacement passed. + private int DetachCounting(ref TElement root, TElement node) + { + if (root == TElement.Zero) { - replacementNode = nodeToDetachLeft; + throw new InvalidOperationException($"The node {node} is not in the tree."); } - else if (node != TElement.Zero) + if (FirstIsToTheLeftOfSecond(node, root)) { - replacementNode = node; + var passed = DetachCounting(ref GetLeftReference(root), node); + DecrementSize(root); + // The left subtree became smaller, so the right one may become too heavy. + RightMaintain(ref root); + return passed + 1; } - if (root == nodeToDetach) + if (FirstIsToTheRightOfSecond(node, root)) { - root = replacementNode; + var passed = DetachCounting(ref GetRightReference(root), node); + DecrementSize(root); + // The right subtree became smaller, so the left one may become too heavy. + LeftMaintain(ref root); + return passed + 1; } - else if ((GetLeft(parent) == nodeToDetach)) + if (root != node) { - SetLeft(parent, replacementNode); + throw new InvalidOperationException("Duplicate link found in the tree."); } - else if ((GetRight(parent) == nodeToDetach)) + var left = GetLeft(node); + var right = GetRight(node); + if (left != TElement.Zero && right != TElement.Zero) { - SetRight(parent, replacementNode); + // Replace the node with its neighbour from the larger subtree, so that the smaller subtree does not shrink. + TElement replacement; + int passed; + var fromLeft = GetSize(left) > GetSize(right); + if (fromLeft) + { + replacement = GetRightest(left); + passed = DetachCounting(ref GetLeftReference(node), replacement); + } + else + { + replacement = GetLeftest(right); + passed = DetachCounting(ref GetRightReference(node), replacement); + } + SetLeft(replacement, GetLeft(node)); + SetRight(replacement, GetRight(node)); + SetSize(replacement, GetSize(node) - TElement.One); + root = replacement; + ClearNode(node); + if (fromLeft) + { + RightMaintain(ref root); + } + else + { + LeftMaintain(ref root); + } + return passed + 1; } - ClearNode(nodeToDetach); + root = left != TElement.Zero ? left : right; + ClearNode(node); + return 1; } + /// + /// + /// Restores the size balanced tree properties of the subtree when its left side may have become too heavy (Maintain(t, false) in the paper). + /// + /// + /// Восстанавливает свойства дерева, сбалансированного по размеру, когда его левая сторона могла стать слишком тяжёлой (Maintain(t, false) в статье). + /// + /// private void LeftMaintain(ref TElement root) { if (root != TElement.Zero) @@ -164,18 +191,16 @@ private void LeftMaintain(ref TElement root) if (rootLeftNode != TElement.Zero) { var rootRightNode = GetRight(root); - var rootRightNodeSize = GetSize(rootRightNode); + var rootRightNodeSize = GetSizeOrZero(rootRightNode); var rootLeftNodeLeftNode = GetLeft(rootLeftNode); - if (rootLeftNodeLeftNode != TElement.Zero && - (rootRightNode == TElement.Zero || (GetSize(rootLeftNodeLeftNode)) > rootRightNodeSize)) + if (rootLeftNodeLeftNode != TElement.Zero && GetSize(rootLeftNodeLeftNode) > rootRightNodeSize) { RightRotate(ref root); } else { var rootLeftNodeRightNode = GetRight(rootLeftNode); - if (rootLeftNodeRightNode != TElement.Zero && - (rootRightNode == TElement.Zero || (GetSize(rootLeftNodeRightNode)) > rootRightNodeSize)) + if (rootLeftNodeRightNode != TElement.Zero && GetSize(rootLeftNodeRightNode) > rootRightNodeSize) { LeftRotate(ref GetLeftReference(root)); RightRotate(ref root); @@ -193,6 +218,14 @@ private void LeftMaintain(ref TElement root) } } + /// + /// + /// Restores the size balanced tree properties of the subtree when its right side may have become too heavy (Maintain(t, true) in the paper). + /// + /// + /// Восстанавливает свойства дерева, сбалансированного по размеру, когда его правая сторона могла стать слишком тяжёлой (Maintain(t, true) в статье). + /// + /// private void RightMaintain(ref TElement root) { if (root != TElement.Zero) @@ -201,18 +234,16 @@ private void RightMaintain(ref TElement root) if (rootRightNode != TElement.Zero) { var rootLeftNode = GetLeft(root); - var rootLeftNodeSize = GetSize(rootLeftNode); + var rootLeftNodeSize = GetSizeOrZero(rootLeftNode); var rootRightNodeRightNode = GetRight(rootRightNode); - if (rootRightNodeRightNode != TElement.Zero && - (rootLeftNode == TElement.Zero || (GetSize(rootRightNodeRightNode)) > rootLeftNodeSize)) + if (rootRightNodeRightNode != TElement.Zero && GetSize(rootRightNodeRightNode) > rootLeftNodeSize) { LeftRotate(ref root); } else { var rootRightNodeLeftNode = GetLeft(rootRightNode); - if (rootRightNodeLeftNode != TElement.Zero && - (rootLeftNode == TElement.Zero || (GetSize(rootRightNodeLeftNode)) > rootLeftNodeSize)) + if (rootRightNodeLeftNode != TElement.Zero && GetSize(rootRightNodeLeftNode) > rootLeftNodeSize) { RightRotate(ref GetRightReference(root)); LeftRotate(ref root); diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index bdf5e30..795fe61 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -681,6 +681,109 @@ public void Detach(ref TElement root, TElement node) /// protected abstract void DetachCore(ref TElement root, TElement node); + /// + /// + /// Returns the largest number of levels that a size balanced tree or an AVL tree with the specified number of nodes can have. + /// + /// + /// Возвращает наибольшее число уровней, которое может иметь дерево, сбалансированное по размеру, или АВЛ-дерево с указанным числом узлов. + /// + /// + /// + /// The number of nodes. + /// Число узлов. + /// + /// + /// The largest height, about 1.44 · log2(size). + /// Наибольшая высота, примерно 1.44 · log2(size). + /// + /// + /// + /// The sparsest tree of either kind with h levels has m(h) = m(h - 1) + m(h - 2) + 1 nodes, where m(0) = 0 and m(1) = 1. + /// + /// + /// Самое разреженное дерево любого из этих видов с h уровнями имеет m(h) = m(h - 1) + m(h - 2) + 1 узлов, где m(0) = 0 и m(1) = 1. + /// + /// + public static int GetMaximumBalancedHeight(TElement size) + { + var count = ulong.CreateSaturating(size); + var height = 0; + ulong previous = 0, current = 1; + while (current <= count) + { + height++; + if (current > ulong.MaxValue - previous - 1) + { + break; + } + (previous, current) = (current, current + previous + 1); + } + return height; + } + + /// + /// + /// Rebuilds the subtree into a complete binary tree with rotations only (Day–Stout–Warren), in linear time and without extra memory. + /// + /// + /// Перестраивает поддерево в полное двоичное дерево только поворотами (Дэй–Стаут–Уоррен) за линейное время и без дополнительной памяти. + /// + /// + /// + /// The reference to the root of the subtree. + /// Ссылка на корень поддерева. + /// + /// + /// + /// The last level is filled from the left, so the result is also a size balanced tree. + /// Only for trees whose nodes keep just the left child, the right child and the size (not for threaded trees). + /// + /// + /// Последний уровень заполняется слева, поэтому результат также является деревом, сбалансированным по размеру. + /// Только для деревьев, узлы которых хранят лишь левого потомка, правого потомка и размер (не для прошитых деревьев). + /// + /// + protected void RebuildComplete(ref TElement root) + { + if (root == TElement.Zero) + { + return; + } + // Turn the tree into a vine: a path of right children in key order. + ref var position = ref root; + while (position != TElement.Zero) + { + if (GetLeft(position) != TElement.Zero) + { + RightRotate(ref position); + } + else + { + position = ref GetRightReference(position); + } + } + // Fold the vine: first the nodes of the incomplete last level, then halve the rest until one node is left. + var size = ulong.CreateTruncating(GetSize(root)); + var lastLevel = size + 1 - (1UL << BitOperations.Log2(size + 1)); + Fold(ref root, lastLevel); + for (var vine = size - lastLevel; vine > 1; ) + { + vine /= 2; + Fold(ref root, vine); + } + } + + private void Fold(ref TElement root, ulong rotations) + { + ref var position = ref root; + for (ulong i = 0; i < rotations; i++) + { + LeftRotate(ref position); + position = ref GetRightReference(position); + } + } + /// /// /// Fixes the sizes using the specified node. From 61c18c60815932e466ca8a3a345f1c9aa9690a4f Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 08:01:35 +0000 Subject: [PATCH 02/46] Keep C++ size balanced trees within the AVL height bound Run Maintain after every detach in SizeBalancedTreeMethods and replace the RecursionlessSizeBalancedTreeMethods heuristic with Chen's algorithm using explicit stacks, matching the C# implementation. Add balance tests that check the height bound and the size balanced property. Refs #115, linksplatform/Data.Doublets#577 --- .../AllTests.cpp | 1 + .../RecursionlessSizeBalancedTree.cpp | 17 + .../SizeBalancedTree.cpp | 17 + .../SizedAndThreadedAVLBalancedTree.cpp | 6 + .../TreeBalanceTests.cpp | 306 +++++++++++++++ .../Trees.h | 4 + .../Platform.Collections.Methods.h | 3 + .../RecursionlessSizeBalancedTreeMethods.h | 362 ++++++++++-------- .../Trees/SizeBalancedTreeMethods.h | 163 ++++---- .../Trees/SizedBinaryTreeMethodsBase.h | 76 ++++ 10 files changed, 725 insertions(+), 230 deletions(-) create mode 100644 cpp/Platform.Collections.Methods.Tests/TreeBalanceTests.cpp diff --git a/cpp/Platform.Collections.Methods.Tests/AllTests.cpp b/cpp/Platform.Collections.Methods.Tests/AllTests.cpp index b43cca9..064810d 100644 --- a/cpp/Platform.Collections.Methods.Tests/AllTests.cpp +++ b/cpp/Platform.Collections.Methods.Tests/AllTests.cpp @@ -2,3 +2,4 @@ #include #include "Trees.h" #include "TreesTests.cpp" +#include "TreeBalanceTests.cpp" diff --git a/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp b/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp index 88ad8cc..a71a0ea 100644 --- a/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp +++ b/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp @@ -21,6 +21,23 @@ public: TElement Count() { return this->GetSizeOrZero(Root); } + public: TElement LeftOf(TElement node) { return this->GetLeftOrDefault(node); } + + public: TElement RightOf(TElement node) { return this->GetRightOrDefault(node); } + + public: TElement SizeOf(TElement node) { return this->GetSizeOrZero(node); } + + /// + /// Writes a node directly, so that tests can build trees that other code could have built. + /// Записывает узел напрямую, чтобы тесты могли строить деревья, которые мог построить другой код. + /// + public: void SetNode(TElement node, TElement left, TElement right, TElement size) + { + this->SetLeft(node, left); + this->SetRight(node, right); + this->SetSize(node, size); + } + public: RecursionlessSizeBalancedTree() { _allocated = 1; } public: TElement Allocate() diff --git a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp index 019344c..5916ea8 100644 --- a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp +++ b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp @@ -21,6 +21,23 @@ public: TElement Count() { return this->GetSizeOrZero(Root); } + public: TElement LeftOf(TElement node) { return this->GetLeftOrDefault(node); } + + public: TElement RightOf(TElement node) { return this->GetRightOrDefault(node); } + + public: TElement SizeOf(TElement node) { return this->GetSizeOrZero(node); } + + /// + /// Writes a node directly, so that tests can build trees that other code could have built. + /// Записывает узел напрямую, чтобы тесты могли строить деревья, которые мог построить другой код. + /// + public: void SetNode(TElement node, TElement left, TElement right, TElement size) + { + this->SetLeft(node, left); + this->SetRight(node, right); + this->SetSize(node, size); + } + public: SizeBalancedTree() { _allocated = 1; } public: TElement Allocate() diff --git a/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp b/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp index 0dd3f83..35de2d6 100644 --- a/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp +++ b/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp @@ -24,6 +24,12 @@ public: TElement Count() { return this->GetSizeOrZero(Root); } + public: TElement LeftOf(TElement node) { return node != 0 && this->GetLeftIsChild(node) ? this->GetLeft(node) : 0; } + + public: TElement RightOf(TElement node) { return node != 0 && this->GetRightIsChild(node) ? this->GetRight(node) : 0; } + + public: TElement SizeOf(TElement node) { return this->GetSizeOrZero(node); } + public: SizedAndThreadedAVLBalancedTree() { _allocated = 1; } public: TElement Allocate() diff --git a/cpp/Platform.Collections.Methods.Tests/TreeBalanceTests.cpp b/cpp/Platform.Collections.Methods.Tests/TreeBalanceTests.cpp new file mode 100644 index 0000000..dba0933 --- /dev/null +++ b/cpp/Platform.Collections.Methods.Tests/TreeBalanceTests.cpp @@ -0,0 +1,306 @@ +namespace Platform::Collections::Methods::Tests +{ + /// + /// Checks that every tree keeps a near-optimal height for workloads that used to degenerate size-balanced trees. + /// Проверяет, что каждое дерево сохраняет близкую к оптимальной высоту на нагрузках, которые раньше вырождали деревья, сбалансированные по размеру. + /// + namespace TreeBalance + { + inline constexpr std::uint32_t N = 2048; + inline constexpr std::size_t Capacity = (2 * N) + 2; + + /// + /// The largest number of levels that an AVL tree or a size balanced tree with the specified number of nodes can have. + /// Наибольшее число уровней, которое может иметь АВЛ-дерево или дерево, сбалансированное по размеру, с указанным числом узлов. + /// + /// + /// The sparsest tree of each kind with h levels has m(h) = m(h - 1) + m(h - 2) + 1 nodes, where m(1) = 1 and m(2) = 2, + /// so both kinds are at most about 1.44 * log2(n) levels high. + /// + inline int MaximumHeight(std::uint64_t count) + { + auto height = 0; + std::uint64_t previous = 0; + std::uint64_t current = 1; + while (current <= count) + { + height++; + auto next = current + previous + 1; + previous = current; + current = next; + } + return height; + } + + template int Height(TTree& tree, std::uint32_t node) + { + if (node == 0) + { + return 0; + } + return 1 + std::max(Height(tree, tree.LeftOf(node)), Height(tree, tree.RightOf(node))); + } + + /// + /// Checks the sizes and Chen's property: each child is at least as large as both children of its sibling. + /// Проверяет размеры и свойство Чена: каждый потомок не меньше обоих потомков своего брата. + /// + template std::uint32_t CheckSizeBalanced(TTree& tree, std::uint32_t node) + { + if (node == 0) + { + return 0; + } + auto left = tree.LeftOf(node); + auto right = tree.RightOf(node); + auto leftSize = CheckSizeBalanced(tree, left); + auto rightSize = CheckSizeBalanced(tree, right); + if (tree.SizeOf(node) != leftSize + rightSize + 1) + { + throw std::runtime_error("Node " + std::to_string(node) + " has a wrong size."); + } + if (leftSize < tree.SizeOf(tree.LeftOf(right)) || leftSize < tree.SizeOf(tree.RightOf(right)) + || rightSize < tree.SizeOf(tree.LeftOf(left)) || rightSize < tree.SizeOf(tree.RightOf(left))) + { + throw std::runtime_error("Node " + std::to_string(node) + " breaks the size balanced tree property."); + } + return leftSize + rightSize + 1; + } + + template void AssertBalanced(TTree& tree, bool sizeBalanced) + { + auto count = tree.Count(); + auto height = Height(tree, tree.Root); + auto limit = MaximumHeight(count); + ASSERT_LE(height, limit) << "height " << height << " exceeds " << limit << " for " << count << " nodes"; + if (sizeBalanced) + { + ASSERT_NO_THROW(CheckSizeBalanced(tree, tree.Root)); + } + } + + template std::string Shape(TTree& tree) + { + std::string shape = std::to_string(tree.Root); + for (std::uint32_t node = 1; node < Capacity; node++) + { + if (tree.SizeOf(node) != 0) + { + shape += " " + std::to_string(node) + ":" + std::to_string(tree.LeftOf(node)) + "," + std::to_string(tree.RightOf(node)) + "," + std::to_string(tree.SizeOf(node)); + } + } + return shape; + } + + inline std::vector Keys(const std::string& workload) + { + std::vector keys; + if (workload == "Ascending") + { + for (std::uint32_t i = 1; i <= N; i++) keys.push_back(i); + } + else if (workload == "Descending") + { + for (std::uint32_t i = N; i >= 1; i--) keys.push_back(i); + } + else if (workload == "Random") + { + for (std::uint32_t i = 1; i <= N; i++) keys.push_back(i); + std::mt19937 random(577); + std::shuffle(keys.begin(), keys.end(), random); + } + else if (workload == "InterleavedHotAndCold") + { + // The pattern of issue linksplatform/Data.Doublets#577: links that share one source + // ("hot" keys in one narrow range) are created alternately with unrelated links ("cold" keys). + for (std::uint32_t i = 1; i <= N; i++) + { + keys.push_back(i); + keys.push_back(N + i); + } + } + else if (workload == "InterleavedHotAndColdMirrored") + { + for (std::uint32_t i = N; i >= 1; i--) + { + keys.push_back(N + i); + keys.push_back(i); + } + } + else if (workload == "AlternatingEnds") + { + for (std::uint32_t i = 1; i <= N; i++) + { + keys.push_back(i); + keys.push_back((2 * N) + 1 - i); + } + } + return keys; + } + + inline const std::string Workloads[] = { "Ascending", "Descending", "Random", "InterleavedHotAndCold", "InterleavedHotAndColdMirrored", "AlternatingEnds" }; + + template void AttachKeepsHeightNearOptimal(bool sizeBalanced) + { + for (const auto& workload : Workloads) + { + SCOPED_TRACE(workload); + auto tree = std::make_unique(); + for (auto key : Keys(workload)) + { + tree->Attach(&tree->Root, key); + AssertBalanced(*tree, sizeBalanced); + if (::testing::Test::HasFatalFailure()) + { + return; + } + } + } + } + + template void DetachKeepsHeightNearOptimal(bool sizeBalanced) + { + auto tree = std::make_unique(); + for (std::uint32_t key = 1; key <= N; key++) + { + tree->Attach(&tree->Root, key); + } + // Removing one whole side shifts all the weight to the other side of the root. + for (std::uint32_t key = 1; key <= N - 8; key++) + { + tree->Detach(&tree->Root, key); + AssertBalanced(*tree, sizeBalanced); + if (::testing::Test::HasFatalFailure()) + { + return; + } + } + } + + template void RandomChurnKeepsHeightNearOptimal(bool sizeBalanced) + { + auto tree = std::make_unique(); + std::mt19937 random(577); + std::vector present; + std::vector absent; + for (std::uint32_t i = 1; i <= N; i++) absent.push_back(i); + for (std::uint32_t step = 0; step < 8 * N; step++) + { + // Bias towards growth in the first half and towards shrinking in the second half. + auto grow = present.empty() || (!absent.empty() && random() % 4 < (step < 4 * N ? 3u : 1u)); + auto& source = grow ? absent : present; + auto index = random() % source.size(); + auto key = source[index]; + source[index] = source.back(); + source.pop_back(); + if (grow) + { + tree->Attach(&tree->Root, key); + present.push_back(key); + } + else + { + tree->Detach(&tree->Root, key); + absent.push_back(key); + } + AssertBalanced(*tree, sizeBalanced); + if (::testing::Test::HasFatalFailure()) + { + return; + } + } + } + + /// + /// A tree built by other code (here a path of right children, as older versions could build) is rebuilt by the first operation that finds a too long path. + /// Дерево, построенное другим кодом (здесь путь из правых потомков, как могли строить старые версии), перестраивается первой операцией, нашедшей слишком длинный путь. + /// + template void TreesBuiltByOtherCodeAreRebuilt(bool attach) + { + for (std::uint32_t count = 1; count <= 200; count++) + { + SCOPED_TRACE(count); + auto tree = std::make_unique(); + for (std::uint32_t node = 1; node <= count; node++) + { + ASSERT_EQ(node, tree->Allocate()); + tree->SetNode(node, 0, node < count ? node + 1 : 0, count - node + 1); + } + tree->Root = 1; + if (attach) + { + tree->Attach(&tree->Root, count + 1); + } + else + { + tree->Detach(&tree->Root, count); + } + auto expected = attach ? count + 1 : count - 1; + ASSERT_EQ(expected, tree->Count()); + AssertBalanced(*tree, true); + for (std::uint32_t key = 1; key <= expected; key++) + { + ASSERT_TRUE(tree->Contains(key, tree->Root)); + } + } + } + + using SizeBalanced = SizeBalancedTree; + using RecursionlessSizeBalanced = RecursionlessSizeBalancedTree; + using AVL = SizedAndThreadedAVLBalancedTree; + } + + TEST(TreeBalanceTests, SizeBalancedTreeAttachKeepsHeightNearOptimal) { TreeBalance::AttachKeepsHeightNearOptimal(true); } + + TEST(TreeBalanceTests, RecursionlessSizeBalancedTreeAttachKeepsHeightNearOptimal) { TreeBalance::AttachKeepsHeightNearOptimal(true); } + + TEST(TreeBalanceTests, SizedAndThreadedAVLBalancedTreeAttachKeepsHeightNearOptimal) { TreeBalance::AttachKeepsHeightNearOptimal(false); } + + TEST(TreeBalanceTests, SizeBalancedTreeDetachKeepsHeightNearOptimal) { TreeBalance::DetachKeepsHeightNearOptimal(true); } + + TEST(TreeBalanceTests, RecursionlessSizeBalancedTreeDetachKeepsHeightNearOptimal) { TreeBalance::DetachKeepsHeightNearOptimal(true); } + + TEST(TreeBalanceTests, SizedAndThreadedAVLBalancedTreeDetachKeepsHeightNearOptimal) { TreeBalance::DetachKeepsHeightNearOptimal(false); } + + TEST(TreeBalanceTests, SizeBalancedTreeRandomChurnKeepsHeightNearOptimal) { TreeBalance::RandomChurnKeepsHeightNearOptimal(true); } + + TEST(TreeBalanceTests, RecursionlessSizeBalancedTreeRandomChurnKeepsHeightNearOptimal) { TreeBalance::RandomChurnKeepsHeightNearOptimal(true); } + + TEST(TreeBalanceTests, SizedAndThreadedAVLBalancedTreeRandomChurnKeepsHeightNearOptimal) { TreeBalance::RandomChurnKeepsHeightNearOptimal(false); } + + TEST(TreeBalanceTests, RecursiveAndRecursionlessTreesHaveTheSameShape) + { + auto recursive = std::make_unique(); + auto recursionless = std::make_unique(); + std::mt19937 random(592); + std::unordered_set present; + for (std::uint32_t step = 0; step < 8 * TreeBalance::N; step++) + { + std::uint32_t key = (random() % TreeBalance::N) + 1; + if (present.erase(key) != 0) + { + recursive->Detach(&recursive->Root, key); + recursionless->Detach(&recursionless->Root, key); + } + else + { + present.insert(key); + recursive->Attach(&recursive->Root, key); + recursionless->Attach(&recursionless->Root, key); + } + if (step % 64 == 0) + { + ASSERT_EQ(TreeBalance::Shape(*recursive), TreeBalance::Shape(*recursionless)) << "step " << step; + } + } + ASSERT_EQ(TreeBalance::Shape(*recursive), TreeBalance::Shape(*recursionless)); + } + + TEST(TreeBalanceTests, SizeBalancedTreeBuiltByOtherCodeIsRebuiltOnAttach) { TreeBalance::TreesBuiltByOtherCodeAreRebuilt(true); } + + TEST(TreeBalanceTests, SizeBalancedTreeBuiltByOtherCodeIsRebuiltOnDetach) { TreeBalance::TreesBuiltByOtherCodeAreRebuilt(false); } + + TEST(TreeBalanceTests, RecursionlessSizeBalancedTreeBuiltByOtherCodeIsRebuiltOnAttach) { TreeBalance::TreesBuiltByOtherCodeAreRebuilt(true); } + + TEST(TreeBalanceTests, RecursionlessSizeBalancedTreeBuiltByOtherCodeIsRebuiltOnDetach) { TreeBalance::TreesBuiltByOtherCodeAreRebuilt(false); } +} diff --git a/cpp/Platform.Collections.Methods.Tests/Trees.h b/cpp/Platform.Collections.Methods.Tests/Trees.h index 9fdcd87..4428365 100644 --- a/cpp/Platform.Collections.Methods.Tests/Trees.h +++ b/cpp/Platform.Collections.Methods.Tests/Trees.h @@ -1,6 +1,10 @@ #pragma once +#include #include +#include +#include +#include #include bool iszero(void* ptr, int bytes) diff --git a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h index ae82cef..23d0953 100644 --- a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h +++ b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h @@ -1,7 +1,10 @@ #pragma once +#include #include #include +#include +#include #include "Polymorph.h" diff --git a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h index a165bd0..b0c8565 100644 --- a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h @@ -7,189 +7,231 @@ using base = SizedBinaryTreeMethodsBase; friend base; + /// + /// A step of the path from the root: the parent (0 for the root position), the side of the child and the side that may become too heavy. + /// Шаг пути от корня: родитель (0 для позиции корня), сторона потомка и сторона, которая может стать слишком тяжёлой. + /// + private: struct Step + { + TElement Parent; + bool IsLeft; + bool LeftMayBeHeavy; + }; + + private: std::vector _path; + private: std::vector _maintenance; + + /// + /// The same algorithm as SizeBalancedTreeMethods, with explicit stacks instead of recursion, so both build trees of identical shape. + /// Тот же алгоритм, что и в SizeBalancedTreeMethods, но с явными стеками вместо рекурсии, поэтому оба строят деревья одинаковой формы. + /// protected: void AttachCore(TElement* root, TElement node) { + auto size = this->object().GetSizeOrZero(*root); + _path.clear(); + TElement parent = 0; + auto isLeft = false; + auto* current = root; + while (*current != 0) + { + this->object().IncrementSize(*current); + auto goLeft = this->object().FirstIsToTheLeftOfSecond(node, *current); + // The subtree that grows may become too heavy. + _path.push_back(Step{parent, isLeft, goLeft}); + parent = *current; + isLeft = goLeft; + current = goLeft ? this->object().GetLeftReference(*current) : this->object().GetRightReference(*current); + } + this->object().SetSize(node, 1); + *current = node; + auto passed = static_cast(_path.size()); + this->MaintainPath(root, 0); + this->RebuildIfDeeperThanBalanced(root, passed, size); + } + + protected: void DetachCore(TElement* root, TElement node) + { + auto size = this->object().GetSizeOrZero(*root); + _path.clear(); + TElement parent = 0; + auto isLeft = false; while (true) { - auto* left = this->object().GetLeftReference(*root); - auto leftSize = this->object().GetSizeOrZero(*left); - auto* right = this->object().GetRightReference(*root); - auto rightSize = this->object().GetSizeOrZero(*right); - if (this->object().FirstIsToTheLeftOfSecond(node, *root)) + auto current = *this->Position(root, parent, isLeft); + if (current == 0) { - if (*left == 0) - { - this->object().IncrementSize(*root); - this->object().SetSize(node, 1); - *left = node; - return; - } - if (this->object().FirstIsToTheLeftOfSecond(node, *left)) - { - if ((leftSize + 1) > rightSize) - { - this->object().RightRotate(root); - } - else - { - this->object().IncrementSize(*root); - root = left; - } - } - else - { - auto leftRightSize = this->object().GetSizeOrZero(this->object().GetRight(*left)); - if ((leftRightSize + 1) > rightSize) - { - if (leftRightSize == 0 && rightSize == 0) - { - this->object().SetLeft(node, *left); - this->object().SetRight(node, *root); - this->object().SetSize(node, leftSize + 2); - this->object().SetLeft(*root, 0); - this->object().SetSize(*root, 1); - *root = node; - return; - } - this->object().LeftRotate(left); - this->object().RightRotate(root); - } - else - { - this->object().IncrementSize(*root); - root = left; - } - } + throw std::runtime_error("The node is not in the tree."); + } + bool goLeft; + if (this->object().FirstIsToTheLeftOfSecond(node, current)) + { + goLeft = true; + } + else if (this->object().FirstIsToTheRightOfSecond(node, current)) + { + goLeft = false; + } + else if (current != node) + { + throw std::runtime_error("Duplicate link found in the tree."); } else { - if (*right == 0) - { - this->object().IncrementSize(*root); - this->object().SetSize(node, 1); - *right = node; - return; - } - if (this->object().FirstIsToTheRightOfSecond(node, *right)) - { - if ((rightSize + 1) > leftSize) - { - this->object().LeftRotate(root); - } - else - { - this->object().IncrementSize(*root); - root = right; - } - } - else + break; + } + // The other subtree may become too heavy when this one shrinks. + _path.push_back(Step{parent, isLeft, !goLeft}); + parent = current; + isLeft = goLeft; + } + // Sizes are decremented only after the node is found, so a failed search leaves the tree intact. + for (const auto& step : _path) + { + this->object().DecrementSize(*this->Position(root, step.Parent, step.IsLeft)); + } + auto ancestors = _path.size(); + // The node itself and, if it has two children, its replacement. + auto passed = static_cast(ancestors) + 1; + auto left = this->object().GetLeft(node); + auto right = this->object().GetRight(node); + if (left != 0 && right != 0) + { + // Replace the node with its neighbour from the larger subtree, so that the smaller subtree does not shrink. + auto fromLeft = this->object().GetSize(left) > this->object().GetSize(right); + auto replacementParent = node; + auto replacementIsLeft = fromLeft; + auto replacement = fromLeft ? left : right; + while (true) + { + auto next = fromLeft ? this->object().GetRight(replacement) : this->object().GetLeft(replacement); + if (next == 0) { - auto rightLeftSize = this->object().GetSizeOrZero(this->object().GetLeft(*right)); - if ((rightLeftSize + 1) > leftSize) - { - if (rightLeftSize == 0 && leftSize == 0) - { - this->object().SetLeft(node, *root); - this->object().SetRight(node, *right); - this->object().SetSize(node, rightSize + 2); - this->object().SetRight(*root, 0); - this->object().SetSize(*root, 1); - *root = node; - return; - } - this->object().RightRotate(right); - this->object().LeftRotate(root); - } - else - { - this->object().IncrementSize(*root); - root = right; - } + break; } + this->object().DecrementSize(replacement); + _path.push_back(Step{replacementParent, replacementIsLeft, fromLeft}); + replacementParent = replacement; + replacementIsLeft = !fromLeft; + replacement = next; } + passed = static_cast(_path.size()) + 2; + *this->Position(root, replacementParent, replacementIsLeft) = fromLeft ? this->object().GetLeft(replacement) : this->object().GetRight(replacement); + this->MaintainPath(root, ancestors); + this->object().SetLeft(replacement, this->object().GetLeft(node)); + this->object().SetRight(replacement, this->object().GetRight(node)); + this->object().SetSize(replacement, this->object().GetSize(node) - 1); + *this->Position(root, parent, isLeft) = replacement; + this->object().ClearNode(node); + this->Maintain(root, Step{parent, isLeft, !fromLeft}); + } + else + { + *this->Position(root, parent, isLeft) = left != 0 ? left : right; + this->object().ClearNode(node); } + this->MaintainPath(root, 0); + this->RebuildIfDeeperThanBalanced(root, passed, size); } - protected: void DetachCore(TElement* root, TElement node) + private: void RebuildIfDeeperThanBalanced(TElement* root, int passed, TElement size) { - while (true) + if (passed > base::GetMaximumBalancedHeight(size)) + { + // The path was longer than in any size balanced tree, so the tree was built by other code. + this->RebuildComplete(root); + } + } + + private: TElement* Position(TElement* root, TElement parent, bool isLeft) + { + if (parent == 0) + { + return root; + } + return isLeft ? this->object().GetLeftReference(parent) : this->object().GetRightReference(parent); + } + + private: void MaintainPath(TElement* root, std::size_t length) + { + while (_path.size() > length) { - auto* left = this->object().GetLeftReference(*root); - auto leftSize = this->object().GetSizeOrZero(*left); - auto* right = this->object().GetRightReference(*root); - auto rightSize = this->object().GetSizeOrZero(*right); - if (this->object().FirstIsToTheLeftOfSecond(node, *root)) + auto step = _path.back(); + _path.pop_back(); + this->Maintain(root, step); + } + } + + private: void Maintain(TElement* root, Step step) + { + _maintenance.clear(); + _maintenance.push_back(step); + while (!_maintenance.empty()) + { + step = _maintenance.back(); + _maintenance.pop_back(); + auto* position = this->Position(root, step.Parent, step.IsLeft); + if (!this->Rotate(position, step.LeftMayBeHeavy)) { - auto decrementedLeftSize = leftSize - 1; - if (this->object().GetSizeOrZero(this->object().GetRightOrDefault(*right)) > decrementedLeftSize) - { - this->object().LeftRotate(root); - } - else if (this->object().GetSizeOrZero(this->object().GetLeftOrDefault(*right)) > decrementedLeftSize) - { - this->object().RightRotate(right); - this->object().LeftRotate(root); - } - else - { - this->object().DecrementSize(*root); - root = left; - } + continue; } - else if (this->object().FirstIsToTheRightOfSecond(node, *root)) + auto top = *position; + // Pushed in reverse order: maintain the left child, then the right child, then the position for each side. + _maintenance.push_back(Step{step.Parent, step.IsLeft, true}); + _maintenance.push_back(Step{step.Parent, step.IsLeft, false}); + _maintenance.push_back(Step{top, false, false}); + _maintenance.push_back(Step{top, true, true}); + } + } + + private: bool Rotate(TElement* root, bool leftMayBeHeavy) + { + if (*root == 0) + { + return false; + } + if (leftMayBeHeavy) + { + auto left = this->object().GetLeft(*root); + if (left == 0) { - auto decrementedRightSize = rightSize - 1; - if (this->object().GetSizeOrZero(this->object().GetLeftOrDefault(*left)) > decrementedRightSize) - { - this->object().RightRotate(root); - } - else if (this->object().GetSizeOrZero(this->object().GetRightOrDefault(*left)) > decrementedRightSize) - { - this->object().LeftRotate(left); - this->object().RightRotate(root); - } - else - { - this->object().DecrementSize(*root); - root = right; - } + return false; } - else + auto rightSize = this->object().GetSizeOrZero(this->object().GetRight(*root)); + auto leftLeft = this->object().GetLeft(left); + if (leftLeft != 0 && this->object().GetSize(leftLeft) > rightSize) { - if (leftSize > 0 && rightSize > 0) - { - TElement replacement = 0; - if (leftSize > rightSize) - { - replacement = this->object().GetRightest(*left); - this->object().DetachCore(left, replacement); - } - else - { - replacement = this->object().GetLeftest(*right); - this->object().DetachCore(right, replacement); - } - this->object().SetLeft(replacement, *left); - this->object().SetRight(replacement, *right); - this->object().SetSize(replacement, leftSize + rightSize); - *root = replacement; - } - else if (leftSize > 0) - { - *root = *left; - } - else if (rightSize > 0) - { - *root = *right; - } - else - { - *root = 0; - } - this->object().ClearNode(node); - return; + this->object().RightRotate(root); + return true; } + auto leftRight = this->object().GetRight(left); + if (leftRight != 0 && this->object().GetSize(leftRight) > rightSize) + { + this->object().LeftRotate(this->object().GetLeftReference(*root)); + this->object().RightRotate(root); + return true; + } + return false; + } + auto right = this->object().GetRight(*root); + if (right == 0) + { + return false; + } + auto leftSize = this->object().GetSizeOrZero(this->object().GetLeft(*root)); + auto rightRight = this->object().GetRight(right); + if (rightRight != 0 && this->object().GetSize(rightRight) > leftSize) + { + this->object().LeftRotate(root); + return true; + } + auto rightLeft = this->object().GetLeft(right); + if (rightLeft != 0 && this->object().GetSize(rightLeft) > leftSize) + { + this->object().RightRotate(this->object().GetRightReference(*root)); + this->object().LeftRotate(root); + return true; } + return false; } }; } diff --git a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h index a192d2e..2f204ae 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h @@ -8,92 +8,115 @@ using base = SizedBinaryTreeMethodsBase; friend base; + /// + /// Chen's size balanced tree: every attach and detach restores the size balanced property with Maintain, so the height never exceeds GetMaximumBalancedHeight(size). If an operation passes more nodes than that bound, the tree was built by other code, so it is rebuilt once in linear time. + /// Дерево Чена, сбалансированное по размеру: каждое присоединение и отсоединение восстанавливает свойство баланса через Maintain, поэтому высота никогда не превышает GetMaximumBalancedHeight(size). Если операция проходит больше узлов, чем эта граница, дерево было построено другим кодом и один раз перестраивается за линейное время. + /// protected: void AttachCore(TElement* root, TElement node) + { + auto size = this->object().GetSizeOrZero(*root); + if (this->AttachCounting(root, node) > base::GetMaximumBalancedHeight(size)) + { + // The path was longer than in any size balanced tree, so the tree was built by other code. + this->RebuildComplete(root); + } + } + + private: int AttachCounting(TElement* root, TElement node) { if (*root == 0) { + this->object().SetSize(node, 1); *root = node; - this->object().IncrementSize(*root); + return 0; + } + this->object().IncrementSize(*root); + int passed; + if (this->object().FirstIsToTheLeftOfSecond(node, *root)) + { + passed = this->AttachCounting(this->object().GetLeftReference(*root), node); + this->LeftMaintain(root); } else { - this->object().IncrementSize(*root); - if (this->object().FirstIsToTheLeftOfSecond(node, *root)) - { - this->object().AttachCore(this->object().GetLeftReference(*root), node); - this->object().LeftMaintain(root); - } - else - { - this->object().AttachCore(this->object().GetRightReference(*root), node); - this->object().RightMaintain(root); - } + passed = this->AttachCounting(this->object().GetRightReference(*root), node); + this->RightMaintain(root); } + return passed + 1; } - protected: void DetachCore(TElement* root, TElement nodeToDetach) + protected: void DetachCore(TElement* root, TElement node) { - auto* currentNode = root; - auto* parent = root; - auto replacementNode = 0; - while (*currentNode != nodeToDetach) - { - this->object().DecrementSize(*currentNode); - if (this->object().FirstIsToTheLeftOfSecond(nodeToDetach, *currentNode)) - { - parent = currentNode; - currentNode = this->object().GetLeftReference(*currentNode); - } - else if (this->object().FirstIsToTheRightOfSecond(nodeToDetach, *currentNode)) - { - parent = currentNode; - currentNode = this->object().GetRightReference(*currentNode); - } - else - { - throw std::runtime_error("Duplicate link found in the tree."); - } - } - auto nodeToDetachLeft = this->object().GetLeft(nodeToDetach); - auto node = this->object().GetRight(nodeToDetach); - if (nodeToDetachLeft != 0 && node != 0) + auto size = this->object().GetSizeOrZero(*root); + if (this->DetachCounting(root, node) > base::GetMaximumBalancedHeight(size)) { - auto leftestNode = this->object().GetLeftest(node); - this->object().DetachCore(this->object().GetRightReference(nodeToDetach), leftestNode); - this->object().SetLeft(leftestNode, nodeToDetachLeft); - node = this->object().GetRight(nodeToDetach); - if (node != 0) - { - this->object().SetRight(leftestNode, node); - this->object().SetSize(leftestNode, (this->object().GetSize(nodeToDetachLeft) + this->object().GetSize(node)) + 1); - } - else - { - this->object().SetSize(leftestNode, this->object().GetSize(nodeToDetachLeft) + 1); - } - replacementNode = leftestNode; + // The path was longer than in any size balanced tree, so the tree was built by other code. + this->RebuildComplete(root); } - else if (nodeToDetachLeft != 0) + } + + private: int DetachCounting(TElement* root, TElement node) + { + if (*root == 0) { - replacementNode = nodeToDetachLeft; + throw std::runtime_error("The node is not in the tree."); } - else if (node != 0) + if (this->object().FirstIsToTheLeftOfSecond(node, *root)) { - replacementNode = node; + auto passed = this->DetachCounting(this->object().GetLeftReference(*root), node); + this->object().DecrementSize(*root); + // The left subtree became smaller, so the right one may become too heavy. + this->RightMaintain(root); + return passed + 1; } - if (*root == nodeToDetach) + if (this->object().FirstIsToTheRightOfSecond(node, *root)) { - *root = replacementNode; + auto passed = this->DetachCounting(this->object().GetRightReference(*root), node); + this->object().DecrementSize(*root); + // The right subtree became smaller, so the left one may become too heavy. + this->LeftMaintain(root); + return passed + 1; } - else if (this->object().GetLeft(*parent) == nodeToDetach) + if (*root != node) { - this->object().SetLeft(*parent, replacementNode); + throw std::runtime_error("Duplicate link found in the tree."); } - else if (this->object().GetRight(*parent) == nodeToDetach) + auto left = this->object().GetLeft(node); + auto right = this->object().GetRight(node); + if (left != 0 && right != 0) { - this->object().SetRight(*parent, replacementNode); + // Replace the node with its neighbour from the larger subtree, so that the smaller subtree does not shrink. + TElement replacement; + int passed; + auto fromLeft = this->object().GetSize(left) > this->object().GetSize(right); + if (fromLeft) + { + replacement = this->object().GetRightest(left); + passed = this->DetachCounting(this->object().GetLeftReference(node), replacement); + } + else + { + replacement = this->object().GetLeftest(right); + passed = this->DetachCounting(this->object().GetRightReference(node), replacement); + } + this->object().SetLeft(replacement, this->object().GetLeft(node)); + this->object().SetRight(replacement, this->object().GetRight(node)); + this->object().SetSize(replacement, this->object().GetSize(node) - 1); + *root = replacement; + this->object().ClearNode(node); + if (fromLeft) + { + this->RightMaintain(root); + } + else + { + this->LeftMaintain(root); + } + return passed + 1; } - this->object().ClearNode(nodeToDetach); + *root = left != 0 ? left : right; + this->object().ClearNode(node); + return 1; } private: void LeftMaintain(TElement* root) @@ -125,10 +148,10 @@ return; } } - this->object().LeftMaintain(this->object().GetLeftReference(*root)); - this->object().RightMaintain(this->object().GetRightReference(*root)); - this->object().LeftMaintain(root); - this->object().RightMaintain(root); + this->LeftMaintain(this->object().GetLeftReference(*root)); + this->RightMaintain(this->object().GetRightReference(*root)); + this->RightMaintain(root); + this->LeftMaintain(root); } } } @@ -162,10 +185,10 @@ return; } } - this->object().LeftMaintain(this->object().GetLeftReference(*root)); - this->object().RightMaintain(this->object().GetRightReference(*root)); - this->object().LeftMaintain(root); - this->object().RightMaintain(root); + this->LeftMaintain(this->object().GetLeftReference(*root)); + this->RightMaintain(this->object().GetRightReference(*root)); + this->RightMaintain(root); + this->LeftMaintain(root); } } } diff --git a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h index 22475b6..c37aba3 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h @@ -55,6 +55,82 @@ return left; } + /// + /// Returns the largest height that a size balanced tree with the given number of nodes can have. + /// Возвращает наибольшую высоту, которую может иметь дерево, сбалансированное по размеру, с заданным числом узлов. + /// + /// + /// The smallest size balanced tree of height h has m(h) = m(h - 1) + m(h - 2) + 1 nodes, the same bound as for AVL trees, so the height never exceeds about 1.44 * log2(n). + /// Наименьшее дерево, сбалансированное по размеру, высоты h содержит m(h) = m(h - 1) + m(h - 2) + 1 узлов, как и AVL-дерево, поэтому высота не превышает примерно 1.44 * log2(n). + /// + public: static int GetMaximumBalancedHeight(TElement size) + { + auto count = static_cast(size); + auto height = 0; + std::uint64_t previous = 0; + std::uint64_t current = 1; + while (current <= count) + { + height++; + if (current > UINT64_MAX - previous - 1) + { + break; + } + auto next = current + previous + 1; + previous = current; + current = next; + } + return height; + } + + /// + /// Rebuilds the tree into a complete tree in linear time with the Day-Stout-Warren algorithm, using only rotations. + /// Перестраивает дерево в полное за линейное время алгоритмом Day-Stout-Warren, используя только повороты. + /// + /// + /// The last level is filled from the left, so the result is also a size balanced tree. Not for threaded trees. + /// Последний уровень заполняется слева, поэтому результат также является деревом, сбалансированным по размеру. Не для прошитых деревьев. + /// + protected: void RebuildComplete(TElement* root) + { + if (*root == 0) + { + return; + } + // Turn the tree into a vine: a path of right children in key order. + auto* position = root; + while (*position != 0) + { + if (this->object().GetLeft(*position) != 0) + { + this->object().RightRotate(position); + } + else + { + position = this->object().GetRightReference(*position); + } + } + // Fold the vine: first the nodes of the incomplete last level, then halve the rest until one node is left. + auto size = static_cast(this->object().GetSize(*root)); + auto lastLevel = size + 1 - std::bit_floor(size + 1); + this->Fold(root, lastLevel); + for (auto vine = size - lastLevel; vine > 1; ) + { + vine /= 2; + this->Fold(root, vine); + } + } + + private: void Fold(TElement* root, std::uint64_t rotations) + { + auto* position = root; + for (std::uint64_t i = 0; i < rotations; i++) + { + this->object().LeftRotate(position); + position = this->object().GetRightReference(*position); + } + } + protected: TElement GetRightest(TElement current) { auto currentRight = this->object().GetRight(current); From 67713caf196ce0832c488c07e5c7da7a8778bc16 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 08:01:35 +0000 Subject: [PATCH 03/46] Release size balanced tree fix and test C# on pull requests Refs #115 --- .github/workflows/csharp.yml | 13 +++++++++++++ ...tform.Collections.Methods.TemplateLibrary.nuspec | 4 ++-- .../Platform.Collections.Methods.csproj | 4 ++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/.github/workflows/csharp.yml b/.github/workflows/csharp.yml index 19ce60a..572c8fb 100644 --- a/.github/workflows/csharp.yml +++ b/.github/workflows/csharp.yml @@ -6,6 +6,11 @@ on: paths: - 'csharp/**' - '.github/workflows/csharp.yml' + pull_request: + branches: main + paths: + - 'csharp/**' + - '.github/workflows/csharp.yml' env: NUGETTOKEN: ${{ secrets.NUGET_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -27,6 +32,8 @@ jobs: dotnet test -c Release -f net8 pushNuGetPackageToGitHubPackageRegistry: needs: test + # Publishing runs only for pushes to main; pull requests only run the tests. + if: ${{ github.event_name == 'push' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 @@ -42,6 +49,8 @@ jobs: pusnToNuget: runs-on: ubuntu-latest needs: test + # Publishing runs only for pushes to main; pull requests only run the tests. + if: ${{ github.event_name == 'push' }} steps: - uses: actions/checkout@v1 with: @@ -59,6 +68,8 @@ jobs: publiseRelease: runs-on: ubuntu-latest needs: test + # Publishing runs only for pushes to main; pull requests only run the tests. + if: ${{ github.event_name == 'push' }} steps: - uses: actions/checkout@v1 with: @@ -79,6 +90,8 @@ jobs: findChangedCsFiles: runs-on: ubuntu-latest needs: test + # Publishing runs only for pushes to main; pull requests only run the tests. + if: ${{ github.event_name == 'push' }} outputs: isCsFilesChanged: ${{ steps.setIsCsFilesChangedOutput.outputs.isCsFilesChanged }} steps: diff --git a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec index d405edf..7498ac5 100644 --- a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec +++ b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec @@ -5,8 +5,8 @@ LinksPlatform's Platform.Collections.Methods Template Library LinksPlatform's Platform.Collections.Methods is a Template Library what contains standard implementation of methods for collections. LinksPlatform's Platform.Collections.Methods is a Template Library what contains set of C++ classes templates to build custom implementations of collections on top of provided standard methods implementations. Use Platform.Collections.Methods.h file to include the library. - Updated build to conan 2.0 - 0.3.0 + Size balanced trees keep Chen's size balanced property on every attach and detach, so their height never exceeds the AVL bound; the recursionless variant now builds the same trees as the recursive one; trees built by older versions are rebuilt once in linear time. + 0.4.0 Konstantin Diachenko Konstantin Diachenko Konstantin Diachenko diff --git a/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj b/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj index 88ecffa..e72e47f 100644 --- a/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj +++ b/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj @@ -4,7 +4,7 @@ LinksPlatform's Platform.Collections.Methods Class Library Konstantin Diachenko Platform.Collections.Methods - 0.7.3 + 0.8.0 Konstantin Diachenko net8 Platform.Collections.Methods @@ -23,7 +23,7 @@ true snupkg latest - Update target framework from net7 to net8. + Size balanced trees keep Chen's size balanced property on every attach and detach, so their height never exceeds the AVL bound; the recursionless variant now builds the same trees as the recursive one; trees built by older versions are rebuilt once in linear time. enable From c334df5f715c923bd8323a4d073a8ccb27e08066 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 08:29:37 +0000 Subject: [PATCH 04/46] Address Codacy findings in the size balanced tree fix Brace single-statement loops and conditions in TreeBalanceTests, fold the vine with a while loop, and return the new root from RebuildComplete instead of taking it by reference. --- .../Trees/SizedBinaryTreeMethodsBase.h | 3 +- .../TreeBalanceTests.cs | 35 +++++++++++++++---- .../RecursionlessSizeBalancedTreeMethods.cs | 2 +- .../Trees/SizeBalancedTreeMethods.cs | 4 +-- .../Trees/SizedBinaryTreeMethodsBase.cs | 16 ++++++--- 5 files changed, 44 insertions(+), 16 deletions(-) diff --git a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h index c37aba3..e0f263f 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h @@ -114,7 +114,8 @@ auto size = static_cast(this->object().GetSize(*root)); auto lastLevel = size + 1 - std::bit_floor(size + 1); this->Fold(root, lastLevel); - for (auto vine = size - lastLevel; vine > 1; ) + auto vine = size - lastLevel; + while (vine > 1) { vine /= 2; this->Fold(root, vine); diff --git a/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs b/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs index 85d8f77..c957a05 100644 --- a/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs +++ b/csharp/Platform.Collections.Methods.Tests/TreeBalanceTests.cs @@ -173,14 +173,23 @@ private static IEnumerable Keys(string workload) switch (workload) { case "Ascending": - for (uint i = 1; i <= N; i++) yield return i; + for (uint i = 1; i <= N; i++) + { + yield return i; + } break; case "Descending": - for (uint i = N; i >= 1; i--) yield return i; + for (uint i = N; i >= 1; i--) + { + yield return i; + } break; case "Random": var random = new System.Random(577); - foreach (var key in Enumerable.Range(1, N).OrderBy(_ => random.Next())) yield return (uint)key; + foreach (var key in Enumerable.Range(1, N).OrderBy(_ => random.Next())) + { + yield return (uint)key; + } break; case "InterleavedHotAndCold": // The pattern of issue linksplatform/Data.Doublets#577: links that share one source @@ -317,8 +326,14 @@ private int HeightOf(uint node) { var left = _tree.LeftOf(current); var right = _tree.RightOf(current); - if (left != 0) next.Add(left); - if (right != 0) next.Add(right); + if (left != 0) + { + next.Add(left); + } + if (right != 0) + { + next.Add(right); + } } level = next; } @@ -341,8 +356,14 @@ private void AssertSizeBalanced(uint root) // Size balanced tree properties (Chen, 2007): each subtree is at least as large as both subtrees of its sibling. Assert.True(_tree.SizeOf(left) >= _tree.SizeOf(_tree.LeftOf(right)) && _tree.SizeOf(left) >= _tree.SizeOf(_tree.RightOf(right)), $"Node {node} breaks the size balanced tree property on its left side."); Assert.True(_tree.SizeOf(right) >= _tree.SizeOf(_tree.LeftOf(left)) && _tree.SizeOf(right) >= _tree.SizeOf(_tree.RightOf(left)), $"Node {node} breaks the size balanced tree property on its right side."); - if (left != 0) stack.Push(left); - if (right != 0) stack.Push(right); + if (left != 0) + { + stack.Push(left); + } + if (right != 0) + { + stack.Push(right); + } } } } diff --git a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs index 993e45f..a739155 100644 --- a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs @@ -214,7 +214,7 @@ private void RebuildIfDeeperThanBalanced(ref TElement root, int passed, TElement { if (passed > GetMaximumBalancedHeight(size)) { - RebuildComplete(ref root); + root = RebuildComplete(root); } } diff --git a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs index 8c41731..b31053e 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs @@ -52,7 +52,7 @@ protected override void AttachCore(ref TElement root, TElement node) if (AttachCounting(ref root, node) > GetMaximumBalancedHeight(size)) { // The path was longer than in any size balanced tree, so the tree was built by other code. - RebuildComplete(ref root); + root = RebuildComplete(root); } } @@ -106,7 +106,7 @@ protected override void DetachCore(ref TElement root, TElement node) if (DetachCounting(ref root, node) > GetMaximumBalancedHeight(size)) { // The path was longer than in any size balanced tree, so the tree was built by other code. - RebuildComplete(ref root); + root = RebuildComplete(root); } } diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index 795fe61..f72c5d2 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -731,9 +731,13 @@ public static int GetMaximumBalancedHeight(TElement size) /// /// /// - /// The reference to the root of the subtree. - /// Ссылка на корень поддерева. + /// The root of the subtree. + /// Корень поддерева. /// + /// + /// The new root of the subtree. + /// Новый корень поддерева. + /// /// /// /// The last level is filled from the left, so the result is also a size balanced tree. @@ -744,11 +748,11 @@ public static int GetMaximumBalancedHeight(TElement size) /// Только для деревьев, узлы которых хранят лишь левого потомка, правого потомка и размер (не для прошитых деревьев). /// /// - protected void RebuildComplete(ref TElement root) + protected TElement RebuildComplete(TElement root) { if (root == TElement.Zero) { - return; + return root; } // Turn the tree into a vine: a path of right children in key order. ref var position = ref root; @@ -767,11 +771,13 @@ protected void RebuildComplete(ref TElement root) var size = ulong.CreateTruncating(GetSize(root)); var lastLevel = size + 1 - (1UL << BitOperations.Log2(size + 1)); Fold(ref root, lastLevel); - for (var vine = size - lastLevel; vine > 1; ) + var vine = size - lastLevel; + while (vine > 1) { vine /= 2; Fold(ref root, vine); } + return root; } private void Fold(ref TElement root, ulong rotations) From 6743b4ba1b9782a882068d70d6ff36bf54e86a3e Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 09:37:43 +0000 Subject: [PATCH 05/46] Maintain C# recursionless attach paths by the direction of the attach The recursionless size balanced tree remembers which way the attach went at every node, so on the way back up it compares only the grandchild that grew until a rotation changes the children. This gives the same rotations as Chen's Maintain with half of the size comparisons. Rotations are virtual so tests can count them, and the debug validation code compiles and checks the right sizes. --- .../RecursionlessSizeBalancedTreeMethods.cs | 158 ++++++++++++++++-- .../Trees/SizedBinaryTreeMethodsBase.cs | 34 ++-- 2 files changed, 160 insertions(+), 32 deletions(-) diff --git a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs index a739155..4763259 100644 --- a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs @@ -17,6 +17,8 @@ namespace Platform.Collections.Methods.Trees /// /// The algorithm is the same as in and builds the same trees. /// The path from the root and the pending Maintain steps are kept in explicit stacks instead of the call stack. + /// An attach also remembers the direction it took at every node of the path, so on the way back up it compares only the size of the grandchild that grew, + /// until a rotation changes the children (see MaintainAttachPath). /// /// /// A position in the tree is stored as its parent and the side of the parent, because a rotation replaces the node at a position but not the position itself. @@ -92,7 +94,7 @@ protected override void AttachCore(ref TElement root, TElement node) SetSize(node, TElement.One); current = node; var passed = _pathLength; - MaintainPath(ref root, 0); + MaintainAttachPath(ref root); RebuildIfDeeperThanBalanced(ref root, passed, size); } @@ -252,55 +254,179 @@ private void MaintainPath(ref TElement root, int length) } } + /// + /// + /// Maintains the path of an attach from the deepest position up to the root, using the directions that the attach took. + /// + /// + /// Поддерживает путь присоединения от самой глубокой позиции до корня, используя направления, по которым шло присоединение. + /// + /// + /// + /// + /// Before the attach the tree was size balanced, and the attach made only one grandchild of each position on the path larger: the one on the path. + /// So while the child on the path has not been rotated, Maintain in the paper can rotate only because of that grandchild, + /// and checking only it gives the same rotations with half of the size comparisons. + /// After a rotation of the child its children are other nodes, so the position is checked fully. + /// The parent of the attached node is skipped: the attached node has no children, so it cannot be too heavy there. + /// + /// + /// До присоединения дерево было сбалансировано по размеру, а присоединение увеличило только одного внука каждой позиции пути: того, что на пути. + /// Поэтому, пока потомок на пути не повёрнут, Maintain из статьи может сделать поворот только из-за этого внука, + /// и проверка только его даёт те же повороты за половину сравнений размеров. + /// После поворота потомка его потомками становятся другие узлы, поэтому позиция проверяется полностью. + /// Родитель присоединённого узла пропускается: у присоединённого узла нет потомков, поэтому он не может быть там слишком тяжёлым. + /// + /// + private void MaintainAttachPath(ref TElement root) + { + var childRotated = false; + for (var i = _pathLength - 2; i >= 0; i--) + { + var step = _path[i]; + ref var position = ref Position(ref root, step.Parent, step.IsLeft); + var rotated = childRotated ? Rotate(ref position, step.LeftMayBeHeavy) : RotateIfGrandchildIsHeavy(ref position, step.LeftMayBeHeavy, _path[i + 1].LeftMayBeHeavy); + if (rotated) + { + MaintainRotated(ref root, step); + } + childRotated = rotated; + } + _pathLength = 0; + } + /// /// /// Restores the size balanced tree properties at the position (Maintain in the paper). - /// The pending steps run in the same order as the recursive calls of . /// /// /// Восстанавливает свойства дерева, сбалансированного по размеру, в позиции (Maintain в статье). - /// Отложенные шаги выполняются в том же порядке, что и рекурсивные вызовы в . /// /// private void Maintain(ref TElement root, Step step) + { + if (Rotate(ref Position(ref root, step.Parent, step.IsLeft), step.LeftMayBeHeavy)) + { + MaintainRotated(ref root, step); + } + } + + /// + /// + /// Finishes Maintain in the paper after the subtree at the position was rotated. + /// The pending steps run in the same order as the recursive calls of . + /// + /// + /// Завершает Maintain из статьи после того, как поддерево в позиции было повёрнуто. + /// Отложенные шаги выполняются в том же порядке, что и рекурсивные вызовы в . + /// + /// + private void MaintainRotated(ref TElement root, Step step) { var count = 0; - _maintenance[count++] = step; - while (count > 0) + while (true) { - step = _maintenance[--count]; - ref var position = ref Position(ref root, step.Parent, step.IsLeft); - if (!Rotate(ref position, step.LeftMayBeHeavy)) - { - continue; - } if (count + 4 > _maintenance.Length) { Array.Resize(ref _maintenance, _maintenance.Length * 2); } - var top = position; + var top = Position(ref root, step.Parent, step.IsLeft); // Pushed in reverse order: maintain the left child, then the right child, then the position for each side. _maintenance[count++] = step with { LeftMayBeHeavy = true }; _maintenance[count++] = step with { LeftMayBeHeavy = false }; _maintenance[count++] = new Step(top, false, false); _maintenance[count++] = new Step(top, true, true); + do + { + if (count == 0) + { + return; + } + step = _maintenance[--count]; + } + while (!Rotate(ref Position(ref root, step.Parent, step.IsLeft), step.LeftMayBeHeavy)); } } /// - /// Rotates the subtree at the position if the specified side is too heavy. - /// Поворачивает поддерево в позиции, если указанная сторона слишком тяжёлая. + /// Rotates the subtree at the position if the grandchild on the side of the attach is heavier than the other child. + /// Поворачивает поддерево в позиции, если внук на стороне присоединения тяжелее другого потомка. /// + /// + /// The position, which is not empty and whose child on the specified side is not empty. + /// Позиция, которая не пуста и потомок которой с указанной стороны не пуст. + /// + /// + /// Whether the attach went to the left child; otherwise to the right child. + /// Шло ли присоединение в левого потомка; иначе в правого. + /// + /// + /// Whether the attach went from the child to its left child; otherwise to its right child. + /// Шло ли присоединение от потомка в его левого потомка; иначе в правого. + /// /// /// Whether the subtree was rotated. /// Было ли поддерево повёрнуто. /// - private bool Rotate(ref TElement root, bool leftMayBeHeavy) + private bool RotateIfGrandchildIsHeavy(ref TElement root, bool leftMayBeHeavy, bool grandchildIsLeft) { - if (root == TElement.Zero) + if (leftMayBeHeavy) { + var left = GetLeft(root); + var rightSize = GetSizeOrZero(GetRight(root)); + if (grandchildIsLeft) + { + if (GetSize(GetLeft(left)) > rightSize) + { + RightRotate(ref root); + return true; + } + } + else if (GetSize(GetRight(left)) > rightSize) + { + LeftRotate(ref GetLeftReference(root)); + RightRotate(ref root); + return true; + } return false; } + var right = GetRight(root); + var leftSize = GetSizeOrZero(GetLeft(root)); + if (grandchildIsLeft) + { + if (GetSize(GetLeft(right)) > leftSize) + { + RightRotate(ref GetRightReference(root)); + LeftRotate(ref root); + return true; + } + } + else if (GetSize(GetRight(right)) > leftSize) + { + LeftRotate(ref root); + return true; + } + return false; + } + + /// + /// Rotates the subtree at the position if the specified side is too heavy. + /// Поворачивает поддерево в позиции, если указанная сторона слишком тяжёлая. + /// + /// + /// The position, which is not empty: positions on a path and children of a rotated node always hold nodes. + /// Позиция, которая не пуста: позиции на пути и потомки повёрнутого узла всегда содержат узлы. + /// + /// + /// Whether the left side may be too heavy; otherwise the right side. + /// Может ли левая сторона быть слишком тяжёлой; иначе правая сторона. + /// + /// + /// Whether the subtree was rotated. + /// Было ли поддерево повёрнуто. + /// + private bool Rotate(ref TElement root, bool leftMayBeHeavy) + { if (leftMayBeHeavy) { var left = GetLeft(root); diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index f72c5d2..a5e416f 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -350,7 +350,7 @@ public abstract class SizedBinaryTreeMethodsBase where TElement: IUn /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected TElement LeftRotate(TElement root) + protected virtual TElement LeftRotate(TElement root) { var right = GetRight(root); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION @@ -394,7 +394,7 @@ protected TElement LeftRotate(TElement root) /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected TElement RightRotate(TElement root) + protected virtual TElement RightRotate(TElement root) { var left = GetLeft(root); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION @@ -576,22 +576,24 @@ public void Attach(ref TElement root, TElement node) Debug.WriteLine("--BeforeAttach--"); Debug.WriteLine(PrintNodes(root)); Debug.WriteLine("----------------"); - var sizeBefore = GetSize(root); + var sizeBefore = GetSizeOrZero(root); #endif if (root == TElement.Zero) { SetSize(node, TElement.One); root = node; - return; } - AttachCore(ref root, node); + else + { + AttachCore(ref root, node); + } #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION Debug.WriteLine("--AfterAttach--"); Debug.WriteLine(PrintNodes(root)); Debug.WriteLine("----------------"); ValidateSizes(root); var sizeAfter = GetSize(root); - if (!(sizeBefore + TElement.One != sizeAfter)) + if (sizeBefore + TElement.One != sizeAfter) { throw new InvalidOperationException("Tree was broken after attach."); } @@ -645,11 +647,11 @@ public void Detach(ref TElement root, TElement node) Debug.WriteLine("--BeforeDetach--"); Debug.WriteLine(PrintNodes(root)); Debug.WriteLine("----------------"); - var sizeBefore = GetSize(root); if (root == TElement.Zero) { - throw new InvalidOperationException($"Элемент с {node} не содержится в дереве."); + throw new InvalidOperationException($"The node {node} is not in the tree."); } + var sizeBefore = GetSize(root); #endif DetachCore(ref root, node); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION @@ -657,8 +659,8 @@ public void Detach(ref TElement root, TElement node) Debug.WriteLine(PrintNodes(root)); Debug.WriteLine("----------------"); ValidateSizes(root); - var sizeAfter = GetSize(root); - if (!(Arithmetic.sizeBefore - TElement.One != sizeAfter)) + var sizeAfter = GetSizeOrZero(root); + if (sizeBefore - TElement.One != sizeAfter) { throw new InvalidOperationException("Tree was broken after detach."); } @@ -806,8 +808,8 @@ public void FixSizes(TElement node) { return; } - FixSizes(GetLeft(node)); - FixSizes(GetRight(node)); + FixSizes(GetLeftOrDefault(node)); + FixSizes(GetRightOrDefault(node)); FixSize(node); } @@ -839,8 +841,8 @@ public void ValidateSizes(TElement node) { throw new InvalidOperationException($"Size of {node} is not valid. Expected size: {expectedSize}, actual size: {size}."); } - ValidateSizes(GetLeft(node)); - ValidateSizes(GetRight(node)); + ValidateSizes(GetLeftOrDefault(node)); + ValidateSizes(GetRightOrDefault(node)); } /// @@ -931,10 +933,10 @@ public void PrintNodes(TElement node, StringBuilder sb, int level) { return; } - PrintNodes(GetLeft(node), sb, level + 1); + PrintNodes(GetLeftOrDefault(node), sb, level + 1); PrintNode(node, sb, level); sb.AppendLine(); - PrintNodes(GetRight(node), sb, level + 1); + PrintNodes(GetRightOrDefault(node), sb, level + 1); } /// From 3bfeb22457241212587b5f3302eccf999e7e1c25 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 09:37:43 +0000 Subject: [PATCH 06/46] Maintain C++ recursionless attach paths by the direction of the attach Mirrors the C# change: direction aware attach maintenance, Maintain steps on an explicit stack, size checks that accept empty children, and debug validation that compiles (ValidateSizes, FixSizes and ValidateSize are now available). --- .../Platform.Collections.Methods.h | 1 + .../RecursionlessSizeBalancedTreeMethods.h | 116 +++++++++++++++--- .../Trees/SizeBalancedTreeMethods.h | 18 +-- .../Trees/SizedBinaryTreeMethodsBase.h | 70 ++++++++--- 4 files changed, 161 insertions(+), 44 deletions(-) diff --git a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h index 23d0953..53b8c29 100644 --- a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h +++ b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include diff --git a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h index b0c8565..e398185 100644 --- a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h @@ -22,8 +22,8 @@ private: std::vector _maintenance; /// - /// The same algorithm as SizeBalancedTreeMethods, with explicit stacks instead of recursion, so both build trees of identical shape. - /// Тот же алгоритм, что и в SizeBalancedTreeMethods, но с явными стеками вместо рекурсии, поэтому оба строят деревья одинаковой формы. + /// The same algorithm as SizeBalancedTreeMethods, with explicit stacks instead of recursion, so both build trees of identical shape. The attach also remembers the direction it took at every node of the path, so on the way back up it compares only the size of the grandchild that grew, until a rotation changes the children (see MaintainAttachPath). + /// Тот же алгоритм, что и в SizeBalancedTreeMethods, но с явными стеками вместо рекурсии, поэтому оба строят деревья одинаковой формы. Присоединение также запоминает направление, по которому шло в каждом узле пути, поэтому на обратном пути сравнивает только размер выросшего внука, пока поворот не изменит потомков (см. MaintainAttachPath). /// protected: void AttachCore(TElement* root, TElement node) { @@ -45,7 +45,7 @@ this->object().SetSize(node, 1); *current = node; auto passed = static_cast(_path.size()); - this->MaintainPath(root, 0); + this->MaintainAttachPath(root); this->RebuildIfDeeperThanBalanced(root, passed, size); } @@ -161,34 +161,122 @@ } } - private: void Maintain(TElement* root, Step step) + /// + /// Maintains the path of an attach from the deepest position up to the root, using the directions that the attach took. + /// Поддерживает путь присоединения от самой глубокой позиции до корня, используя направления, по которым шло присоединение. + /// + /// + /// Before the attach the tree was size balanced, and the attach made only one grandchild of each position on the path larger: the one on the path. So while the child on the path has not been rotated, Maintain in the paper can rotate only because of that grandchild, and checking only it gives the same rotations with half of the size comparisons. After a rotation of the child its children are other nodes, so the position is checked fully. The parent of the attached node is skipped: the attached node has no children, so it cannot be too heavy there. + /// До присоединения дерево было сбалансировано по размеру, а присоединение увеличило только одного внука каждой позиции пути: того, что на пути. Поэтому, пока потомок на пути не повёрнут, Maintain из статьи может сделать поворот только из-за этого внука, и проверка только его даёт те же повороты за половину сравнений размеров. После поворота потомка его потомками становятся другие узлы, поэтому позиция проверяется полностью. Родитель присоединённого узла пропускается: у присоединённого узла нет потомков, поэтому он не может быть там слишком тяжёлым. + /// + private: void MaintainAttachPath(TElement* root) { - _maintenance.clear(); - _maintenance.push_back(step); - while (!_maintenance.empty()) + auto childRotated = false; + for (auto i = static_cast(_path.size()) - 2; i >= 0; i--) { - step = _maintenance.back(); - _maintenance.pop_back(); + auto step = _path[i]; auto* position = this->Position(root, step.Parent, step.IsLeft); - if (!this->Rotate(position, step.LeftMayBeHeavy)) + auto rotated = childRotated ? this->Rotate(position, step.LeftMayBeHeavy) : this->RotateIfGrandchildIsHeavy(position, step.LeftMayBeHeavy, _path[i + 1].LeftMayBeHeavy); + if (rotated) { - continue; + this->MaintainRotated(root, step); } - auto top = *position; + childRotated = rotated; + } + _path.clear(); + } + + /// + /// Restores the size balanced tree properties at the position (Maintain in the paper). + /// Восстанавливает свойства дерева, сбалансированного по размеру, в позиции (Maintain в статье). + /// + private: void Maintain(TElement* root, Step step) + { + if (this->Rotate(this->Position(root, step.Parent, step.IsLeft), step.LeftMayBeHeavy)) + { + this->MaintainRotated(root, step); + } + } + + /// + /// Finishes Maintain in the paper after the subtree at the position was rotated. The pending steps run in the same order as the recursive calls of SizeBalancedTreeMethods. + /// Завершает Maintain из статьи после того, как поддерево в позиции было повёрнуто. Отложенные шаги выполняются в том же порядке, что и рекурсивные вызовы в SizeBalancedTreeMethods. + /// + private: void MaintainRotated(TElement* root, Step step) + { + _maintenance.clear(); + while (true) + { + auto top = *this->Position(root, step.Parent, step.IsLeft); // Pushed in reverse order: maintain the left child, then the right child, then the position for each side. _maintenance.push_back(Step{step.Parent, step.IsLeft, true}); _maintenance.push_back(Step{step.Parent, step.IsLeft, false}); _maintenance.push_back(Step{top, false, false}); _maintenance.push_back(Step{top, true, true}); + do + { + if (_maintenance.empty()) + { + return; + } + step = _maintenance.back(); + _maintenance.pop_back(); + } + while (!this->Rotate(this->Position(root, step.Parent, step.IsLeft), step.LeftMayBeHeavy)); } } - private: bool Rotate(TElement* root, bool leftMayBeHeavy) + /// + /// Rotates the subtree at the position, which is not empty and whose child on the side of the attach is not empty, if the grandchild on the side of the attach is heavier than the other child. + /// Поворачивает поддерево в позиции, которая не пуста и потомок которой на стороне присоединения не пуст, если внук на стороне присоединения тяжелее другого потомка. + /// + private: bool RotateIfGrandchildIsHeavy(TElement* root, bool leftMayBeHeavy, bool grandchildIsLeft) { - if (*root == 0) + if (leftMayBeHeavy) { + auto left = this->object().GetLeft(*root); + auto rightSize = this->object().GetSizeOrZero(this->object().GetRight(*root)); + if (grandchildIsLeft) + { + if (this->object().GetSize(this->object().GetLeft(left)) > rightSize) + { + this->object().RightRotate(root); + return true; + } + } + else if (this->object().GetSize(this->object().GetRight(left)) > rightSize) + { + this->object().LeftRotate(this->object().GetLeftReference(*root)); + this->object().RightRotate(root); + return true; + } return false; } + auto right = this->object().GetRight(*root); + auto leftSize = this->object().GetSizeOrZero(this->object().GetLeft(*root)); + if (grandchildIsLeft) + { + if (this->object().GetSize(this->object().GetLeft(right)) > leftSize) + { + this->object().RightRotate(this->object().GetRightReference(*root)); + this->object().LeftRotate(root); + return true; + } + } + else if (this->object().GetSize(this->object().GetRight(right)) > leftSize) + { + this->object().LeftRotate(root); + return true; + } + return false; + } + + /// + /// Rotates the subtree at the position, which is not empty (positions on a path and children of a rotated node always hold nodes), if the specified side is too heavy. + /// Поворачивает поддерево в позиции, которая не пуста (позиции на пути и потомки повёрнутого узла всегда содержат узлы), если указанная сторона слишком тяжёлая. + /// + private: bool Rotate(TElement* root, bool leftMayBeHeavy) + { if (leftMayBeHeavy) { auto left = this->object().GetLeft(*root); diff --git a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h index 2f204ae..14de295 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h @@ -126,19 +126,16 @@ auto rootLeftNode = this->object().GetLeft(*root); if (rootLeftNode != 0) { - auto rootRightNode = this->object().GetRight(*root); - auto rootRightNodeSize = this->object().GetSize(rootRightNode); + auto rootRightNodeSize = this->object().GetSizeOrZero(this->object().GetRight(*root)); auto rootLeftNodeLeftNode = this->object().GetLeft(rootLeftNode); - if (rootLeftNodeLeftNode != 0 && - (rootRightNode == 0 || this->object().GetSize(rootLeftNodeLeftNode) > rootRightNodeSize)) + if (rootLeftNodeLeftNode != 0 && this->object().GetSize(rootLeftNodeLeftNode) > rootRightNodeSize) { this->object().RightRotate(root); } else { auto rootLeftNodeRightNode = this->object().GetRight(rootLeftNode); - if (rootLeftNodeRightNode != 0 && - (rootRightNode == 0 || this->object().GetSize(rootLeftNodeRightNode) > rootRightNodeSize)) + if (rootLeftNodeRightNode != 0 && this->object().GetSize(rootLeftNodeRightNode) > rootRightNodeSize) { this->object().LeftRotate(this->object().GetLeftReference(*root)); this->object().RightRotate(root); @@ -163,19 +160,16 @@ auto rootRightNode = this->object().GetRight(*root); if (rootRightNode != 0) { - auto rootLeftNode = this->object().GetLeft(*root); - auto rootLeftNodeSize = this->object().GetSize(rootLeftNode); + auto rootLeftNodeSize = this->object().GetSizeOrZero(this->object().GetLeft(*root)); auto rootRightNodeRightNode = this->object().GetRight(rootRightNode); - if (rootRightNodeRightNode != 0 && - (rootLeftNode == 0 || this->object().GetSize(rootRightNodeRightNode) > rootLeftNodeSize)) + if (rootRightNodeRightNode != 0 && this->object().GetSize(rootRightNodeRightNode) > rootLeftNodeSize) { this->object().LeftRotate(root); } else { auto rootRightNodeLeftNode = this->object().GetLeft(rootRightNode); - if (rootRightNodeLeftNode != 0 && - (rootLeftNode == 0 || this->object().GetSize(rootRightNodeLeftNode) > rootLeftNodeSize)) + if (rootRightNodeLeftNode != 0 && this->object().GetSize(rootRightNodeLeftNode) > rootLeftNodeSize) { this->object().RightRotate(this->object().GetRightReference(*root)); this->object().LeftRotate(root); diff --git a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h index e0f263f..a6f6dad 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h @@ -189,22 +189,18 @@ { #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION this->object().ValidateSizes(*root); - Debug.WriteLine("--BeforeAttach--"); - Debug.WriteLine(this->object().PrintNodes(*root)); - Debug.WriteLine("----------------"); - auto sizeBefore = this->object().GetSize(*root); + auto sizeBefore = this->object().GetSizeOrZero(*root); #endif if (*root == 0) { this->object().SetSize(node, 1); *root = node; - return; } - this->object().AttachCore(root, node); + else + { + this->object().AttachCore(root, node); + } #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION - Debug.WriteLine("--AfterAttach--"); - Debug.WriteLine(this->object().PrintNodes(*root)); - Debug.WriteLine("----------------"); this->object().ValidateSizes(*root); auto sizeAfter = this->object().GetSize(*root); if ((sizeBefore + 1) != sizeAfter) @@ -218,27 +214,65 @@ { #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION this->object().ValidateSizes(*root); - Debug.WriteLine("--BeforeDetach--"); - Debug.WriteLine(this->object().PrintNodes(*root)); - Debug.WriteLine("----------------"); - auto sizeBefore = this->object().GetSize(*root); if (*root == 0) { - throw std::runtime_error(std::string("Элемент с ").append(Platform::Converters::To(node)).append(" не содержится в дереве.")); + throw std::runtime_error(std::string("The node ").append(std::to_string(node)).append(" is not in the tree.")); } + auto sizeBefore = this->object().GetSize(*root); #endif this->object().DetachCore(root, node); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION - Debug.WriteLine("--AfterDetach--"); - Debug.WriteLine(this->object().PrintNodes(*root)); - Debug.WriteLine("----------------"); this->object().ValidateSizes(*root); - auto sizeAfter = this->object().GetSize(*root); + auto sizeAfter = this->object().GetSizeOrZero(*root); if ((sizeBefore - 1) != sizeAfter) { throw std::runtime_error("Tree was broken after detach."); } #endif } + + /// + /// Recalculates the sizes of all nodes of the subtree from the sizes of their children. + /// Пересчитывает размеры всех узлов поддерева по размерам их потомков. + /// + public: void FixSizes(TElement node) + { + if (node == 0) + { + return; + } + this->object().FixSizes(this->object().GetLeftOrDefault(node)); + this->object().FixSizes(this->object().GetRightOrDefault(node)); + this->object().FixSize(node); + } + + /// + /// Throws an exception if the size of any node of the subtree is not the sum of the sizes of its children plus one. + /// Выбрасывает исключение, если размер любого узла поддерева не равен сумме размеров его потомков плюс один. + /// + public: void ValidateSizes(TElement node) + { + if (node == 0) + { + return; + } + this->object().ValidateSize(node); + this->object().ValidateSizes(this->object().GetLeftOrDefault(node)); + this->object().ValidateSizes(this->object().GetRightOrDefault(node)); + } + + /// + /// Throws an exception if the size of the node is not the sum of the sizes of its children plus one. + /// Выбрасывает исключение, если размер узла не равен сумме размеров его потомков плюс один. + /// + public: void ValidateSize(TElement node) + { + auto size = this->object().GetSize(node); + auto expectedSize = this->object().GetLeftSize(node) + this->object().GetRightSize(node) + 1; + if (size != expectedSize) + { + throw std::runtime_error(std::string("Size of ").append(std::to_string(node)).append(" is not valid. Expected size: ").append(std::to_string(expectedSize)).append(", actual size: ").append(std::to_string(size)).append(".")); + } + } }; } From f864a2336c6245da62df9b5b978630f8f6376e96 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 09:42:46 +0000 Subject: [PATCH 07/46] Remove unreachable empty-root guard from recursive Maintain Every Maintain call in the recursive tree targets a node on the path of the operation or a child that a rotation has just moved up, so the subtree is never empty. The recursionless maintenance stack now starts with 8 steps and grows on demand. --- .../Trees/SizeBalancedTreeMethods.h | 78 ++++++++--------- .../RecursionlessSizeBalancedTreeMethods.cs | 3 +- .../Trees/SizeBalancedTreeMethods.cs | 86 ++++++++++--------- experiments/remove_root_guard.py | 29 +++++++ 4 files changed, 113 insertions(+), 83 deletions(-) create mode 100644 experiments/remove_root_guard.py diff --git a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h index 14de295..741b3ed 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h @@ -119,71 +119,69 @@ return 1; } + // Maintain(t, false) in the paper: the left side of the subtree may have become too heavy. + // The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. private: void LeftMaintain(TElement* root) { - if (*root != 0) + auto rootLeftNode = this->object().GetLeft(*root); + if (rootLeftNode != 0) { - auto rootLeftNode = this->object().GetLeft(*root); - if (rootLeftNode != 0) + auto rootRightNodeSize = this->object().GetSizeOrZero(this->object().GetRight(*root)); + auto rootLeftNodeLeftNode = this->object().GetLeft(rootLeftNode); + if (rootLeftNodeLeftNode != 0 && this->object().GetSize(rootLeftNodeLeftNode) > rootRightNodeSize) { - auto rootRightNodeSize = this->object().GetSizeOrZero(this->object().GetRight(*root)); - auto rootLeftNodeLeftNode = this->object().GetLeft(rootLeftNode); - if (rootLeftNodeLeftNode != 0 && this->object().GetSize(rootLeftNodeLeftNode) > rootRightNodeSize) + this->object().RightRotate(root); + } + else + { + auto rootLeftNodeRightNode = this->object().GetRight(rootLeftNode); + if (rootLeftNodeRightNode != 0 && this->object().GetSize(rootLeftNodeRightNode) > rootRightNodeSize) { + this->object().LeftRotate(this->object().GetLeftReference(*root)); this->object().RightRotate(root); } else { - auto rootLeftNodeRightNode = this->object().GetRight(rootLeftNode); - if (rootLeftNodeRightNode != 0 && this->object().GetSize(rootLeftNodeRightNode) > rootRightNodeSize) - { - this->object().LeftRotate(this->object().GetLeftReference(*root)); - this->object().RightRotate(root); - } - else - { - return; - } + return; } - this->LeftMaintain(this->object().GetLeftReference(*root)); - this->RightMaintain(this->object().GetRightReference(*root)); - this->RightMaintain(root); - this->LeftMaintain(root); } + this->LeftMaintain(this->object().GetLeftReference(*root)); + this->RightMaintain(this->object().GetRightReference(*root)); + this->RightMaintain(root); + this->LeftMaintain(root); } } + // Maintain(t, true) in the paper: the right side of the subtree may have become too heavy. + // The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. private: void RightMaintain(TElement* root) { - if (*root != 0) + auto rootRightNode = this->object().GetRight(*root); + if (rootRightNode != 0) { - auto rootRightNode = this->object().GetRight(*root); - if (rootRightNode != 0) + auto rootLeftNodeSize = this->object().GetSizeOrZero(this->object().GetLeft(*root)); + auto rootRightNodeRightNode = this->object().GetRight(rootRightNode); + if (rootRightNodeRightNode != 0 && this->object().GetSize(rootRightNodeRightNode) > rootLeftNodeSize) { - auto rootLeftNodeSize = this->object().GetSizeOrZero(this->object().GetLeft(*root)); - auto rootRightNodeRightNode = this->object().GetRight(rootRightNode); - if (rootRightNodeRightNode != 0 && this->object().GetSize(rootRightNodeRightNode) > rootLeftNodeSize) + this->object().LeftRotate(root); + } + else + { + auto rootRightNodeLeftNode = this->object().GetLeft(rootRightNode); + if (rootRightNodeLeftNode != 0 && this->object().GetSize(rootRightNodeLeftNode) > rootLeftNodeSize) { + this->object().RightRotate(this->object().GetRightReference(*root)); this->object().LeftRotate(root); } else { - auto rootRightNodeLeftNode = this->object().GetLeft(rootRightNode); - if (rootRightNodeLeftNode != 0 && this->object().GetSize(rootRightNodeLeftNode) > rootLeftNodeSize) - { - this->object().RightRotate(this->object().GetRightReference(*root)); - this->object().LeftRotate(root); - } - else - { - return; - } + return; } - this->LeftMaintain(this->object().GetLeftReference(*root)); - this->RightMaintain(this->object().GetRightReference(*root)); - this->RightMaintain(root); - this->LeftMaintain(root); } + this->LeftMaintain(this->object().GetLeftReference(*root)); + this->RightMaintain(this->object().GetRightReference(*root)); + this->RightMaintain(root); + this->LeftMaintain(root); } } }; diff --git a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs index 4763259..ee0ad60 100644 --- a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs @@ -56,7 +56,8 @@ public abstract class RecursionlessSizeBalancedTreeMethods : SizedBina private Step[] _path = new Step[64]; private int _pathLength; - private Step[] _maintenance = new Step[64]; + // Usually only a few Maintain steps are pending at once (at most 11 in the tests), so this stack starts small and grows when needed. + private Step[] _maintenance = new Step[8]; /// /// diff --git a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs index b31053e..87f3d34 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs @@ -183,38 +183,39 @@ private int DetachCounting(ref TElement root, TElement node) /// Восстанавливает свойства дерева, сбалансированного по размеру, когда его левая сторона могла стать слишком тяжёлой (Maintain(t, false) в статье). /// /// + /// + /// The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. + /// Поддерево никогда не пусто: оно лежит на пути операции или является потомком узла, который только что поднял поворот. + /// private void LeftMaintain(ref TElement root) { - if (root != TElement.Zero) + var rootLeftNode = GetLeft(root); + if (rootLeftNode != TElement.Zero) { - var rootLeftNode = GetLeft(root); - if (rootLeftNode != TElement.Zero) + var rootRightNode = GetRight(root); + var rootRightNodeSize = GetSizeOrZero(rootRightNode); + var rootLeftNodeLeftNode = GetLeft(rootLeftNode); + if (rootLeftNodeLeftNode != TElement.Zero && GetSize(rootLeftNodeLeftNode) > rootRightNodeSize) + { + RightRotate(ref root); + } + else { - var rootRightNode = GetRight(root); - var rootRightNodeSize = GetSizeOrZero(rootRightNode); - var rootLeftNodeLeftNode = GetLeft(rootLeftNode); - if (rootLeftNodeLeftNode != TElement.Zero && GetSize(rootLeftNodeLeftNode) > rootRightNodeSize) + var rootLeftNodeRightNode = GetRight(rootLeftNode); + if (rootLeftNodeRightNode != TElement.Zero && GetSize(rootLeftNodeRightNode) > rootRightNodeSize) { + LeftRotate(ref GetLeftReference(root)); RightRotate(ref root); } else { - var rootLeftNodeRightNode = GetRight(rootLeftNode); - if (rootLeftNodeRightNode != TElement.Zero && GetSize(rootLeftNodeRightNode) > rootRightNodeSize) - { - LeftRotate(ref GetLeftReference(root)); - RightRotate(ref root); - } - else - { - return; - } + return; } - LeftMaintain(ref GetLeftReference(root)); - RightMaintain(ref GetRightReference(root)); - RightMaintain(ref root); - LeftMaintain(ref root); } + LeftMaintain(ref GetLeftReference(root)); + RightMaintain(ref GetRightReference(root)); + RightMaintain(ref root); + LeftMaintain(ref root); } } @@ -226,38 +227,39 @@ private void LeftMaintain(ref TElement root) /// Восстанавливает свойства дерева, сбалансированного по размеру, когда его правая сторона могла стать слишком тяжёлой (Maintain(t, true) в статье). /// /// + /// + /// The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. + /// Поддерево никогда не пусто: оно лежит на пути операции или является потомком узла, который только что поднял поворот. + /// private void RightMaintain(ref TElement root) { - if (root != TElement.Zero) + var rootRightNode = GetRight(root); + if (rootRightNode != TElement.Zero) { - var rootRightNode = GetRight(root); - if (rootRightNode != TElement.Zero) + var rootLeftNode = GetLeft(root); + var rootLeftNodeSize = GetSizeOrZero(rootLeftNode); + var rootRightNodeRightNode = GetRight(rootRightNode); + if (rootRightNodeRightNode != TElement.Zero && GetSize(rootRightNodeRightNode) > rootLeftNodeSize) + { + LeftRotate(ref root); + } + else { - var rootLeftNode = GetLeft(root); - var rootLeftNodeSize = GetSizeOrZero(rootLeftNode); - var rootRightNodeRightNode = GetRight(rootRightNode); - if (rootRightNodeRightNode != TElement.Zero && GetSize(rootRightNodeRightNode) > rootLeftNodeSize) + var rootRightNodeLeftNode = GetLeft(rootRightNode); + if (rootRightNodeLeftNode != TElement.Zero && GetSize(rootRightNodeLeftNode) > rootLeftNodeSize) { + RightRotate(ref GetRightReference(root)); LeftRotate(ref root); } else { - var rootRightNodeLeftNode = GetLeft(rootRightNode); - if (rootRightNodeLeftNode != TElement.Zero && GetSize(rootRightNodeLeftNode) > rootLeftNodeSize) - { - RightRotate(ref GetRightReference(root)); - LeftRotate(ref root); - } - else - { - return; - } + return; } - LeftMaintain(ref GetLeftReference(root)); - RightMaintain(ref GetRightReference(root)); - RightMaintain(ref root); - LeftMaintain(ref root); } + LeftMaintain(ref GetLeftReference(root)); + RightMaintain(ref GetRightReference(root)); + RightMaintain(ref root); + LeftMaintain(ref root); } } } diff --git a/experiments/remove_root_guard.py b/experiments/remove_root_guard.py new file mode 100644 index 0000000..6279aba --- /dev/null +++ b/experiments/remove_root_guard.py @@ -0,0 +1,29 @@ +"""One-off refactoring helper: removes the unreachable `root != 0` guard of LeftMaintain/RightMaintain +(the position is never empty: it is on a path or a child of a node that was just rotated) and dedents the body.""" +import re, sys + +def rewrite(path, guard): + lines = open(path, encoding='utf-8-sig').read().split('\n') + had_bom = open(path, 'rb').read(3) == b'\xef\xbb\xbf' + out, i = [], 0 + while i < len(lines): + line = lines[i] + if re.search(r'(private|private:) void (Left|Right)Maintain\(', line): + out.append(line); out.append(lines[i + 1]) # signature and '{' + assert lines[i + 2].strip() == guard, (path, lines[i + 2]) + assert lines[i + 3].strip() == '{' + indent = len(lines[i + 3]) - len(lines[i + 3].lstrip()) + j = i + 4 + body = [] + while not (lines[j].strip() == '}' and len(lines[j]) - len(lines[j].lstrip()) == indent): + body.append(lines[j][4:] if lines[j].startswith(' ' * (indent + 4)) else lines[j]) + j += 1 + out.extend(body) + i = j + 1 + continue + out.append(line) + i += 1 + data = '\n'.join(out) + open(path, 'w', encoding='utf-8-sig' if had_bom else 'utf-8').write(data) + +rewrite(sys.argv[1], sys.argv[2]) From 1295c97597c8b6249267ecbc789f95517785d88e Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 09:53:15 +0000 Subject: [PATCH 08/46] Undo path size changes when an AVL attach or detach fails A duplicate attach or a detach of a missing node threw after the sizes on the search path were already changed, which left the tree invalid. Both the C# and the C++ AVL trees now restore the sizes before throwing. --- .../SizedAndThreadedAVLBalancedTreeMethods.h | 19 ++++++++++++++ .../SizedAndThreadedAVLBalancedTreeMethods.cs | 26 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h index 759c61d..4481c66 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h @@ -114,6 +114,7 @@ } else { + this->UndoSizeChanges(path, pathPosition, true); throw std::runtime_error("Node with the same key already attached to a tree."); } } @@ -301,6 +302,22 @@ return current; } + // Undoes the size changes that the search made on the path, so that a failed attach or detach leaves the tree intact. + private: void UndoSizeChanges(const TElement* path, std::int32_t pathPosition, bool sizesWereIncremented) + { + while (--pathPosition > 0) + { + if (sizesWereIncremented) + { + this->object().DecrementSize(path[pathPosition]); + } + else + { + this->object().IncrementSize(path[pathPosition]); + } + } + } + protected: void DetachCore(TElement* root, TElement node) { { @@ -319,6 +336,7 @@ { if (!this->object().GetLeftIsChild(currentNode)) { + this->UndoSizeChanges(path, pathPosition, false); throw std::runtime_error("Cannot find a node."); } this->object().DecrementSize(currentNode); @@ -329,6 +347,7 @@ { if (!this->object().GetRightIsChild(currentNode)) { + this->UndoSizeChanges(path, pathPosition, false); throw std::runtime_error("Cannot find a node."); } this->object().DecrementSize(currentNode); diff --git a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs index a82a0bd..e266d56 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs @@ -381,6 +381,7 @@ protected override void AttachCore(ref TElement root, TElement node) } else { + UndoSizeChanges(path, pathPosition, true); throw new InvalidOperationException("Node with the same key already attached to a tree."); } } @@ -635,6 +636,29 @@ protected override TElement GetPrevious(TElement node) return current; } + /// + /// + /// Undoes the size changes that the search made on the path, so that a failed attach or detach leaves the tree intact. + /// + /// + /// Отменяет изменения размеров, сделанные поиском на пути, чтобы неудачное присоединение или отсоединение оставляло дерево нетронутым. + /// + /// + private void UndoSizeChanges(TElement[] path, int pathPosition, bool sizesWereIncremented) + { + while (--pathPosition > 0) + { + if (sizesWereIncremented) + { + DecrementSize(path[pathPosition]); + } + else + { + IncrementSize(path[pathPosition]); + } + } + } + /// /// /// Detaches the core using the specified root. @@ -676,6 +700,7 @@ protected override void DetachCore(ref TElement root, TElement node) { if (!GetLeftIsChild(currentNode)) { + UndoSizeChanges(path, pathPosition, false); throw new InvalidOperationException("Cannot find a node."); } DecrementSize(currentNode); @@ -686,6 +711,7 @@ protected override void DetachCore(ref TElement root, TElement node) { if (!GetRightIsChild(currentNode)) { + UndoSizeChanges(path, pathPosition, false); throw new InvalidOperationException("Cannot find a node."); } DecrementSize(currentNode); From f630e3d79c3d8d2748a9c15ff7fd705a8bcbc447 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 09:53:15 +0000 Subject: [PATCH 09/46] Test rotations, edge cases and lists to reach full C# coverage - Rotations happen exactly when the size balanced properties require them, and the recursive and the recursionless trees rotate identically. - Every order of up to eight nodes keeps the properties. - Failed operations, size validation, printing, neighbours, rebuild and the maximum balanced height are covered for every tree. - Doubly linked lists are checked against a reference model. --- .../DoublyLinkedListTests.cs | 152 +++++++ .../DoublyLinkedLists.cs | 253 +++++++++++ .../RecursionlessSizeBalancedTree.cs | 57 ++- .../SizeBalancedTree.cs | 57 ++- .../SizeBalancedTreeRotationTests.cs | 332 ++++++++++++++ .../SizedAndThreadedAVLBalancedTree.cs | 66 ++- .../TreeEdgeCaseTests.cs | 411 ++++++++++++++++++ 7 files changed, 1325 insertions(+), 3 deletions(-) create mode 100644 csharp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cs diff --git a/csharp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cs b/csharp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cs new file mode 100644 index 0000000..9f836b5 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Checks every doubly linked list against a reference list after each operation. + /// Проверяет каждый двусвязный список по эталонному списку после каждой операции. + /// + public static class DoublyLinkedListTests + { + private const int Capacity = 64; + private const int Heads = 3; + + public static IEnumerable Lists => new[] + { + new object[] { "AbsoluteCircular" }, + new object[] { "AbsoluteOpen" }, + new object[] { "RelativeCircular" }, + new object[] { "RelativeOpen" }, + }; + + [Theory] + [MemberData(nameof(Lists))] + public static void EveryOperationKeepsTheListConsistent(string listName) + { + var lists = Create(listName); + var models = lists.Select(_ => new List()).ToArray(); + var free = Enumerable.Range(1, Capacity - 1).Select(i => (uint)i).ToList(); + var random = new System.Random(115); + var operations = new int[5]; + for (var step = 0; step < 20000; step++) + { + var index = random.Next(lists.Length); + var list = lists[index]; + var model = models[index]; + if (model.Count == 0 && free.Count == 0) + { + // The other lists hold every element, so this list can neither grow nor shrink. + continue; + } + var operation = model.Count == 0 ? random.Next(2) : free.Count == 0 ? 4 : random.Next(5); + operations[operation]++; + switch (operation) + { + case 0: + { + var element = Take(free, random); + list.AttachAsFirst(element); + model.Insert(0, element); + break; + } + case 1: + { + var element = Take(free, random); + list.AttachAsLast(element); + model.Add(element); + break; + } + case 2: + { + var position = random.Next(model.Count); + var element = Take(free, random); + list.AttachBefore(model[position], element); + model.Insert(position, element); + break; + } + case 3: + { + var position = random.Next(model.Count); + var element = Take(free, random); + list.AttachAfter(model[position], element); + model.Insert(position + 1, element); + break; + } + default: + { + var position = random.Next(model.Count); + var element = model[position]; + list.Detach(element); + model.RemoveAt(position); + Assert.Equal(0u, list.PreviousOf(element)); + Assert.Equal(0u, list.NextOf(element)); + free.Add(element); + break; + } + } + AssertEqual(model, list); + } + Assert.All(operations, count => Assert.True(count > 1000)); + } + + [Theory] + [MemberData(nameof(Lists))] + public static void SingleElementListsAreLinkedToThemselvesOrToNothing(string listName) + { + var list = Create(listName)[0]; + list.AttachAsLast(7); + AssertEqual(new List { 7 }, list); + var expectedLink = list.IsCircular ? 7u : 0u; + Assert.Equal(expectedLink, list.PreviousOf(7)); + Assert.Equal(expectedLink, list.NextOf(7)); + list.Detach(7); + AssertEqual(new List(), list); + list.AttachAsFirst(9); + AssertEqual(new List { 9 }, list); + } + + private static uint Take(List free, System.Random random) + { + var index = random.Next(free.Count); + var element = free[index]; + free[index] = free[^1]; + free.RemoveAt(free.Count - 1); + return element; + } + + private static IInspectableList[] Create(string listName) => listName switch + { + "AbsoluteCircular" => new IInspectableList[] { new AbsoluteCircularDoublyLinkedList(Capacity) }, + "AbsoluteOpen" => new IInspectableList[] { new AbsoluteOpenDoublyLinkedList(Capacity) }, + "RelativeCircular" => Views(new RelativeCircularDoublyLinkedList(Capacity, Heads).For), + "RelativeOpen" => Views(new RelativeOpenDoublyLinkedList(Capacity, Heads).For), + _ => throw new ArgumentOutOfRangeException(nameof(listName)), + }; + + private static IInspectableList[] Views(Func view) => Enumerable.Range(0, Heads).Select(head => view((uint)head)).ToArray(); + + private static void AssertEqual(List expected, IInspectableList list) + { + Assert.Equal((uint)expected.Count, list.Size); + if (expected.Count == 0) + { + Assert.Equal(0u, list.First); + Assert.Equal(0u, list.Last); + return; + } + Assert.Equal(expected[0], list.First); + Assert.Equal(expected[^1], list.Last); + for (var i = 0; i < expected.Count; i++) + { + var element = expected[i]; + var previous = i > 0 ? expected[i - 1] : list.IsCircular ? expected[^1] : 0u; + var next = i < expected.Count - 1 ? expected[i + 1] : list.IsCircular ? expected[0] : 0u; + Assert.Equal(previous, list.PreviousOf(element)); + Assert.Equal(next, list.NextOf(element)); + } + } + } +} diff --git a/csharp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cs b/csharp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cs new file mode 100644 index 0000000..866420a --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cs @@ -0,0 +1,253 @@ +using Platform.Collections.Methods.Lists; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Read-only view of a test list that the list tests use to walk it. + /// Представление тестового списка только для чтения, используемое тестами списков для его обхода. + /// + public interface IInspectableList + { + bool IsCircular { get; } + + uint First { get; } + + uint Last { get; } + + uint Size { get; } + + uint PreviousOf(uint element); + + uint NextOf(uint element); + + void AttachBefore(uint baseElement, uint newElement); + + void AttachAfter(uint baseElement, uint newElement); + + void AttachAsFirst(uint element); + + void AttachAsLast(uint element); + + void Detach(uint element); + } + + public class AbsoluteCircularDoublyLinkedList : AbsoluteCircularDoublyLinkedListMethods, IInspectableList + { + private readonly uint[] _previous; + private readonly uint[] _next; + private uint _first; + private uint _last; + private uint _size; + + public AbsoluteCircularDoublyLinkedList(int capacity) => (_previous, _next) = (new uint[capacity], new uint[capacity]); + + public bool IsCircular => true; + + public uint First => _first; + + public uint Last => _last; + + public uint Size => _size; + + public uint PreviousOf(uint element) => _previous[element]; + + public uint NextOf(uint element) => _next[element]; + + protected override uint GetFirst() => _first; + + protected override uint GetLast() => _last; + + protected override uint GetSize() => _size; + + protected override void SetFirst(uint element) => _first = element; + + protected override void SetLast(uint element) => _last = element; + + protected override void SetSize(uint size) => _size = size; + + protected override uint GetPrevious(uint element) => _previous[element]; + + protected override uint GetNext(uint element) => _next[element]; + + protected override void SetPrevious(uint element, uint previous) => _previous[element] = previous; + + protected override void SetNext(uint element, uint next) => _next[element] = next; + } + + public class AbsoluteOpenDoublyLinkedList : AbsoluteOpenDoublyLinkedListMethods, IInspectableList + { + private readonly uint[] _previous; + private readonly uint[] _next; + private uint _first; + private uint _last; + private uint _size; + + public AbsoluteOpenDoublyLinkedList(int capacity) => (_previous, _next) = (new uint[capacity], new uint[capacity]); + + public bool IsCircular => false; + + public uint First => _first; + + public uint Last => _last; + + public uint Size => _size; + + public uint PreviousOf(uint element) => _previous[element]; + + public uint NextOf(uint element) => _next[element]; + + protected override uint GetFirst() => _first; + + protected override uint GetLast() => _last; + + protected override uint GetSize() => _size; + + protected override void SetFirst(uint element) => _first = element; + + protected override void SetLast(uint element) => _last = element; + + protected override void SetSize(uint size) => _size = size; + + protected override uint GetPrevious(uint element) => _previous[element]; + + protected override uint GetNext(uint element) => _next[element]; + + protected override void SetPrevious(uint element, uint previous) => _previous[element] = previous; + + protected override void SetNext(uint element, uint next) => _next[element] = next; + } + + /// + /// Several circular lists that share one storage; each list is identified by its head element. + /// Несколько кольцевых списков с общим хранилищем; каждый список определяется своим головным элементом. + /// + public class RelativeCircularDoublyLinkedList : RelativeCircularDoublyLinkedListMethods + { + private readonly uint[] _previous; + private readonly uint[] _next; + private readonly uint[] _first; + private readonly uint[] _last; + private readonly uint[] _size; + + public RelativeCircularDoublyLinkedList(int capacity, int heads) => (_previous, _next, _first, _last, _size) = (new uint[capacity], new uint[capacity], new uint[heads], new uint[heads], new uint[heads]); + + public IInspectableList For(uint head) => new View(this, head); + + protected override uint GetFirst(uint headElement) => _first[headElement]; + + protected override uint GetLast(uint headElement) => _last[headElement]; + + protected override uint GetSize(uint headElement) => _size[headElement]; + + protected override void SetFirst(uint headElement, uint element) => _first[headElement] = element; + + protected override void SetLast(uint headElement, uint element) => _last[headElement] = element; + + protected override void SetSize(uint headElement, uint size) => _size[headElement] = size; + + protected override uint GetPrevious(uint element) => _previous[element]; + + protected override uint GetNext(uint element) => _next[element]; + + protected override void SetPrevious(uint element, uint previous) => _previous[element] = previous; + + protected override void SetNext(uint element, uint next) => _next[element] = next; + + private sealed class View : IInspectableList + { + private readonly RelativeCircularDoublyLinkedList _list; + private readonly uint _head; + + public View(RelativeCircularDoublyLinkedList list, uint head) => (_list, _head) = (list, head); + + public bool IsCircular => true; + + public uint First => _list._first[_head]; + + public uint Last => _list._last[_head]; + + public uint Size => _list._size[_head]; + + public uint PreviousOf(uint element) => _list._previous[element]; + + public uint NextOf(uint element) => _list._next[element]; + + public void AttachBefore(uint baseElement, uint newElement) => _list.AttachBefore(_head, baseElement, newElement); + + public void AttachAfter(uint baseElement, uint newElement) => _list.AttachAfter(_head, baseElement, newElement); + + public void AttachAsFirst(uint element) => _list.AttachAsFirst(_head, element); + + public void AttachAsLast(uint element) => _list.AttachAsLast(_head, element); + + public void Detach(uint element) => _list.Detach(_head, element); + } + } + + /// + /// Several open lists that share one storage; each list is identified by its head element. + /// Несколько незамкнутых списков с общим хранилищем; каждый список определяется своим головным элементом. + /// + public class RelativeOpenDoublyLinkedList : RelativeOpenDoublyLinkedListMethods + { + private readonly uint[] _previous; + private readonly uint[] _next; + private readonly uint[] _first; + private readonly uint[] _last; + private readonly uint[] _size; + + public RelativeOpenDoublyLinkedList(int capacity, int heads) => (_previous, _next, _first, _last, _size) = (new uint[capacity], new uint[capacity], new uint[heads], new uint[heads], new uint[heads]); + + public IInspectableList For(uint head) => new View(this, head); + + protected override uint GetFirst(uint headElement) => _first[headElement]; + + protected override uint GetLast(uint headElement) => _last[headElement]; + + protected override uint GetSize(uint headElement) => _size[headElement]; + + protected override void SetFirst(uint headElement, uint element) => _first[headElement] = element; + + protected override void SetLast(uint headElement, uint element) => _last[headElement] = element; + + protected override void SetSize(uint headElement, uint size) => _size[headElement] = size; + + protected override uint GetPrevious(uint element) => _previous[element]; + + protected override uint GetNext(uint element) => _next[element]; + + protected override void SetPrevious(uint element, uint previous) => _previous[element] = previous; + + protected override void SetNext(uint element, uint next) => _next[element] = next; + + private sealed class View : IInspectableList + { + private readonly RelativeOpenDoublyLinkedList _list; + private readonly uint _head; + + public View(RelativeOpenDoublyLinkedList list, uint head) => (_list, _head) = (list, head); + + public bool IsCircular => false; + + public uint First => _list._first[_head]; + + public uint Last => _list._last[_head]; + + public uint Size => _list._size[_head]; + + public uint PreviousOf(uint element) => _list._previous[element]; + + public uint NextOf(uint element) => _list._next[element]; + + public void AttachBefore(uint baseElement, uint newElement) => _list.AttachBefore(_head, baseElement, newElement); + + public void AttachAfter(uint baseElement, uint newElement) => _list.AttachAfter(_head, baseElement, newElement); + + public void AttachAsFirst(uint element) => _list.AttachAsFirst(_head, element); + + public void AttachAsLast(uint element) => _list.AttachAsLast(_head, element); + + public void Detach(uint element) => _list.Detach(_head, element); + } + } +} diff --git a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs index fc0e174..94aacdb 100644 --- a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs @@ -29,6 +29,57 @@ private struct TreeElement public TElement SizeOf(TElement node) => GetSizeOrZero(node); + /// + /// The number of rotations made since the counter was last reset. + /// Число поворотов, сделанных с момента последнего сброса счётчика. + /// + public long Rotations; + + /// + /// The number of node sizes read since the counter was last reset. + /// Число прочитанных размеров узлов с момента последнего сброса счётчика. + /// + public long SizeReads; + + /// + /// When set, every rotation is recorded as "L" or "R" followed by the node that moved down. + /// Если задан, каждый поворот записывается как "L" или "R" и узел, который опустился вниз. + /// + public List? RotationLog; + + public TElement NextOf(TElement node) => GetNext(node); + + public TElement PreviousOf(TElement node) => GetPrevious(node); + + public TElement LeftestOf(TElement node) => GetLeftest(node); + + public TElement RightestOf(TElement node) => GetRightest(node); + + public void PrintNodeTo(TElement node, StringBuilder sb) => PrintNode(node, sb); + + public TElement Rebuild(TElement root) => RebuildComplete(root); + + public void SetNode(TElement node, TElement left, TElement right, TElement size) + { + SetLeft(node, left); + SetRight(node, right); + SetSize(node, size); + } + + protected override TElement LeftRotate(TElement root) + { + Rotations++; + RotationLog?.Add("L" + root); + return base.LeftRotate(root); + } + + protected override TElement RightRotate(TElement root) + { + Rotations++; + RotationLog?.Add("R" + root); + return base.RightRotate(root); + } + public RecursionlessSizeBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); public TElement Allocate() @@ -75,7 +126,11 @@ public void Free(TElement node) protected override TElement GetRight(TElement node) => GetElement(node).Right; - protected override TElement GetSize(TElement node) => GetElement(node).Size; + protected override TElement GetSize(TElement node) + { + SizeReads++; + return GetElement(node).Size; + } protected override void PrintNodeValue(TElement node, StringBuilder sb) => sb.Append(node); diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs index 4ac8686..31f9cdc 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs @@ -29,6 +29,57 @@ private struct TreeElement public TElement SizeOf(TElement node) => GetSizeOrZero(node); + /// + /// The number of rotations made since the counter was last reset. + /// Число поворотов, сделанных с момента последнего сброса счётчика. + /// + public long Rotations; + + /// + /// The number of node sizes read since the counter was last reset. + /// Число прочитанных размеров узлов с момента последнего сброса счётчика. + /// + public long SizeReads; + + /// + /// When set, every rotation is recorded as "L" or "R" followed by the node that moved down. + /// Если задан, каждый поворот записывается как "L" или "R" и узел, который опустился вниз. + /// + public List? RotationLog; + + public TElement NextOf(TElement node) => GetNext(node); + + public TElement PreviousOf(TElement node) => GetPrevious(node); + + public TElement LeftestOf(TElement node) => GetLeftest(node); + + public TElement RightestOf(TElement node) => GetRightest(node); + + public void PrintNodeTo(TElement node, StringBuilder sb) => PrintNode(node, sb); + + public TElement Rebuild(TElement root) => RebuildComplete(root); + + public void SetNode(TElement node, TElement left, TElement right, TElement size) + { + SetLeft(node, left); + SetRight(node, right); + SetSize(node, size); + } + + protected override TElement LeftRotate(TElement root) + { + Rotations++; + RotationLog?.Add("L" + root); + return base.LeftRotate(root); + } + + protected override TElement RightRotate(TElement root) + { + Rotations++; + RotationLog?.Add("R" + root); + return base.RightRotate(root); + } + public SizeBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); public TElement Allocate() @@ -76,7 +127,11 @@ public void Free(TElement node) protected override TElement GetRight(TElement node) => GetElement(node).Right; - protected override TElement GetSize(TElement node) => GetElement(node).Size; + protected override TElement GetSize(TElement node) + { + SizeReads++; + return GetElement(node).Size; + } protected override void PrintNodeValue(TElement node, StringBuilder sb) => sb.Append(node); diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs new file mode 100644 index 0000000..03757ee --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs @@ -0,0 +1,332 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; +using Xunit.Abstractions; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Checks that size balanced trees rotate only when the size balanced tree properties require it and that both implementations make the same rotations. + /// Проверяет, что деревья, сбалансированные по размеру, делают повороты только тогда, когда этого требуют свойства дерева, и что обе реализации делают одинаковые повороты. + /// + public class SizeBalancedTreeRotationTests + { + private const int N = 2048; + private readonly ITestOutputHelper _output; + + public SizeBalancedTreeRotationTests(ITestOutputHelper output) => _output = output; + + public static IEnumerable Workloads => new[] { "Ascending", "Descending", "Random", "InterleavedHotAndCold", "AlternatingEnds" }.Select(w => new object[] { w }); + + /// + /// An attach rotates if and only if the plain binary search tree insertion would break a size balanced tree property. + /// Присоединение делает поворот тогда и только тогда, когда простая вставка в двоичное дерево поиска нарушила бы свойство дерева, сбалансированного по размеру. + /// + [Theory] + [MemberData(nameof(Workloads))] + public void AttachRotatesOnlyWhenThePropertiesRequireIt(string workload) + { + var recursive = new SizeBalancedTree(2 * N + 2) { RotationLog = new List() }; + var recursionless = new RecursionlessSizeBalancedTree(2 * N + 2) { RotationLog = new List() }; + var attachesWithRotations = 0; + var keys = Keys(workload).ToList(); + foreach (var key in keys) + { + var needsRotations = InsertionBreaksSizeBalance(recursive, recursive.Root, key); + recursive.RotationLog.Clear(); + recursionless.RotationLog.Clear(); + recursive.Attach(ref recursive.Root, key); + recursionless.Attach(ref recursionless.Root, key); + Assert.Equal(needsRotations, recursive.RotationLog.Count > 0); + Assert.Equal(recursive.RotationLog, recursionless.RotationLog); + attachesWithRotations += needsRotations ? 1 : 0; + } + Assert.Equal(Shape(recursive, recursive.Root, keys.Count), Shape(recursionless, recursionless.Root, keys.Count)); + _output.WriteLine($"{workload}: {attachesWithRotations} of {keys.Count} attaches rotated, {recursive.Rotations} rotations in total."); + } + + /// + /// Inserting the keys of a complete tree level by level never breaks the properties, so no rotations happen and the tree stays complete. + /// Вставка ключей полного дерева по уровням никогда не нарушает свойств, поэтому поворотов нет и дерево остаётся полным. + /// + [Fact] + public void LevelOrderAttachOfACompleteTreeMakesNoRotations() + { + const uint count = 1023; + var recursive = new SizeBalancedTree((int)count + 2); + var recursionless = new RecursionlessSizeBalancedTree((int)count + 2); + var level = new List<(uint Low, uint High)> { (1, count) }; + while (level.Count > 0) + { + var next = new List<(uint Low, uint High)>(); + foreach (var (low, high) in level) + { + var middle = (low + high) / 2; + recursive.Attach(ref recursive.Root, middle); + recursionless.Attach(ref recursionless.Root, middle); + if (low < middle) + { + next.Add((low, middle - 1)); + } + if (middle < high) + { + next.Add((middle + 1, high)); + } + } + level = next; + } + Assert.Equal(0, recursive.Rotations); + Assert.Equal(0, recursionless.Rotations); + Assert.Equal(10, Height(recursive, recursive.Root)); + Assert.Equal(Shape(recursive, recursive.Root, (int)count), Shape(recursionless, recursionless.Root, (int)count)); + } + + /// + /// Both implementations make exactly the same rotations in any mix of attaches and detaches. + /// Обе реализации делают в точности одинаковые повороты при любом сочетании присоединений и отсоединений. + /// + [Fact] + public void RecursiveAndRecursionlessTreesMakeTheSameRotations() + { + var recursive = new SizeBalancedTree(N + 2) { RotationLog = new List() }; + var recursionless = new RecursionlessSizeBalancedTree(N + 2) { RotationLog = new List() }; + var random = new System.Random(116); + var present = new HashSet(); + for (var step = 0; step < 16 * N; step++) + { + var key = (uint)random.Next(1, N + 1); + if (present.Remove(key)) + { + recursive.Detach(ref recursive.Root, key); + recursionless.Detach(ref recursionless.Root, key); + } + else + { + present.Add(key); + recursive.Attach(ref recursive.Root, key); + recursionless.Attach(ref recursionless.Root, key); + } + Assert.Equal(recursive.RotationLog.Count, recursionless.RotationLog.Count); + } + Assert.Equal(recursive.RotationLog, recursionless.RotationLog); + Assert.True(recursive.Rotations > 0); + } + + /// + /// Size balanced trees make O(1) rotations per attach on average (Chen, 2007), so the total stays linear even for sorted input. + /// Деревья, сбалансированные по размеру, делают в среднем O(1) поворотов на присоединение (Чэнь, 2007), поэтому общее число остаётся линейным даже для упорядоченного ввода. + /// + [Theory] + [MemberData(nameof(Workloads))] + public void RotationsPerAttachAreConstantOnAverage(string workload) + { + var tree = new RecursionlessSizeBalancedTree(2 * N + 2); + var count = 0; + foreach (var key in Keys(workload)) + { + tree.Attach(ref tree.Root, key); + count++; + } + _output.WriteLine($"{workload}: {tree.Rotations} rotations for {count} attaches."); + Assert.True(tree.Rotations <= 2 * count, $"{tree.Rotations} rotations for {count} attaches."); + } + + /// + /// The recursionless attach uses the direction of the attach to skip the checks that cannot fail, so it reads fewer sizes than Chen's Maintain. + /// Нерекурсивное присоединение использует направление присоединения, чтобы пропускать проверки, которые не могут не пройти, поэтому читает меньше размеров, чем Maintain Чэня. + /// + [Theory] + [MemberData(nameof(Workloads))] + public void RecursionlessAttachReadsFewerSizes(string workload) + { + var recursive = new SizeBalancedTree(2 * N + 2); + var recursionless = new RecursionlessSizeBalancedTree(2 * N + 2); + foreach (var key in Keys(workload)) + { + recursive.Attach(ref recursive.Root, key); + recursionless.Attach(ref recursionless.Root, key); + } + _output.WriteLine($"{workload}: recursive {recursive.SizeReads}, recursionless {recursionless.SizeReads} size reads."); + Assert.True(recursionless.SizeReads < recursive.SizeReads, $"recursive {recursive.SizeReads}, recursionless {recursionless.SizeReads}"); + } + + /// + /// Every order of attaches and detaches of up to 8 nodes keeps the properties and gives the same tree in both implementations. + /// Любой порядок присоединений и отсоединений до 8 узлов сохраняет свойства и даёт одинаковое дерево в обеих реализациях. + /// + [Fact] + public void EveryOrderOfUpToEightNodesKeepsTheProperties() + { + for (var count = 1; count <= 8; count++) + { + foreach (var order in Permutations(count)) + { + var recursive = new SizeBalancedTree(count + 2) { RotationLog = new List() }; + var recursionless = new RecursionlessSizeBalancedTree(count + 2) { RotationLog = new List() }; + var avl = new SizedAndThreadedAVLBalancedTree(count + 2); + for (var i = 0; i < count; i++) + { + var needsRotations = InsertionBreaksSizeBalance(recursive, recursive.Root, order[i]); + var rotations = recursive.Rotations; + recursive.Attach(ref recursive.Root, order[i]); + recursionless.Attach(ref recursionless.Root, order[i]); + avl.Attach(ref avl.Root, order[i]); + Assert.Equal(needsRotations, recursive.Rotations > rotations); + AssertValid(recursive, recursive.Root, i + 1); + AssertValid(avl, avl.Root, i + 1, sizeBalanced: false); + Assert.Equal(Shape(recursive, recursive.Root, count), Shape(recursionless, recursionless.Root, count)); + } + // Detach in the same order, so that every order of detaches is also checked. + for (var i = 0; i < count; i++) + { + recursive.Detach(ref recursive.Root, order[i]); + recursionless.Detach(ref recursionless.Root, order[i]); + avl.Detach(ref avl.Root, order[i]); + AssertValid(recursive, recursive.Root, count - i - 1); + AssertValid(avl, avl.Root, count - i - 1, sizeBalanced: false); + Assert.Equal(Shape(recursive, recursive.Root, count), Shape(recursionless, recursionless.Root, count)); + } + Assert.Equal(recursive.RotationLog, recursionless.RotationLog); + } + } + } + + /// + /// Whether inserting the key with a plain binary search tree insertion would break a size balanced tree property. + /// Нарушила бы вставка ключа простой вставкой в двоичное дерево поиска свойство дерева, сбалансированного по размеру. + /// + /// + /// Only the sizes of the nodes on the path grow, so only the checks of a grandparent g against its child p on the path + /// and the sibling of p can fail: the sibling must stay at least as large as the grown child c of p. + /// + private static bool InsertionBreaksSizeBalance(TTree tree, uint root, uint key) where TTree : IInspectableTree + { + var path = new List(); + for (var node = root; node != 0; node = key < node ? tree.LeftOf(node) : tree.RightOf(node)) + { + path.Add(node); + } + path.Add(0); // The new node. + for (var i = 2; i < path.Count; i++) + { + var grandparent = path[i - 2]; + var parent = path[i - 1]; + var sibling = tree.LeftOf(grandparent) == parent ? tree.RightOf(grandparent) : tree.LeftOf(grandparent); + var grownChildSize = tree.SizeOf(path[i]) + 1; + if (tree.SizeOf(sibling) < grownChildSize) + { + return true; + } + } + return false; + } + + internal static void AssertValid(TTree tree, uint root, int count, bool sizeBalanced = true) where TTree : IInspectableTree + { + Assert.Equal((uint)count, tree.SizeOf(root)); + Assert.True(Height(tree, root) <= TreeBalanceTests.MaximumHeight(count)); + var keys = new List(); + Walk(root); + Assert.Equal(keys.OrderBy(k => k), keys); + void Walk(uint node) + { + if (node == 0) + { + return; + } + var left = tree.LeftOf(node); + var right = tree.RightOf(node); + Assert.Equal(tree.SizeOf(left) + tree.SizeOf(right) + 1, tree.SizeOf(node)); + if (sizeBalanced) + { + Assert.True(tree.SizeOf(left) >= Math.Max(tree.SizeOf(tree.LeftOf(right)), tree.SizeOf(tree.RightOf(right)))); + Assert.True(tree.SizeOf(right) >= Math.Max(tree.SizeOf(tree.LeftOf(left)), tree.SizeOf(tree.RightOf(left)))); + } + Walk(left); + keys.Add(node); + Walk(right); + } + } + + internal static int Height(TTree tree, uint node) where TTree : IInspectableTree => node == 0 ? 0 : 1 + Math.Max(Height(tree, tree.LeftOf(node)), Height(tree, tree.RightOf(node))); + + internal static string Shape(TTree tree, uint root, int count) where TTree : IInspectableTree + { + var shape = new System.Text.StringBuilder().Append(root).Append(';'); + for (uint node = 1; node <= count; node++) + { + shape.Append(tree.LeftOf(node)).Append(',').Append(tree.RightOf(node)).Append(',').Append(tree.SizeOf(node)).Append(';'); + } + return shape.ToString(); + } + + internal static IEnumerable Permutations(int count) + { + var order = Enumerable.Range(1, count).Select(i => (uint)i).ToArray(); + while (true) + { + yield return (uint[])order.Clone(); + // Next permutation in lexicographic order. + var i = count - 2; + while (i >= 0 && order[i] > order[i + 1]) + { + i--; + } + if (i < 0) + { + yield break; + } + var j = count - 1; + while (order[j] < order[i]) + { + j--; + } + (order[i], order[j]) = (order[j], order[i]); + Array.Reverse(order, i + 1, count - i - 1); + } + } + + private static IEnumerable Keys(string workload) + { + switch (workload) + { + case "Ascending": + for (uint i = 1; i <= N; i++) + { + yield return i; + } + break; + case "Descending": + for (uint i = N; i >= 1; i--) + { + yield return i; + } + break; + case "Random": + var random = new System.Random(577); + foreach (var key in Enumerable.Range(1, N).OrderBy(_ => random.Next())) + { + yield return (uint)key; + } + break; + case "InterleavedHotAndCold": + for (uint i = 1; i <= N; i++) + { + yield return i; + yield return N + i; + } + break; + case "AlternatingEnds": + for (uint i = 1; i <= N; i++) + { + yield return i; + yield return (2 * N) + 1 - i; + } + break; + default: + throw new ArgumentOutOfRangeException(nameof(workload)); + } + } + } +} diff --git a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs index dd6978c..2e7da62 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs @@ -32,6 +32,66 @@ private struct TreeElement public TElement SizeOf(TElement node) => GetSizeOrZero(node); + /// + /// The number of rotations made since the counter was last reset. + /// Число поворотов, сделанных с момента последнего сброса счётчика. + /// + public long Rotations; + + /// + /// The number of node sizes read since the counter was last reset. + /// Число прочитанных размеров узлов с момента последнего сброса счётчика. + /// + public long SizeReads; + + /// + /// When set, every rotation is recorded as "L" or "R" followed by the node that moved down. + /// Если задан, каждый поворот записывается как "L" или "R" и узел, который опустился вниз. + /// + public List? RotationLog; + + public TElement NextOf(TElement node) => GetNext(node); + + public TElement PreviousOf(TElement node) => GetPrevious(node); + + public TElement LeftestOf(TElement node) => GetLeftest(node); + + public TElement RightestOf(TElement node) => GetRightest(node); + + public void PrintNodeTo(TElement node, StringBuilder sb) => PrintNode(node, sb); + + public sbyte BalanceOf(TElement node) => GetBalance(node); + + public bool LeftIsChildOf(TElement node) => GetLeftIsChild(node); + + public bool RightIsChildOf(TElement node) => GetRightIsChild(node); + + /// + /// The left link of the node: the left child or, when there is no left child, the thread to the previous node. + /// Левая ссылка узла: левый потомок или, если его нет, нить к предыдущему узлу. + /// + public TElement LeftLinkOf(TElement node) => GetLeft(node); + + /// + /// The right link of the node: the right child or, when there is no right child, the thread to the next node. + /// Правая ссылка узла: правый потомок или, если его нет, нить к следующему узлу. + /// + public TElement RightLinkOf(TElement node) => GetRight(node); + + public TElement RotateLeftWithBalance(TElement node) + { + Rotations++; + RotationLog?.Add("L" + node); + return LeftRotateWithBalance(node); + } + + public TElement RotateRightWithBalance(TElement node) + { + Rotations++; + RotationLog?.Add("R" + node); + return RightRotateWithBalance(node); + } + public SizedAndThreadedAVLBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); public TElement Allocate() @@ -85,7 +145,11 @@ public void Free(TElement node) protected override TElement GetRight(TElement node) => GetElement(node).Right; - protected override TElement GetSize(TElement node) => GetElement(node).Size; + protected override TElement GetSize(TElement node) + { + SizeReads++; + return GetElement(node).Size; + } protected override void PrintNodeValue(TElement node, StringBuilder sb) => sb.Append(node); diff --git a/csharp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cs b/csharp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cs new file mode 100644 index 0000000..ea163d6 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cs @@ -0,0 +1,411 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Text; +using Platform.Collections.Methods.Trees; +using Xunit; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Checks failed operations, the helper methods of the trees and the rotations of the AVL tree. + /// Проверяет неудачные операции, вспомогательные методы деревьев и повороты АВЛ-дерева. + /// + public static class TreeEdgeCaseTests + { + public static IEnumerable SizeBalancedTrees => new[] { new object[] { false }, new object[] { true } }; + + [Theory] + [MemberData(nameof(SizeBalancedTrees))] + public static void DetachOfAMissingNodeLeavesTheTreeIntact(bool recursionless) + { + var tree = CreateSizeBalancedTree(recursionless, 16); + ref var root = ref tree.Root; + var exception = Assert.Throws(() => tree.Detach(ref tree.Root, 1)); + Assert.Equal("The node 1 is not in the tree.", exception.Message); + for (uint node = 2; node <= 12; node += 2) + { + tree.Attach(ref root, node); + } + var shape = SizeBalancedTreeRotationTests.Shape(tree, root, 14); + foreach (var missing in new uint[] { 1, 5, 13 }) + { + exception = Assert.Throws(() => tree.Detach(ref tree.Root, missing)); + Assert.Equal($"The node {missing} is not in the tree.", exception.Message); + Assert.Equal(shape, SizeBalancedTreeRotationTests.Shape(tree, root, 14)); + } + } + + [Theory] + [MemberData(nameof(SizeBalancedTrees))] + public static void DetachOfANodeWhoseKeyIsSharedFailsAndLeavesTheTreeIntact(bool recursionless) + { + var tree = recursionless ? (SizedBinaryTreeMethodsBase)new HalfKeyRecursionlessSizeBalancedTree() : new HalfKeySizeBalancedTree(); + var inspectable = (IInspectableTree)tree; + uint root = 0; + // Nodes 2 and 3 have the same key 1, so the second one goes to the right of the first one. + tree.Attach(ref root, 2); + tree.Attach(ref root, 3); + Assert.Equal(2u, root); + var shape = SizeBalancedTreeRotationTests.Shape(inspectable, root, 5); + var exception = Assert.Throws(() => tree.Detach(ref root, 3)); + Assert.Equal("Duplicate link found in the tree.", exception.Message); + Assert.Equal(shape, SizeBalancedTreeRotationTests.Shape(inspectable, root, 5)); + Assert.True(tree.Contains(3, root)); + tree.Detach(ref root, 2); + tree.Detach(ref root, 3); + Assert.Equal(0u, root); + } + + [Fact] + public static void FailedAttachAndDetachOfTheAVLTreeLeaveTheTreeIntact() + { + var tree = new SizedAndThreadedAVLBalancedTree(34); + Assert.Equal("Cannot find a node.", Assert.Throws(() => tree.Detach(ref tree.Root, 1)).Message); + for (uint node = 2; node <= 32; node += 2) + { + tree.Attach(ref tree.Root, node); + } + var shape = AvlShape(tree, 33); + foreach (var node in new uint[] { 2, 16, 32, 10 }) + { + Assert.Equal("Node with the same key already attached to a tree.", Assert.Throws(() => tree.Attach(ref tree.Root, node)).Message); + Assert.Equal(shape, AvlShape(tree, 33)); + } + foreach (var node in new uint[] { 1, 15, 17, 33 }) + { + Assert.Equal("Cannot find a node.", Assert.Throws(() => tree.Detach(ref tree.Root, node)).Message); + Assert.Equal(shape, AvlShape(tree, 33)); + } + tree.ValidateSizes(tree.Root); + } + + [Fact] + public static void MaximumBalancedHeightMatchesTheSparsestTrees() + { + Assert.Equal(0, SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(0)); + Assert.Equal(1, SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(1)); + Assert.Equal(2, SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(2)); + Assert.Equal(2, SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(3)); + Assert.Equal(3, SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(4)); + for (var count = 0; count <= 5000; count++) + { + Assert.Equal(TreeBalanceTests.MaximumHeight(count), SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight((uint)count)); + } + // The largest sizes stop the sequence before it overflows. + Assert.Equal(Reference(byte.MaxValue), SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(byte.MaxValue)); + Assert.Equal(Reference(uint.MaxValue), SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(uint.MaxValue)); + Assert.Equal(Reference(ulong.MaxValue), SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(ulong.MaxValue)); + Assert.Equal(91, SizedBinaryTreeMethodsBase.GetMaximumBalancedHeight(ulong.MaxValue)); + + static int Reference(BigInteger count) + { + var height = 0; + BigInteger previous = 0, current = 1; + while (current <= count) + { + height++; + (previous, current) = (current, current + previous + 1); + } + return height; + } + } + + [Theory] + [MemberData(nameof(SizeBalancedTrees))] + public static void RebuildMakesACompleteTree(bool recursionless) + { + var tree = CreateSizeBalancedTree(recursionless, 130); + Assert.Equal(0u, tree.Rebuild(0)); + for (uint count = 1; count <= 128; count++) + { + // A path of left children: the largest key is the root. + for (uint node = 1; node <= count; node++) + { + tree.SetNode(node, node > 1 ? node - 1 : 0, 0, node); + } + var root = tree.Rebuild(count); + SizeBalancedTreeRotationTests.AssertValid(tree, root, (int)count); + Assert.Equal(BitOperations.Log2(count) + 1, SizeBalancedTreeRotationTests.Height(tree, root)); + } + } + + [Theory] + [MemberData(nameof(SizeBalancedTrees))] + public static void SizesAreValidatedAndFixed(bool recursionless) + { + var tree = CreateSizeBalancedTree(recursionless, 8); + tree.FixSizes(0); + tree.ValidateSizes(0); + for (uint node = 1; node <= 7; node++) + { + tree.Attach(ref tree.Root, node); + } + tree.ValidateSizes(tree.Root); + tree.ValidateSize(tree.Root); + var root = tree.Root; + Assert.Equal(4u, root); + tree.SetNode(root, tree.LeftOf(root), tree.RightOf(root), 1); + Assert.Equal("Size of 4 is not valid. Expected size: 7, actual size: 1.", Assert.Throws(() => tree.ValidateSizes(root)).Message); + Assert.Equal("Size of 4 is not valid. Expected size: 7, actual size: 1.", Assert.Throws(() => tree.ValidateSize(root)).Message); + tree.FixSizes(root); + tree.ValidateSizes(root); + // A wrong size below is found by the validation of the whole subtree, but not by the validation of the node alone. + tree.SetNode(1, 0, 0, 2); + tree.ValidateSize(root); + Assert.Equal("Size of 2 is not valid. Expected size: 4, actual size: 3.", Assert.Throws(() => tree.ValidateSizes(root)).Message); + tree.FixSizes(root); + tree.ValidateSizes(root); + Assert.Equal(7u, tree.SizeOf(root)); + } + + [Fact] + public static void SizesOfTheAVLTreeAreValidatedAndFixed() + { + var tree = new SizedAndThreadedAVLBalancedTree(8); + for (uint node = 1; node <= 7; node++) + { + tree.Attach(ref tree.Root, node); + } + tree.FixSizes(tree.Root); + tree.ValidateSizes(tree.Root); + Assert.Equal(7u, tree.SizeOf(tree.Root)); + } + + [Theory] + [MemberData(nameof(SizeBalancedTrees))] + public static void NodesArePrinted(bool recursionless) + { + var tree = CreateSizeBalancedTree(recursionless, 4); + for (uint node = 1; node <= 3; node++) + { + tree.Attach(ref tree.Root, node); + } + Assert.Equal("22 s3", tree.PrintNode(2)); + Assert.Equal($"\t11 s1{Environment.NewLine}22 s3{Environment.NewLine}\t33 s1{Environment.NewLine}", tree.PrintNodes(tree.Root)); + var sb = new StringBuilder(); + tree.PrintNodeTo(3, sb); + Assert.Equal("33 s1", sb.ToString()); + Assert.Equal(string.Empty, tree.PrintNodes(0)); + } + + [Fact] + public static void NodesOfTheAVLTreeArePrinted() + { + var tree = new SizedAndThreadedAVLBalancedTree(4); + for (uint node = 1; node <= 3; node++) + { + tree.Attach(ref tree.Root, node); + } + Assert.Equal("22 s3 lr 0", tree.PrintNode(2)); + Assert.Equal($"\t11 s1 LR 0{Environment.NewLine}22 s3 lr 0{Environment.NewLine}\t33 s1 LR 0{Environment.NewLine}", tree.PrintNodes(tree.Root)); + } + + [Theory] + [MemberData(nameof(SizeBalancedTrees))] + public static void NeighboursAreFound(bool recursionless) + { + const uint count = 100; + var tree = CreateSizeBalancedTree(recursionless, (int)count + 1); + var random = new System.Random(605); + foreach (var node in Enumerable.Range(1, (int)count).OrderBy(_ => random.Next())) + { + tree.Attach(ref tree.Root, (uint)node); + } + Assert.Equal(1u, tree.LeftestOf(tree.Root)); + Assert.Equal(count, tree.RightestOf(tree.Root)); + for (uint node = 1; node <= count; node++) + { + // Without threads only the neighbours inside the subtree of the node can be found. + if (tree.RightOf(node) != 0) + { + Assert.Equal(node + 1, tree.NextOf(node)); + } + if (tree.LeftOf(node) != 0) + { + Assert.Equal(node - 1, tree.PreviousOf(node)); + } + } + } + + [Fact] + public static void NeighboursAreFoundInTheAVLTree() + { + const uint count = 100; + var tree = new SizedAndThreadedAVLBalancedTree((int)count + 1); + var random = new System.Random(605); + foreach (var node in Enumerable.Range(1, (int)count).OrderBy(_ => random.Next())) + { + tree.Attach(ref tree.Root, (uint)node); + } + Assert.Equal(1u, tree.LeftestOf(tree.Root)); + Assert.Equal(count, tree.RightestOf(tree.Root)); + for (uint node = 1; node <= count; node++) + { + // Threads lead to the neighbours of every node. + Assert.Equal(node < count ? node + 1 : 0, tree.NextOf(node)); + Assert.Equal(node - 1, tree.PreviousOf(node)); + } + } + + /// + /// Rotations of the AVL tree keep the sizes, the threads and the balances right whatever the balances before the rotation are. + /// Повороты АВЛ-дерева сохраняют правильными размеры, нити и показатели баланса, какими бы ни были показатели баланса до поворота. + /// + [Fact] + public static void AVLRotationsKeepBalancesSizesAndThreads() + { + var random = new System.Random(476); + var branches = new HashSet(); + for (var trial = 0; trial < 300; trial++) + { + var count = random.Next(2, 40); + var tree = new SizedAndThreadedAVLBalancedTree(count + 1); + foreach (var node in Enumerable.Range(1, count).OrderBy(_ => random.Next())) + { + tree.Attach(ref tree.Root, (uint)node); + } + for (var rotation = 0; rotation < 8; rotation++) + { + var root = tree.Root; + var left = random.Next(2) == 0; + var child = left ? tree.RightOf(root) : tree.LeftOf(root); + if (child == 0) + { + left = !left; + child = left ? tree.RightOf(root) : tree.LeftOf(root); + } + int rootBalance = tree.BalanceOf(root), childBalance = tree.BalanceOf(child); + branches.Add($"{(left ? "L" : "R")}{Math.Sign(childBalance)}{Math.Sign(rootBalance)}"); + tree.Root = left ? tree.RotateLeftWithBalance(root) : tree.RotateRightWithBalance(root); + Assert.Equal(child, tree.Root); + AssertAvlLinks(tree, count); + } + } + // Every sign of the balance of the child was met with every sign of the balance of the root, in both directions. + Assert.True(branches.Count == 2 * 3 * 3, string.Join(",", branches)); + } + + private static void AssertAvlLinks(SizedAndThreadedAVLBalancedTree tree, int count) + { + var keys = new List(); + Height(tree.Root); + Assert.Equal(Enumerable.Range(1, count).Select(i => (uint)i), keys); + for (uint node = 1; node <= count; node++) + { + if (!tree.LeftIsChildOf(node)) + { + Assert.Equal(node - 1, tree.LeftLinkOf(node)); + } + if (!tree.RightIsChildOf(node)) + { + Assert.Equal(node < count ? node + 1 : 0, tree.RightLinkOf(node)); + } + } + + int Height(uint node) + { + if (node == 0) + { + return 0; + } + var left = Height(tree.LeftOf(node)); + keys.Add(node); + var right = Height(tree.RightOf(node)); + Assert.Equal(right - left, tree.BalanceOf(node)); + Assert.Equal(tree.SizeOf(tree.LeftOf(node)) + tree.SizeOf(tree.RightOf(node)) + 1, tree.SizeOf(node)); + return 1 + Math.Max(left, right); + } + } + + private static string AvlShape(SizedAndThreadedAVLBalancedTree tree, int count) + { + var shape = new StringBuilder().Append(tree.Root).Append(';'); + for (uint node = 1; node <= count; node++) + { + shape.Append(tree.LeftLinkOf(node)).Append(tree.LeftIsChildOf(node) ? 'l' : 'L').Append(',') + .Append(tree.RightLinkOf(node)).Append(tree.RightIsChildOf(node) ? 'r' : 'R').Append(',') + .Append(tree.SizeOf(node)).Append(',').Append(tree.BalanceOf(node)).Append(';'); + } + return shape.ToString(); + } + + private static ISizeBalancedTestTree CreateSizeBalancedTree(bool recursionless, int capacity) => recursionless + ? new RecursionlessTestTree(capacity) + : new RecursiveTestTree(capacity); + + /// + /// The members that the tests of this class use from both kinds of size balanced test trees. + /// Члены обоих видов тестовых деревьев, сбалансированных по размеру, используемые тестами этого класса. + /// + private interface ISizeBalancedTestTree : IInspectableTree + { + ref uint Root { get; } + + void Attach(ref uint root, uint node); + + void Detach(ref uint root, uint node); + + uint Rebuild(uint root); + + void SetNode(uint node, uint left, uint right, uint size); + + uint NextOf(uint node); + + uint PreviousOf(uint node); + + uint LeftestOf(uint node); + + uint RightestOf(uint node); + + void FixSizes(uint node); + + void ValidateSizes(uint node); + + void ValidateSize(uint node); + + string PrintNodes(uint node); + + string PrintNode(uint node); + + void PrintNodeTo(uint node, StringBuilder sb); + } + + private sealed class RecursiveTestTree : SizeBalancedTree, ISizeBalancedTestTree + { + public RecursiveTestTree(int capacity) : base(capacity) { } + + ref uint ISizeBalancedTestTree.Root => ref Root; + } + + private sealed class RecursionlessTestTree : RecursionlessSizeBalancedTree, ISizeBalancedTestTree + { + public RecursionlessTestTree(int capacity) : base(capacity) { } + + ref uint ISizeBalancedTestTree.Root => ref Root; + } + + /// + /// A tree whose key of a node is half of the node, so that two nodes can share one key. + /// Дерево, в котором ключ узла равен половине узла, поэтому два узла могут иметь один ключ. + /// + private sealed class HalfKeySizeBalancedTree : SizeBalancedTree + { + public HalfKeySizeBalancedTree() : base(8) { } + + protected override bool FirstIsToTheLeftOfSecond(uint first, uint second) => first / 2 < second / 2; + + protected override bool FirstIsToTheRightOfSecond(uint first, uint second) => first / 2 > second / 2; + } + + private sealed class HalfKeyRecursionlessSizeBalancedTree : RecursionlessSizeBalancedTree + { + public HalfKeyRecursionlessSizeBalancedTree() : base(8) { } + + protected override bool FirstIsToTheLeftOfSecond(uint first, uint second) => first / 2 < second / 2; + + protected override bool FirstIsToTheRightOfSecond(uint first, uint second) => first / 2 > second / 2; + } + } +} From 5fbdb8d10a327a19e36f3d62ccd79049299fec4b Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:00:52 +0000 Subject: [PATCH 10/46] Test C++ rotations, edge cases and lists like the C# tests Port the rotation, edge case and doubly linked list tests to C++, instrument the test trees to count rotations and size reads, and report the missing node in the detach error message as the C# trees do. --- .../AllTests.cpp | 3 + .../DoublyLinkedListTests.cpp | 193 ++++++++++ .../DoublyLinkedLists.cpp | 176 +++++++++ .../RecursionlessSizeBalancedTree.cpp | 67 +++- .../SizeBalancedTree.cpp | 67 +++- .../SizeBalancedTreeRotationTests.cpp | 277 ++++++++++++++ .../SizedAndThreadedAVLBalancedTree.cpp | 57 ++- .../TreeEdgeCaseTests.cpp | 340 ++++++++++++++++++ .../Trees.h | 5 + .../RecursionlessSizeBalancedTreeMethods.h | 2 +- .../Trees/SizeBalancedTreeMethods.h | 2 +- 11 files changed, 1180 insertions(+), 9 deletions(-) create mode 100644 cpp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cpp create mode 100644 cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp create mode 100644 cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp create mode 100644 cpp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cpp diff --git a/cpp/Platform.Collections.Methods.Tests/AllTests.cpp b/cpp/Platform.Collections.Methods.Tests/AllTests.cpp index 064810d..ca89363 100644 --- a/cpp/Platform.Collections.Methods.Tests/AllTests.cpp +++ b/cpp/Platform.Collections.Methods.Tests/AllTests.cpp @@ -3,3 +3,6 @@ #include "Trees.h" #include "TreesTests.cpp" #include "TreeBalanceTests.cpp" +#include "SizeBalancedTreeRotationTests.cpp" +#include "TreeEdgeCaseTests.cpp" +#include "DoublyLinkedListTests.cpp" diff --git a/cpp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cpp b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cpp new file mode 100644 index 0000000..f441b2f --- /dev/null +++ b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedListTests.cpp @@ -0,0 +1,193 @@ +namespace Platform::Collections::Methods::Tests +{ + /// + /// Checks every doubly linked list against a reference list after each operation. + /// Проверяет каждый двусвязный список по эталонному списку после каждой операции. + /// + namespace DoublyLinkedList + { + inline constexpr std::size_t Capacity = 64; + inline constexpr std::size_t Heads = 3; + + template void AssertEqual(const std::vector& expected, const TView& list) + { + ASSERT_EQ(expected.size(), list.Size()); + if (expected.empty()) + { + ASSERT_EQ(0u, list.First()); + ASSERT_EQ(0u, list.Last()); + return; + } + ASSERT_EQ(expected.front(), list.First()); + ASSERT_EQ(expected.back(), list.Last()); + for (std::size_t i = 0; i < expected.size(); i++) + { + auto element = expected[i]; + auto previous = i > 0 ? expected[i - 1] : list.IsCircular() ? expected.back() : 0u; + auto next = i < expected.size() - 1 ? expected[i + 1] : list.IsCircular() ? expected.front() : 0u; + ASSERT_EQ(previous, list.PreviousOf(element)) << "element " << element; + ASSERT_EQ(next, list.NextOf(element)) << "element " << element; + } + } + + inline std::uint32_t Take(std::vector& free, std::mt19937& random) + { + auto index = std::uniform_int_distribution(0, free.size() - 1)(random); + auto element = free[index]; + free[index] = free.back(); + free.pop_back(); + return element; + } + + inline std::size_t Below(std::size_t count, std::mt19937& random) { return std::uniform_int_distribution(0, count - 1)(random); } + + template void EveryOperationKeepsTheListConsistent(std::vector lists) + { + std::vector> models(lists.size()); + std::vector free; + for (std::uint32_t element = 1; element < Capacity; element++) + { + free.push_back(element); + } + std::mt19937 random(115); + int operations[5] = { 0 }; + for (auto step = 0; step < 20000; step++) + { + auto index = Below(lists.size(), random); + auto& list = lists[index]; + auto& model = models[index]; + if (model.empty() && free.empty()) + { + // The other lists hold every element, so this list can neither grow nor shrink. + continue; + } + auto operation = model.empty() ? Below(2, random) : free.empty() ? 4 : Below(5, random); + operations[operation]++; + switch (operation) + { + case 0: + { + auto element = Take(free, random); + list.AttachAsFirst(element); + model.insert(model.begin(), element); + break; + } + case 1: + { + auto element = Take(free, random); + list.AttachAsLast(element); + model.push_back(element); + break; + } + case 2: + { + auto position = Below(model.size(), random); + auto element = Take(free, random); + list.AttachBefore(model[position], element); + model.insert(model.begin() + position, element); + break; + } + case 3: + { + auto position = Below(model.size(), random); + auto element = Take(free, random); + list.AttachAfter(model[position], element); + model.insert(model.begin() + position + 1, element); + break; + } + default: + { + auto position = Below(model.size(), random); + auto element = model[position]; + list.Detach(element); + model.erase(model.begin() + position); + ASSERT_EQ(0u, list.PreviousOf(element)); + ASSERT_EQ(0u, list.NextOf(element)); + free.push_back(element); + break; + } + } + AssertEqual(model, list); + if (::testing::Test::HasFatalFailure()) + { + return; + } + } + for (auto count : operations) + { + ASSERT_GT(count, 1000); + } + } + + template void SingleElementListsAreLinkedToThemselvesOrToNothing(TView list) + { + list.AttachAsLast(7); + AssertEqual({ 7 }, list); + auto expectedLink = list.IsCircular() ? 7u : 0u; + ASSERT_EQ(expectedLink, list.PreviousOf(7)); + ASSERT_EQ(expectedLink, list.NextOf(7)); + list.Detach(7); + AssertEqual({}, list); + list.AttachAsFirst(9); + AssertEqual({ 9 }, list); + } + + template std::vector> Absolute(TList& list) { return { { &list, 0 } }; } + + template std::vector> Relative(TList& list) + { + std::vector> views; + for (std::uint32_t head = 0; head < Heads; head++) + { + views.push_back({ &list, head }); + } + return views; + } + + using AbsoluteCircular = AbsoluteCircularDoublyLinkedList; + using AbsoluteOpen = AbsoluteOpenDoublyLinkedList; + using RelativeCircular = RelativeCircularDoublyLinkedList; + using RelativeOpen = RelativeOpenDoublyLinkedList; + } + + TEST(DoublyLinkedListTests, AbsoluteCircularListKeepsConsistent) + { + using namespace DoublyLinkedList; + auto list = std::make_unique(); + EveryOperationKeepsTheListConsistent(Absolute(*list)); + } + + TEST(DoublyLinkedListTests, AbsoluteOpenListKeepsConsistent) + { + using namespace DoublyLinkedList; + auto list = std::make_unique(); + EveryOperationKeepsTheListConsistent(Absolute(*list)); + } + + TEST(DoublyLinkedListTests, RelativeCircularListsKeepConsistent) + { + using namespace DoublyLinkedList; + auto list = std::make_unique(); + EveryOperationKeepsTheListConsistent(Relative(*list)); + } + + TEST(DoublyLinkedListTests, RelativeOpenListsKeepConsistent) + { + using namespace DoublyLinkedList; + auto list = std::make_unique(); + EveryOperationKeepsTheListConsistent(Relative(*list)); + } + + TEST(DoublyLinkedListTests, SingleElementListsAreLinkedToThemselvesOrToNothing) + { + using namespace DoublyLinkedList; + auto absoluteCircular = std::make_unique(); + SingleElementListsAreLinkedToThemselvesOrToNothing(Absolute(*absoluteCircular)[0]); + auto absoluteOpen = std::make_unique(); + SingleElementListsAreLinkedToThemselvesOrToNothing(Absolute(*absoluteOpen)[0]); + auto relativeCircular = std::make_unique(); + SingleElementListsAreLinkedToThemselvesOrToNothing(Relative(*relativeCircular)[0]); + auto relativeOpen = std::make_unique(); + SingleElementListsAreLinkedToThemselvesOrToNothing(Relative(*relativeOpen)[0]); + } +} diff --git a/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp new file mode 100644 index 0000000..6e0d357 --- /dev/null +++ b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp @@ -0,0 +1,176 @@ +namespace Platform::Collections::Methods::Tests +{ + /// + /// Storage of the links of the test lists: one array of previous and one array of next elements, shared by all lists of a test. + /// Хранилище связей тестовых списков: один массив предыдущих и один массив следующих элементов, общие для всех списков теста. + /// + template struct ListLinks + { + public: std::uint32_t Previous[N] = { 0 }; + public: std::uint32_t Next[N] = { 0 }; + }; + + template class AbsoluteCircularDoublyLinkedList : public Platform::Collections::Methods::Lists::AbsoluteCircularDoublyLinkedListMethods, std::uint32_t> + { + + public: static constexpr bool IsCircular = true; + + public: ListLinks Links; + public: std::uint32_t First = 0; + public: std::uint32_t Last = 0; + public: std::uint32_t Size = 0; + + public: std::uint32_t GetFirst() { return First; } + + public: std::uint32_t GetLast() { return Last; } + + public: std::uint32_t GetSize() { return Size; } + + public: void SetFirst(std::uint32_t element) { First = element; } + + public: void SetLast(std::uint32_t element) { Last = element; } + + public: void SetSize(std::uint32_t size) { Size = size; } + + public: std::uint32_t GetPrevious(std::uint32_t element) { return Links.Previous[element]; } + + public: std::uint32_t GetNext(std::uint32_t element) { return Links.Next[element]; } + + public: void SetPrevious(std::uint32_t element, std::uint32_t previous) { Links.Previous[element] = previous; } + + public: void SetNext(std::uint32_t element, std::uint32_t next) { Links.Next[element] = next; } + }; + + template class AbsoluteOpenDoublyLinkedList : public Platform::Collections::Methods::Lists::AbsoluteOpenDoublyLinkedListMethods, std::uint32_t> + { + + public: static constexpr bool IsCircular = false; + + public: ListLinks Links; + public: std::uint32_t First = 0; + public: std::uint32_t Last = 0; + public: std::uint32_t Size = 0; + + public: std::uint32_t GetFirst() { return First; } + + public: std::uint32_t GetLast() { return Last; } + + public: std::uint32_t GetSize() { return Size; } + + public: void SetFirst(std::uint32_t element) { First = element; } + + public: void SetLast(std::uint32_t element) { Last = element; } + + public: void SetSize(std::uint32_t size) { Size = size; } + + public: std::uint32_t GetPrevious(std::uint32_t element) { return Links.Previous[element]; } + + public: std::uint32_t GetNext(std::uint32_t element) { return Links.Next[element]; } + + public: void SetPrevious(std::uint32_t element, std::uint32_t previous) { Links.Previous[element] = previous; } + + public: void SetNext(std::uint32_t element, std::uint32_t next) { Links.Next[element] = next; } + }; + + /// + /// Several circular lists that share one storage; each list is identified by its head element. + /// Несколько кольцевых списков с общим хранилищем; каждый список определяется своим головным элементом. + /// + template class RelativeCircularDoublyLinkedList : public Platform::Collections::Methods::Lists::RelativeCircularDoublyLinkedListMethods, std::uint32_t> + { + + public: static constexpr bool IsCircular = true; + + public: ListLinks Links; + public: std::uint32_t First[Heads] = { 0 }; + public: std::uint32_t Last[Heads] = { 0 }; + public: std::uint32_t Size[Heads] = { 0 }; + + public: std::uint32_t GetFirst(std::uint32_t headElement) { return First[headElement]; } + + public: std::uint32_t GetLast(std::uint32_t headElement) { return Last[headElement]; } + + public: std::uint32_t GetSize(std::uint32_t headElement) { return Size[headElement]; } + + public: void SetFirst(std::uint32_t headElement, std::uint32_t element) { First[headElement] = element; } + + public: void SetLast(std::uint32_t headElement, std::uint32_t element) { Last[headElement] = element; } + + public: void SetSize(std::uint32_t headElement, std::uint32_t size) { Size[headElement] = size; } + + public: std::uint32_t GetPrevious(std::uint32_t element) { return Links.Previous[element]; } + + public: std::uint32_t GetNext(std::uint32_t element) { return Links.Next[element]; } + + public: void SetPrevious(std::uint32_t element, std::uint32_t previous) { Links.Previous[element] = previous; } + + public: void SetNext(std::uint32_t element, std::uint32_t next) { Links.Next[element] = next; } + }; + + /// + /// Several open lists that share one storage; each list is identified by its head element. + /// Несколько незамкнутых списков с общим хранилищем; каждый список определяется своим головным элементом. + /// + template class RelativeOpenDoublyLinkedList : public Platform::Collections::Methods::Lists::RelativeOpenDoublyLinkedListMethods, std::uint32_t> + { + + public: static constexpr bool IsCircular = false; + + public: ListLinks Links; + public: std::uint32_t First[Heads] = { 0 }; + public: std::uint32_t Last[Heads] = { 0 }; + public: std::uint32_t Size[Heads] = { 0 }; + + public: std::uint32_t GetFirst(std::uint32_t headElement) { return First[headElement]; } + + public: std::uint32_t GetLast(std::uint32_t headElement) { return Last[headElement]; } + + public: std::uint32_t GetSize(std::uint32_t headElement) { return Size[headElement]; } + + public: void SetFirst(std::uint32_t headElement, std::uint32_t element) { First[headElement] = element; } + + public: void SetLast(std::uint32_t headElement, std::uint32_t element) { Last[headElement] = element; } + + public: void SetSize(std::uint32_t headElement, std::uint32_t size) { Size[headElement] = size; } + + public: std::uint32_t GetPrevious(std::uint32_t element) { return Links.Previous[element]; } + + public: std::uint32_t GetNext(std::uint32_t element) { return Links.Next[element]; } + + public: void SetPrevious(std::uint32_t element, std::uint32_t previous) { Links.Previous[element] = previous; } + + public: void SetNext(std::uint32_t element, std::uint32_t next) { Links.Next[element] = next; } + }; + + /// + /// One list of a test, absolute or relative to a head element, with a common interface for the list tests. + /// Один список теста, абсолютный или относительный головного элемента, с общим интерфейсом для тестов списков. + /// + template struct ListView + { + public: TList* List; + public: std::uint32_t Head; + + public: bool IsCircular() const { return TList::IsCircular; } + + public: std::uint32_t First() const { if constexpr (Relative) { return List->First[Head]; } else { return List->First; } } + + public: std::uint32_t Last() const { if constexpr (Relative) { return List->Last[Head]; } else { return List->Last; } } + + public: std::uint32_t Size() const { if constexpr (Relative) { return List->Size[Head]; } else { return List->Size; } } + + public: std::uint32_t PreviousOf(std::uint32_t element) const { return List->Links.Previous[element]; } + + public: std::uint32_t NextOf(std::uint32_t element) const { return List->Links.Next[element]; } + + public: void AttachBefore(std::uint32_t baseElement, std::uint32_t newElement) { if constexpr (Relative) { List->AttachBefore(Head, baseElement, newElement); } else { List->AttachBefore(baseElement, newElement); } } + + public: void AttachAfter(std::uint32_t baseElement, std::uint32_t newElement) { if constexpr (Relative) { List->AttachAfter(Head, baseElement, newElement); } else { List->AttachAfter(baseElement, newElement); } } + + public: void AttachAsFirst(std::uint32_t element) { if constexpr (Relative) { List->AttachAsFirst(Head, element); } else { List->AttachAsFirst(element); } } + + public: void AttachAsLast(std::uint32_t element) { if constexpr (Relative) { List->AttachAsLast(Head, element); } else { List->AttachAsLast(element); } } + + public: void Detach(std::uint32_t element) { if constexpr (Relative) { List->Detach(Head, element); } else { List->Detach(element); } } + }; +} diff --git a/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp b/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp index a71a0ea..5b63feb 100644 --- a/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp +++ b/cpp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cpp @@ -27,6 +27,63 @@ public: TElement SizeOf(TElement node) { return this->GetSizeOrZero(node); } + /// + /// The number of rotations and of size reads, and the log of the rotations when LogRotations is set. + /// Число поворотов и чтений размера, а также журнал поворотов, если установлен LogRotations. + /// + public: std::int64_t Rotations = 0; + + public: std::int64_t SizeReads = 0; + + public: bool LogRotations = false; + + public: std::vector RotationLog; + + public: TElement NextOf(TElement node) { return this->GetNext(node); } + + public: TElement PreviousOf(TElement node) { return this->GetPrevious(node); } + + public: TElement LeftestOf(TElement node) { return this->GetLeftest(node); } + + public: TElement RightestOf(TElement node) { return this->GetRightest(node); } + + /// + /// Nodes are compared by node >> KeyShift, so that tests can give several nodes the same key. + /// Узлы сравниваются по node >> KeyShift, чтобы тесты могли дать нескольким узлам один ключ. + /// + public: int KeyShift = 0; + + public: TElement Rebuild(TElement root) + { + this->RebuildComplete(&root); + return root; + } + + public: using base::LeftRotate; + + public: using base::RightRotate; + + public: TElement LeftRotate(TElement root) + { + this->CountRotation("L", root); + return base::LeftRotate(root); + } + + public: TElement RightRotate(TElement root) + { + this->CountRotation("R", root); + return base::RightRotate(root); + } + + private: void CountRotation(const char* direction, TElement root) + { + Rotations++; + if (LogRotations) + { + RotationLog.push_back(direction + std::to_string(root)); + } + } + /// /// Writes a node directly, so that tests can build trees that other code could have built. /// Записывает узел напрямую, чтобы тесты могли строить деревья, которые мог построить другой код. @@ -73,9 +130,9 @@ public: bool IsEmpty(TElement node) { return iszero(this->GetElement(node), sizeof(TreeElement)); } - protected: bool FirstIsToTheLeftOfSecond(TElement first, TElement second) { return first < second; } + protected: bool FirstIsToTheLeftOfSecond(TElement first, TElement second) { return (first >> KeyShift) < (second >> KeyShift); } - protected: bool FirstIsToTheRightOfSecond(TElement first, TElement second) { return first > second; } + protected: bool FirstIsToTheRightOfSecond(TElement first, TElement second) { return (first >> KeyShift) > (second >> KeyShift); } protected: TElement* GetLeftReference(TElement node) { return &GetElement(node)->Left; } @@ -85,7 +142,11 @@ protected: TElement GetRight(TElement node) { return this->GetElement(node)->Right; } - protected: TElement GetSize(TElement node) { return this->GetElement(node)->Size; } + protected: TElement GetSize(TElement node) + { + SizeReads++; + return this->GetElement(node)->Size; + } protected: void SetLeft(TElement node, TElement left) { this->GetElement(node)->Left = left; } diff --git a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp index 5916ea8..fb6d02c 100644 --- a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp +++ b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTree.cpp @@ -27,6 +27,63 @@ public: TElement SizeOf(TElement node) { return this->GetSizeOrZero(node); } + /// + /// The number of rotations and of size reads, and the log of the rotations when LogRotations is set. + /// Число поворотов и чтений размера, а также журнал поворотов, если установлен LogRotations. + /// + public: std::int64_t Rotations = 0; + + public: std::int64_t SizeReads = 0; + + public: bool LogRotations = false; + + public: std::vector RotationLog; + + public: TElement NextOf(TElement node) { return this->GetNext(node); } + + public: TElement PreviousOf(TElement node) { return this->GetPrevious(node); } + + public: TElement LeftestOf(TElement node) { return this->GetLeftest(node); } + + public: TElement RightestOf(TElement node) { return this->GetRightest(node); } + + /// + /// Nodes are compared by node >> KeyShift, so that tests can give several nodes the same key. + /// Узлы сравниваются по node >> KeyShift, чтобы тесты могли дать нескольким узлам один ключ. + /// + public: int KeyShift = 0; + + public: TElement Rebuild(TElement root) + { + this->RebuildComplete(&root); + return root; + } + + public: using base::LeftRotate; + + public: using base::RightRotate; + + public: TElement LeftRotate(TElement root) + { + this->CountRotation("L", root); + return base::LeftRotate(root); + } + + public: TElement RightRotate(TElement root) + { + this->CountRotation("R", root); + return base::RightRotate(root); + } + + private: void CountRotation(const char* direction, TElement root) + { + Rotations++; + if (LogRotations) + { + RotationLog.push_back(direction + std::to_string(root)); + } + } + /// /// Writes a node directly, so that tests can build trees that other code could have built. /// Записывает узел напрямую, чтобы тесты могли строить деревья, которые мог построить другой код. @@ -73,9 +130,9 @@ public: bool IsEmpty(TElement node) { return iszero(this->GetElement(node), sizeof(TreeElement)); } - protected: bool FirstIsToTheLeftOfSecond(TElement first, TElement second) { return first < second; } + protected: bool FirstIsToTheLeftOfSecond(TElement first, TElement second) { return (first >> KeyShift) < (second >> KeyShift); } - protected: bool FirstIsToTheRightOfSecond(TElement first, TElement second) { return first > second; } + protected: bool FirstIsToTheRightOfSecond(TElement first, TElement second) { return (first >> KeyShift) > (second >> KeyShift); } protected: TElement* GetLeftReference(TElement node) { return &GetElement(node)->Left; } @@ -85,7 +142,11 @@ protected: TElement GetRight(TElement node) { return this->GetElement(node)->Right; } - protected: TElement GetSize(TElement node) { return this->GetElement(node)->Size; } + protected: TElement GetSize(TElement node) + { + SizeReads++; + return this->GetElement(node)->Size; + } protected: void SetLeft(TElement node, TElement left) { this->GetElement(node)->Left = left; } diff --git a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp new file mode 100644 index 0000000..b6e8ee3 --- /dev/null +++ b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp @@ -0,0 +1,277 @@ +namespace Platform::Collections::Methods::Tests +{ + /// + /// Checks that size balanced trees rotate only when the size balanced tree properties require it and that both implementations make the same rotations. + /// Проверяет, что деревья, сбалансированные по размеру, делают повороты только тогда, когда этого требуют свойства дерева, и что обе реализации делают одинаковые повороты. + /// + namespace SizeBalancedTreeRotation + { + using TreeBalance::Capacity; + using TreeBalance::N; + + /// + /// Whether inserting the key with a plain binary search tree insertion would break a size balanced tree property. + /// Нарушила бы вставка ключа простой вставкой в двоичное дерево поиска свойство дерева, сбалансированного по размеру. + /// + /// + /// Only the sizes of the nodes on the path grow, so only the checks of a grandparent g against its child p on the path + /// and the sibling of p can fail: the sibling must stay at least as large as the grown child c of p. + /// + template bool InsertionBreaksSizeBalance(TTree& tree, std::uint32_t root, std::uint32_t key) + { + std::vector path; + for (auto node = root; node != 0; node = key < node ? tree.LeftOf(node) : tree.RightOf(node)) + { + path.push_back(node); + } + path.push_back(0); // The new node. + for (std::size_t i = 2; i < path.size(); i++) + { + auto grandparent = path[i - 2]; + auto parent = path[i - 1]; + auto sibling = tree.LeftOf(grandparent) == parent ? tree.RightOf(grandparent) : tree.LeftOf(grandparent); + auto grownChildSize = tree.SizeOf(path[i]) + 1; + if (tree.SizeOf(sibling) < grownChildSize) + { + return true; + } + } + return false; + } + + /// + /// Checks the sizes, the order of the keys, the height bound and, for size balanced trees, Chen's properties. + /// Проверяет размеры, порядок ключей, ограничение высоты и, для деревьев, сбалансированных по размеру, свойства Чена. + /// + template void AssertValid(TTree& tree, std::uint32_t root, std::uint32_t count, bool sizeBalanced = true) + { + ASSERT_EQ(count, tree.SizeOf(root)); + ASSERT_LE(TreeBalance::Height(tree, root), TreeBalance::MaximumHeight(count)); + std::vector keys; + std::function walk = [&](std::uint32_t node) + { + if (node == 0) + { + return; + } + auto left = tree.LeftOf(node); + auto right = tree.RightOf(node); + ASSERT_EQ(tree.SizeOf(left) + tree.SizeOf(right) + 1, tree.SizeOf(node)); + if (sizeBalanced) + { + ASSERT_GE(tree.SizeOf(left), std::max(tree.SizeOf(tree.LeftOf(right)), tree.SizeOf(tree.RightOf(right)))); + ASSERT_GE(tree.SizeOf(right), std::max(tree.SizeOf(tree.LeftOf(left)), tree.SizeOf(tree.RightOf(left)))); + } + walk(left); + keys.push_back(node); + walk(right); + }; + walk(root); + ASSERT_TRUE(std::is_sorted(keys.begin(), keys.end())); + } + + template std::string Shape(TTree& tree, std::uint32_t root, std::uint32_t count) + { + auto shape = std::to_string(root) + ";"; + for (std::uint32_t node = 1; node <= count; node++) + { + shape += std::to_string(tree.LeftOf(node)) + "," + std::to_string(tree.RightOf(node)) + "," + std::to_string(tree.SizeOf(node)) + ";"; + } + return shape; + } + + inline const std::string Workloads[] = { "Ascending", "Descending", "Random", "InterleavedHotAndCold", "AlternatingEnds" }; + + using SizeBalanced = SizeBalancedTree; + using RecursionlessSizeBalanced = RecursionlessSizeBalancedTree; + } + + /// + /// An attach rotates if and only if the plain binary search tree insertion would break a size balanced tree property. + /// Присоединение делает поворот тогда и только тогда, когда простая вставка в двоичное дерево поиска нарушила бы свойство дерева, сбалансированного по размеру. + /// + TEST(SizeBalancedTreeRotationTests, AttachRotatesOnlyWhenThePropertiesRequireIt) + { + using namespace SizeBalancedTreeRotation; + for (const auto& workload : Workloads) + { + SCOPED_TRACE(workload); + auto recursive = std::make_unique(); + auto recursionless = std::make_unique(); + recursive->LogRotations = recursionless->LogRotations = true; + auto keys = TreeBalance::Keys(workload); + auto attachesWithRotations = 0; + for (auto key : keys) + { + auto needsRotations = InsertionBreaksSizeBalance(*recursive, recursive->Root, key); + recursive->RotationLog.clear(); + recursionless->RotationLog.clear(); + recursive->Attach(&recursive->Root, key); + recursionless->Attach(&recursionless->Root, key); + ASSERT_EQ(needsRotations, !recursive->RotationLog.empty()) << "key " << key; + ASSERT_EQ(recursive->RotationLog, recursionless->RotationLog) << "key " << key; + attachesWithRotations += needsRotations ? 1 : 0; + } + auto count = static_cast(keys.size()); + ASSERT_EQ(Shape(*recursive, recursive->Root, count), Shape(*recursionless, recursionless->Root, count)); + std::cout << workload << ": " << attachesWithRotations << " of " << count << " attaches rotated, " << recursive->Rotations << " rotations in total." << std::endl; + } + } + + /// + /// Inserting the keys of a complete tree level by level never breaks the properties, so no rotations happen and the tree stays complete. + /// Вставка ключей полного дерева по уровням никогда не нарушает свойств, поэтому поворотов нет и дерево остаётся полным. + /// + TEST(SizeBalancedTreeRotationTests, LevelOrderAttachOfACompleteTreeMakesNoRotations) + { + using namespace SizeBalancedTreeRotation; + const std::uint32_t count = 1023; + auto recursive = std::make_unique(); + auto recursionless = std::make_unique(); + std::vector> level { { 1, count } }; + while (!level.empty()) + { + std::vector> next; + for (auto [low, high] : level) + { + auto middle = (low + high) / 2; + recursive->Attach(&recursive->Root, middle); + recursionless->Attach(&recursionless->Root, middle); + if (low < middle) + { + next.emplace_back(low, middle - 1); + } + if (middle < high) + { + next.emplace_back(middle + 1, high); + } + } + level = next; + } + ASSERT_EQ(0, recursive->Rotations); + ASSERT_EQ(0, recursionless->Rotations); + ASSERT_EQ(10, TreeBalance::Height(*recursive, recursive->Root)); + ASSERT_EQ(Shape(*recursive, recursive->Root, count), Shape(*recursionless, recursionless->Root, count)); + } + + /// + /// Both implementations make exactly the same rotations in any mix of attaches and detaches. + /// Обе реализации делают в точности одинаковые повороты при любом сочетании присоединений и отсоединений. + /// + TEST(SizeBalancedTreeRotationTests, RecursiveAndRecursionlessTreesMakeTheSameRotations) + { + using namespace SizeBalancedTreeRotation; + auto recursive = std::make_unique(); + auto recursionless = std::make_unique(); + recursive->LogRotations = recursionless->LogRotations = true; + std::mt19937 random(116); + std::uniform_int_distribution keys(1, N); + std::unordered_set present; + for (std::uint32_t step = 0; step < 16 * N; step++) + { + auto key = keys(random); + if (present.erase(key) != 0) + { + recursive->Detach(&recursive->Root, key); + recursionless->Detach(&recursionless->Root, key); + } + else + { + present.insert(key); + recursive->Attach(&recursive->Root, key); + recursionless->Attach(&recursionless->Root, key); + } + ASSERT_EQ(recursive->RotationLog.size(), recursionless->RotationLog.size()) << "step " << step; + } + ASSERT_EQ(recursive->RotationLog, recursionless->RotationLog); + ASSERT_GT(recursive->Rotations, 0); + } + + /// + /// Size balanced trees make O(1) rotations per attach on average (Chen, 2007), so the total stays linear even for sorted input. + /// Деревья, сбалансированные по размеру, делают в среднем O(1) поворотов на присоединение (Чэнь, 2007), поэтому общее число остаётся линейным даже для упорядоченного ввода. + /// + TEST(SizeBalancedTreeRotationTests, RotationsPerAttachAreConstantOnAverage) + { + using namespace SizeBalancedTreeRotation; + for (const auto& workload : Workloads) + { + SCOPED_TRACE(workload); + auto tree = std::make_unique(); + auto keys = TreeBalance::Keys(workload); + for (auto key : keys) + { + tree->Attach(&tree->Root, key); + } + std::cout << workload << ": " << tree->Rotations << " rotations for " << keys.size() << " attaches." << std::endl; + ASSERT_LE(tree->Rotations, static_cast(2 * keys.size())); + } + } + + /// + /// The recursionless attach uses the direction of the attach to skip the checks that cannot fail, so it reads fewer sizes than Chen's Maintain. + /// Нерекурсивное присоединение использует направление присоединения, чтобы пропускать проверки, которые не могут не пройти, поэтому читает меньше размеров, чем Maintain Чэня. + /// + TEST(SizeBalancedTreeRotationTests, RecursionlessAttachReadsFewerSizes) + { + using namespace SizeBalancedTreeRotation; + for (const auto& workload : Workloads) + { + SCOPED_TRACE(workload); + auto recursive = std::make_unique(); + auto recursionless = std::make_unique(); + for (auto key : TreeBalance::Keys(workload)) + { + recursive->Attach(&recursive->Root, key); + recursionless->Attach(&recursionless->Root, key); + } + std::cout << workload << ": recursive " << recursive->SizeReads << ", recursionless " << recursionless->SizeReads << " size reads." << std::endl; + ASSERT_LT(recursionless->SizeReads, recursive->SizeReads); + } + } + + /// + /// Every order of attaches and detaches of up to 8 nodes keeps the properties and gives the same tree in both implementations. + /// Любой порядок присоединений и отсоединений до 8 узлов сохраняет свойства и даёт одинаковое дерево в обеих реализациях. + /// + TEST(SizeBalancedTreeRotationTests, EveryOrderOfUpToEightNodesKeepsTheProperties) + { + using namespace SizeBalancedTreeRotation; + for (std::uint32_t count = 1; count <= 8; count++) + { + std::vector order(count); + std::iota(order.begin(), order.end(), 1u); + do + { + auto recursive = std::make_unique>(); + auto recursionless = std::make_unique>(); + auto avl = std::make_unique>(); + recursive->LogRotations = recursionless->LogRotations = true; + for (std::uint32_t i = 0; i < count; i++) + { + auto needsRotations = InsertionBreaksSizeBalance(*recursive, recursive->Root, order[i]); + auto rotations = recursive->Rotations; + recursive->Attach(&recursive->Root, order[i]); + recursionless->Attach(&recursionless->Root, order[i]); + avl->Attach(&avl->Root, order[i]); + ASSERT_EQ(needsRotations, recursive->Rotations > rotations); + AssertValid(*recursive, recursive->Root, i + 1); + AssertValid(*avl, avl->Root, i + 1, false); + ASSERT_EQ(Shape(*recursive, recursive->Root, count), Shape(*recursionless, recursionless->Root, count)); + } + // Detach in the same order, so that every order of detaches is also checked. + for (std::uint32_t i = 0; i < count; i++) + { + recursive->Detach(&recursive->Root, order[i]); + recursionless->Detach(&recursionless->Root, order[i]); + avl->Detach(&avl->Root, order[i]); + AssertValid(*recursive, recursive->Root, count - i - 1); + AssertValid(*avl, avl->Root, count - i - 1, false); + ASSERT_EQ(Shape(*recursive, recursive->Root, count), Shape(*recursionless, recursionless->Root, count)); + } + ASSERT_EQ(recursive->RotationLog, recursionless->RotationLog); + } + while (std::next_permutation(order.begin(), order.end())); + } + } +} diff --git a/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp b/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp index 35de2d6..190e223 100644 --- a/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp +++ b/cpp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cpp @@ -30,6 +30,57 @@ public: TElement SizeOf(TElement node) { return this->GetSizeOrZero(node); } + /// + /// The number of rotations and of size reads, and the log of the rotations when LogRotations is set. + /// Число поворотов и чтений размера, а также журнал поворотов, если установлен LogRotations. + /// + public: std::int64_t Rotations = 0; + + public: std::int64_t SizeReads = 0; + + public: bool LogRotations = false; + + public: std::vector RotationLog; + + public: TElement NextOf(TElement node) { return this->GetNext(node); } + + public: TElement PreviousOf(TElement node) { return this->GetPrevious(node); } + + public: TElement LeftestOf(TElement node) { return this->GetLeftest(node); } + + public: TElement RightestOf(TElement node) { return this->GetRightest(node); } + + public: std::int8_t BalanceOf(TElement node) { return this->GetBalance(node); } + + public: bool LeftIsChildOf(TElement node) { return this->GetLeftIsChild(node); } + + public: bool RightIsChildOf(TElement node) { return this->GetRightIsChild(node); } + + public: TElement LeftLinkOf(TElement node) { return this->GetLeft(node); } + + public: TElement RightLinkOf(TElement node) { return this->GetRight(node); } + + public: TElement RotateLeftWithBalance(TElement node) + { + this->CountRotation("L", node); + return this->LeftRotateWithBalance(node); + } + + public: TElement RotateRightWithBalance(TElement node) + { + this->CountRotation("R", node); + return this->RightRotateWithBalance(node); + } + + private: void CountRotation(const char* direction, TElement root) + { + Rotations++; + if (LogRotations) + { + RotationLog.push_back(direction + std::to_string(root)); + } + } + public: SizedAndThreadedAVLBalancedTree() { _allocated = 1; } public: TElement Allocate() @@ -83,7 +134,11 @@ protected: TElement GetRight(TElement node) { return this->GetElement(node)->Right; } - protected: TElement GetSize(TElement node) { return this->GetElement(node)->Size; } + protected: TElement GetSize(TElement node) + { + SizeReads++; + return this->GetElement(node)->Size; + } protected: void SetBalance(TElement node, std::int8_t value) { this->GetElement(node)->Balance = value; } diff --git a/cpp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cpp b/cpp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cpp new file mode 100644 index 0000000..145491b --- /dev/null +++ b/cpp/Platform.Collections.Methods.Tests/TreeEdgeCaseTests.cpp @@ -0,0 +1,340 @@ +namespace Platform::Collections::Methods::Tests +{ + /// + /// Checks failed operations, the helper methods of the trees and the rotations of the AVL tree. + /// Проверяет неудачные операции, вспомогательные методы деревьев и повороты АВЛ-дерева. + /// + namespace TreeEdgeCase + { + template std::string MessageOf(TAction action) + { + try + { + action(); + } + catch (const std::runtime_error& exception) + { + return exception.what(); + } + return "no exception"; + } + + template void DetachOfAMissingNodeLeavesTheTreeIntact() + { + auto tree = std::make_unique(); + ASSERT_EQ("The node 1 is not in the tree.", MessageOf([&] { tree->Detach(&tree->Root, 1); })); + for (std::uint32_t node = 2; node <= 12; node += 2) + { + tree->Attach(&tree->Root, node); + } + auto shape = SizeBalancedTreeRotation::Shape(*tree, tree->Root, 14); + for (std::uint32_t missing : { 1u, 5u, 13u }) + { + ASSERT_EQ("The node " + std::to_string(missing) + " is not in the tree.", MessageOf([&] { tree->Detach(&tree->Root, missing); })); + ASSERT_EQ(shape, SizeBalancedTreeRotation::Shape(*tree, tree->Root, 14)); + } + } + + template void DetachOfANodeWhoseKeyIsSharedFailsAndLeavesTheTreeIntact() + { + auto tree = std::make_unique(); + // The key of a node is half of the node, so nodes 2 and 3 have the same key 1 and the second one goes to the right of the first one. + tree->KeyShift = 1; + tree->Attach(&tree->Root, 2); + tree->Attach(&tree->Root, 3); + ASSERT_EQ(2u, tree->Root); + auto shape = SizeBalancedTreeRotation::Shape(*tree, tree->Root, 5); + ASSERT_EQ("Duplicate link found in the tree.", MessageOf([&] { tree->Detach(&tree->Root, 3); })); + ASSERT_EQ(shape, SizeBalancedTreeRotation::Shape(*tree, tree->Root, 5)); + ASSERT_TRUE(tree->Contains(3, tree->Root)); + tree->Detach(&tree->Root, 2); + tree->Detach(&tree->Root, 3); + ASSERT_EQ(0u, tree->Root); + } + + template void RebuildMakesACompleteTree() + { + auto tree = std::make_unique(); + ASSERT_EQ(0u, tree->Rebuild(0)); + for (std::uint32_t count = 1; count <= 128; count++) + { + // A path of left children: the largest key is the root. + for (std::uint32_t node = 1; node <= count; node++) + { + tree->SetNode(node, node > 1 ? node - 1 : 0, 0, node); + } + auto root = tree->Rebuild(count); + SizeBalancedTreeRotation::AssertValid(*tree, root, count); + ASSERT_EQ(std::bit_width(count), TreeBalance::Height(*tree, root)); + } + } + + template void SizesAreValidatedAndFixed() + { + auto tree = std::make_unique(); + tree->FixSizes(0); + tree->ValidateSizes(0); + for (std::uint32_t node = 1; node <= 7; node++) + { + tree->Attach(&tree->Root, node); + } + tree->ValidateSizes(tree->Root); + tree->ValidateSize(tree->Root); + auto root = tree->Root; + ASSERT_EQ(4u, root); + tree->SetNode(root, tree->LeftOf(root), tree->RightOf(root), 1); + ASSERT_EQ("Size of 4 is not valid. Expected size: 7, actual size: 1.", MessageOf([&] { tree->ValidateSizes(root); })); + ASSERT_EQ("Size of 4 is not valid. Expected size: 7, actual size: 1.", MessageOf([&] { tree->ValidateSize(root); })); + tree->FixSizes(root); + tree->ValidateSizes(root); + // A wrong size below is found by the validation of the whole subtree, but not by the validation of the node alone. + tree->SetNode(1, 0, 0, 2); + tree->ValidateSize(root); + ASSERT_EQ("Size of 2 is not valid. Expected size: 4, actual size: 3.", MessageOf([&] { tree->ValidateSizes(root); })); + tree->FixSizes(root); + tree->ValidateSizes(root); + ASSERT_EQ(7u, tree->SizeOf(root)); + } + + template void NeighboursAreFound() + { + const std::uint32_t count = 100; + auto tree = std::make_unique(); + std::vector nodes(count); + std::iota(nodes.begin(), nodes.end(), 1u); + std::mt19937 random(605); + std::shuffle(nodes.begin(), nodes.end(), random); + for (auto node : nodes) + { + tree->Attach(&tree->Root, node); + } + ASSERT_EQ(1u, tree->LeftestOf(tree->Root)); + ASSERT_EQ(count, tree->RightestOf(tree->Root)); + for (std::uint32_t node = 1; node <= count; node++) + { + // Without threads only the neighbours inside the subtree of the node can be found. + if (tree->RightOf(node) != 0) + { + ASSERT_EQ(node + 1, tree->NextOf(node)); + } + if (tree->LeftOf(node) != 0) + { + ASSERT_EQ(node - 1, tree->PreviousOf(node)); + } + } + } + + template void AssertAvlLinks(TTree& tree, std::uint32_t count) + { + std::vector keys; + std::function height = [&](std::uint32_t node) + { + if (node == 0) + { + return 0; + } + auto left = height(tree.LeftOf(node)); + keys.push_back(node); + auto right = height(tree.RightOf(node)); + EXPECT_EQ(right - left, tree.BalanceOf(node)) << "node " << node; + EXPECT_EQ(tree.SizeOf(tree.LeftOf(node)) + tree.SizeOf(tree.RightOf(node)) + 1, tree.SizeOf(node)) << "node " << node; + return 1 + std::max(left, right); + }; + height(tree.Root); + std::vector expected(count); + std::iota(expected.begin(), expected.end(), 1u); + ASSERT_EQ(expected, keys); + for (std::uint32_t node = 1; node <= count; node++) + { + if (!tree.LeftIsChildOf(node)) + { + ASSERT_EQ(node - 1, tree.LeftLinkOf(node)); + } + if (!tree.RightIsChildOf(node)) + { + ASSERT_EQ(node < count ? node + 1 : 0, tree.RightLinkOf(node)); + } + } + } + + template std::string AvlShape(TTree& tree, std::uint32_t count) + { + auto shape = std::to_string(tree.Root) + ";"; + for (std::uint32_t node = 1; node <= count; node++) + { + shape += std::to_string(tree.LeftLinkOf(node)) + (tree.LeftIsChildOf(node) ? "l," : "L,") + + std::to_string(tree.RightLinkOf(node)) + (tree.RightIsChildOf(node) ? "r," : "R,") + + std::to_string(tree.SizeOf(node)) + "," + std::to_string(tree.BalanceOf(node)) + ";"; + } + return shape; + } + + /// + /// The maximum balanced height computed without the overflow check; doubles are exact enough to tell the terms of the sequence near the largest sizes apart. + /// Наибольшая сбалансированная высота, вычисленная без проверки переполнения; точности double достаточно, чтобы различить члены последовательности около наибольших размеров. + /// + inline int ReferenceMaximumBalancedHeight(double count) + { + auto height = 0; + double previous = 0; + double current = 1; + while (current <= count) + { + height++; + auto next = current + previous + 1; + previous = current; + current = next; + } + return height; + } + + using SizeBalanced = SizeBalancedTree<130, std::uint32_t>; + using RecursionlessSizeBalanced = RecursionlessSizeBalancedTree<130, std::uint32_t>; + } + + TEST(TreeEdgeCaseTests, SizeBalancedTreeDetachOfAMissingNodeLeavesTheTreeIntact) { TreeEdgeCase::DetachOfAMissingNodeLeavesTheTreeIntact(); } + + TEST(TreeEdgeCaseTests, RecursionlessSizeBalancedTreeDetachOfAMissingNodeLeavesTheTreeIntact) { TreeEdgeCase::DetachOfAMissingNodeLeavesTheTreeIntact(); } + + TEST(TreeEdgeCaseTests, SizeBalancedTreeDetachOfANodeWhoseKeyIsSharedFailsAndLeavesTheTreeIntact) { TreeEdgeCase::DetachOfANodeWhoseKeyIsSharedFailsAndLeavesTheTreeIntact(); } + + TEST(TreeEdgeCaseTests, RecursionlessSizeBalancedTreeDetachOfANodeWhoseKeyIsSharedFailsAndLeavesTheTreeIntact) { TreeEdgeCase::DetachOfANodeWhoseKeyIsSharedFailsAndLeavesTheTreeIntact(); } + + TEST(TreeEdgeCaseTests, SizeBalancedTreeRebuildMakesACompleteTree) { TreeEdgeCase::RebuildMakesACompleteTree(); } + + TEST(TreeEdgeCaseTests, RecursionlessSizeBalancedTreeRebuildMakesACompleteTree) { TreeEdgeCase::RebuildMakesACompleteTree(); } + + TEST(TreeEdgeCaseTests, SizeBalancedTreeSizesAreValidatedAndFixed) { TreeEdgeCase::SizesAreValidatedAndFixed(); } + + TEST(TreeEdgeCaseTests, RecursionlessSizeBalancedTreeSizesAreValidatedAndFixed) { TreeEdgeCase::SizesAreValidatedAndFixed(); } + + TEST(TreeEdgeCaseTests, SizeBalancedTreeNeighboursAreFound) { TreeEdgeCase::NeighboursAreFound(); } + + TEST(TreeEdgeCaseTests, RecursionlessSizeBalancedTreeNeighboursAreFound) { TreeEdgeCase::NeighboursAreFound(); } + + TEST(TreeEdgeCaseTests, FailedAttachAndDetachOfTheAVLTreeLeaveTheTreeIntact) + { + using namespace TreeEdgeCase; + auto tree = std::make_unique>(); + ASSERT_EQ("Cannot find a node.", MessageOf([&] { tree->Detach(&tree->Root, 1); })); + for (std::uint32_t node = 2; node <= 32; node += 2) + { + tree->Attach(&tree->Root, node); + } + auto shape = AvlShape(*tree, 33); + for (std::uint32_t node : { 2u, 16u, 32u, 10u }) + { + ASSERT_EQ("Node with the same key already attached to a tree.", MessageOf([&] { tree->Attach(&tree->Root, node); })); + ASSERT_EQ(shape, AvlShape(*tree, 33)); + } + for (std::uint32_t node : { 1u, 15u, 17u, 33u }) + { + ASSERT_EQ("Cannot find a node.", MessageOf([&] { tree->Detach(&tree->Root, node); })); + ASSERT_EQ(shape, AvlShape(*tree, 33)); + } + tree->ValidateSizes(tree->Root); + } + + TEST(TreeEdgeCaseTests, MaximumBalancedHeightMatchesTheSparsestTrees) + { + using namespace TreeEdgeCase; + using Base = Platform::Collections::Methods::Trees::SizedBinaryTreeMethodsBase; + ASSERT_EQ(0, Base::GetMaximumBalancedHeight(0)); + ASSERT_EQ(1, Base::GetMaximumBalancedHeight(1)); + ASSERT_EQ(2, Base::GetMaximumBalancedHeight(2)); + ASSERT_EQ(2, Base::GetMaximumBalancedHeight(3)); + ASSERT_EQ(3, Base::GetMaximumBalancedHeight(4)); + for (std::uint32_t count = 0; count <= 5000; count++) + { + ASSERT_EQ(TreeBalance::MaximumHeight(count), Base::GetMaximumBalancedHeight(count)); + } + // The largest sizes stop the sequence before it overflows. + using ByteBase = Platform::Collections::Methods::Trees::SizedBinaryTreeMethodsBase, std::uint8_t>; + using LongBase = Platform::Collections::Methods::Trees::SizedBinaryTreeMethodsBase, std::uint64_t>; + ASSERT_EQ(ReferenceMaximumBalancedHeight(static_cast(UINT8_MAX)), ByteBase::GetMaximumBalancedHeight(UINT8_MAX)); + ASSERT_EQ(ReferenceMaximumBalancedHeight(static_cast(UINT32_MAX)), Base::GetMaximumBalancedHeight(UINT32_MAX)); + ASSERT_EQ(ReferenceMaximumBalancedHeight(static_cast(UINT64_MAX)), LongBase::GetMaximumBalancedHeight(UINT64_MAX)); + ASSERT_EQ(91, LongBase::GetMaximumBalancedHeight(UINT64_MAX)); + } + + TEST(TreeEdgeCaseTests, SizesOfTheAVLTreeAreValidatedAndFixed) + { + auto tree = std::make_unique>(); + for (std::uint32_t node = 1; node <= 7; node++) + { + tree->Attach(&tree->Root, node); + } + tree->FixSizes(tree->Root); + tree->ValidateSizes(tree->Root); + ASSERT_EQ(7u, tree->SizeOf(tree->Root)); + } + + TEST(TreeEdgeCaseTests, NeighboursAreFoundInTheAVLTree) + { + const std::uint32_t count = 100; + auto tree = std::make_unique>(); + std::vector nodes(count); + std::iota(nodes.begin(), nodes.end(), 1u); + std::mt19937 random(605); + std::shuffle(nodes.begin(), nodes.end(), random); + for (auto node : nodes) + { + tree->Attach(&tree->Root, node); + } + ASSERT_EQ(1u, tree->LeftestOf(tree->Root)); + ASSERT_EQ(count, tree->RightestOf(tree->Root)); + for (std::uint32_t node = 1; node <= count; node++) + { + // Threads lead to the neighbours of every node. + ASSERT_EQ(node < count ? node + 1 : 0, tree->NextOf(node)); + ASSERT_EQ(node - 1, tree->PreviousOf(node)); + } + } + + /// + /// Rotations of the AVL tree keep the sizes, the threads and the balances right whatever the balances before the rotation are. + /// Повороты АВЛ-дерева сохраняют правильными размеры, нити и показатели баланса, какими бы ни были показатели баланса до поворота. + /// + TEST(TreeEdgeCaseTests, AVLRotationsKeepBalancesSizesAndThreads) + { + using namespace TreeEdgeCase; + std::mt19937 random(476); + std::set branches; + for (auto trial = 0; trial < 300; trial++) + { + auto count = std::uniform_int_distribution(2, 39)(random); + auto tree = std::make_unique>(); + std::vector nodes(count); + std::iota(nodes.begin(), nodes.end(), 1u); + std::shuffle(nodes.begin(), nodes.end(), random); + for (auto node : nodes) + { + tree->Attach(&tree->Root, node); + } + for (auto rotation = 0; rotation < 8; rotation++) + { + auto root = tree->Root; + auto left = (random() & 1) == 0; + auto child = left ? tree->RightOf(root) : tree->LeftOf(root); + if (child == 0) + { + left = !left; + child = left ? tree->RightOf(root) : tree->LeftOf(root); + } + int rootBalance = tree->BalanceOf(root); + int childBalance = tree->BalanceOf(child); + auto sign = [](int value) { return std::to_string((value > 0) - (value < 0)); }; + branches.insert((left ? "L" : "R") + sign(childBalance) + sign(rootBalance)); + tree->Root = left ? tree->RotateLeftWithBalance(root) : tree->RotateRightWithBalance(root); + ASSERT_EQ(child, tree->Root); + AssertAvlLinks(*tree, count); + if (::testing::Test::HasFailure()) + { + return; + } + } + } + // Every sign of the balance of the child was met with every sign of the balance of the root, in both directions. + ASSERT_EQ(2u * 3 * 3, branches.size()); + } +} diff --git a/cpp/Platform.Collections.Methods.Tests/Trees.h b/cpp/Platform.Collections.Methods.Tests/Trees.h index 4428365..4d1aed9 100644 --- a/cpp/Platform.Collections.Methods.Tests/Trees.h +++ b/cpp/Platform.Collections.Methods.Tests/Trees.h @@ -2,10 +2,14 @@ #include #include +#include #include +#include #include +#include #include #include +#include bool iszero(void* ptr, int bytes) { @@ -25,3 +29,4 @@ bool iszero(void* ptr, int bytes) #include "SizeBalancedTree.cpp" #include "SizedAndThreadedAVLBalancedTree.cpp" #include "TestExtensions.cpp" +#include "DoublyLinkedLists.cpp" diff --git a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h index e398185..d7b5824 100644 --- a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h @@ -60,7 +60,7 @@ auto current = *this->Position(root, parent, isLeft); if (current == 0) { - throw std::runtime_error("The node is not in the tree."); + throw std::runtime_error(std::string("The node ").append(std::to_string(node)).append(" is not in the tree.")); } bool goLeft; if (this->object().FirstIsToTheLeftOfSecond(node, current)) diff --git a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h index 741b3ed..18ccb18 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h @@ -59,7 +59,7 @@ { if (*root == 0) { - throw std::runtime_error("The node is not in the tree."); + throw std::runtime_error(std::string("The node ").append(std::to_string(node)).append(" is not in the tree.")); } if (this->object().FirstIsToTheLeftOfSecond(node, *root)) { From d9b0f1d5656f283f7d912cb46866c5e549ded4f7 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:14:21 +0000 Subject: [PATCH 11/46] Benchmark attach and detach of all three trees in C# and C++ The C# benchmarks use BenchmarkDotNet, the C++ benchmarks use google benchmark. Both attach and detach 1000 and 100000 nodes in ascending, descending and random order. CMake now registers the tests with CTest, requires GTest and benchmark only for the targets that use them, and fetches the Platform.Interfaces headers (cpp_0.3.41) when conan does not provide them. --- cpp/CMakeLists.txt | 27 +++- .../TreesBenchmark.cpp | 120 +++++++++++------- ...form.Collections.Methods.Benchmarks.csproj | 20 +++ .../Program.cs | 9 ++ .../TreeBenchmarks.cs | 109 ++++++++++++++++ csharp/Platform.Collections.Methods.sln | 14 ++ 6 files changed, 245 insertions(+), 54 deletions(-) create mode 100644 csharp/Platform.Collections.Methods.Benchmarks/Platform.Collections.Methods.Benchmarks.csproj create mode 100644 csharp/Platform.Collections.Methods.Benchmarks/Program.cs create mode 100644 csharp/Platform.Collections.Methods.Benchmarks/TreeBenchmarks.cs diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index aca73d4..4f1459f 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.13) +cmake_minimum_required(VERSION 3.16) set(LINKS_PLATFORM_TESTS ON CACHE BOOL "Whether to compile tests") set(LINKS_PLATFORM_BENCHMARKS ON CACHE BOOL "Whether to compile benchmarks") @@ -9,23 +9,40 @@ set(CONAN_DISABLE_CHECK_COMPILER TRUE) project(Platform.Collections.Methods CXX) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) -find_package(GTest) -find_package(benchmark) -find_package(Platform.Interfaces) - add_library(${PROJECT_NAME}.Library INTERFACE) target_include_directories(${PROJECT_NAME}.Library INTERFACE ${PROJECT_NAME}) +target_compile_features(${PROJECT_NAME}.Library INTERFACE cxx_std_20) + +# The headers need Platform.Interfaces (Polymorph.h). Conan provides it when its toolchain is used; +# otherwise the headers of the same release (cpp_0.3.41) are fetched from GitHub by commit. +find_package(Platform.Interfaces QUIET) +if(NOT TARGET Platform.Interfaces::Platform.Interfaces) + include(FetchContent) + FetchContent_Declare(PlatformInterfaces + GIT_REPOSITORY https://github.com/linksplatform/Interfaces.git + GIT_TAG 6b48e959bf25b5574fe2ee30afcccd8d7261403a # cpp_0.3.41 + # Only the headers are used, so the Interfaces CMake project (and its tests) is not added. + SOURCE_SUBDIR headers-only) + FetchContent_MakeAvailable(PlatformInterfaces) + add_library(Platform.Interfaces INTERFACE) + target_include_directories(Platform.Interfaces INTERFACE ${platforminterfaces_SOURCE_DIR}/cpp/Platform.Interfaces) + add_library(Platform.Interfaces::Platform.Interfaces ALIAS Platform.Interfaces) +endif() target_link_libraries(${PROJECT_NAME}.Library INTERFACE Platform.Interfaces::Platform.Interfaces) if(${LINKS_PLATFORM_TESTS}) + find_package(GTest REQUIRED) + enable_testing() add_executable(${PROJECT_NAME}.Tests ${PROJECT_NAME}.Tests/AllTests.cpp) set_target_properties(${PROJECT_NAME}.Tests PROPERTIES CXX_STANDARD 20) target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest) target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest_main) target_link_libraries(${PROJECT_NAME}.Tests PRIVATE ${PROJECT_NAME}.Library) + add_test(NAME ${PROJECT_NAME}.Tests COMMAND ${PROJECT_NAME}.Tests) endif() if(${LINKS_PLATFORM_BENCHMARKS}) + find_package(benchmark REQUIRED) add_executable(${PROJECT_NAME}.Benchmarks ${PROJECT_NAME}.Benchmarks/AllBenchmarks.cpp) set_target_properties(${PROJECT_NAME}.Benchmarks PROPERTIES CXX_STANDARD 20) target_link_libraries(${PROJECT_NAME}.Benchmarks PRIVATE benchmark::benchmark) diff --git a/cpp/Platform.Collections.Methods.Benchmarks/TreesBenchmark.cpp b/cpp/Platform.Collections.Methods.Benchmarks/TreesBenchmark.cpp index c0a0ff8..f24afbd 100644 --- a/cpp/Platform.Collections.Methods.Benchmarks/TreesBenchmark.cpp +++ b/cpp/Platform.Collections.Methods.Benchmarks/TreesBenchmark.cpp @@ -1,67 +1,89 @@ #include -#include -#include +#include +#include +#include +#include +#include +#include #include #include "../Platform.Collections.Methods.Tests/Trees.h" using namespace Platform::Collections::Methods::Tests; -static void BM_RecursionlessSizeBalancedTree(benchmark::State& state) { - const int _n = state.range(0); - - RecursionlessSizeBalancedTree<10000, std::uint32_t> recursionlessSizeBalancedTree; - - for (auto _ : state) { - TestExtensions::TestMultipleCreationsAndDeletions(recursionlessSizeBalancedTree, - [&]() -> std::size_t { return recursionlessSizeBalancedTree.Allocate(); }, - [&](std::uint32_t link) -> auto { recursionlessSizeBalancedTree.Free(link); }, - &recursionlessSizeBalancedTree.Root, - [&]() -> std::size_t { return recursionlessSizeBalancedTree.Count(); }, - _n); +namespace +{ + // The trees hold this many nodes; the largest benchmark uses all of them but the zero node. + constexpr std::size_t Capacity = 100001; + + enum Order : std::int64_t { Ascending, Descending, Random }; + + // The attach and the detach orders of the nodes 1..n. + std::pair, std::vector> Orders(std::size_t n, std::int64_t order) + { + std::vector nodes(n); + std::iota(nodes.begin(), nodes.end(), 1u); + if (order == Descending) + { + std::reverse(nodes.begin(), nodes.end()); + } + if (order != Random) + { + return { nodes, nodes }; + } + std::mt19937 random(115); + auto detach = nodes; + std::shuffle(nodes.begin(), nodes.end(), random); + std::shuffle(detach.begin(), detach.end(), random); + return { nodes, detach }; } - state.SetItemsProcessed(state.iterations() * _n); -} - -static void BM_SizeBalancedTree(benchmark::State& state) { - const int _n = state.range(0); - - SizeBalancedTree<10000, std::uint32_t> sizeBalancedTree; - - for (auto _ : state) { - TestExtensions::TestMultipleCreationsAndDeletions(sizeBalancedTree, - [&]() -> std::size_t { return sizeBalancedTree.Allocate(); }, - [&](std::uint32_t link) -> auto { sizeBalancedTree.Free(link); }, - &sizeBalancedTree.Root, - [&]() -> std::size_t { return sizeBalancedTree.Count(); }, - _n); + // Attaches the nodes 1..n to a tree and then detaches all of them. + template void AttachAndDetach(benchmark::State& state) + { + auto n = static_cast(state.range(0)); + auto [attach, detach] = Orders(n, state.range(1)); + auto tree = std::make_unique(); + for (std::size_t i = 0; i < n; i++) + { + tree->Allocate(); + } + for (auto _ : state) + { + for (auto node : attach) + { + tree->Attach(&tree->Root, node); + } + benchmark::DoNotOptimize(tree->Root); + for (auto node : detach) + { + tree->Detach(&tree->Root, node); + } + } + state.SetItemsProcessed(state.iterations() * static_cast(n) * 2); } - state.SetItemsProcessed(state.iterations() * _n); + void Arguments(benchmark::internal::Benchmark* benchmark) + { + benchmark->ArgNames({ "N", "Order" }); + for (auto n : { 1000, 100000 }) + { + for (auto order : { Ascending, Descending, Random }) + { + benchmark->Args({ n, order }); + } + } + } } -static void BM_SizedAndThreadedAVLBalancedTree(benchmark::State& state) { - const int _n = state.range(0); +static void BM_SizeBalancedTree(benchmark::State& state) { AttachAndDetach>(state); } - SizedAndThreadedAVLBalancedTree<10000, std::uint32_t> avlTree; +static void BM_RecursionlessSizeBalancedTree(benchmark::State& state) { AttachAndDetach>(state); } - for (auto _ : state) { - TestExtensions::TestMultipleCreationsAndDeletions(avlTree, - [&]() -> std::size_t { return avlTree.Allocate(); }, - [&](std::uint32_t link) -> auto { avlTree.Free(link); }, - &avlTree.Root, - [&]() -> std::size_t { return avlTree.Count(); }, - _n); - } - - state.SetItemsProcessed(state.iterations() * _n); -} +static void BM_SizedAndThreadedAVLBalancedTree(benchmark::State& state) { AttachAndDetach>(state); } -// Define the benchmarks -BENCHMARK(BM_RecursionlessSizeBalancedTree)->Arg(2000); -BENCHMARK(BM_SizeBalancedTree)->Arg(2000); -BENCHMARK(BM_SizedAndThreadedAVLBalancedTree)->Arg(2000); +BENCHMARK(BM_SizeBalancedTree)->Apply(Arguments); +BENCHMARK(BM_RecursionlessSizeBalancedTree)->Apply(Arguments); +BENCHMARK(BM_SizedAndThreadedAVLBalancedTree)->Apply(Arguments); -// Run the benchmarks BENCHMARK_MAIN(); diff --git a/csharp/Platform.Collections.Methods.Benchmarks/Platform.Collections.Methods.Benchmarks.csproj b/csharp/Platform.Collections.Methods.Benchmarks/Platform.Collections.Methods.Benchmarks.csproj new file mode 100644 index 0000000..b844bb8 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Benchmarks/Platform.Collections.Methods.Benchmarks.csproj @@ -0,0 +1,20 @@ + + + + Exe + net8 + false + latest + enable + true + + + + + + + + + + + diff --git a/csharp/Platform.Collections.Methods.Benchmarks/Program.cs b/csharp/Platform.Collections.Methods.Benchmarks/Program.cs new file mode 100644 index 0000000..f2f5232 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Benchmarks/Program.cs @@ -0,0 +1,9 @@ +using BenchmarkDotNet.Running; + +namespace Platform.Collections.Methods.Benchmarks +{ + public static class Program + { + public static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); + } +} diff --git a/csharp/Platform.Collections.Methods.Benchmarks/TreeBenchmarks.cs b/csharp/Platform.Collections.Methods.Benchmarks/TreeBenchmarks.cs new file mode 100644 index 0000000..c2ac081 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Benchmarks/TreeBenchmarks.cs @@ -0,0 +1,109 @@ +using System; +using System.Linq; +using BenchmarkDotNet.Attributes; +using Platform.Collections.Methods.Tests; + +namespace Platform.Collections.Methods.Benchmarks +{ + /// + /// The order in which the nodes are attached to and detached from a tree. + /// Порядок, в котором узлы присоединяются к дереву и отсоединяются от него. + /// + public enum Order + { + Ascending, + Descending, + Random, + } + + /// + /// Attaches N nodes to a tree and then detaches all of them, for each tree implementation. + /// Присоединяет N узлов к дереву, а затем отсоединяет их все, для каждой реализации дерева. + /// + [MemoryDiagnoser] + public class TreeBenchmarks + { + private SizeBalancedTree _sizeBalancedTree = null!; + private RecursionlessSizeBalancedTree _recursionlessSizeBalancedTree = null!; + private SizedAndThreadedAVLBalancedTree _avlTree = null!; + private uint[] _attachOrder = Array.Empty(); + private uint[] _detachOrder = Array.Empty(); + + [Params(1000, 100000)] + public int N { get; set; } + + [Params(Order.Ascending, Order.Descending, Order.Random)] + public Order Order { get; set; } + + [GlobalSetup] + public void Setup() + { + _sizeBalancedTree = new SizeBalancedTree(N + 1); + _recursionlessSizeBalancedTree = new RecursionlessSizeBalancedTree(N + 1); + _avlTree = new SizedAndThreadedAVLBalancedTree(N + 1); + for (var i = 0; i < N; i++) + { + _sizeBalancedTree.Allocate(); + _recursionlessSizeBalancedTree.Allocate(); + _avlTree.Allocate(); + } + var nodes = Enumerable.Range(1, N).Select(node => (uint)node).ToArray(); + var random = new System.Random(115); + _attachOrder = Order switch + { + Order.Ascending => nodes, + Order.Descending => Enumerable.Reverse(nodes).ToArray(), + _ => nodes.OrderBy(_ => random.Next()).ToArray(), + }; + _detachOrder = Order == Order.Random ? nodes.OrderBy(_ => random.Next()).ToArray() : _attachOrder; + } + + [Benchmark(Baseline = true)] + public uint SizeBalancedTree() + { + var tree = _sizeBalancedTree; + foreach (var node in _attachOrder) + { + tree.Attach(ref tree.Root, node); + } + var count = tree.Count; + foreach (var node in _detachOrder) + { + tree.Detach(ref tree.Root, node); + } + return count; + } + + [Benchmark] + public uint RecursionlessSizeBalancedTree() + { + var tree = _recursionlessSizeBalancedTree; + foreach (var node in _attachOrder) + { + tree.Attach(ref tree.Root, node); + } + var count = tree.Count; + foreach (var node in _detachOrder) + { + tree.Detach(ref tree.Root, node); + } + return count; + } + + [Benchmark] + public uint SizedAndThreadedAVLBalancedTree() + { + var tree = _avlTree; + foreach (var node in _attachOrder) + { + tree.Attach(ref tree.Root, node); + } + var count = tree.Count; + foreach (var node in _detachOrder) + { + tree.Detach(ref tree.Root, node); + } + return count; + } + } +} diff --git a/csharp/Platform.Collections.Methods.sln b/csharp/Platform.Collections.Methods.sln index 112ec06..fdda974 100644 --- a/csharp/Platform.Collections.Methods.sln +++ b/csharp/Platform.Collections.Methods.sln @@ -9,6 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Platform.Collections.Method EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Platform.Collections.Methods.Tests.Console", "Platform.Collections.Methods.Tests.Console\Platform.Collections.Methods.Tests.Console.csproj", "{D8068FF2-5830-4199-8D3B-7775A1FBC4A6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Platform.Collections.Methods.Benchmarks", "Platform.Collections.Methods.Benchmarks\Platform.Collections.Methods.Benchmarks.csproj", "{D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -55,6 +57,18 @@ Global {D8068FF2-5830-4199-8D3B-7775A1FBC4A6}.Release|x64.Build.0 = Release|Any CPU {D8068FF2-5830-4199-8D3B-7775A1FBC4A6}.Release|x86.ActiveCfg = Release|Any CPU {D8068FF2-5830-4199-8D3B-7775A1FBC4A6}.Release|x86.Build.0 = Release|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Debug|x64.ActiveCfg = Debug|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Debug|x64.Build.0 = Debug|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Debug|x86.ActiveCfg = Debug|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Debug|x86.Build.0 = Debug|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Release|Any CPU.Build.0 = Release|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Release|x64.ActiveCfg = Release|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Release|x64.Build.0 = Release|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Release|x86.ActiveCfg = Release|Any CPU + {D0869D05-0B1B-4FF7-A8AA-B04B6FF32C7E}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From d6c4dbf484ba35984ea9fbeeceb817bd72d8251d Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:21:37 +0000 Subject: [PATCH 12/46] Fetch Platform.Interfaces, GTest and benchmark in CMake when no package provides them Add options for sanitizers, gcov coverage and tree self-validation so CI builds every configuration from the same CMakeLists.txt. --- cpp/CMakeLists.txt | 68 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 4f1459f..35bb3f2 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -3,12 +3,17 @@ cmake_minimum_required(VERSION 3.16) set(LINKS_PLATFORM_TESTS ON CACHE BOOL "Whether to compile tests") set(LINKS_PLATFORM_BENCHMARKS ON CACHE BOOL "Whether to compile benchmarks") set(LINKS_PLATFORM_EXTRA_FLAGS "" CACHE STRING "Extra compiler flags") +set(LINKS_PLATFORM_SANITIZERS "" CACHE STRING "Sanitizers for the tests, e.g. address;undefined") +set(LINKS_PLATFORM_COVERAGE OFF CACHE BOOL "Whether to instrument the tests for gcov line coverage") +set(LINKS_PLATFORM_TREE_VALIDATION OFF CACHE BOOL "Whether the trees validate themselves after every attach and detach (ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION)") set(CONAN_DISABLE_CHECK_COMPILER TRUE) project(Platform.Collections.Methods CXX) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +include(FetchContent) + add_library(${PROJECT_NAME}.Library INTERFACE) target_include_directories(${PROJECT_NAME}.Library INTERFACE ${PROJECT_NAME}) target_compile_features(${PROJECT_NAME}.Library INTERFACE cxx_std_20) @@ -17,7 +22,6 @@ target_compile_features(${PROJECT_NAME}.Library INTERFACE cxx_std_20) # otherwise the headers of the same release (cpp_0.3.41) are fetched from GitHub by commit. find_package(Platform.Interfaces QUIET) if(NOT TARGET Platform.Interfaces::Platform.Interfaces) - include(FetchContent) FetchContent_Declare(PlatformInterfaces GIT_REPOSITORY https://github.com/linksplatform/Interfaces.git GIT_TAG 6b48e959bf25b5574fe2ee30afcccd8d7261403a # cpp_0.3.41 @@ -30,21 +34,65 @@ if(NOT TARGET Platform.Interfaces::Platform.Interfaces) endif() target_link_libraries(${PROJECT_NAME}.Library INTERFACE Platform.Interfaces::Platform.Interfaces) +# Applies the options of this file to a test or benchmark executable. +function(links_platform_configure target) + set_target_properties(${target} PROPERTIES CXX_STANDARD 20 CXX_STANDARD_REQUIRED ON) + target_link_libraries(${target} PRIVATE ${PROJECT_NAME}.Library) + if(LINKS_PLATFORM_EXTRA_FLAGS) + separate_arguments(extra_flags NATIVE_COMMAND "${LINKS_PLATFORM_EXTRA_FLAGS}") + target_compile_options(${target} PRIVATE ${extra_flags}) + endif() + if(LINKS_PLATFORM_TREE_VALIDATION) + target_compile_definitions(${target} PRIVATE ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION=1) + endif() + if(MSVC) + target_compile_options(${target} PRIVATE /W3 /bigobj /permissive-) + else() + target_compile_options(${target} PRIVATE -Wall -Wextra) + endif() +endfunction() + if(${LINKS_PLATFORM_TESTS}) - find_package(GTest REQUIRED) + find_package(GTest QUIET) + if(NOT TARGET GTest::gtest_main) + # Platforms without a GTest package (Windows, macOS without Homebrew's googletest) build it from source. + set(INSTALL_GTEST OFF CACHE BOOL "" FORCE) + set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + FetchContent_Declare(googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG b514bdc898e2951020cbdca1304b75f5950d1f59 # v1.15.2 + GIT_SHALLOW FALSE) + FetchContent_MakeAvailable(googletest) + endif() enable_testing() add_executable(${PROJECT_NAME}.Tests ${PROJECT_NAME}.Tests/AllTests.cpp) - set_target_properties(${PROJECT_NAME}.Tests PROPERTIES CXX_STANDARD 20) - target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest) - target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest_main) - target_link_libraries(${PROJECT_NAME}.Tests PRIVATE ${PROJECT_NAME}.Library) + links_platform_configure(${PROJECT_NAME}.Tests) + target_link_libraries(${PROJECT_NAME}.Tests PRIVATE GTest::gtest GTest::gtest_main) + if(LINKS_PLATFORM_SANITIZERS) + list(JOIN LINKS_PLATFORM_SANITIZERS "," sanitizers) + target_compile_options(${PROJECT_NAME}.Tests PRIVATE -fsanitize=${sanitizers} -fno-sanitize-recover=all -fno-omit-frame-pointer) + target_link_options(${PROJECT_NAME}.Tests PRIVATE -fsanitize=${sanitizers}) + endif() + if(LINKS_PLATFORM_COVERAGE) + target_compile_options(${PROJECT_NAME}.Tests PRIVATE --coverage -O0 -fno-inline -fno-elide-constructors) + target_link_options(${PROJECT_NAME}.Tests PRIVATE --coverage) + endif() add_test(NAME ${PROJECT_NAME}.Tests COMMAND ${PROJECT_NAME}.Tests) endif() if(${LINKS_PLATFORM_BENCHMARKS}) - find_package(benchmark REQUIRED) + find_package(benchmark QUIET) + if(NOT TARGET benchmark::benchmark) + set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE) + set(BENCHMARK_ENABLE_GTEST_TESTS OFF CACHE BOOL "" FORCE) + set(BENCHMARK_ENABLE_INSTALL OFF CACHE BOOL "" FORCE) + FetchContent_Declare(benchmark + GIT_REPOSITORY https://github.com/google/benchmark.git + GIT_TAG c58e6d0710581e3a08d65c349664128a8d9a2461 # v1.9.1 + GIT_SHALLOW FALSE) + FetchContent_MakeAvailable(benchmark) + endif() add_executable(${PROJECT_NAME}.Benchmarks ${PROJECT_NAME}.Benchmarks/AllBenchmarks.cpp) - set_target_properties(${PROJECT_NAME}.Benchmarks PROPERTIES CXX_STANDARD 20) + links_platform_configure(${PROJECT_NAME}.Benchmarks) target_link_libraries(${PROJECT_NAME}.Benchmarks PRIVATE benchmark::benchmark) - target_link_libraries(${PROJECT_NAME}.Benchmarks PRIVATE ${PROJECT_NAME}.Library) -endif() \ No newline at end of file +endif() From f92756ed312740a43b2d15eadcc99d791f516bfe Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:21:37 +0000 Subject: [PATCH 13/46] Pack the C++ headers with the .NET SDK and check the package by compiling a consumer The nuspec now depends on Platform.Interfaces.TemplateLibrary 0.3.41, whose Polymorph.h the headers include. The icon and MSBuild targets come from the last published package (0.3.0). --- .github/scripts/check-cpp-nuget-package.sh | 120 +++++++++++ .../scripts/check-cpp-nuget-package.test.mjs | 61 ++++++ .github/scripts/pack-cpp-nuget.mjs | 194 ++++++++++++++++++ .github/scripts/pack-cpp-nuget.test.mjs | 68 ++++++ ...Collections.Methods.TemplateLibrary.nuspec | 5 +- cpp/nuget/TemplateLibrary.targets | 13 ++ cpp/nuget/icon.png | Bin 0 -> 6569 bytes 7 files changed, 460 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/check-cpp-nuget-package.sh create mode 100644 .github/scripts/check-cpp-nuget-package.test.mjs create mode 100644 .github/scripts/pack-cpp-nuget.mjs create mode 100644 .github/scripts/pack-cpp-nuget.test.mjs create mode 100644 cpp/nuget/TemplateLibrary.targets create mode 100644 cpp/nuget/icon.png diff --git a/.github/scripts/check-cpp-nuget-package.sh b/.github/scripts/check-cpp-nuget-package.sh new file mode 100644 index 0000000..d17e383 --- /dev/null +++ b/.github/scripts/check-cpp-nuget-package.sh @@ -0,0 +1,120 @@ +#!/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 (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 +# 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="$(cd "$(dirname "$package")" && pwd)/$(basename "$package")" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# ..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 '" +while read -r dependency_id dependency_version; do + [ -n "$dependency_id" ] || continue + downloads+="" +done <<< "$dependencies" +cat > "$work/project/check.csproj" < + netstandard2.0truetrue + $downloads + +XML +# The package under test comes only from the local feed; its dependencies only from nuget.org. +cat > "$work/project/nuget.config" < + + + + + + +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" +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 +#include + +using namespace Platform::Collections::Methods::Trees; + +struct Tree : SizeBalancedTreeMethods +{ + 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" diff --git a/.github/scripts/check-cpp-nuget-package.test.mjs b/.github/scripts/check-cpp-nuget-package.test.mjs new file mode 100644 index 0000000..cf26fdb --- /dev/null +++ b/.github/scripts/check-cpp-nuget-package.test.mjs @@ -0,0 +1,61 @@ +#!/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 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/); +}); diff --git a/.github/scripts/pack-cpp-nuget.mjs b/.github/scripts/pack-cpp-nuget.mjs new file mode 100644 index 0000000..a7017db --- /dev/null +++ b/.github/scripts/pack-cpp-nuget.mjs @@ -0,0 +1,194 @@ +#!/usr/bin/env node + +/** + * Pack the header-only C++ library as a native NuGet package. + * + * The shared linksplatform/Workflows deploy-cpp job ran + * `sudo apt-get install nuget`, but Ubuntu 24.04 no longer ships the Mono + * NuGet CLI, and its recipe_folder pointed at another library, so the C++ + * package could not be released. This script stages the layout of the last + * published package (0.3.0) and packs it with the .NET SDK through a throwaway + * project that points at the nuspec: + * + * images/icon.png + * build/native/.targets + * lib/native/include/[Lists/|Trees/]
.h + * + * Usage: node pack-cpp-nuget.mjs [--verbose] + * `--verbose`, VERBOSE=1 or RUNNER_DEBUG=1 prints the staged files and the + * full dotnet output. Writes package_id, version and package_path to + * GITHUB_OUTPUT and the release notes to /release-notes.md. + */ + +import { execFileSync } from "node:child_process"; +import { + appendFileSync, + copyFileSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const repositoryRoot = path.resolve(import.meta.dirname, "../.."); +export const nuspecPath = path.join( + repositoryRoot, + "cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec", +); +const headersDirectory = path.dirname(nuspecPath); +const assetsDirectory = path.join(repositoryRoot, "cpp/nuget"); + +const readElement = (nuspec, name) => { + const match = new RegExp(`<${name}>([^<]+)`).exec(nuspec); + if (!match) { + throw new Error(`The nuspec has no <${name}> element`); + } + return match[1].trim(); +}; + +export const readPackageInfo = (nuspec) => ({ + id: readElement(nuspec, "id"), + version: readElement(nuspec, "version"), + releaseNotes: readElement(nuspec, "releaseNotes"), +}); + +export const expectedEntries = (id, headers) => [ + "images/icon.png", + `build/native/${id}.targets`, + ...headers.map((header) => `lib/native/include/${header}`), +]; + +export const withStagedFiles = (nuspec) => { + if (//.test(nuspec)) { + throw new Error("The nuspec already lists ; the pack layout is generated"); + } + return nuspec.replace( + "", + '\n \n \n ', + ); +}; + +export const findMissingEntries = (expected, actual) => { + const present = new Set(actual); + return expected.filter((entry) => !present.has(entry)); +}; + +// Header paths relative to the nuspec directory, with "/" separators. +export const listHeaders = (directory = headersDirectory) => + readdirSync(directory, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".h")) + .map((entry) => path.relative(directory, path.join(entry.parentPath, entry.name)).split(path.sep).join("/")) + .sort(); + +const listPackageEntries = (packagePath) => + execFileSync("unzip", ["-Z1", packagePath], { encoding: "utf8" }) + .split("\n") + .filter(Boolean); + +const setOutput = (name, value) => { + console.log(`${name}=${value}`); + if (process.env.GITHUB_OUTPUT) { + appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`); + } +}; + +export const run = (args = process.argv.slice(2), environment = process.env) => { + const verbose = + args.includes("--verbose") || + environment.VERBOSE === "1" || + environment.RUNNER_DEBUG === "1"; + const outputDirectory = args.find((arg) => !arg.startsWith("--")); + if (!outputDirectory) { + console.error("Usage: node pack-cpp-nuget.mjs [--verbose]"); + return 2; + } + + const nuspec = readFileSync(nuspecPath, "utf8"); + const { id, version, releaseNotes } = readPackageInfo(nuspec); + const headers = listHeaders(); + if (headers.length === 0) { + console.error(`::error title=C++ NuGet pack failed::No headers in ${headersDirectory}`); + return 1; + } + + const staging = mkdtempSync(path.join(tmpdir(), "cpp-nuget-")); + try { + const content = path.join(staging, "content"); + for (const directory of ["images", "build/native", "lib/native/include"]) { + mkdirSync(path.join(content, directory), { recursive: true }); + } + copyFileSync(path.join(assetsDirectory, "icon.png"), path.join(content, "images/icon.png")); + copyFileSync( + path.join(assetsDirectory, "TemplateLibrary.targets"), + path.join(content, `build/native/${id}.targets`), + ); + for (const header of headers) { + mkdirSync(path.dirname(path.join(content, "lib/native/include", header)), { recursive: true }); + copyFileSync( + path.join(headersDirectory, header), + path.join(content, "lib/native/include", header), + ); + } + writeFileSync(path.join(staging, `${id}.nuspec`), withStagedFiles(nuspec)); + writeFileSync( + path.join(staging, "pack.csproj"), + [ + '', + " ", + " netstandard2.0", + " false", + " true", + ` ${id}.nuspec`, + " $(MSBuildProjectDirectory)", + " ", + "", + "", + ].join("\n"), + ); + + const absoluteOutput = path.resolve(outputDirectory); + mkdirSync(absoluteOutput, { recursive: true }); + const packOutput = execFileSync( + "dotnet", + ["pack", path.join(staging, "pack.csproj"), "--output", absoluteOutput, "--nologo"], + { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }, + ); + if (verbose) { + console.log(packOutput); + } + + const packagePath = path.join(absoluteOutput, `${id}.${version}.nupkg`); + const entries = listPackageEntries(packagePath); + if (verbose) { + console.log(entries.join("\n")); + } + const missing = findMissingEntries(expectedEntries(id, headers), entries); + const stray = entries.filter((entry) => /(^|\/)(obj|bin)\/|\.csproj$/.test(entry)); + for (const entry of missing) { + console.error(`::error title=C++ NuGet pack failed::${entry} is missing from ${packagePath}`); + } + for (const entry of stray) { + console.error(`::error title=C++ NuGet pack failed::${entry} must not be packed`); + } + if (missing.length > 0 || stray.length > 0) { + return 1; + } + + writeFileSync(path.join(absoluteOutput, "release-notes.md"), `${releaseNotes}\n`); + console.log(`Packed ${id} ${version} with ${headers.length} headers.`); + setOutput("package_id", id); + setOutput("version", version); + setOutput("package_path", packagePath); + return 0; + } finally { + rmSync(staging, { recursive: true, force: true }); + } +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = run(); +} diff --git a/.github/scripts/pack-cpp-nuget.test.mjs b/.github/scripts/pack-cpp-nuget.test.mjs new file mode 100644 index 0000000..c82faa0 --- /dev/null +++ b/.github/scripts/pack-cpp-nuget.test.mjs @@ -0,0 +1,68 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { + expectedEntries, + findMissingEntries, + listHeaders, + nuspecPath, + readPackageInfo, + withStagedFiles, +} from "./pack-cpp-nuget.mjs"; + +const nuspec = readFileSync(nuspecPath, "utf8"); + +test("reads the package identity and release notes from the nuspec", () => { + const info = readPackageInfo(nuspec); + assert.equal(info.id, "Platform.Collections.Methods.TemplateLibrary"); + assert.match(info.version, /^\d+\.\d+\.\d+$/); + assert.ok(info.releaseNotes.length > 0); +}); + +test("fails loudly when a required nuspec element is missing", () => { + assert.throws( + () => readPackageInfo("x"), + /no element/, + ); +}); + +test("adds the staged content after the metadata without editing it", () => { + const staged = withStagedFiles(nuspec); + assert.ok(staged.startsWith(nuspec.slice(0, nuspec.indexOf("")))); + assert.match(staged, /<\/metadata>\n \n \n <\/files>/); + assert.throws(() => withStagedFiles(staged), /already lists /); +}); + +test("expects the layout of the last package published to nuget.org (0.3.0)", () => { + assert.deepEqual(expectedEntries("Id", ["A.h", "B[T].h"]), [ + "images/icon.png", + "build/native/Id.targets", + "lib/native/include/A.h", + "lib/native/include/B[T].h", + ]); +}); + +test("reports every expected entry that the package lacks", () => { + assert.deepEqual( + findMissingEntries(["images/icon.png", "lib/native/include/A.h"], ["images/icon.png"]), + ["lib/native/include/A.h"], + ); +}); + +test("packs the headers of the Lists and Trees folders as in 0.3.0", () => { + const headers = listHeaders(); + for (const header of [ + "Platform.Collections.Methods.h", + "GenericCollectionMethodsBase.h", + "Lists/AbsoluteCircularDoublyLinkedListMethods.h", + "Trees/RecursionlessSizeBalancedTreeMethods.h", + "Trees/SizeBalancedTreeMethods.h", + "Trees/SizedAndThreadedAVLBalancedTreeMethods.h", + "Trees/SizedBinaryTreeMethodsBase.h", + ]) { + assert.ok(headers.includes(header), `${header} is not packed`); + } + assert.deepEqual(headers.filter((header) => header.includes("\\")), []); +}); diff --git a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec index 7498ac5..6a86a87 100644 --- a/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec +++ b/cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec @@ -17,7 +17,10 @@ LGPL-3.0-only true - + + + + diff --git a/cpp/nuget/TemplateLibrary.targets b/cpp/nuget/TemplateLibrary.targets new file mode 100644 index 0000000..174d2d1 --- /dev/null +++ b/cpp/nuget/TemplateLibrary.targets @@ -0,0 +1,13 @@ + + + + + ;%(PreprocessorDefinitions) + $(MSBuildThisFileDirectory)..\..\lib\native\include\;%(AdditionalIncludeDirectories) + + + $(MSBuildThisFileDirectory)..\..\lib\native\include\;%(AdditionalIncludeDirectories) + + + + diff --git a/cpp/nuget/icon.png b/cpp/nuget/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c1ad0cac5d8e94045982ba35f38e0a265f25f408 GIT binary patch literal 6569 zcmV;a8CK?rP) zaB^>EX>4U6ba`-PAZ2)IW&i+q+U=TacI3Eng#Tj|UIN~a<=}aaci`pw3y@N)ds=ht zzT+3HP9rRJ8i}Pd7W<$90yQq()+*e#kNMpEP%lsDp2YDRz+xV@vbFWA~rya%)-ZbZl_;JxK z*WGdZ9;cg3G5YNbNAD+b*SQ*sZ+_mSME$zsiy=QNRB|)PT;R0-oQu2nZMq*ftK4}x zuJn$<$nnp==GPN{`uo#B=Lm1k+4>nP=H(S|rlHK~FISNecixz$8((LhgZ=eKi49~h z-7r@c*zI_R7|H#>R=9Z%HW@CBZ%Mnd-T?>^_fAa41u|f>3&~|?i}%Gj;#kQ~XXZXc zKgfVfCi%rIeGDO!oa%LNzEj-2)+hg*hF(ZSqEHH{p@2wMj45X7tpcHLQb;kSlv7DH zwbXOSF{hk!$>OPALWw1nTuP~>m0m-QHPu{8t+mzOd<)Q6GA*~#YHO``ZrWpKtj_hF z6T^=%;z%QpGU{lfPvA4-Of%0i>uj?xzrun7%*v~*y4vd7ZJ@N{PCM_i>u$Rruy(?U zC!KuCsi&R(nYA~oKWFXN%>8}V+?zFj6Q%3QkF0UJl#d~t=p-p;WXwlL#)~olpuKWt ztBcVqbIO@*K9~@aXO>CHSxy-vgK;~bj{D5rkIa3WH$!y)w|Vow%bZc_{)x;PrS41S z{+hSnWNr0Jx8Wv8RY*)>$UymVQTLVqXeWPmH1^*d;Qt5u=D72iX>7mFks9FTH0A6X zPVQ&Kt<$IFF+$#Jjk5vCS^F&Ca|y|&31TX(;ndPwtwLJzskCqo>91w?RE`^^>dVgV z!==EC5&+*lgmI4@;{9c&ZfYaNYh2F%vm&>#J2-C*(I;D zRu1ltd{XaqmF7}#Fu`m9e$YiujMEo8v)wNC;NYO0n;(mxKF*}?`B_GY>$p;=2iU~X z1~)frM1xxo+q>!QxLznpX4THjtfEmA&&S6H>dkV#t#v%h*(bS^R_Cogbj7ZmW-G*K z6U>~>&Sj;6qMVC3#Z|@`E@&ycu3bu7Ly_uvakEke!}ZhYAuG9?iPm|=d z0;#y-caA5QkyqZWlr?YiI~kt!w}>#$3z)8s%4GAIW00HzO2#J0G}cNEV7f>Gh)E2G zxh_YCel%|<~V{MjcoSfd&y}fmVJ6!B?sG~8$dJCBt0t?BnQ~Y7evS? zb6C;5p*w9rtz>@KvU1ais0CGbDI_Iw;zVmJW$W4X&1eWnAGfo3Ll@ULV?A>U{3%DW1%nS$gAwv6IeE z&V^u9Js<}br+b_|h$vXHt8|xqP4t@0fFYJ%9Nof?{$zc48q|e^Tmv)ucyW&;+$}M| zUTw!hsB=~(W@?lKrREYTqo4GrbOV(NU=M&bO+l-N5_bFzOzF@QLQ~BL+xFtSi^j7i zq2)GbAK$5otWuA&)#Lzh+9nfAtJg6}neRzdO5cUB>_vn{O#pSMMhkRPH5`h^%UNU_Iv6SwTC>=TKvJ-r8qi3&MK&U3b(b*@^^g2GeK8}8*zn6HhzeLt za9U9bv|&HSo4r2ge2SKIEw`u!@Ccj0J*rxw5>_6pjfw623nz({Y6=sImQ1GJ3;`A7 zEy2Opfi$Xa6*4bquSy=b&_%J#lu#qHMY5JM@hK<)PdvLr@)#xJB<$QX(d{cp`HHl! zM<$i|n0zt>Tms|rLZxI)-h$fR3fj)KZ7R92zC|Y*NvxT;ZFTA<%oy;8HlhC3=x1qr z>YZ*=i&+bam=djEr8-y=)qf^(sjmwzUX?W-*r5KsGelsUnNQ7xhn~T5Q%70E zmbEsz8~UiK&L^}NDJJ^p%oKBb1lFWF)zvWQ!+369)HEAqm9M}OvS@J9GI=xs%Ysli zLOplirnGNfQRdWFfZ=hya*z1JkQ}xCE_KKE%Z@A`%z3Sa-)aze6ZJ4a9z0ke zU>YceH26{idJWY@6{hWAX6`;QT_-a-Brw!PUbSOxOAQhd;71!7)U=hPxKPmk2408k zks(GUmm|uPPR4BLO6p?`L_Ptk1Q7S8!ZtKz zpO6t50K=(ii@lXx^dR7QqJ^j+MyxU3xH-Tljp*BWq$CZ=z+RL}&)j^VMl7C>7$8+J zT`Z4--=d0IPI2)jIG$MNR7pUIbM>R1-XKz(Au_CDK@;MOoO1^ z9OfFe?KS1b+e03y!aHAKVt#|0zu*WKhoXsz=9ZzmC{Hl!TF=}bdA#b=C{7>+9R?w$ z`}&*A*AT@=@|6-r}ctje_zGM4hlv zOb){z-Dugd^rdQ~du?mt+O#!7=p^)>{sFd8Oc;&};5sz0%9Y;9)Pji3DVI{b`PO8_ zuZ^fV(4>BN$HhdXZ50c2F_^6~H!1}w0wx)V&?>U+wY{`-yF@~UU00+%z+@$%k@G^&4O_t8j*~6kg{4AN9e3~=VDmV zCkmr9?HC;Srgat6q(8OZrJk{tE^6R*VF?aY$cE}UPqn3Ma+iqy!|MgUYRUZ+>C!-Q zVtPI!@e#h-MuXBoEFnz9hz?ACL$htD!09v37Dv0~yu#DxF|!$)N#X6c7Had?ol>!D)%b}engyTjZGZnbqF4mb9Z7Gp3+25gM?n1@hMc4%1U?DYrN6{ z;f*f$aH>O^KzWRZIsz6`8c+|dwuDmJLYu$(h;9Y8#8*>IgUY%j=Wb;QNcIxkM(v;y zMR4xgl)Dz@cdnx{6Ev}yraC6zur4f5^K%oNFr36HVD73Spac|w9E9N_j? z2gmOQ!fZRMUaf6)%ZyT9DFI^M536oFy6iQ*<+^K!7*)_RdI^z{0zRrL@P2}-jQgPH zbk8CgCU$fx5*Zs5Zdv(@Rwvm#j6R>&C;=!W9?dalVTy*MDuLX|X%8M-Oq%f^5tjgq zh0c|*pA1z+9(R7GJYjmHw}SuY`RLo@phY;Ovc#RXB=$CvGV8n{%UX%HYcSP!ee}Ze zD(zbk(tahlUNbg|{yS;(?!kpiyCoMhKkcF1HvIXcjp+EA0>2kD`z zVAYb3_S=v^W?@hZ@}kQFYr98zRY!Zn&Bgqt6=ahk*Umh%$m5`bQLnHpoutZ&hKqpZ z$&1KXg_+J%@=txwtY;Au^Tv`~4ly64ON2^MvG&pJHe@r@Dy2-F7nYHMUd6OOU8O|0 z?0*7q^Y2y030W!}vLi;A7+`Y*@fK6{HW*tK^YSXcYP|VcmZsC|f!6_>?;|Uyg z6;{>mM3DA+iV3;-h_H3ecv!r`V&RXmY5v6p7*@eiN)0$x!Yr$>kmQv& zUi-5S$+D3(_Po+pt~GT831~!@?m*B{`gLbS&BWd%g4KMGX;CFiltF_~qqJr+sL=E7 zWnnP8|J=JGMoGHbku5QVo|!l%c0p45(1XQtv^R7Grvc}gzMHQ~9_2aP%CjNA>4|n? zLWe8J6b8W)lgS)IP7Rsvb>T&y$&cr|GirJe`Ryjr-yhAty1=#3N5(=d5+2WG2W|dJ zs@N}^m}bnU8)03F=dkT#B%XZ%(K=$M3SN59LA;Z84;s3hixJ*@2eKGLViamdZswjn zywar`3h8C3LO&G)DM8?RoI;U+a&Zuqdi7L)%N@H;y)T!sI?(u*%~O%-vMf6c%U3<< zyW`J>Q*@H_W-%DcTn?Y`S9n#&WQ zyEU$V69EuFoc9$5#iJ~;KT_QA9@V2q-ekGpLWcxA{eq=JF90{&-jE!4lnu7={lFN( z0kO=GJ+^#(4u>n&QyFQGOIY<9_3)^_$Eb_2B+_WvacVc8zP$86?nuzR+;Q7Lxlg8W z88WHZ@`!$~tG;cCsPs@fmwEKgH1YRqwvy(vBm7LI0e{rWl+@XfNZ&8d>`m66PMN zwozNZ&(=kpEX>4Tx0C=2zkv&Mm zKpe$iQ>7v;4y_>KkfAzR5EXHhDi*;)X)CnqU~=gfG-*guTpR`0f`cE6RRjdyW16NwdUuy!hpQJZBTJ#7Q*aj}HJDR))Th80XiHPkdbi+g3yelq>OM2Uh@Hsf(6Ypmg4B_I$RJe zaOKaz8&&I&Fs21b%CqX~Rm{rjCcx*+Z0;w}BDJ>4Uw0I1yCtbmz?S$D24EqdwbXLn zO0M85a@Un7#A;pt!i_&`xw!{Jx%t1m5@xRCu@`N8xW!q?idR`59smsuHUj>j003lZ z>HDDqV6JAu&v&~&l0tCiw|*h1+k5b#3>TfpBWw$O z671|;DNFg&r_)pm7AzbufS$10d|&*@wJ5zibsLDSwZ5BMZyXCD&(a9PaMjtO{`sc=YI) zOdZ|QrcGzY3*byEPNz(TPmWJo0)7g8671?~fzcQUdVX&1Ue%sGf$;($@vx!@p9k$A z!SB6|eW3?Hy3x_`UQly0GtbfO-WRI#yy!J)haliwFmtogu!Wtt624LxSj(g&--rc} z+3X^q3w0^1E~XBJJTOuLlxXL@oGN)$AV~;gdNL#kdSqrcqO0p=00tNgeeimJMRxYL z@Ou9YXLhezh0=~YSnKP$k&cH$XE*_vn3i^*fQxtT$o79o0{J{(s$w@RY=5atYMNL81|ZZB z@G~pxJF3+|-wep1Zu(sQfI|9_#~M`;O%Q3EcmPNQX3TI9XlFrzN2;r<8*RR|R;o*~ zOP(oK-dxtm%5duoJAlDR&`}ikQ=_3|&bu5?X__CJZPo2dHe|0@b3HrV@njAxY)&rY zzNPr zgM%>_0eTj_J@||JZJfX5O=(BM|K%uj<*eNfruqgV!rl;5r7(zT8s_*xkrk{R@fm(G zYnFi`bu`~w&mCzo1Hj6ft)R$!&iZO}LFtDFA|+*0B(y~&`}XtkTmZOWEdH0c3=Yq(JuGXRXx-va Date: Sun, 29 Nov 2026 10:43:32 +0000 Subject: [PATCH 14/46] Keep the exceptions in tree validation mode and build C# with it on request Detach in ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION mode no longer checks for a missing node itself, so it throws the same exception as without validation (C++ and C#). dotnet test -p:TreeValidation=true defines the symbol for C#. The library builds with -warnaserror (nullable fixes, Source Link 8.0.0) and the package carries the README, the icon and embedded symbols. --- .../Trees/SizedBinaryTreeMethodsBase.h | 8 +++---- .../RecursionlessSizeBalancedTree.cs | 2 +- .../SizeBalancedTree.cs | 2 +- .../SizedAndThreadedAVLBalancedTree.cs | 2 +- .../Platform.Collections.Methods.csproj | 21 +++++++++++------- .../SizedAndThreadedAVLBalancedTreeMethods.cs | 4 ++-- .../Trees/SizedBinaryTreeMethodsBase.cs | 17 ++++++-------- csharp/Platform.Collections.Methods/icon.png | Bin 0 -> 6569 bytes 8 files changed, 28 insertions(+), 28 deletions(-) create mode 100644 csharp/Platform.Collections.Methods/icon.png diff --git a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h index a6f6dad..1db22f7 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h @@ -214,11 +214,9 @@ { #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION this->object().ValidateSizes(*root); - if (*root == 0) - { - throw std::runtime_error(std::string("The node ").append(std::to_string(node)).append(" is not in the tree.")); - } - auto sizeBefore = this->object().GetSize(*root); + // DetachCore reports a missing node (also in an empty tree) with the + // same exception as without validation. + auto sizeBefore = this->object().GetSizeOrZero(*root); #endif this->object().DetachCore(root, node); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION diff --git a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs index 94aacdb..f46b78e 100644 --- a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs @@ -19,7 +19,7 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - public TElement Root; + public TElement Root = TElement.Zero; public TElement Count => GetSizeOrZero(Root); diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs index 31f9cdc..5508a61 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs @@ -19,7 +19,7 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - public TElement Root; + public TElement Root = TElement.Zero; public TElement Count => GetSizeOrZero(Root); diff --git a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs index 2e7da62..f9ac6e6 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs @@ -22,7 +22,7 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - public TElement Root; + public TElement Root = TElement.Zero; public TElement Count => GetSizeOrZero(Root); diff --git a/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj b/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj index e72e47f..8a87022 100644 --- a/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj +++ b/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj @@ -9,8 +9,9 @@ net8 Platform.Collections.Methods Platform.Collections.Methods - LinksPlatform;Collections.Methods;CircularDoublyLinkedListMethods;DoublyLinkedListMethodsBase;OpenDoublyLinkedListMethods;RecursionlessSizeBalancedTreeMethods;SizeBalancedTreeMethods;SizedAndThreadedAVLBalancedTreeMethods;SizedBinaryTreeMethodsBase;GenericCollectionMethodsBase - https://raw.githubusercontent.com/linksplatform/Documentation/18469f4d033ee9a5b7b84caab9c585acab2ac519/doc/Avatar-rainbow-icon-64x64.png + LinksPlatform;Collections.Methods;CircularDoublyLinkedListMethods;DoublyLinkedListMethodsBase;OpenDoublyLinkedListMethods;RecursionlessSizeBalancedTreeMethods;SizeBalancedTreeMethods;SizedAndThreadedAVLBalancedTreeMethods;SizedBinaryTreeMethodsBase + README.md + icon.png https://linksplatform.github.io/Collections.Methods Unlicense git @@ -20,24 +21,28 @@ true true true - true - snupkg + embedded latest Size balanced trees keep Chen's size balanced property on every attach and detach, so their height never exceeds the AVL bound; the recursionless variant now builds the same trees as the recursive one; trees built by older versions are rebuilt once in linear time. enable + + + $(DefineConstants);ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION + + - + - - + + + - diff --git a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs index e266d56..52a2045 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs @@ -181,7 +181,7 @@ protected override void PrintNode(TElement node, StringBuilder sb, int level) /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected override TElement GetLeftOrDefault(TElement node) => GetLeftIsChild(node) ? GetLeft(node) : default; + protected override TElement GetLeftOrDefault(TElement node) => GetLeftIsChild(node) ? GetLeft(node) : TElement.Zero; /// /// @@ -198,7 +198,7 @@ protected override void PrintNode(TElement node, StringBuilder sb, int level) /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected override TElement GetRightOrDefault(TElement node) => GetRightIsChild(node) ? GetRight(node) : default; + protected override TElement GetRightOrDefault(TElement node) => GetRightIsChild(node) ? GetRight(node) : TElement.Zero; /// /// diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index a5e416f..9d7f05f 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -17,7 +17,6 @@ namespace Platform.Collections.Methods.Trees /// /// /// - /// public abstract class SizedBinaryTreeMethodsBase where TElement: IUnsignedNumber, IComparisonOperators { /// @@ -213,7 +212,7 @@ public abstract class SizedBinaryTreeMethodsBase where TElement: IUn /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected virtual TElement GetLeftOrDefault(TElement node) => node == default ? default : GetLeft(node); + protected virtual TElement GetLeftOrDefault(TElement node) => node == TElement.Zero ? TElement.Zero : GetLeft(node); /// /// @@ -230,7 +229,7 @@ public abstract class SizedBinaryTreeMethodsBase where TElement: IUn /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected virtual TElement GetRightOrDefault(TElement node) => node == default ? default : GetRight(node); + protected virtual TElement GetRightOrDefault(TElement node) => node == TElement.Zero ? TElement.Zero : GetRight(node); /// /// @@ -647,11 +646,9 @@ public void Detach(ref TElement root, TElement node) Debug.WriteLine("--BeforeDetach--"); Debug.WriteLine(PrintNodes(root)); Debug.WriteLine("----------------"); - if (root == TElement.Zero) - { - throw new InvalidOperationException($"The node {node} is not in the tree."); - } - var sizeBefore = GetSize(root); + // DetachCore reports a missing node (also in an empty tree) with the + // same exception as without validation. + var sizeBefore = GetSizeOrZero(root); #endif DetachCore(ref root, node); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION @@ -757,7 +754,7 @@ protected TElement RebuildComplete(TElement root) return root; } // Turn the tree into a vine: a path of right children in key order. - ref var position = ref root; + ref TElement position = ref root; while (position != TElement.Zero) { if (GetLeft(position) != TElement.Zero) @@ -784,7 +781,7 @@ protected TElement RebuildComplete(TElement root) private void Fold(ref TElement root, ulong rotations) { - ref var position = ref root; + ref TElement position = ref root; for (ulong i = 0; i < rotations; i++) { LeftRotate(ref position); diff --git a/csharp/Platform.Collections.Methods/icon.png b/csharp/Platform.Collections.Methods/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c1ad0cac5d8e94045982ba35f38e0a265f25f408 GIT binary patch literal 6569 zcmV;a8CK?rP) zaB^>EX>4U6ba`-PAZ2)IW&i+q+U=TacI3Eng#Tj|UIN~a<=}aaci`pw3y@N)ds=ht zzT+3HP9rRJ8i}Pd7W<$90yQq()+*e#kNMpEP%lsDp2YDRz+xV@vbFWA~rya%)-ZbZl_;JxK z*WGdZ9;cg3G5YNbNAD+b*SQ*sZ+_mSME$zsiy=QNRB|)PT;R0-oQu2nZMq*ftK4}x zuJn$<$nnp==GPN{`uo#B=Lm1k+4>nP=H(S|rlHK~FISNecixz$8((LhgZ=eKi49~h z-7r@c*zI_R7|H#>R=9Z%HW@CBZ%Mnd-T?>^_fAa41u|f>3&~|?i}%Gj;#kQ~XXZXc zKgfVfCi%rIeGDO!oa%LNzEj-2)+hg*hF(ZSqEHH{p@2wMj45X7tpcHLQb;kSlv7DH zwbXOSF{hk!$>OPALWw1nTuP~>m0m-QHPu{8t+mzOd<)Q6GA*~#YHO``ZrWpKtj_hF z6T^=%;z%QpGU{lfPvA4-Of%0i>uj?xzrun7%*v~*y4vd7ZJ@N{PCM_i>u$Rruy(?U zC!KuCsi&R(nYA~oKWFXN%>8}V+?zFj6Q%3QkF0UJl#d~t=p-p;WXwlL#)~olpuKWt ztBcVqbIO@*K9~@aXO>CHSxy-vgK;~bj{D5rkIa3WH$!y)w|Vow%bZc_{)x;PrS41S z{+hSnWNr0Jx8Wv8RY*)>$UymVQTLVqXeWPmH1^*d;Qt5u=D72iX>7mFks9FTH0A6X zPVQ&Kt<$IFF+$#Jjk5vCS^F&Ca|y|&31TX(;ndPwtwLJzskCqo>91w?RE`^^>dVgV z!==EC5&+*lgmI4@;{9c&ZfYaNYh2F%vm&>#J2-C*(I;D zRu1ltd{XaqmF7}#Fu`m9e$YiujMEo8v)wNC;NYO0n;(mxKF*}?`B_GY>$p;=2iU~X z1~)frM1xxo+q>!QxLznpX4THjtfEmA&&S6H>dkV#t#v%h*(bS^R_Cogbj7ZmW-G*K z6U>~>&Sj;6qMVC3#Z|@`E@&ycu3bu7Ly_uvakEke!}ZhYAuG9?iPm|=d z0;#y-caA5QkyqZWlr?YiI~kt!w}>#$3z)8s%4GAIW00HzO2#J0G}cNEV7f>Gh)E2G zxh_YCel%|<~V{MjcoSfd&y}fmVJ6!B?sG~8$dJCBt0t?BnQ~Y7evS? zb6C;5p*w9rtz>@KvU1ais0CGbDI_Iw;zVmJW$W4X&1eWnAGfo3Ll@ULV?A>U{3%DW1%nS$gAwv6IeE z&V^u9Js<}br+b_|h$vXHt8|xqP4t@0fFYJ%9Nof?{$zc48q|e^Tmv)ucyW&;+$}M| zUTw!hsB=~(W@?lKrREYTqo4GrbOV(NU=M&bO+l-N5_bFzOzF@QLQ~BL+xFtSi^j7i zq2)GbAK$5otWuA&)#Lzh+9nfAtJg6}neRzdO5cUB>_vn{O#pSMMhkRPH5`h^%UNU_Iv6SwTC>=TKvJ-r8qi3&MK&U3b(b*@^^g2GeK8}8*zn6HhzeLt za9U9bv|&HSo4r2ge2SKIEw`u!@Ccj0J*rxw5>_6pjfw623nz({Y6=sImQ1GJ3;`A7 zEy2Opfi$Xa6*4bquSy=b&_%J#lu#qHMY5JM@hK<)PdvLr@)#xJB<$QX(d{cp`HHl! zM<$i|n0zt>Tms|rLZxI)-h$fR3fj)KZ7R92zC|Y*NvxT;ZFTA<%oy;8HlhC3=x1qr z>YZ*=i&+bam=djEr8-y=)qf^(sjmwzUX?W-*r5KsGelsUnNQ7xhn~T5Q%70E zmbEsz8~UiK&L^}NDJJ^p%oKBb1lFWF)zvWQ!+369)HEAqm9M}OvS@J9GI=xs%Ysli zLOplirnGNfQRdWFfZ=hya*z1JkQ}xCE_KKE%Z@A`%z3Sa-)aze6ZJ4a9z0ke zU>YceH26{idJWY@6{hWAX6`;QT_-a-Brw!PUbSOxOAQhd;71!7)U=hPxKPmk2408k zks(GUmm|uPPR4BLO6p?`L_Ptk1Q7S8!ZtKz zpO6t50K=(ii@lXx^dR7QqJ^j+MyxU3xH-Tljp*BWq$CZ=z+RL}&)j^VMl7C>7$8+J zT`Z4--=d0IPI2)jIG$MNR7pUIbM>R1-XKz(Au_CDK@;MOoO1^ z9OfFe?KS1b+e03y!aHAKVt#|0zu*WKhoXsz=9ZzmC{Hl!TF=}bdA#b=C{7>+9R?w$ z`}&*A*AT@=@|6-r}ctje_zGM4hlv zOb){z-Dugd^rdQ~du?mt+O#!7=p^)>{sFd8Oc;&};5sz0%9Y;9)Pji3DVI{b`PO8_ zuZ^fV(4>BN$HhdXZ50c2F_^6~H!1}w0wx)V&?>U+wY{`-yF@~UU00+%z+@$%k@G^&4O_t8j*~6kg{4AN9e3~=VDmV zCkmr9?HC;Srgat6q(8OZrJk{tE^6R*VF?aY$cE}UPqn3Ma+iqy!|MgUYRUZ+>C!-Q zVtPI!@e#h-MuXBoEFnz9hz?ACL$htD!09v37Dv0~yu#DxF|!$)N#X6c7Had?ol>!D)%b}engyTjZGZnbqF4mb9Z7Gp3+25gM?n1@hMc4%1U?DYrN6{ z;f*f$aH>O^KzWRZIsz6`8c+|dwuDmJLYu$(h;9Y8#8*>IgUY%j=Wb;QNcIxkM(v;y zMR4xgl)Dz@cdnx{6Ev}yraC6zur4f5^K%oNFr36HVD73Spac|w9E9N_j? z2gmOQ!fZRMUaf6)%ZyT9DFI^M536oFy6iQ*<+^K!7*)_RdI^z{0zRrL@P2}-jQgPH zbk8CgCU$fx5*Zs5Zdv(@Rwvm#j6R>&C;=!W9?dalVTy*MDuLX|X%8M-Oq%f^5tjgq zh0c|*pA1z+9(R7GJYjmHw}SuY`RLo@phY;Ovc#RXB=$CvGV8n{%UX%HYcSP!ee}Ze zD(zbk(tahlUNbg|{yS;(?!kpiyCoMhKkcF1HvIXcjp+EA0>2kD`z zVAYb3_S=v^W?@hZ@}kQFYr98zRY!Zn&Bgqt6=ahk*Umh%$m5`bQLnHpoutZ&hKqpZ z$&1KXg_+J%@=txwtY;Au^Tv`~4ly64ON2^MvG&pJHe@r@Dy2-F7nYHMUd6OOU8O|0 z?0*7q^Y2y030W!}vLi;A7+`Y*@fK6{HW*tK^YSXcYP|VcmZsC|f!6_>?;|Uyg z6;{>mM3DA+iV3;-h_H3ecv!r`V&RXmY5v6p7*@eiN)0$x!Yr$>kmQv& zUi-5S$+D3(_Po+pt~GT831~!@?m*B{`gLbS&BWd%g4KMGX;CFiltF_~qqJr+sL=E7 zWnnP8|J=JGMoGHbku5QVo|!l%c0p45(1XQtv^R7Grvc}gzMHQ~9_2aP%CjNA>4|n? zLWe8J6b8W)lgS)IP7Rsvb>T&y$&cr|GirJe`Ryjr-yhAty1=#3N5(=d5+2WG2W|dJ zs@N}^m}bnU8)03F=dkT#B%XZ%(K=$M3SN59LA;Z84;s3hixJ*@2eKGLViamdZswjn zywar`3h8C3LO&G)DM8?RoI;U+a&Zuqdi7L)%N@H;y)T!sI?(u*%~O%-vMf6c%U3<< zyW`J>Q*@H_W-%DcTn?Y`S9n#&WQ zyEU$V69EuFoc9$5#iJ~;KT_QA9@V2q-ekGpLWcxA{eq=JF90{&-jE!4lnu7={lFN( z0kO=GJ+^#(4u>n&QyFQGOIY<9_3)^_$Eb_2B+_WvacVc8zP$86?nuzR+;Q7Lxlg8W z88WHZ@`!$~tG;cCsPs@fmwEKgH1YRqwvy(vBm7LI0e{rWl+@XfNZ&8d>`m66PMN zwozNZ&(=kpEX>4Tx0C=2zkv&Mm zKpe$iQ>7v;4y_>KkfAzR5EXHhDi*;)X)CnqU~=gfG-*guTpR`0f`cE6RRjdyW16NwdUuy!hpQJZBTJ#7Q*aj}HJDR))Th80XiHPkdbi+g3yelq>OM2Uh@Hsf(6Ypmg4B_I$RJe zaOKaz8&&I&Fs21b%CqX~Rm{rjCcx*+Z0;w}BDJ>4Uw0I1yCtbmz?S$D24EqdwbXLn zO0M85a@Un7#A;pt!i_&`xw!{Jx%t1m5@xRCu@`N8xW!q?idR`59smsuHUj>j003lZ z>HDDqV6JAu&v&~&l0tCiw|*h1+k5b#3>TfpBWw$O z671|;DNFg&r_)pm7AzbufS$10d|&*@wJ5zibsLDSwZ5BMZyXCD&(a9PaMjtO{`sc=YI) zOdZ|QrcGzY3*byEPNz(TPmWJo0)7g8671?~fzcQUdVX&1Ue%sGf$;($@vx!@p9k$A z!SB6|eW3?Hy3x_`UQly0GtbfO-WRI#yy!J)haliwFmtogu!Wtt624LxSj(g&--rc} z+3X^q3w0^1E~XBJJTOuLlxXL@oGN)$AV~;gdNL#kdSqrcqO0p=00tNgeeimJMRxYL z@Ou9YXLhezh0=~YSnKP$k&cH$XE*_vn3i^*fQxtT$o79o0{J{(s$w@RY=5atYMNL81|ZZB z@G~pxJF3+|-wep1Zu(sQfI|9_#~M`;O%Q3EcmPNQX3TI9XlFrzN2;r<8*RR|R;o*~ zOP(oK-dxtm%5duoJAlDR&`}ikQ=_3|&bu5?X__CJZPo2dHe|0@b3HrV@njAxY)&rY zzNPr zgM%>_0eTj_J@||JZJfX5O=(BM|K%uj<*eNfruqgV!rl;5r7(zT8s_*xkrk{R@fm(G zYnFi`bu`~w&mCzo1Hj6ft)R$!&iZO}LFtDFA|+*0B(y~&`}XtkTmZOWEdH0c3=Yq(JuGXRXx-va Date: Sun, 29 Nov 2026 10:43:32 +0000 Subject: [PATCH 15/46] Run the C++ tests on every compiler with sanitizers, validation and coverage cpp/build-and-test.sh builds the tests and runs them through CTest. cpp-test.yml runs it on pull requests and main for GCC, Clang, AppleClang and MSVC, once with AddressSanitizer, UBSan and self-validating trees, and requires 100% line coverage of the headers with gcovr. deploy-cpp.yml publishes only the tested package, with NuGet trusted publishing first and NUGET_TOKEN as a fallback, after a release preflight. --- .github/scripts/cpp-build-and-test.test.mjs | 99 +++++++ .github/scripts/cpp-workflow-policy.test.mjs | 107 ++++++++ .github/scripts/preflight-nuget-release.mjs | 254 ++++++++++++++++++ .../scripts/preflight-nuget-release.test.mjs | 250 +++++++++++++++++ .github/scripts/push-nuget-package.sh | 49 ++++ .github/scripts/push-nuget-package.test.mjs | 88 ++++++ .github/scripts/workflow-jobs.mjs | 25 ++ .github/workflows/cpp-test.yml | 188 +++++++++++-- .github/workflows/deploy-cpp.yml | 121 ++++++++- cpp/build-and-test.sh | 44 +++ 10 files changed, 1201 insertions(+), 24 deletions(-) create mode 100644 .github/scripts/cpp-build-and-test.test.mjs create mode 100644 .github/scripts/cpp-workflow-policy.test.mjs create mode 100644 .github/scripts/preflight-nuget-release.mjs create mode 100644 .github/scripts/preflight-nuget-release.test.mjs create mode 100644 .github/scripts/push-nuget-package.sh create mode 100644 .github/scripts/push-nuget-package.test.mjs create mode 100644 .github/scripts/workflow-jobs.mjs create mode 100755 cpp/build-and-test.sh diff --git a/.github/scripts/cpp-build-and-test.test.mjs b/.github/scripts/cpp-build-and-test.test.mjs new file mode 100644 index 0000000..59c9bc3 --- /dev/null +++ b/.github/scripts/cpp-build-and-test.test.mjs @@ -0,0 +1,99 @@ +#!/usr/bin/env node + +// Runs cpp/build-and-test.sh against stub cmake and ctest commands that log +// their arguments, so the options CI passes through the environment are +// checked without building anything. + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const script = fileURLToPath(new URL("../../cpp/build-and-test.sh", import.meta.url)); + +const runWithStubs = (environment = {}, failing = "") => { + const bin = mkdtempSync(join(tmpdir(), "cmake-stub-")); + try { + for (const tool of ["cmake", "ctest"]) { + writeFileSync( + join(bin, tool), + [ + "#!/usr/bin/env bash", + `printf '${tool}' >> "${join(bin, "calls")}"`, + `printf ' [%s]' "$@" >> "${join(bin, "calls")}"`, + `echo >> "${join(bin, "calls")}"`, + tool === failing ? "exit 7" : "exit 0", + "", + ].join("\n"), + ); + chmodSync(join(bin, tool), 0o755); + } + const result = spawnSync("bash", [script], { + encoding: "utf8", + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + VERBOSE: "", + RUNNER_DEBUG: "", + BUILD_TYPE: "", + SANITIZERS: "", + TREE_VALIDATION: "", + COVERAGE: "", + BENCHMARKS: "", + CMAKE_ARGS: "", + ...environment, + }, + }); + let calls = []; + try { + calls = readFileSync(join(bin, "calls"), "utf8").trim().split("\n"); + } catch { + // No tool was called. + } + return { ...result, calls }; + } finally { + rmSync(bin, { recursive: true, force: true }); + } +}; + +test("configures, builds and runs the tests, failing when no test ran", () => { + const { status, calls } = runWithStubs(); + assert.equal(status, 0); + assert.equal(calls.length, 3); + assert.match(calls[0], /^cmake \[-S\] \[\.\] \[-B\] \[build\] \[-DCMAKE_BUILD_TYPE=Release\] \[-DLINKS_PLATFORM_TESTS=ON\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_BENCHMARKS=OFF\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_TREE_VALIDATION=OFF\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_COVERAGE=OFF\]/); + assert.equal(calls[1], "cmake [--build] [build] [--config] [Release] [--parallel]"); + assert.match(calls[2], /^ctest .*\[--build-config\] \[Release\].*\[--no-tests=error\]/); +}); + +test("passes the CI options through to CMake", () => { + const { status, calls } = runWithStubs({ + BUILD_TYPE: "Debug", + SANITIZERS: "address;undefined", + TREE_VALIDATION: "1", + COVERAGE: "1", + BENCHMARKS: "1", + CMAKE_ARGS: "-DA=1 -DB=2", + }); + assert.equal(status, 0); + assert.match(calls[0], /\[-DCMAKE_BUILD_TYPE=Debug\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_SANITIZERS=address;undefined\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_TREE_VALIDATION=ON\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_COVERAGE=ON\]/); + assert.match(calls[0], /\[-DLINKS_PLATFORM_BENCHMARKS=ON\] .*\[-DA=1\] \[-DB=2\]$/); + assert.match(calls[2], /\[--build-config\] \[Debug\]/); +}); + +test("stops at the first failing step", () => { + const configure = runWithStubs({}, "cmake"); + assert.equal(configure.status, 7); + assert.equal(configure.calls.length, 1); + const tests = runWithStubs({}, "ctest"); + assert.equal(tests.status, 7); + assert.equal(tests.calls.length, 3); +}); diff --git a/.github/scripts/cpp-workflow-policy.test.mjs b/.github/scripts/cpp-workflow-policy.test.mjs new file mode 100644 index 0000000..98a398a --- /dev/null +++ b/.github/scripts/cpp-workflow-policy.test.mjs @@ -0,0 +1,107 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { getJobs } from "./workflow-jobs.mjs"; + +const read = (path) => readFileSync(new URL(path, import.meta.url), "utf8"); +const testWorkflow = read("../workflows/cpp-test.yml"); +const deployWorkflow = read("../workflows/deploy-cpp.yml"); +const benchmarksWorkflow = read("../workflows/benchmarks.yml"); +const buildScript = read("../../cpp/build-and-test.sh"); +const cmake = read("../../cpp/CMakeLists.txt"); +const testJobs = getJobs(testWorkflow); +const deployJobs = getJobs(deployWorkflow); + +test("keeps the workflow names that README badges reference", () => { + assert.match(testWorkflow, /^name: Test cpp$/m); + assert.match(deployWorkflow, /^name: Deploy new cpp version$/m); +}); + +test("tests pull requests and main whenever C++ sources change", () => { + const push = testWorkflow.slice(testWorkflow.indexOf(" push:"), testWorkflow.indexOf(" pull_request:")); + const pullRequest = testWorkflow.slice(testWorkflow.indexOf(" pull_request:"), testWorkflow.indexOf(" workflow_call:")); + assert.match(push, /branches: \[main\]/); + for (const trigger of [push, pullRequest]) { + assert.doesNotMatch(trigger, /types:/); + assert.match(trigger, /- 'cpp\/\*\*'/); + } +}); + +test("runs the tests instead of only compiling them", () => { + assert.match(testJobs.get("test"), /\n {10}cpp\/build-and-test\.sh\n/); + assert.match(buildScript, /ctest .*--no-tests=error/); +}); + +test("tests every compiler that consumes the headers, with sanitizers and tree validation", () => { + const job = testJobs.get("test"); + for (const os of ["ubuntu-24.04", "macos-15", "windows-2025"]) { + assert.match(job, new RegExp(`os: ${os}\\n`)); + } + assert.match(job, /cxx: g\+\+/); + assert.match(job, /cxx: clang\+\+/); + assert.match(job, /sanitizers: address;undefined/); + assert.match(job, /tree-validation: '1'/); + assert.match(job, /fail-fast: false/); + // Matrix jobs share a job-level group unless it names the matrix entry. + assert.match(job, /group: .*\$\{\{ matrix\.name \}\}/); + assert.match(cmake, /-fsanitize=\$\{sanitizers\}/); + assert.match(cmake, /ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION=1/); +}); + +test("lets the build script decide what is built", () => { + assert.doesNotMatch(cmake, /CMAKE_CXX_FLAGS.*-march/); + assert.match(buildScript, /-DLINKS_PLATFORM_TESTS=ON/); + assert.match(buildScript, /-DLINKS_PLATFORM_TREE_VALIDATION=/); + assert.match(buildScript, /-DLINKS_PLATFORM_COVERAGE=/); + assert.match(buildScript, /cmake --build .*--config "\$build_type"/); + assert.match(buildScript, /ctest .*--build-config "\$build_type"/); +}); + +test("requires every line of the headers to be covered by the tests", () => { + const job = testJobs.get("coverage"); + assert.match(job, /COVERAGE: '1'/); + assert.match(job, /pipx run gcovr==\d+\.\d+ /); + assert.match(job, /--filter '\.\*\/Platform\\\.Collections\\\.Methods\/\.\*'/); + assert.match(job, /--fail-under-line 100/); +}); + +test("packs with dotnet and verifies the package on every run", () => { + const job = testJobs.get("pack"); + assert.match(job, /pack-cpp-nuget\.mjs "\$RUNNER_TEMP\/cpp-nuget"/); + assert.match(job, /check-cpp-nuget-package\.sh "\$PACKAGE_PATH"/); + assert.match(job, /check-cpp-nuget-package\.test\.mjs/); + assert.match(job, /name: cpp-nuget-package/); + assert.match(job, /if-no-files-found: error/); +}); + +test("deploys only what the local test workflow built and tested", () => { + assert.match(deployJobs.get("test"), /uses: \.\/\.github\/workflows\/cpp-test\.yml/); + assert.match(deployJobs.get("releasePreflight"), /needs: test/); + assert.match(deployJobs.get("releasePreflight"), /preflight-nuget-release\.mjs/); + assert.match(deployJobs.get("pushToNuget"), /needs: \[test, releasePreflight\]/); + assert.match(deployJobs.get("pushToNuget"), /push-nuget-package\.sh "\$RUNNER_TEMP\/cpp-nuget"\/\*\.nupkg/); +}); + +test("supports trusted publishing with the API key as a fallback", () => { + const job = deployJobs.get("pushToNuget"); + assert.match(job, /\n id-token: write/); + assert.match(job, /uses: NuGet\/login@[0-9a-f]{40} # v\d/); + assert.match(job, /NUGET_API_KEY: \$\{\{ steps\.nuget-login\.outputs\.NUGET_API_KEY \|\| secrets\.NUGET_TOKEN \}\}/); +}); + +test("creates the GitHub release only after the NuGet push succeeded", () => { + const job = deployJobs.get("publishRelease"); + assert.match(job, /needs: \[test, pushToNuget\]/); + assert.doesNotMatch(job, /\n if:/); + assert.match(job, /gh release create "\$tag" "\$archive"/); +}); + +test("runs the benchmarks only on request, but keeps them compiling on every change", () => { + const triggers = benchmarksWorkflow.slice(benchmarksWorkflow.indexOf("\non:\n"), benchmarksWorkflow.indexOf("\npermissions:")); + assert.match(triggers, /\n {2}workflow_dispatch:/); + assert.doesNotMatch(triggers, /\n {2}(?:push|pull_request|pull_request_target|schedule):/); + assert.match(getJobs(benchmarksWorkflow).get("cpp"), /BENCHMARKS: '1'/); + assert.match(testJobs.get("test"), /benchmarks: '1'/); +}); diff --git a/.github/scripts/preflight-nuget-release.mjs b/.github/scripts/preflight-nuget-release.mjs new file mode 100644 index 0000000..3b7e60f --- /dev/null +++ b/.github/scripts/preflight-nuget-release.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node + +/** + * Decide whether a NuGet release still has to be published and check the + * credentials that publishing needs, before any package is pushed. + * + * linksplatform/Interfaces#150 found two blind spots in the previous presence-only check: + * - every push to main tried to push an already published version, so an + * expired NUGET_TOKEN failed runs that had nothing to publish; + * - an unpublished version (C# 0.5.1-0.6.1, C++ 0.3.43-0.4.1) was never + * reported as such, and the C++ release was created anyway. + * + * The version check uses the public flat-container index, which needs no key. + * An API key is checked without publishing anything, through the same two + * calls that `nuget push` makes for symbol packages (NuGetGallery + * ApiController): POST /api/v2/package/create-verification-key/ rejects an + * invalid, expired or non-push key with 401/403, and GET + * /api/v2/verifykey// with the returned one-time key + * rejects a key whose glob or owner does not cover the package. The gallery + * deletes the one-time key after that call. Trusted publishing (NUGET_USER) + * avoids long-lived keys altogether. + * + * Environment: PACKAGE_ID, PACKAGE_VERSION (or CSPROJ to read both), + * GITHUB_TOKEN, NUGET_TOKEN, NUGET_USER, NUGET_INDEX_URL and NUGET_GALLERY_URL + * (tests), VERBOSE=1 or RUNNER_DEBUG=1 for diagnostic output. + * Outputs: publish_required=true|false, auth=trusted-publishing|api-key|none. + */ + +import { appendFileSync, readFileSync } from "node:fs"; + +const defaultIndexUrl = "https://api.nuget.org/v3-flatcontainer"; +const defaultGalleryUrl = "https://www.nuget.org"; + +export const readCsproj = (source) => { + const read = (name) => new RegExp(`<${name}>([^<]+)`).exec(source)?.[1]?.trim(); + return { + packageId: read("PackageId") ?? read("AssemblyName"), + version: read("Version") ?? read("VersionPrefix"), + }; +}; + +export const versionIndexUrl = (packageId, indexUrl = defaultIndexUrl) => + `${indexUrl}/${packageId.toLowerCase()}/index.json`; + +/** + * @returns {Promise<{ published: boolean | undefined, latest?: string, detail: string }>} + * `published` is undefined when nuget.org could not be queried; `latest` is + * the newest published version, if any. + */ +export const fetchPublished = async ({ packageId, version, indexUrl, fetchImpl = fetch }) => { + const url = versionIndexUrl(packageId, indexUrl); + try { + const response = await fetchImpl(url, { signal: AbortSignal.timeout(30_000) }); + if (response.status === 404) { + return { published: false, detail: `${url} returned 404` }; + } + if (!response.ok) { + return { published: undefined, detail: `${url} returned ${response.status}` }; + } + const { versions = [] } = await response.json(); + return { + published: versions.includes(version.toLowerCase()), + latest: versions.at(-1), + detail: `${url} lists ${versions.length} versions`, + }; + } catch (error) { + return { published: undefined, detail: `${url} failed: ${error.message}` }; + } +}; + +/** + * @returns {Promise<{ valid: boolean | undefined, detail: string }>} + * `valid` is undefined when nuget.org could not answer, and also when no + * version is published yet: then only the key itself can be checked, not + * whether it may push this package. + */ +export const verifyApiKey = async ({ + packageId, + publishedVersion, + apiKey, + galleryUrl = defaultGalleryUrl, + fetchImpl = fetch, +}) => { + const id = encodeURIComponent(packageId); + const createUrl = `${galleryUrl}/api/v2/package/create-verification-key/${id}`; + let key; + try { + const response = await fetchImpl(createUrl, { + method: "POST", + headers: { "X-NuGet-ApiKey": apiKey }, + body: "", + signal: AbortSignal.timeout(30_000), + }); + if (response.status === 401 || response.status === 403) { + return { valid: false, detail: `${createUrl} returned ${response.status}` }; + } + if (!response.ok) { + return { valid: undefined, detail: `${createUrl} returned ${response.status}` }; + } + key = (await response.json()).Key; + } catch (error) { + return { valid: undefined, detail: `${createUrl} failed: ${error.message}` }; + } + if (!key) { + return { valid: undefined, detail: `${createUrl} returned no verification key` }; + } + if (!publishedVersion) { + return { + valid: undefined, + detail: `${createUrl} accepted the key, but no published version exists to check its package scope`, + }; + } + + const verifyUrl = `${galleryUrl}/api/v2/verifykey/${id}/${encodeURIComponent(publishedVersion)}`; + try { + const response = await fetchImpl(verifyUrl, { + headers: { "X-NuGet-ApiKey": key }, + signal: AbortSignal.timeout(30_000), + }); + if (response.status === 401 || response.status === 403) { + return { valid: false, detail: `${verifyUrl} returned ${response.status}` }; + } + return { + valid: response.ok ? true : undefined, + detail: `${verifyUrl} returned ${response.status}`, + }; + } catch (error) { + return { valid: undefined, detail: `${verifyUrl} failed: ${error.message}` }; + } +}; + +export const evaluateRelease = ({ published, githubToken, nugetToken, nugetUser, keyValid, keyDetail }) => { + const failures = []; + const warnings = []; + + if (!githubToken) { + failures.push("GITHUB_TOKEN is unavailable"); + } + if (published === undefined) { + warnings.push( + "nuget.org could not be queried; the push will run with --skip-duplicate", + ); + } + + const publishRequired = published !== true; + let auth = "none"; + if (nugetUser) { + auth = "trusted-publishing"; + } else if (nugetToken) { + auth = "api-key"; + } + + if (publishRequired && auth === "none") { + failures.push( + "The version is not on nuget.org but neither the NUGET_USER variable (trusted publishing) nor the NUGET_TOKEN secret is configured", + ); + } + if (publishRequired && auth === "api-key") { + if (keyValid === false) { + failures.push( + "nuget.org rejected the NUGET_TOKEN secret: it is invalid, expired, or not scoped to push this package. Create a new key at https://www.nuget.org/account/apikeys with push scope for the package and store it as the NUGET_TOKEN repository secret, or configure trusted publishing (https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) and set the NUGET_USER repository variable", + ); + } else if (keyValid === undefined) { + const reason = keyDetail ? ` (${keyDetail})` : ""; + warnings.push(`nuget.org could not verify the NUGET_TOKEN secret${reason}; the push will show whether it is accepted`); + } + } + + return { passed: failures.length === 0, publishRequired, auth, failures, warnings }; +}; + +const setOutput = (environment, name, value) => { + console.log(`${name}=${value}`); + if (environment.GITHUB_OUTPUT) { + appendFileSync(environment.GITHUB_OUTPUT, `${name}=${value}\n`); + } +}; + +export const run = async (environment = process.env, fetchImpl = fetch) => { + const verbose = environment.VERBOSE === "1" || environment.RUNNER_DEBUG === "1"; + let packageId = environment.PACKAGE_ID; + let version = environment.PACKAGE_VERSION; + if (environment.CSPROJ) { + const project = readCsproj(readFileSync(environment.CSPROJ, "utf8")); + packageId ||= project.packageId; + version ||= project.version; + } + if (!packageId || !version) { + console.error("::error title=NuGet release preflight failed::Package id or version is unknown"); + return 1; + } + + const { published, latest, detail } = await fetchPublished({ + packageId, + version, + indexUrl: environment.NUGET_INDEX_URL || defaultIndexUrl, + fetchImpl, + }); + if (verbose) { + console.log(`Version index: ${detail}`); + } + + const nugetToken = environment.NUGET_TOKEN ?? ""; + const nugetUser = environment.NUGET_USER ?? ""; + let keyValid; + let keyDetail; + if (published !== true && nugetToken && !nugetUser) { + const verification = await verifyApiKey({ + packageId, + publishedVersion: latest, + apiKey: nugetToken, + galleryUrl: environment.NUGET_GALLERY_URL || defaultGalleryUrl, + fetchImpl, + }); + keyValid = verification.valid; + keyDetail = verification.detail; + if (verbose) { + console.log(`API key verification: ${verification.detail}`); + } + } + + const result = evaluateRelease({ + published, + githubToken: environment.GITHUB_TOKEN ?? "", + nugetToken, + nugetUser, + keyValid, + keyDetail, + }); + + for (const warning of result.warnings) { + console.log(`::warning title=NuGet release preflight::${warning}`); + } + for (const failure of result.failures) { + console.error(`::error title=NuGet release preflight failed::${failure}`); + } + + if (result.publishRequired) { + console.log(`${packageId} ${version} is not on nuget.org yet; it will be published using ${result.auth}.`); + if (result.auth === "api-key" && keyValid) { + console.log("nuget.org accepted NUGET_TOKEN for pushing this package."); + } + } else { + console.log(`${packageId} ${version} is already on nuget.org; publishing will be skipped.`); + } + + setOutput(environment, "publish_required", String(result.publishRequired)); + setOutput(environment, "auth", result.auth); + return result.passed ? 0 : 1; +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = await run(); +} diff --git a/.github/scripts/preflight-nuget-release.test.mjs b/.github/scripts/preflight-nuget-release.test.mjs new file mode 100644 index 0000000..792e95e --- /dev/null +++ b/.github/scripts/preflight-nuget-release.test.mjs @@ -0,0 +1,250 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + evaluateRelease, + fetchPublished, + readCsproj, + run, + verifyApiKey, + versionIndexUrl, +} from "./preflight-nuget-release.mjs"; + +const respond = (status, body = {}) => async () => ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, +}); + +test("reads the C# package identity from the project file", () => { + const csproj = readFileSync( + new URL("../../csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj", import.meta.url), + "utf8", + ); + const project = readCsproj(csproj); + assert.equal(project.packageId, "Platform.Collections.Methods"); + assert.match(project.version, /^\d+\.\d+\.\d+$/); +}); + +test("queries the lower-case flat-container index", () => { + assert.equal( + versionIndexUrl("Platform.Collections.Methods.TemplateLibrary"), + "https://api.nuget.org/v3-flatcontainer/platform.collections.methods.templatelibrary/index.json", + ); +}); + +test("detects published, unpublished, unknown and unreachable packages", async () => { + const query = (fetchImpl) => + fetchPublished({ packageId: "P", version: "1.0.0-Beta", fetchImpl }); + assert.equal((await query(respond(200, { versions: ["1.0.0-beta"] }))).published, true); + assert.equal((await query(respond(200, { versions: ["0.9.0"] }))).published, false); + assert.equal((await query(respond(404))).published, false); + assert.equal((await query(respond(503))).published, undefined); + assert.equal( + (await query(async () => { + throw new Error("offline"); + })).published, + undefined, + ); +}); + +test("skips publishing an existing version without NuGet credentials", () => { + assert.deepEqual( + evaluateRelease({ published: true, githubToken: "g", nugetToken: "", nugetUser: "" }), + { passed: true, publishRequired: false, auth: "none", failures: [], warnings: [] }, + ); +}); + +test("fails before pushing when an unpublished version has no credentials", () => { + const result = evaluateRelease({ published: false, githubToken: "", nugetToken: "", nugetUser: "" }); + assert.equal(result.passed, false); + assert.equal(result.publishRequired, true); + assert.deepEqual(result.failures.length, 2); + assert.match(result.failures[1], /NUGET_USER .* NUGET_TOKEN/); +}); + +test("prefers trusted publishing over the long-lived API key", () => { + const result = evaluateRelease({ published: false, githubToken: "g", nugetToken: "k", nugetUser: "linksplatform" }); + assert.equal(result.auth, "trusted-publishing"); + assert.equal(result.passed, true); +}); + +test("still publishes with --skip-duplicate when nuget.org is unreachable", () => { + const result = evaluateRelease({ published: undefined, githubToken: "g", nugetToken: "k", nugetUser: "" }); + assert.equal(result.passed, true); + assert.equal(result.publishRequired, true); + assert.equal(result.auth, "api-key"); + assert.equal(result.warnings.length, 2); + assert.match(result.warnings[1], /could not verify the NUGET_TOKEN/); +}); + +test("says why the API key could not be verified", () => { + const result = evaluateRelease({ + published: false, + githubToken: "g", + nugetToken: "k", + nugetUser: "", + keyValid: undefined, + keyDetail: "no published version exists to check its package scope", + }); + assert.equal(result.passed, true); + assert.match(result.warnings[0], /NUGET_TOKEN secret \(no published version exists .*\); the push/); +}); + +// Answers each request from a "METHOD url" -> [status, body] table and records the calls. +const gallery = (routes) => { + const calls = []; + const fetchImpl = async (url, options = {}) => { + const request = `${options.method ?? "GET"} ${url}`; + calls.push({ request, key: options.headers?.["X-NuGet-ApiKey"] }); + const route = routes[request]; + if (!route) { + throw new Error(`unexpected ${request}`); + } + return respond(...route)(); + }; + return { calls, fetchImpl }; +}; +const createUrl = "POST https://www.nuget.org/api/v2/package/create-verification-key/Platform.Collections.Methods"; +const verifyUrl = "GET https://www.nuget.org/api/v2/verifykey/Platform.Collections.Methods/0.5.0"; + +test("verifies an API key in two steps without publishing", async () => { + const { calls, fetchImpl } = gallery({ + [createUrl]: [200, { Key: "one-time", Expires: "2026-10-07T00:00:00Z" }], + [verifyUrl]: [200], + }); + const result = await verifyApiKey({ + packageId: "Platform.Collections.Methods", + publishedVersion: "0.5.0", + apiKey: "secret", + fetchImpl, + }); + assert.equal(result.valid, true); + assert.deepEqual(calls, [ + { request: createUrl, key: "secret" }, + { request: verifyUrl, key: "one-time" }, + ]); +}); + +test("rejects an invalid or expired API key (linksplatform/Interfaces#150)", async () => { + for (const status of [401, 403]) { + const { calls, fetchImpl } = gallery({ [createUrl]: [status] }); + const result = await verifyApiKey({ + packageId: "Platform.Collections.Methods", + publishedVersion: "0.5.0", + apiKey: "expired", + fetchImpl, + }); + assert.equal(result.valid, false); + assert.equal(calls.length, 1); + } +}); + +test("rejects an API key that is not scoped to the package", async () => { + const { fetchImpl } = gallery({ + [createUrl]: [200, { Key: "one-time" }], + [verifyUrl]: [403], + }); + const result = await verifyApiKey({ + packageId: "Platform.Collections.Methods", + publishedVersion: "0.5.0", + apiKey: "other-glob", + fetchImpl, + }); + assert.equal(result.valid, false); +}); + +test("does not claim a package scope it cannot check for a package that was never published", async () => { + const { calls, fetchImpl } = gallery({ [createUrl]: [200, { Key: "one-time" }] }); + const result = await verifyApiKey({ packageId: "Platform.Collections.Methods", apiKey: "k", fetchImpl }); + assert.equal(result.valid, undefined); + assert.match(result.detail, /no published version/); + assert.equal(calls.length, 1); +}); + +test("reports an unknown key state when nuget.org cannot answer", async () => { + const verify = (fetchImpl) => + verifyApiKey({ packageId: "Platform.Collections.Methods", publishedVersion: "0.5.0", apiKey: "k", fetchImpl }); + assert.equal((await verify(gallery({ [createUrl]: [503] }).fetchImpl)).valid, undefined); + assert.equal((await verify(gallery({ [createUrl]: [200, {}] }).fetchImpl)).valid, undefined); + assert.equal( + (await verify(gallery({ [createUrl]: [200, { Key: "one-time" }], [verifyUrl]: [500] }).fetchImpl)).valid, + undefined, + ); + assert.equal((await verify(gallery({}).fetchImpl)).valid, undefined); +}); + +test("fails before pushing when nuget.org rejects NUGET_TOKEN", () => { + const result = evaluateRelease({ + published: false, + githubToken: "g", + nugetToken: "expired", + nugetUser: "", + keyValid: false, + }); + assert.equal(result.passed, false); + assert.match(result.failures[0], /rejected the NUGET_TOKEN secret/); +}); + +test("does not verify NUGET_TOKEN when nothing has to be published", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.5.0"] }], + }); + const exitCode = await run( + { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.5.0", GITHUB_TOKEN: "g", NUGET_TOKEN: "expired" }, + fetchImpl, + ); + assert.equal(exitCode, 0); + assert.equal(calls.length, 1); +}); + +test("fails the preflight with an expired NUGET_TOKEN for an unpublished version", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.4.0", "0.5.0"] }], + [createUrl]: [403], + }); + const exitCode = await run( + { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.6.1", GITHUB_TOKEN: "g", NUGET_TOKEN: "expired" }, + fetchImpl, + ); + assert.equal(exitCode, 1); + assert.equal(calls.length, 2); +}); + +test("verifies the package scope against the newest published version", async () => { + const { calls, fetchImpl } = gallery({ + "GET https://api.nuget.org/v3-flatcontainer/platform.collections.methods/index.json": [200, { versions: ["0.4.0", "0.5.0"] }], + [createUrl]: [200, { Key: "one-time" }], + [verifyUrl]: [200], + }); + const exitCode = await run( + { PACKAGE_ID: "Platform.Collections.Methods", PACKAGE_VERSION: "0.6.1", GITHUB_TOKEN: "g", NUGET_TOKEN: "valid" }, + fetchImpl, + ); + assert.equal(exitCode, 0); + assert.equal(calls.at(-1).request, verifyUrl); +}); + +test("writes the decision to GITHUB_OUTPUT", async () => { + const directory = mkdtempSync(path.join(tmpdir(), "preflight-")); + const output = path.join(directory, "output"); + try { + const exitCode = await run( + { + PACKAGE_ID: "Platform.Collections.Methods", + PACKAGE_VERSION: "0.5.0", + GITHUB_TOKEN: "g", + GITHUB_OUTPUT: output, + }, + respond(200, { versions: ["0.5.0"] }), + ); + assert.equal(exitCode, 0); + assert.equal(readFileSync(output, "utf8"), "publish_required=false\nauth=none\n"); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/.github/scripts/push-nuget-package.sh b/.github/scripts/push-nuget-package.sh new file mode 100644 index 0000000..91e1786 --- /dev/null +++ b/.github/scripts/push-nuget-package.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Push one package to nuget.org, or skip when the release preflight found the +# version already published. A rejected key only surfaced as a bare +# "403 (The specified API key is invalid, has expired, ...)" line (linksplatform/Interfaces#150); +# this prints what the maintainer has to change instead. +# +# Usage: push-nuget-package.sh +# Environment: +# NUGET_API_KEY short-lived trusted-publishing key or the NUGET_TOKEN secret +# PUBLISH_REQUIRED output of preflight-nuget-release.mjs (default: true) +# AUTH trusted-publishing or api-key, used in the guidance +# 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: push-nuget-package.sh }" +if [ "${PUBLISH_REQUIRED:-true}" != true ]; then + echo "$(basename "$package") is already on nuget.org; nothing to publish." + exit 0 +fi +if [ ! -s "$package" ]; then + echo "::error title=NuGet push failed::$package does not exist" + exit 1 +fi +if [ -z "${NUGET_API_KEY:-}" ]; then + echo "::error title=NuGet push failed::No API key: configure the NUGET_USER variable for trusted publishing or the NUGET_TOKEN secret" + exit 1 +fi + +log="$(mktemp)" +trap 'rm -f "$log"' EXIT +if dotnet nuget push "$package" \ + --source https://api.nuget.org/v3/index.json \ + --api-key "$NUGET_API_KEY" \ + --skip-duplicate 2>&1 | tee "$log"; then + exit 0 +fi + +if grep -qE '(^|[^0-9])403([^0-9]|$)|Forbidden' "$log"; then + if [ "${AUTH:-api-key}" = trusted-publishing ]; then + echo "::error title=nuget.org rejected the trusted publishing key::Check that the nuget.org trusted publishing policy for this package names repository ${GITHUB_REPOSITORY:-} and workflow file $(basename "${GITHUB_WORKFLOW_REF%@*}") and that its owner still owns the package." + else + echo "::error title=nuget.org rejected NUGET_TOKEN::The NUGET_TOKEN secret is invalid, expired, or not scoped to push this package. Create a new key at https://www.nuget.org/account/apikeys with push scope for the package and store it as the NUGET_TOKEN repository secret, or configure trusted publishing (https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) and set the NUGET_USER repository variable." + fi +fi +exit 1 diff --git a/.github/scripts/push-nuget-package.test.mjs b/.github/scripts/push-nuget-package.test.mjs new file mode 100644 index 0000000..cab896b --- /dev/null +++ b/.github/scripts/push-nuget-package.test.mjs @@ -0,0 +1,88 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const script = new URL("./push-nuget-package.sh", import.meta.url).pathname; +// The exact line nuget.org returned in run 36213154898 (linksplatform/Interfaces#150). +const rejectedKey = + "error: Response status code does not indicate success: 403 (The specified API key is invalid, has expired, or does not have permission to access the specified package.)."; + +const withFakeDotnet = (dotnetBody, callback) => { + const directory = mkdtempSync(path.join(tmpdir(), "push-nuget-")); + try { + const dotnet = path.join(directory, "dotnet"); + writeFileSync(dotnet, `#!/usr/bin/env bash\necho "$@" > "${directory}/args"\n${dotnetBody}\n`); + chmodSync(dotnet, 0o755); + const nupkg = path.join(directory, "P.1.0.0.nupkg"); + writeFileSync(nupkg, "package"); + return callback({ directory, nupkg }); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const push = (directory, nupkg, environment) => + spawnSync("bash", [script, nupkg], { + encoding: "utf8", + env: { PATH: `${directory}:${process.env.PATH}`, ...environment }, + }); + +test("skips the push when the version is already published", () => { + withFakeDotnet("exit 99", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { PUBLISH_REQUIRED: "false" }); + assert.equal(result.status, 0); + assert.match(result.stdout, /already on nuget\.org/); + }); +}); + +test("fails without a key instead of silently skipping", () => { + withFakeDotnet("exit 0", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { PUBLISH_REQUIRED: "true" }); + assert.equal(result.status, 1); + assert.match(result.stdout, /::error title=NuGet push failed::No API key/); + }); +}); + +test("pushes with --skip-duplicate to nuget.org", () => { + withFakeDotnet("exit 0", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { NUGET_API_KEY: "key" }); + assert.equal(result.status, 0); + const args = spawnSync("cat", [path.join(directory, "args")], { encoding: "utf8" }).stdout; + assert.match(args, /^nuget push .*P\.1\.0\.0\.nupkg --source https:\/\/api\.nuget\.org\/v3\/index\.json --api-key key --skip-duplicate/); + }); +}); + +test("explains how to renew an expired NUGET_TOKEN", () => { + withFakeDotnet(`echo '${rejectedKey}'; exit 1`, ({ directory, nupkg }) => { + const result = push(directory, nupkg, { NUGET_API_KEY: "expired", AUTH: "api-key" }); + assert.equal(result.status, 1); + assert.match(result.stdout, /::error title=nuget\.org rejected NUGET_TOKEN::/); + assert.match(result.stdout, /trusted-publishing/); + }); +}); + +test("explains how to fix a rejected trusted publishing policy", () => { + withFakeDotnet(`echo '${rejectedKey}'; exit 1`, ({ directory, nupkg }) => { + const result = push(directory, nupkg, { + NUGET_API_KEY: "short-lived", + AUTH: "trusted-publishing", + GITHUB_REPOSITORY: "linksplatform/Collections.Methods", + GITHUB_WORKFLOW_REF: "linksplatform/Collections.Methods/.github/workflows/csharp.yml@refs/heads/main", + }); + assert.equal(result.status, 1); + assert.match(result.stdout, /rejected the trusted publishing key::.*linksplatform\/Collections\.Methods .*csharp\.yml/); + }); +}); + +test("keeps other push failures red without misleading guidance", () => { + withFakeDotnet("echo 'error: 500 (Internal Server Error)'; exit 1", ({ directory, nupkg }) => { + const result = push(directory, nupkg, { NUGET_API_KEY: "key" }); + assert.equal(result.status, 1); + assert.doesNotMatch(result.stdout, /rejected/); + }); +}); diff --git a/.github/scripts/workflow-jobs.mjs b/.github/scripts/workflow-jobs.mjs new file mode 100644 index 0000000..de5cb29 --- /dev/null +++ b/.github/scripts/workflow-jobs.mjs @@ -0,0 +1,25 @@ +// Splits a workflow file into its jobs without a YAML dependency, for the +// workflow policy tests. +export const getJobs = (source) => { + const jobs = new Map(); + const lines = source.slice(source.indexOf("\njobs:\n") + 1).split("\n"); + let currentName; + let currentLines = []; + + for (const line of lines.slice(1)) { + const match = /^ ([A-Za-z_][\w-]*):\s*$/.exec(line); + if (match) { + if (currentName) { + jobs.set(currentName, currentLines.join("\n")); + } + currentName = match[1]; + currentLines = [line]; + } else if (currentName) { + currentLines.push(line); + } + } + if (currentName) { + jobs.set(currentName, currentLines.join("\n")); + } + return jobs; +}; diff --git a/.github/workflows/cpp-test.yml b/.github/workflows/cpp-test.yml index fc4d56b..e2e5e7c 100644 --- a/.github/workflows/cpp-test.yml +++ b/.github/workflows/cpp-test.yml @@ -2,24 +2,178 @@ name: Test cpp on: push: - branches: - - 'main' + branches: [main] paths: - - 'cpp/**.h' - - 'cpp/**.cpp' - - 'cpp/CMakeLists.txt' - - 'cpp/conanfile.txt' + - 'cpp/**' + - '.github/scripts/cpp-*' + - '.github/scripts/*cpp-nuget*' + - '.github/scripts/*nuget-*' + - '.github/workflows/cpp-test.yml' pull_request: - types: - - edited - branches: - - 'main' + branches: [main] paths: - - 'cpp/**.h' - - 'cpp/**.cpp' - - 'cpp/CMakeLists.txt' - - 'cpp/conanfile.txt' - + - 'cpp/**' + - '.github/scripts/cpp-*' + - '.github/scripts/*cpp-nuget*' + - '.github/scripts/*nuget-*' + - '.github/workflows/cpp-test.yml' + workflow_call: + outputs: + package_id: + description: NuGet package id read from the nuspec + value: ${{ jobs.pack.outputs.package_id }} + version: + description: NuGet package version read from the nuspec + value: ${{ jobs.pack.outputs.version }} + workflow_dispatch: + +permissions: + contents: read + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + jobs: - main: - uses: linksplatform/Workflows/.github/workflows/cpp-test.yml@main + test: + name: test (${{ matrix.name }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + # Job-level groups: deploy-cpp.yml calls this workflow, and its own + # workflow-level group must not be shared with these jobs. The matrix name + # keeps the matrix jobs from cancelling each other. + concurrency: + group: check-${{ github.workflow }}-${{ github.ref }}-test-${{ matrix.name }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + # The headers are consumed by every compiler that restores the NuGet or + # Conan package, so each one has to build and pass the tests. + strategy: + fail-fast: false + matrix: + include: + # Also builds the benchmarks, so they keep compiling; they run only + # in the manual Benchmarks workflow. + - name: linux-gcc + os: ubuntu-24.04 + cc: gcc + cxx: g++ + benchmarks: '1' + - name: linux-clang + os: ubuntu-24.04 + cc: clang + cxx: clang++ + # Every attach and detach validates the whole tree (sizes, order and + # the size balanced property) under AddressSanitizer and UBSan. + - name: linux-gcc-sanitizers-validation + os: ubuntu-24.04 + cc: gcc + cxx: g++ + build-type: Debug + sanitizers: address;undefined + tree-validation: '1' + - name: macos-appleclang + os: macos-15 + - name: windows-msvc + os: windows-2025 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # The previous shared workflow only compiled the tests, so failing tests + # still passed CI. The script runs them through CTest. + - name: Build and run the tests + env: + MATRIX_CC: ${{ matrix.cc }} + MATRIX_CXX: ${{ matrix.cxx }} + BUILD_TYPE: ${{ matrix.build-type || 'Release' }} + SANITIZERS: ${{ matrix.sanitizers }} + TREE_VALIDATION: ${{ matrix.tree-validation }} + BENCHMARKS: ${{ matrix.benchmarks }} + run: | + # macOS and Windows use the platform compiler that CMake detects. + if [ -n "$MATRIX_CXX" ]; then + export CC="$MATRIX_CC" CXX="$MATRIX_CXX" + fi + cpp/build-and-test.sh + + coverage: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + concurrency: + group: check-${{ github.workflow }}-${{ github.ref }}-coverage + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Build and run the tests with gcov + env: + CC: gcc + CXX: g++ + BUILD_TYPE: Debug + COVERAGE: '1' + run: cpp/build-and-test.sh + + # Every line of the library headers has to be executed by the tests. + # --merge-lines merges the lines of all template instantiations. + - name: Require full line coverage of the headers + run: | + pipx run gcovr==8.8 --root cpp --object-directory cpp/build \ + --filter '.*/Platform\.Collections\.Methods/.*' \ + --merge-lines --gcov-ignore-parse-errors=all \ + --txt --txt-summary --fail-under-line 100 \ + --markdown "$RUNNER_TEMP/coverage.md" + cat "$RUNNER_TEMP/coverage.md" >> "$GITHUB_STEP_SUMMARY" + + pack: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + concurrency: + group: check-${{ github.workflow }}-${{ github.ref }}-pack + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + outputs: + package_id: ${{ steps.pack.outputs.package_id }} + version: ${{ steps.pack.outputs.version }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Test the build script + run: node --test .github/scripts/cpp-build-and-test.test.mjs + + - name: Test the NuGet release scripts + run: node --test .github/scripts/pack-cpp-nuget.test.mjs .github/scripts/check-cpp-nuget-package.test.mjs .github/scripts/preflight-nuget-release.test.mjs .github/scripts/push-nuget-package.test.mjs + + # Ubuntu 24.04 has no nuget apt package, which the shared deploy workflow + # installed; dotnet pack builds the package layout of 0.3.0 from the nuspec. + - name: Pack NuGet package + id: pack + run: node .github/scripts/pack-cpp-nuget.mjs "$RUNNER_TEMP/cpp-nuget" + + # A package that packs is not necessarily usable: restore it and its + # Platform.Interfaces dependency like a consumer and build a tree with + # its headers before it can be published. + - name: Restore and use the NuGet package + env: + PACKAGE_PATH: ${{ steps.pack.outputs.package_path }} + run: .github/scripts/check-cpp-nuget-package.sh "$PACKAGE_PATH" + + - name: Upload NuGet package + uses: actions/upload-artifact@v7 + with: + name: cpp-nuget-package + path: ${{ runner.temp }}/cpp-nuget + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/deploy-cpp.yml b/.github/workflows/deploy-cpp.yml index 9304934..586aab9 100644 --- a/.github/workflows/deploy-cpp.yml +++ b/.github/workflows/deploy-cpp.yml @@ -2,15 +2,122 @@ name: Deploy new cpp version on: push: - branches: main + branches: [main] paths: - 'cpp/**/*.nuspec' + - '.github/scripts/pack-cpp-nuget.mjs' + - '.github/scripts/check-cpp-nuget-package.sh' + - '.github/scripts/preflight-nuget-release.mjs' + - '.github/scripts/push-nuget-package.sh' + - '.github/workflows/cpp-test.yml' + - '.github/workflows/deploy-cpp.yml' workflow_dispatch: +permissions: + contents: read + +concurrency: + group: deploy-cpp-${{ github.ref }} + cancel-in-progress: false + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + jobs: - main: - uses: linksplatform/Workflows/.github/workflows/deploy-cpp.yml@main - with: - recipe_folder: "platform.delegates" - secrets: - NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + test: + uses: ./.github/workflows/cpp-test.yml + + releasePreflight: + needs: test + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + publishRequired: ${{ steps.preflight.outputs.publish_required }} + auth: ${{ steps.preflight.outputs.auth }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Check release state and credentials + id: preflight + env: + PACKAGE_ID: ${{ needs.test.outputs.package_id }} + PACKAGE_VERSION: ${{ needs.test.outputs.version }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + NUGET_USER: ${{ vars.NUGET_USER }} + run: node .github/scripts/preflight-nuget-release.mjs + + pushToNuget: + needs: [test, releasePreflight] + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Download NuGet package + uses: actions/download-artifact@v8 + with: + name: cpp-nuget-package + path: ${{ runner.temp }}/cpp-nuget + + - name: Log in to NuGet with trusted publishing + id: nuget-login + if: ${{ needs.releasePreflight.outputs.auth == 'trusted-publishing' && needs.releasePreflight.outputs.publishRequired == 'true' }} + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ vars.NUGET_USER }} + + - name: Push NuGet package to NuGet.org + env: + AUTH: ${{ needs.releasePreflight.outputs.auth }} + PUBLISH_REQUIRED: ${{ needs.releasePreflight.outputs.publishRequired }} + NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY || secrets.NUGET_TOKEN }} + run: .github/scripts/push-nuget-package.sh "$RUNNER_TEMP/cpp-nuget"/*.nupkg + + # Waits for the push, so a release always has its package on nuget.org. + publishRelease: + needs: [test, pushToNuget] + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Download NuGet package + uses: actions/download-artifact@v8 + with: + name: cpp-nuget-package + path: ${{ runner.temp }}/cpp-nuget + + - name: Publish GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PACKAGE_ID: ${{ needs.test.outputs.package_id }} + VERSION: ${{ needs.test.outputs.version }} + run: | + tag="cpp_${VERSION}" + if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "Release ${tag} already exists." + exit 0 + fi + archive="$RUNNER_TEMP/platform.collections.methods_${VERSION}.zip" + (cd cpp && zip -q -r "$archive" Platform.Collections.Methods) + notes="https://www.nuget.org/packages/${PACKAGE_ID}/${VERSION}"$'\n\n'"$(cat "$RUNNER_TEMP/cpp-nuget/release-notes.md")" + gh release create "$tag" "$archive" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "[C++] ${VERSION}" --notes "$notes" diff --git a/cpp/build-and-test.sh b/cpp/build-and-test.sh new file mode 100755 index 0000000..284ea21 --- /dev/null +++ b/cpp/build-and-test.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Build the C++ tests with CMake, then run them through CTest. CI calls this +# script, so a passing build always means that the tests were executed (the +# shared linksplatform/Workflows job only compiled them, and only when a pull +# request description was edited). +# +# CMakeLists.txt uses installed Platform.Interfaces, GTest and benchmark +# packages when CMake finds them (e.g. through CMAKE_PREFIX_PATH or a Conan +# toolchain) and fetches pinned commits of them otherwise. +# +# Environment: +# BUILD_DIR build directory relative to cpp/ (default: build) +# BUILD_TYPE CMake build type (default: Release) +# SANITIZERS sanitizers for the tests, e.g. "address;undefined" (default: none) +# TREE_VALIDATION 1 makes every tree check itself after each attach and detach +# COVERAGE 1 instruments the tests for gcov line coverage +# BENCHMARKS 1 also builds the benchmarks (default: 0) +# CMAKE_ARGS extra arguments for the CMake configure step +# CC, CXX compilers; CMake reads them +# 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 + +cd "$(dirname "$0")" +build_dir="${BUILD_DIR:-build}" +build_type="${BUILD_TYPE:-Release}" +on_off() { if [ "${1:-}" = 1 ]; then echo ON; else echo OFF; fi; } + +# shellcheck disable=SC2086 # CMAKE_ARGS is a list of arguments. +cmake -S . -B "$build_dir" \ + -DCMAKE_BUILD_TYPE="$build_type" \ + -DLINKS_PLATFORM_TESTS=ON \ + -DLINKS_PLATFORM_BENCHMARKS="$(on_off "${BENCHMARKS:-}")" \ + -DLINKS_PLATFORM_SANITIZERS="${SANITIZERS:-}" \ + -DLINKS_PLATFORM_TREE_VALIDATION="$(on_off "${TREE_VALIDATION:-}")" \ + -DLINKS_PLATFORM_COVERAGE="$(on_off "${COVERAGE:-}")" \ + ${CMAKE_ARGS:-} +# --config and -C select the build type of multi-config generators (MSVC). +cmake --build "$build_dir" --config "$build_type" --parallel +# --no-tests=error turns "nothing was run" into a failure instead of a pass. +ctest --test-dir "$build_dir" --build-config "$build_type" --output-on-failure --no-tests=error From 4fa848ee756719b39fb254a0155a12e3edcf7f40 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:43:42 +0000 Subject: [PATCH 16/46] Require full C# coverage and self-validating trees before a C# release csharp.yml now runs on pull requests and main without the shared linksplatform/Workflows jobs: it tests and packs the library, requires 100% line coverage (check-csharp-coverage.mjs), reruns the tests with -p:TreeValidation=true, builds the docfx site and PDF, and publishes to nuget.org with trusted publishing first and NUGET_TOKEN as a fallback. pipelineStatus fails if any required job failed or was skipped. --- .github/scripts/check-csharp-coverage.mjs | 122 +++++ .../scripts/check-csharp-coverage.test.mjs | 134 ++++++ .../scripts/check-csharp-pipeline-status.mjs | 75 +++ .../check-csharp-pipeline-status.test.mjs | 132 ++++++ .../scripts/csharp-workflow-policy.test.mjs | 213 +++++++++ .github/scripts/generate-csharp-pdf.sh | 81 ++++ .github/scripts/publish-csharp-docs.sh | 45 ++ .github/scripts/validate-csharp-docs.sh | 29 ++ .github/scripts/validate-csharp-docs.test.mjs | 64 +++ .github/scripts/validate-csharp-package.sh | 43 ++ .github/workflows/csharp.yml | 448 +++++++++++++----- csharp/docfx.json | 43 ++ csharp/filter.yml | 3 + csharp/toc.yml | 4 + 14 files changed, 1330 insertions(+), 106 deletions(-) create mode 100644 .github/scripts/check-csharp-coverage.mjs create mode 100644 .github/scripts/check-csharp-coverage.test.mjs create mode 100644 .github/scripts/check-csharp-pipeline-status.mjs create mode 100644 .github/scripts/check-csharp-pipeline-status.test.mjs create mode 100644 .github/scripts/csharp-workflow-policy.test.mjs create mode 100644 .github/scripts/generate-csharp-pdf.sh create mode 100644 .github/scripts/publish-csharp-docs.sh create mode 100644 .github/scripts/validate-csharp-docs.sh create mode 100644 .github/scripts/validate-csharp-docs.test.mjs create mode 100644 .github/scripts/validate-csharp-package.sh create mode 100644 csharp/docfx.json create mode 100644 csharp/filter.yml create mode 100644 csharp/toc.yml diff --git a/.github/scripts/check-csharp-coverage.mjs b/.github/scripts/check-csharp-coverage.mjs new file mode 100644 index 0000000..df1013e --- /dev/null +++ b/.github/scripts/check-csharp-coverage.mjs @@ -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 ] [--verbose] ... + * `--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>. +// 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 directory. + const 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 = /]*>[\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(/]*>[\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("") + 1); + for (const [line] of classLines.matchAll(/]*>/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 ] [--verbose] ..."); + 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(); +} diff --git a/.github/scripts/check-csharp-coverage.test.mjs b/.github/scripts/check-csharp-coverage.test.mjs new file mode 100644 index 0000000..a889061 --- /dev/null +++ b/.github/scripts/check-csharp-coverage.test.mjs @@ -0,0 +1,134 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { collectLines, run, summarize } from "./check-csharp-coverage.mjs"; + +const report = (packages) => ` + + +${packages} + +`; + +const classSource = (file, lines) => ` + + + +${lines.map(([number, hits]) => ` `).join("\n")} + + + + +${lines.map(([number, hits]) => ` `).join("\n")} + + `; + +const packageSource = (name, classes) => ` + +${classes.join("\n")} + + `; + +const library = "Platform.Collections.Methods"; + +const withReports = (sources, callback) => { + const directory = mkdtempSync(join(tmpdir(), "coverage-")); + try { + const paths = sources.map((source, index) => { + const path = join(directory, `coverage${index}.cobertura.xml`); + writeFileSync(path, source); + return path; + }); + return callback(paths, directory); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const capture = (callback) => { + const errors = []; + const logs = []; + const { error, log } = console; + console.error = (message) => errors.push(message); + console.log = (message) => logs.push(message); + try { + return { status: callback(), errors, logs }; + } finally { + console.error = error; + console.log = log; + } +}; + +test("counts only the library package and each line once per class", () => { + const source = report( + [ + packageSource(library, [classSource("Trees/A.cs", [[1, 2], [2, 0]])]), + packageSource("Platform.Collections.Methods.Tests", [classSource("Tests/T.cs", [[1, 0]])]), + ].join("\n"), + ); + const summary = summarize(collectLines([source], library)); + assert.deepEqual(summary, { files: [{ file: "Trees/A.cs", total: 2, missed: [2] }], total: 2, covered: 1 }); +}); + +test("treats a line hit in any report or class as covered", () => { + const first = report(packageSource(library, [classSource("Trees/A.cs", [[1, 0], [2, 1]])])); + const second = report(packageSource(library, [classSource("Trees/A.cs", [[1, 3], [2, 0]])])); + assert.deepEqual(summarize(collectLines([first, second], library)).covered, 2); +}); + +test("fails with the file and line of every uncovered line", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 1], [7, 0]]), classSource("Lists/B.cs", [[3, 0]])])); + withReports([source], (paths, directory) => { + const summaryPath = join(directory, "summary.md"); + const { status, errors, logs } = capture(() => run(paths, { GITHUB_STEP_SUMMARY: summaryPath })); + assert.equal(status, 1); + assert.deepEqual(errors, [ + "::error file=Lists/B.cs,line=3,title=Line not covered::No C# test executes this line.", + "::error file=Trees/A.cs,line=7,title=Line not covered::No C# test executes this line.", + ]); + assert.deepEqual(logs, [`${library}: 1 of 3 lines covered (33.33%).`]); + assert.match(readFileSync(summaryPath, "utf8"), /\| Trees\/A\.cs \| 50\.00% \| 7 \|/); + }); +}); + +test("passes when every line is covered", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 1], [2, 4]])])); + withReports([source], (paths) => { + const { status, errors } = capture(() => run(["--verbose", ...paths], {})); + assert.equal(status, 0); + assert.deepEqual(errors, []); + }); +}); + +test("fails when the report has no such package instead of passing vacuously", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 1]])])); + withReports([source], (paths) => { + const { status, errors } = capture(() => run(["--package", "Other", ...paths], {})); + assert.equal(status, 1); + assert.deepEqual(errors, ["::error title=C# coverage check failed::No coverage report contains the package Other"]); + }); +}); + +test("reports files relative to the workspace, so annotations find them", () => { + const source = report(packageSource(library, [classSource("Trees/A.cs", [[1, 0]])])).replace( + " ", + " \n /work/repo/csharp/Platform.Collections.Methods/\n \n ", + ); + withReports([source], (paths) => { + const { status, errors } = capture(() => run(paths, { GITHUB_WORKSPACE: "/work/repo" })); + assert.equal(status, 1); + assert.deepEqual(errors, [ + "::error file=csharp/Platform.Collections.Methods/Trees/A.cs,line=1,title=Line not covered::No C# test executes this line.", + ]); + }); +}); + +test("prints the usage without reports", () => { + const { status, errors } = capture(() => run([], {})); + assert.equal(status, 2); + assert.match(errors[0], /^Usage:/); +}); diff --git a/.github/scripts/check-csharp-pipeline-status.mjs b/.github/scripts/check-csharp-pipeline-status.mjs new file mode 100644 index 0000000..b5a85a2 --- /dev/null +++ b/.github/scripts/check-csharp-pipeline-status.mjs @@ -0,0 +1,75 @@ +#!/usr/bin/env node + +const allJobNames = [ + "test", + "coverage", + "treeValidation", + "releasePreflight", + "pushNuGetPackageToGitHubPackageRegistry", + "pushToNuget", + "publishRelease", + "findChangedCsFiles", + "generatePdfWithCode", + "buildDocumentation", + "publishDocumentation", +]; + +export const evaluatePipeline = ({ eventName, documentationChanged, needs }) => { + // The tests, their full coverage and the self-validating trees gate every run. + const required = new Set(["test", "coverage", "treeValidation", "findChangedCsFiles"]); + + if (documentationChanged) { + required.add("generatePdfWithCode"); + required.add("buildDocumentation"); + required.add("publishDocumentation"); + } + + if (eventName === "push") { + required.add("releasePreflight"); + required.add("pushNuGetPackageToGitHubPackageRegistry"); + required.add("pushToNuget"); + required.add("publishRelease"); + } + + const failures = []; + for (const name of allJobNames) { + const result = needs[name]?.result; + if (!result) { + failures.push(`${name}: result is missing`); + } else if (required.has(name) && result !== "success") { + failures.push(`${name}: required job finished with ${result}`); + } else if (!required.has(name) && !["success", "skipped"].includes(result)) { + failures.push(`${name}: optional job finished with ${result}`); + } + } + + return { passed: failures.length === 0, failures }; +}; + +export const run = (environment = process.env) => { + let needs; + try { + needs = JSON.parse(environment.NEEDS_JSON ?? ""); + } catch (error) { + console.error(`::error title=C# pipeline status invalid::${error.message}`); + return 1; + } + + const result = evaluatePipeline({ + eventName: environment.EVENT_NAME ?? "", + documentationChanged: environment.DOCUMENTATION_CHANGED === "true", + needs, + }); + + for (const failure of result.failures) { + console.error(`::error title=C# pipeline failed::${failure}`); + } + if (result.passed) { + console.log("Every required C# pipeline job succeeded."); + } + return result.passed ? 0 : 1; +}; + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + process.exitCode = run(); +} diff --git a/.github/scripts/check-csharp-pipeline-status.test.mjs b/.github/scripts/check-csharp-pipeline-status.test.mjs new file mode 100644 index 0000000..be77c73 --- /dev/null +++ b/.github/scripts/check-csharp-pipeline-status.test.mjs @@ -0,0 +1,132 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import test from "node:test"; +import { evaluatePipeline } from "./check-csharp-pipeline-status.mjs"; + +const results = (overrides = {}) => + Object.fromEntries( + [ + "test", + "coverage", + "treeValidation", + "releasePreflight", + "pushNuGetPackageToGitHubPackageRegistry", + "pushToNuget", + "publishRelease", + "findChangedCsFiles", + "generatePdfWithCode", + "buildDocumentation", + "publishDocumentation", + ].map((name) => [name, { result: overrides[name] ?? "skipped" }]), + ); + +test("accepts a pull request after validation and documentation builds pass", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + findChangedCsFiles: "success", + generatePdfWithCode: "success", + buildDocumentation: "success", + publishDocumentation: "success", + }); + assert.deepEqual( + evaluatePipeline({ eventName: "pull_request", documentationChanged: true, needs }), + { passed: true, failures: [] }, + ); +}); + +test("rejects a skipped documentation assembly on pull requests", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + findChangedCsFiles: "success", + generatePdfWithCode: "success", + buildDocumentation: "success", + }); + assert.deepEqual( + evaluatePipeline({ eventName: "pull_request", documentationChanged: true, needs }), + { + passed: false, + failures: ["publishDocumentation: required job finished with skipped"], + }, + ); +}); + +test("accepts expected documentation skips when no maintained input changed", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + releasePreflight: "success", + pushNuGetPackageToGitHubPackageRegistry: "success", + pushToNuget: "success", + publishRelease: "success", + findChangedCsFiles: "success", + }); + assert.deepEqual( + evaluatePipeline({ eventName: "push", documentationChanged: false, needs }), + { passed: true, failures: [] }, + ); +}); + +test("turns a failed publish and its skipped release into an explicit failure", () => { + const needs = results({ + test: "success", + coverage: "success", + treeValidation: "success", + releasePreflight: "success", + pushNuGetPackageToGitHubPackageRegistry: "success", + pushToNuget: "failure", + publishRelease: "skipped", + findChangedCsFiles: "success", + }); + const result = evaluatePipeline({ + eventName: "push", + documentationChanged: false, + needs, + }); + + assert.equal(result.passed, false); + assert.deepEqual(result.failures, [ + "pushToNuget: required job finished with failure", + "publishRelease: required job finished with skipped", + ]); +}); + +test("rejects a pull request whose coverage or tree validation failed", () => { + const needs = results({ + test: "success", + coverage: "failure", + treeValidation: "skipped", + findChangedCsFiles: "success", + }); + const result = evaluatePipeline({ + eventName: "pull_request", + documentationChanged: false, + needs, + }); + + assert.equal(result.passed, false); + assert.deepEqual(result.failures, [ + "coverage: required job finished with failure", + "treeValidation: required job finished with skipped", + ]); +}); + +test("reports cancelled jobs instead of allowing a grey timeout", () => { + const needs = results({ + test: "cancelled", + findChangedCsFiles: "skipped", + }); + const result = evaluatePipeline({ + eventName: "pull_request", + documentationChanged: false, + needs, + }); + + assert.equal(result.passed, false); + assert.match(result.failures.join("\n"), /test: required job finished with cancelled/); +}); diff --git a/.github/scripts/csharp-workflow-policy.test.mjs b/.github/scripts/csharp-workflow-policy.test.mjs new file mode 100644 index 0000000..7392189 --- /dev/null +++ b/.github/scripts/csharp-workflow-policy.test.mjs @@ -0,0 +1,213 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { getJobs } from "./workflow-jobs.mjs"; + +const workflowPath = new URL("../workflows/csharp.yml", import.meta.url); +const workflow = readFileSync(workflowPath, "utf8"); + +const jobs = getJobs(workflow); + +test("configures Git's initial branch before checkout runs", () => { + const topLevel = workflow.slice(0, workflow.indexOf("\ndefaults:")); + assert.match(topLevel, /\n GIT_CONFIG_COUNT: '1'/); + assert.match(topLevel, /\n GIT_CONFIG_KEY_0: init\.defaultBranch/); + assert.match(topLevel, /\n GIT_CONFIG_VALUE_0: main/); +}); + +test("validates every maintained C# workflow input on pull requests", () => { + assert.match(workflow, /pull_request:/); + assert.match(workflow, /- '\.github\/scripts\/\*csharp\*'/); + assert.match(workflow, /- 'csharp\/\*\*'/); +}); + +test("uses repository-owned build scripts instead of mutable downloads", () => { + assert.doesNotMatch(workflow, /raw\.githubusercontent\.com/); + assert.doesNotMatch(workflow, /\bwget\b/); + assert.doesNotMatch(workflow, /python-pygments/); + assert.doesNotMatch(workflow, /apt-get install(?:\s+-y)?\s+nuget/); +}); + +test("declares least-privilege checkout credentials", () => { + const lines = workflow.split("\n"); + const failures = []; + + for (let index = 0; index < lines.length; index += 1) { + if (!lines[index].includes("uses: actions/checkout@")) { + continue; + } + const step = lines.slice(index, index + 8).join("\n"); + if (!/persist-credentials:\s*false/.test(step)) { + failures.push(`line ${index + 1}: ${lines[index].trim()}`); + } + } + + assert.deepEqual(failures, []); +}); + +test("caps every job so hangs cannot run indefinitely", () => { + assert.ok(jobs.size > 0, "workflow jobs should be parsed"); + for (const [name, job] of jobs) { + assert.match(job, /\n timeout-minutes:\s*\d+/, `${name} has no timeout`); + } +}); + +test("pins the runner image so latest-image migrations do not create warnings", () => { + assert.doesNotMatch(workflow, /runs-on: ubuntu-latest/); + for (const [name, job] of jobs) { + assert.match(job, /\n runs-on: ubuntu-24\.04/, `${name} has an unpinned runner`); + } +}); + +test("gates both package publishers on a release preflight", () => { + const preflight = jobs.get("releasePreflight"); + assert.ok(preflight, "releasePreflight job should exist"); + assert.match(preflight, /NUGET_TOKEN: \$\{\{ secrets\.NUGET_TOKEN \}\}/); + assert.match(preflight, /GITHUB_TOKEN: \$\{\{ secrets\.GITHUB_TOKEN \}\}/); + assert.match(preflight, /NUGET_USER: \$\{\{ vars\.NUGET_USER \}\}/); + assert.match(preflight, /preflight-nuget-release\.mjs/); + + for (const name of [ + "pushNuGetPackageToGitHubPackageRegistry", + "pushToNuget", + ]) { + assert.match( + jobs.get(name), + /needs: \[test, coverage, treeValidation, releasePreflight\]/, + `${name} must wait for the tests, coverage, tree validation and preflight`, + ); + } +}); + +test("packs and publishes each NuGet package in separate ordered steps", () => { + for (const [jobName, outputDirectory] of [ + ["pushNuGetPackageToGitHubPackageRegistry", "github-packages"], + ["pushToNuget", "nuget-packages"], + ]) { + const job = jobs.get(jobName); + const output = `"$RUNNER_TEMP/${outputDirectory}"`; + const pack = job.indexOf("- name: Pack NuGet package"); + const push = job.indexOf("- name: Push NuGet package"); + + assert.ok(pack >= 0, `${jobName} has no pack step`); + assert.ok(push > pack, `${jobName} must push after packing`); + assert.match(job.slice(pack, push), /run: dotnet pack /); + assert.ok(job.slice(pack, push).includes(`--output ${output}`)); + assert.match(job.slice(push), /run: (?:dotnet nuget push|\.\.\/\.github\/scripts\/push-nuget-package\.sh) /); + assert.ok(job.slice(push).includes(`${output}/*.nupkg`)); + assert.equal( + job.slice(pack, push).includes("dotnet nuget push"), + false, + `${jobName} pushes inside the pack step`, + ); + } + + const github = jobs.get("pushNuGetPackageToGitHubPackageRegistry"); + const addSource = github.indexOf("- name: Add GitHub NuGet source"); + assert.ok(addSource > github.indexOf("- name: Pack NuGet package")); + assert.ok(addSource < github.indexOf("- name: Push NuGet package")); + assert.match(github.slice(addSource), /run: dotnet nuget add source /); + assert.match(github, /--source GitHub --api-key "\$GITHUB_TOKEN"/); +}); + +test("publishes to nuget.org only when the preflight found the version missing", () => { + const job = jobs.get("pushToNuget"); + assert.match(job, /\n id-token: write/); + assert.match(job, /uses: NuGet\/login@[0-9a-f]{40} # v\d/); + assert.match( + job, + /if: \$\{\{ needs\.releasePreflight\.outputs\.auth == 'trusted-publishing' && needs\.releasePreflight\.outputs\.publishRequired == 'true' \}\}/, + ); + assert.match(job, /PUBLISH_REQUIRED: \$\{\{ needs\.releasePreflight\.outputs\.publishRequired \}\}/); + assert.match(job, /NUGET_API_KEY: \$\{\{ steps\.nuget-login\.outputs\.NUGET_API_KEY \|\| secrets\.NUGET_TOKEN \}\}/); + assert.doesNotMatch(job, /run: dotnet nuget push/); +}); + +test("detects changed documentation inputs without third-party actions", () => { + const job = jobs.get("findChangedCsFiles"); + assert.doesNotMatch(workflow, /uses: tj-actions\//); + assert.match(job, /fetch-depth: 0/); + assert.match(job, /git diff --name-only "\$BASE_SHA" "\$GITHUB_SHA"/); + assert.match(job, /git cat-file -e/); +}); + +test("builds PDF and API documentation in parallel before publishing both", () => { + const pdf = jobs.get("generatePdfWithCode"); + const documentation = jobs.get("buildDocumentation"); + const publisher = jobs.get("publishDocumentation"); + + assert.ok(pdf, "generatePdfWithCode job should exist"); + assert.ok(documentation, "buildDocumentation job should exist"); + assert.ok(publisher, "publishDocumentation job should exist"); + assert.match(pdf, /needs: \[findChangedCsFiles\]/); + assert.match(documentation, /needs: \[findChangedCsFiles\]/); + assert.doesNotMatch(documentation, /needs:.*generatePdfWithCode/); + assert.doesNotMatch(pdf, /github\.event_name == 'push'/); + assert.doesNotMatch(documentation, /github\.event_name == 'push'/); + assert.match(pdf, /name: csharp-pdf/); + assert.match(documentation, /name: csharp-documentation/); + assert.doesNotMatch(workflow, /actions\/download-artifact@/); + assert.match( + publisher, + /needs: \[findChangedCsFiles, generatePdfWithCode, buildDocumentation\]/, + ); + assert.match(publisher, /--name csharp-documentation/); + assert.match(publisher, /--name csharp-pdf/); + assert.match( + publisher, + /if: \$\{\{ needs\.findChangedCsFiles\.outputs\.documentationChanged == 'true' \}\}/, + ); + assert.match( + publisher, + /- name: Publish documentation to gh-pages\n if: \$\{\{ github\.event_name == 'push' \}\}/, + ); +}); + +test("validates generated API pages before upload and after download", () => { + const documentation = jobs.get("buildDocumentation"); + const publisher = jobs.get("publishDocumentation"); + + assert.match(documentation, /docfx" docfx\.json --warningsAsErrors/); + assert.match(documentation, /validate-csharp-docs\.sh _site/); + assert.match(publisher, /validate-csharp-docs\.sh _site/); +}); + +test("aggregates every job result so skipped dependents cannot hide failures", () => { + const gate = jobs.get("pipelineStatus"); + assert.ok(gate, "pipelineStatus job should exist"); + assert.match(gate, /if: \$\{\{ !cancelled\(\) \}\}/); + assert.match(gate, /check-csharp-pipeline-status\.mjs/); + + for (const name of [...jobs.keys()].filter((name) => name !== "pipelineStatus")) { + assert.match(gate, new RegExp(`\\n - ${name}(?:\\n|$)`), `${name} is not observed`); + } +}); + +test("requires full line coverage of the library", () => { + const job = jobs.get("coverage"); + assert.ok(job, "coverage job should exist"); + assert.match(job, /--collect "XPlat Code Coverage"/); + assert.match(job, /check-csharp-coverage\.mjs "\$RUNNER_TEMP"\/coverage\/\*\*\/coverage\.cobertura\.xml/); + assert.match(workflow, /- '\.github\/scripts\/\*csharp\*'/); +}); + +test("runs the tests with trees that validate themselves after every change", () => { + const job = jobs.get("treeValidation"); + assert.ok(job, "treeValidation job should exist"); + assert.match(job, /-p:TreeValidation=true/); + // Debug would evaluate the tree dumps passed to Debug.WriteLine. + assert.match(job, /--configuration Release/); + const project = readFileSync(new URL("../../csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj", import.meta.url), "utf8"); + assert.match(project, /Condition="'\$\(TreeValidation\)' == 'true'"/); + assert.match(project, /ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION/); +}); + +test("runs the C# benchmarks only on request", () => { + const benchmarks = readFileSync(new URL("../workflows/benchmarks.yml", import.meta.url), "utf8"); + assert.match(getJobs(benchmarks).get("csharp"), /dotnet run --project Platform\.Collections\.Methods\.Benchmarks/); + assert.doesNotMatch(benchmarks, /\n {2}(?:push|pull_request|schedule):/); + // The tests build the whole solution, so the benchmarks keep compiling. + assert.match(readFileSync(new URL("./validate-csharp-package.sh", import.meta.url), "utf8"), /dotnet (?:build|test)/); +}); diff --git a/.github/scripts/generate-csharp-pdf.sh b/.github/scripts/generate-csharp-pdf.sh new file mode 100644 index 0000000..cb445b4 --- /dev/null +++ b/.github/scripts/generate-csharp-pdf.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +output_directory=${1:-"$repository_root/csharp/_site"} +work_directory=$(mktemp -d) + +cleanup() { + rm -rf "$work_directory" +} +trap cleanup EXIT + +sudo apt-get update & +update_pid=$! +wait "$update_pid" +sudo apt-get install -y \ + ghostscript \ + python3-pygments \ + texlive \ + texlive-lang-cyrillic \ + texlive-latex-extra & +install_pid=$! +wait "$install_pid" + +document="$work_directory/document.tex" +cat > "$document" <<'LATEX' +\documentclass[11pt,a4paper,fleqn]{report} +\usepackage[left=5mm,top=5mm,right=5mm,bottom=5mm]{geometry} +\usepackage[T1]{fontenc} +\usepackage[T2A]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{fvextra} +\usepackage{minted} +\usemintedstyle{vs} +\usepackage{makeidx} +\usepackage[columns=1]{idxlayout} +\usepackage[tiny]{titlesec} +\makeindex +\titlespacing\chapter{0mm}{0mm}{0mm} +\titlespacing\section{0mm}{0mm}{0mm} +\DeclareUnicodeCharacter{221E}{\ensuremath{\infty}} +\DeclareUnicodeCharacter{FFFD}{\ensuremath{ }} +\begin{document} +\sffamily +\chapter*{LinksPlatform's Platform.Collections.Methods Class Library} +LATEX + +while IFS= read -r -d '' source_file; do + relative_path=${source_file#"$repository_root/"} + latex_path=${relative_path//_/\\_} + { + printf '\\index{%s}\n' "$latex_path" + printf '\\section{%s}\n' "$latex_path" + printf '%s\n' '\begin{minted}[tabsize=2,breaklines,breakanywhere,linenos=true,xleftmargin=7mm,framesep=4mm]{csharp}' + sed $'1s/^\xEF\xBB\xBF//' "$source_file" + printf '%s\n' '\end{minted}' + } >> "$document" +done < <( + find \ + "$repository_root/csharp/Platform.Collections.Methods" \ + "$repository_root/csharp/Platform.Collections.Methods.Tests" \ + -type f -name '*.cs' ! -path '*/bin/*' ! -path '*/obj/*' -print0 | + sort -z +) + +cat >> "$document" <<'LATEX' +\printindex +\end{document} +LATEX + +( + cd "$work_directory" + pdflatex -shell-escape -interaction=nonstopmode -halt-on-error document.tex + makeindex document.idx + pdflatex -shell-escape -interaction=nonstopmode -halt-on-error document.tex +) + +mkdir -p "$output_directory" +cp "$work_directory/document.pdf" "$output_directory/Platform.Collections.Methods.pdf" +echo "Generated $output_directory/Platform.Collections.Methods.pdf" diff --git a/.github/scripts/publish-csharp-docs.sh b/.github/scripts/publish-csharp-docs.sh new file mode 100644 index 0000000..7e0eb59 --- /dev/null +++ b/.github/scripts/publish-csharp-docs.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash + +set -euo pipefail + +if [[ -z ${GITHUB_REPOSITORY:-} || -z ${GITHUB_TOKEN:-} ]]; then + echo "GITHUB_REPOSITORY and GITHUB_TOKEN are required." >&2 + exit 1 +fi + +site_directory=${1:-_site} +if [[ ! -f "$site_directory/index.html" || ! -f "$site_directory/Platform.Collections.Methods.pdf" ]]; then + echo "$site_directory must contain index.html and Platform.Collections.Methods.pdf." >&2 + exit 1 +fi + +site_directory=$(cd "$site_directory" && pwd) +deploy_directory=$(mktemp -d) + +cleanup() { + rm -rf "$deploy_directory" +} +trap cleanup EXIT + +authorization=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0) +repository_url="https://github.com/${GITHUB_REPOSITORY}.git" +git -c http.extraheader="AUTHORIZATION: basic $authorization" clone \ + --branch gh-pages --depth 1 "$repository_url" "$deploy_directory" + +destination="$deploy_directory/csharp" +mkdir -p "$destination" +find "$destination" -mindepth 1 -delete +cp -a "$site_directory/." "$destination/" + +git -C "$deploy_directory" config user.name linksplatform +git -C "$deploy_directory" config user.email linksplatformtechnologies@gmail.com +git -C "$deploy_directory" add --all + +if git -C "$deploy_directory" diff --cached --quiet; then + echo "Documentation is already current." + exit 0 +fi + +git -C "$deploy_directory" commit -m "Deploy C# documentation: ${GITHUB_SHA:-unknown}" +git -C "$deploy_directory" -c http.extraheader="AUTHORIZATION: basic $authorization" \ + push origin HEAD:gh-pages diff --git a/.github/scripts/validate-csharp-docs.sh b/.github/scripts/validate-csharp-docs.sh new file mode 100644 index 0000000..7432608 --- /dev/null +++ b/.github/scripts/validate-csharp-docs.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +set -euo pipefail + +site=${1:?Usage: validate-csharp-docs.sh SITE_DIRECTORY} + +for file in \ + index.html \ + api/Platform.Collections.Methods.html \ + api/Platform.Collections.Methods.Trees.SizeBalancedTreeMethods-1.html \ + Platform.Collections.Methods.Documentation.pdf \ + xrefmap.yml; do + if [[ ! -s "$site/$file" ]]; then + echo "Documentation site is missing $site/$file." >&2 + exit 1 + fi +done + +if [[ $(head -c 5 "$site/Platform.Collections.Methods.Documentation.pdf") != '%PDF-' ]]; then + echo "Documentation PDF is invalid: $site/Platform.Collections.Methods.Documentation.pdf." >&2 + exit 1 +fi + +if ! grep -Fq 'Platform.Collections.Methods.Documentation.pdf' "$site/index.html"; then + echo "Documentation home page is missing its PDF link: $site/index.html." >&2 + exit 1 +fi + +echo "Validated DocFX home page, API pages, documentation PDF, and cross-reference map." diff --git a/.github/scripts/validate-csharp-docs.test.mjs b/.github/scripts/validate-csharp-docs.test.mjs new file mode 100644 index 0000000..21b7d40 --- /dev/null +++ b/.github/scripts/validate-csharp-docs.test.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; + +const validator = new URL("./validate-csharp-docs.sh", import.meta.url).pathname; + +const withSite = (files, check, contents = {}) => { + const site = mkdtempSync(join(tmpdir(), "csharp-docs-")); + try { + for (const file of files) { + const path = join(site, file); + mkdirSync(join(path, ".."), { recursive: true }); + const content = file === "index.html" + ? 'Documentation PDF' + : file.endsWith(".pdf") ? "%PDF-1.7\n" : "generated content"; + writeFileSync(path, contents[file] ?? content); + } + check(spawnSync("bash", [validator, site], { encoding: "utf8" })); + } finally { + rmSync(site, { recursive: true, force: true }); + } +}; + +const requiredFiles = [ + "index.html", + "api/Platform.Collections.Methods.html", + "api/Platform.Collections.Methods.Trees.SizeBalancedTreeMethods-1.html", + "xrefmap.yml", + "Platform.Collections.Methods.Documentation.pdf", +]; + +test("accepts a complete DocFX site", () => { + withSite(requiredFiles, ({ status, stderr }) => { + assert.equal(status, 0, stderr); + }); +}); + +for (const missingFile of requiredFiles) { + test(`rejects a site missing ${missingFile}`, () => { + withSite(requiredFiles.filter((file) => file !== missingFile), ({ status, stderr }) => { + assert.notEqual(status, 0); + assert.ok(stderr.includes(missingFile), stderr); + }); + }); +} + +test("rejects an invalid documentation PDF", () => { + withSite(requiredFiles, ({ status, stderr }) => { + assert.notEqual(status, 0); + assert.match(stderr, /Documentation PDF is invalid/); + }, { "Platform.Collections.Methods.Documentation.pdf": "not a PDF" }); +}); + +test("rejects a site with no documentation PDF link", () => { + withSite(requiredFiles, ({ status, stderr }) => { + assert.notEqual(status, 0); + assert.match(stderr, /home page is missing its PDF link/); + }, { "index.html": "generated content" }); +}); diff --git a/.github/scripts/validate-csharp-package.sh b/.github/scripts/validate-csharp-package.sh new file mode 100644 index 0000000..82f1de2 --- /dev/null +++ b/.github/scripts/validate-csharp-package.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +solution="$repository_root/csharp/Platform.Collections.Methods.sln" +test_project="$repository_root/csharp/Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj" +package_project="$repository_root/csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj" +package_output=$(mktemp -d) + +cleanup() { + rm -rf "$package_output" +} +trap cleanup EXIT + +dotnet restore "$solution" --nologo +dotnet build "$solution" --configuration Release --no-restore --no-incremental --nologo -warnaserror +dotnet test "$test_project" --configuration Release --framework net8 --no-build --no-restore --nologo +dotnet pack "$package_project" --configuration Release --no-build --no-restore \ + --output "$package_output" --nologo -warnaserror + +mapfile -t packages < <(find "$package_output" -maxdepth 1 -type f -name '*.nupkg' -print) +mapfile -t symbol_packages < <(find "$package_output" -maxdepth 1 -type f -name '*.snupkg' -print) + +if [[ ${#packages[@]} -ne 1 ]]; then + echo "Expected one .nupkg, found ${#packages[@]}." >&2 + exit 1 +fi + +if [[ ${#symbol_packages[@]} -ne 0 ]]; then + echo "Expected embedded symbols instead of a separate .snupkg." >&2 + exit 1 +fi + +package_contents=$(unzip -Z1 "${packages[0]}") +for expected_file in README.md icon.png lib/net8.0/Platform.Collections.Methods.dll lib/net8.0/Platform.Collections.Methods.xml; do + if ! grep -Fxq "$expected_file" <<< "$package_contents"; then + echo "${packages[0]} is missing $expected_file." >&2 + exit 1 + fi +done + +echo "Validated ${packages[0]} with embedded symbols." diff --git a/.github/workflows/csharp.yml b/.github/workflows/csharp.yml index 572c8fb..9cc72e5 100644 --- a/.github/workflows/csharp.yml +++ b/.github/workflows/csharp.yml @@ -2,147 +2,383 @@ name: csharp on: push: - branches: main + branches: main paths: - 'csharp/**' + - 'README.md' + - '.github/scripts/*csharp*' + - '.github/scripts/*nuget-*' - '.github/workflows/csharp.yml' pull_request: branches: main paths: - 'csharp/**' + - 'README.md' + - '.github/scripts/*csharp*' + - '.github/scripts/*nuget-*' - '.github/workflows/csharp.yml' + +permissions: + actions: read + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + env: - NUGETTOKEN: ${{ secrets.NUGET_TOKEN }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SCRIPTS_BASE_URL: https://raw.githubusercontent.com/linksplatform/Scripts/main/MultiProjectRepository - + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + defaults: run: working-directory: csharp jobs: test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Validate tests and NuGet package + run: ../.github/scripts/validate-csharp-package.sh + + - name: Test C# workflow safeguards + run: node --test ../.github/scripts/*csharp*.test.mjs ../.github/scripts/*nuget-*.test.mjs + + # Every line of the library has to be executed by the tests, so a change + # cannot leave a rotation, a rebuild or an error path untested. + coverage: + runs-on: ubuntu-24.04 + timeout-minutes: 15 steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 with: - submodules: true - - name: Test + dotnet-version: '8.0.x' + + - name: Run the tests with coverage + run: >- + dotnet test Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj + --configuration Release --framework net8 --nologo + --collect "XPlat Code Coverage" + --results-directory "$RUNNER_TEMP/coverage" + + - name: Require full line coverage of the library run: | - dotnet test -c Release -f net8 + shopt -s globstar + node ../.github/scripts/check-csharp-coverage.mjs "$RUNNER_TEMP"/coverage/**/coverage.cobertura.xml + + # ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION makes every attach and detach check + # the sizes of the whole tree, so the tests also prove that no operation + # leaves a broken tree behind, even for a moment the tests do not inspect. + # Release keeps the Debug.WriteLine tree dumps compiled out. + treeValidation: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Run the tests with self-validating trees + run: >- + dotnet test Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj + --configuration Release --framework net8 --nologo -warnaserror + -p:TreeValidation=true + + releasePreflight: + if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + publishRequired: ${{ steps.preflight.outputs.publish_required }} + auth: ${{ steps.preflight.outputs.auth }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Check release state and credentials + id: preflight + env: + CSPROJ: Platform.Collections.Methods/Platform.Collections.Methods.csproj + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + NUGET_USER: ${{ vars.NUGET_USER }} + run: node ../.github/scripts/preflight-nuget-release.mjs + pushNuGetPackageToGitHubPackageRegistry: - needs: test - # Publishing runs only for pushes to main; pull requests only run the tests. + needs: [test, coverage, treeValidation, releasePreflight] if: ${{ github.event_name == 'push' }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: write steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 with: - submodules: true - - uses: nuget/setup-nuget@v1 - - name: Publish NuGet package to GitHub Package Registry - run: | - dotnet build -c Release - dotnet pack -c Release - nuget source Add -Name "GitHub" -Source "https://nuget.pkg.github.com/linksplatform/index.json" -UserName linksplatform -Password ${{ secrets.GITHUB_TOKEN }} - nuget push **/*.nupkg -Source "GitHub" -SkipDuplicate - pusnToNuget: - runs-on: ubuntu-latest - needs: test - # Publishing runs only for pushes to main; pull requests only run the tests. + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Pack NuGet package + run: dotnet pack Platform.Collections.Methods/Platform.Collections.Methods.csproj --configuration Release --output "$RUNNER_TEMP/github-packages" --nologo -warnaserror + + - name: Add GitHub NuGet source + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: dotnet nuget add source https://nuget.pkg.github.com/linksplatform/index.json --name GitHub --username linksplatform --password "$GITHUB_TOKEN" --store-password-in-clear-text + + # GitHub Packages authenticates with GITHUB_TOKEN; trusted publishing is + # a nuget.org feature, so zizmor's suggestion does not apply here. + - name: Push NuGet package to GitHub Package Registry + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: dotnet nuget push "$RUNNER_TEMP/github-packages"/*.nupkg --source GitHub --api-key "$GITHUB_TOKEN" --skip-duplicate # zizmor: ignore[use-trusted-publishing] + + pushToNuget: + needs: [test, coverage, treeValidation, releasePreflight] if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + id-token: write steps: - - uses: actions/checkout@v1 - with: - submodules: true - - name: Read project information - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/read_csharp_package_info.sh" - bash ./read_csharp_package_info.sh - - name: Publish NuGet package - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/push-csharp-nuget.sh" - bash ./push-csharp-nuget.sh - publiseRelease: - runs-on: ubuntu-latest - needs: test - # Publishing runs only for pushes to main; pull requests only run the tests. + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Pack NuGet package + run: dotnet pack Platform.Collections.Methods/Platform.Collections.Methods.csproj --configuration Release --output "$RUNNER_TEMP/nuget-packages" --nologo -warnaserror + + - name: Log in to NuGet with trusted publishing + id: nuget-login + if: ${{ needs.releasePreflight.outputs.auth == 'trusted-publishing' && needs.releasePreflight.outputs.publishRequired == 'true' }} + uses: NuGet/login@8d196754b4036150537f80ac539e15c2f1028841 # v1.2.0 + with: + user: ${{ vars.NUGET_USER }} + + - name: Push NuGet package to NuGet.org + env: + AUTH: ${{ needs.releasePreflight.outputs.auth }} + PUBLISH_REQUIRED: ${{ needs.releasePreflight.outputs.publishRequired }} + NUGET_API_KEY: ${{ steps.nuget-login.outputs.NUGET_API_KEY || secrets.NUGET_TOKEN }} + run: ../.github/scripts/push-nuget-package.sh "$RUNNER_TEMP/nuget-packages"/*.nupkg + + publishRelease: + needs: [pushNuGetPackageToGitHubPackageRegistry, pushToNuget] if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v7 with: - submodules: true - - name: Read project information - if: ${{ github.event_name == 'push' }} - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/read_csharp_package_info.sh" - bash ./read_csharp_package_info.sh - - name: Publish release + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Publish GitHub release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/publish-release.sh" - chmod +x ./publish-release.sh - wget "$SCRIPTS_BASE_URL/publish-csharp-release.sh" - bash ./publish-csharp-release.sh + project=Platform.Collections.Methods/Platform.Collections.Methods.csproj + version=$(dotnet msbuild "$project" -nologo -getProperty:VersionPrefix) + release_notes=$(dotnet msbuild "$project" -nologo -getProperty:PackageReleaseNotes) + tag="csharp_${version}" + title="[C#] ${version}" + package_url="https://www.nuget.org/packages/Platform.Collections.Methods/${version}" + notes="${package_url}"$'\n\n'"${release_notes}" + if gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "Release ${tag} already exists." + else + gh release create "$tag" --repo "$GITHUB_REPOSITORY" --title "$title" --notes "$notes" + fi + findChangedCsFiles: - runs-on: ubuntu-latest needs: test - # Publishing runs only for pushes to main; pull requests only run the tests. - if: ${{ github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 outputs: - isCsFilesChanged: ${{ steps.setIsCsFilesChangedOutput.outputs.isCsFilesChanged }} + documentationChanged: ${{ steps.detect.outputs.documentationChanged }} steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - name: Get changed files using defaults - id: changed-files - uses: tj-actions/changed-files@v21 - - name: Set output isCsFilesChanged - id: setIsCsFilesChangedOutput - run: | - isCsFilesChanged='false' - echo "Changed files: ${{ steps.changed-files.outputs.all_changed_files }}" - for changedFile in ${{ steps.changed-files.outputs.all_changed_files }}; do - if [[ $changedFile == *.cs ]] - then - echo "isCsFilesChanged='true'" - isCsFilesChanged='true' + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + # git diff replaces tj-actions/changed-files, which was compromised in + # March 2025 (CVE-2025-30066) and was referenced by a mutable tag. + - name: Detect documentation inputs + id: detect + env: + BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + run: | + if [ -n "$BASE_SHA" ] && git cat-file -e "${BASE_SHA}^{commit}" 2>/dev/null; then + changed_files=$(git diff --name-only "$BASE_SHA" "$GITHUB_SHA") + else + echo "No base commit to compare with; treating documentation inputs as changed." + changed_files=README.md fi - done - echo "::set-output name=isCsFilesChanged::${isCsFilesChanged}" - echo "isCsFilesChanged: ${isCsFilesChanged}" + if [ "${RUNNER_DEBUG:-}" = 1 ]; then + printf 'Changed files:\n%s\n' "$changed_files" + fi + documentation_changed=false + for changed_file in $changed_files; do + case "$changed_file" in + *.cs|README.md|.github/workflows/csharp.yml|.github/scripts/*csharp*|csharp/docfx.json|csharp/filter.yml|csharp/toc.yml) + documentation_changed=true + ;; + esac + done + echo "documentationChanged=${documentation_changed}" >> "$GITHUB_OUTPUT" + echo "Documentation inputs changed: ${documentation_changed}" + generatePdfWithCode: - runs-on: ubuntu-latest needs: [findChangedCsFiles] - if: ${{ needs.findChangedCsFiles.outputs.isCsFilesChanged == 'true' }} + if: ${{ needs.findChangedCsFiles.outputs.documentationChanged == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 steps: - - uses: actions/checkout@v1 - with: - submodules: true - - name: Generate PDF with code - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/format-csharp-files.py" - wget "$SCRIPTS_BASE_URL/format-csharp-document.sh" - wget "$SCRIPTS_BASE_URL/generate-csharp-pdf.sh" - bash ./generate-csharp-pdf.sh - publishDocumentation: - runs-on: ubuntu-latest + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Generate PDF with code + run: ../.github/scripts/generate-csharp-pdf.sh + + - name: Upload generated PDF + timeout-minutes: 5 + uses: actions/upload-artifact@v7 + with: + name: csharp-pdf + path: csharp/_site/Platform.Collections.Methods.pdf + if-no-files-found: error + retention-days: 1 + + buildDocumentation: needs: [findChangedCsFiles] - if: ${{ needs.findChangedCsFiles.outputs.isCsFilesChanged == 'true' }} + if: ${{ needs.findChangedCsFiles.outputs.documentationChanged == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 steps: - - uses: actions/checkout@v1 - with: - submodules: true - - name: Publish documentation to gh-pages branch - run: | - export REPOSITORY_NAME=$(basename ${{ github.repository }}) - wget "$SCRIPTS_BASE_URL/docfx.json" - wget "$SCRIPTS_BASE_URL/filter.yml" - wget "$SCRIPTS_BASE_URL/toc.yml" - wget "$SCRIPTS_BASE_URL/publish-csharp-docs.sh" - bash ./publish-csharp-docs.sh + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + - name: Build API documentation + run: | + dotnet tool install docfx --tool-path "$RUNNER_TEMP/docfx" --version 2.80.1 + "$RUNNER_TEMP/docfx/docfx" docfx.json --warningsAsErrors + cp _site/README.html _site/index.html + + - name: Validate documentation output + run: ../.github/scripts/validate-csharp-docs.sh _site + + - name: Upload documentation site + timeout-minutes: 5 + uses: actions/upload-artifact@v7 + with: + name: csharp-documentation + path: csharp/_site + if-no-files-found: error + retention-days: 1 + + publishDocumentation: + needs: [findChangedCsFiles, generatePdfWithCode, buildDocumentation] + if: ${{ needs.findChangedCsFiles.outputs.documentationChanged == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: write + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Download documentation artifacts + env: + GH_TOKEN: ${{ github.token }} + run: | + gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --name csharp-documentation --dir _site + gh run download "$GITHUB_RUN_ID" --repo "$GITHUB_REPOSITORY" --name csharp-pdf --dir _site + + - name: Validate documentation site + run: | + ../.github/scripts/validate-csharp-docs.sh _site + test -s _site/Platform.Collections.Methods.pdf + + - name: Publish documentation to gh-pages + if: ${{ github.event_name == 'push' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: ../.github/scripts/publish-csharp-docs.sh _site + + pipelineStatus: + needs: + - test + - coverage + - treeValidation + - releasePreflight + - pushNuGetPackageToGitHubPackageRegistry + - pushToNuget + - publishRelease + - findChangedCsFiles + - generatePdfWithCode + - buildDocumentation + - publishDocumentation + if: ${{ !cancelled() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Check aggregate pipeline status + env: + DOCUMENTATION_CHANGED: ${{ needs.findChangedCsFiles.outputs.documentationChanged }} + EVENT_NAME: ${{ github.event_name }} + NEEDS_JSON: ${{ toJSON(needs) }} + run: node ../.github/scripts/check-csharp-pipeline-status.mjs diff --git a/csharp/docfx.json b/csharp/docfx.json new file mode 100644 index 0000000..4415866 --- /dev/null +++ b/csharp/docfx.json @@ -0,0 +1,43 @@ +{ + "metadata": [ + { + "src": [ + { + "files": ["Platform.Collections.Methods/Platform.Collections.Methods.csproj"] + } + ], + "dest": "obj/api", + "filter": "filter.yml" + } + ], + "build": { + "content": [ + { + "files": ["**/*.yml"], + "src": "obj/api", + "dest": "api" + }, + { + "files": ["README.md"], + "src": ".." + }, + { + "files": ["toc.yml"] + } + ], + "globalMetadata": { + "_appTitle": "LinksPlatform's Platform.Collections.Methods Library", + "_enableSearch": true, + "pdf": true, + "pdfFileName": "Platform.Collections.Methods.Documentation.pdf", + "pdfTocPage": true, + "_gitContribute": { + "branch": "main" + }, + "_gitUrlPattern": "github" + }, + "markdownEngineName": "markdig", + "template": ["default", "modern"], + "dest": "_site" + } +} diff --git a/csharp/filter.yml b/csharp/filter.yml new file mode 100644 index 0000000..2bed1fa --- /dev/null +++ b/csharp/filter.yml @@ -0,0 +1,3 @@ +apiRules: + - exclude: + uidRegex: (Tests|Benchmarks)(\.[A-Za-z]+)?$ diff --git a/csharp/toc.yml b/csharp/toc.yml new file mode 100644 index 0000000..89c0820 --- /dev/null +++ b/csharp/toc.yml @@ -0,0 +1,4 @@ +- name: Home + href: ../README.md +- name: API Documentation + href: obj/api/toc.yml From d4afb7abc204261d8a1fa3bedfb3e53db448f5ce Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:43:42 +0000 Subject: [PATCH 17/46] Run the C# and C++ benchmarks on request Benchmarks are noisy on shared runners, so benchmarks.yml runs only from workflow_dispatch and stores the results in the run summary and artifacts. The test workflows keep the benchmarks compiling. --- .github/workflows/benchmarks.yml | 128 +++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 .github/workflows/benchmarks.yml diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml new file mode 100644 index 0000000..c095dfe --- /dev/null +++ b/.github/workflows/benchmarks.yml @@ -0,0 +1,128 @@ +name: Benchmarks + +# Benchmarks take long and are noisy on shared runners, so they only run on +# request (Actions > Benchmarks > Run workflow). Pull requests and main run the +# unit tests in csharp.yml and cpp-test.yml instead, which also keep the +# benchmarks compiling. +on: + workflow_dispatch: + inputs: + language: + description: Which benchmarks to run + type: choice + options: [both, csharp, cpp] + default: both + csharp-filter: + description: BenchmarkDotNet --filter pattern + type: string + default: '*' + cpp-filter: + description: Google Benchmark --benchmark_filter regular expression + type: string + default: '.*' + cpp-repetitions: + description: Google Benchmark --benchmark_repetitions + type: number + default: 5 + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + csharp: + if: ${{ inputs.language != 'cpp' }} + runs-on: ubuntu-24.04 + timeout-minutes: 120 + defaults: + run: + working-directory: csharp + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: '8.0.x' + + # Attach and detach of every node of the recursive and recursionless + # size balanced trees and of the AVL tree (the baseline), in ascending, + # descending and random order. + - name: Run C# benchmarks + env: + FILTER: ${{ inputs.csharp-filter }} + run: >- + dotnet run --project Platform.Collections.Methods.Benchmarks + --configuration Release --framework net8 + -- --filter "$FILTER" --exporters github json + --artifacts "$RUNNER_TEMP/csharp-benchmarks" + + - name: Summarize C# benchmarks + run: cat "$RUNNER_TEMP"/csharp-benchmarks/results/*-report-github.md >> "$GITHUB_STEP_SUMMARY" + + - name: Upload C# benchmark results + uses: actions/upload-artifact@v7 + with: + name: csharp-benchmarks + path: ${{ runner.temp }}/csharp-benchmarks/results + if-no-files-found: error + retention-days: 30 + + cpp: + if: ${{ inputs.language != 'csharp' }} + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Build the benchmarks and run the tests + env: + CC: gcc + CXX: g++ + BENCHMARKS: '1' + run: cpp/build-and-test.sh + + - name: Run C++ benchmarks + env: + FILTER: ${{ inputs.cpp-filter }} + REPETITIONS: ${{ inputs.cpp-repetitions }} + run: >- + cpp/build/bin/Platform.Collections.Methods.Benchmarks + --benchmark_filter="$FILTER" + --benchmark_repetitions="$REPETITIONS" + --benchmark_report_aggregates_only=true + --benchmark_out="$RUNNER_TEMP/cpp-benchmarks.json" + --benchmark_out_format=json + | tee "$RUNNER_TEMP/cpp-benchmarks.txt" + + - name: Summarize C++ benchmarks + run: | + { + echo '### C++ benchmarks' + echo + echo '```' + cat "$RUNNER_TEMP/cpp-benchmarks.txt" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload C++ benchmark results + uses: actions/upload-artifact@v7 + with: + name: cpp-benchmarks + path: | + ${{ runner.temp }}/cpp-benchmarks.json + ${{ runner.temp }}/cpp-benchmarks.txt + if-no-files-found: error + retention-days: 30 From edd68144c6c2c6fca3bd852bd89b05d2237e32ce Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:43:42 +0000 Subject: [PATCH 18/46] Lint, audit and scan the repository like linksplatform/Interfaces workflows.yml runs actionlint, zizmor and the workflow policy tests; secrets.yml scans for committed secrets; codeql.yml analyzes Actions, C++ and C# and reviews dependency changes; readme-badges.yml checks that the badges point at existing workflows. Dependabot also updates the actions, with a cooldown, and AutoMerge.yml enables auto-merge with gh instead of the removed @dependabot merge comments. The README documents the balance guarantees, tests, benchmarks and the trusted publishing setup. --- .github/dependabot.yml | 9 + .github/scripts/check-readme-badges.mjs | 160 ++++++++++++++++++ .github/scripts/check-readme-badges.test.mjs | 112 ++++++++++++ .../scripts/codeql-workflow-policy.test.mjs | 51 ++++++ .github/scripts/workflow-policy.test.mjs | 148 ++++++++++++++++ .github/workflows/AutoMerge.yml | 48 +++++- .github/workflows/codeql.yml | 78 +++++++++ .github/workflows/readme-badges.yml | 46 +++++ .github/workflows/secrets.yml | 44 +++++ .github/workflows/workflows.yml | 85 ++++++++++ .github/zizmor.yml | 13 ++ .secretlintrc.json | 7 + README.md | 65 ++++++- .../secretlint-detects-planted-secret.sh | 15 ++ 14 files changed, 870 insertions(+), 11 deletions(-) create mode 100644 .github/scripts/check-readme-badges.mjs create mode 100644 .github/scripts/check-readme-badges.test.mjs create mode 100644 .github/scripts/codeql-workflow-policy.test.mjs create mode 100644 .github/scripts/workflow-policy.test.mjs create mode 100644 .github/workflows/codeql.yml create mode 100644 .github/workflows/readme-badges.yml create mode 100644 .github/workflows/secrets.yml create mode 100644 .github/workflows/workflows.yml create mode 100644 .github/zizmor.yml create mode 100644 .secretlintrc.json create mode 100755 experiments/secretlint-detects-planted-secret.sh diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aec207e..2c408a6 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -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 diff --git a/.github/scripts/check-readme-badges.mjs b/.github/scripts/check-readme-badges.mjs new file mode 100644 index 0000000..43439bb --- /dev/null +++ b/.github/scripts/check-readme-badges.mjs @@ -0,0 +1,160 @@ +#!/usr/bin/env node + +/** + * Verifies that every GitHub Actions badge in README.md points at a workflow + * that actually exists in .github/workflows. + * + * Background (linksplatform/Interfaces#141): the C++ badge used + * https://github.com/linksplatform/Interfaces/workflows/deploy-cpp/badge.svg + * The path segment after /workflows/ must be the workflow *name* (the `name:` + * field inside the YAML file), not the file name. No workflow is named + * "deploy-cpp" (deploy-cpp.yml is named "Deploy new cpp version"), so GitHub + * answered 404 and the badge rendered as a broken image. + * + * Usage: + * node .github/scripts/check-readme-badges.mjs [--verbose] + * [--readme ] [--workflows ] + * + * --readme and --workflows default to this repository's README.md and + * .github/workflows, and exist so the test suite can point the check at + * fixtures. + * + * Exits with code 1 and a description of every unresolved badge when a badge + * references a workflow that does not exist. + */ + +import { readFileSync, readdirSync, existsSync } from "fs"; +import { join, dirname, resolve } from "path"; +import { fileURLToPath } from "url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repositoryRoot = resolve(__dirname, "..", ".."); + +const readOption = (option, fallback) => { + const index = process.argv.indexOf(option); + return index === -1 || index === process.argv.length - 1 + ? fallback + : resolve(process.argv[index + 1]); +}; + +const workflowsDirectory = readOption("--workflows", join(repositoryRoot, ".github", "workflows")); +const readmePath = readOption("--readme", join(repositoryRoot, "README.md")); + +const verbose = process.argv.includes("--verbose"); +const trace = (...args) => { + if (verbose) { + console.log("[trace]", ...args); + } +}; + +/** Reads the top-level `name:` of a workflow file, unquoting it when needed. */ +const readWorkflowName = (filePath) => { + const nameLine = readFileSync(filePath, "utf8") + .split(/\r?\n/) + .find((line) => /^name:\s*\S/.test(line)); + if (!nameLine) { + return null; + } + return nameLine.replace(/^name:\s*/, "").trim().replace(/^["'](.*)["']$/, "$1"); +}; + +const collectWorkflows = () => { + if (!existsSync(workflowsDirectory)) { + return []; + } + return readdirSync(workflowsDirectory) + .filter((fileName) => /\.ya?ml$/.test(fileName)) + .map((fileName) => ({ + fileName, + name: readWorkflowName(join(workflowsDirectory, fileName)), + })); +}; + +/** + * `actions?workflow=Deploy+new+cpp+version` encodes spaces as `+`, while + * `workflows/Deploy%20new%20cpp%20version/badge.svg` encodes them as `%20`. + */ +const decodeWorkflowReference = (value, isQueryParameter) => + decodeURIComponent(isQueryParameter ? value.replace(/\+/g, "%20") : value); + +/** Every way README.md can refer to a workflow of this repository. */ +const referencePatterns = [ + { + kind: "badge (workflow name)", + pattern: /https:\/\/github\.com\/[^/\s)]+\/[^/\s)]+\/workflows\/([^/\s)]+)\/badge\.svg/g, + resolve: (match) => ({ by: "name", value: decodeWorkflowReference(match[1], false) }), + }, + { + kind: "link (workflow name)", + pattern: /https:\/\/github\.com\/[^/\s)]+\/[^/\s)]+\/actions\?workflow=([^\s)]+)/g, + resolve: (match) => ({ by: "name", value: decodeWorkflowReference(match[1], true) }), + }, + { + // Covers both the badge form (.../actions/workflows//badge.svg) and the + // plain link form (.../actions/workflows/). The trailing boundary keeps + // the capture from backtracking into a truncated file name such as "cpp-test.ym". + kind: "workflow file", + pattern: /https:\/\/github\.com\/[^/\s)]+\/[^/\s)]+\/actions\/workflows\/([^/\s)?#]+)(\/badge\.svg)?(?=[\s)?#]|$)/g, + resolve: (match) => ({ + kind: match[2] ? "badge (workflow file)" : "link (workflow file)", + by: "file", + value: decodeWorkflowReference(match[1], false), + }), + }, +]; + +const collectReferences = (readme) => { + const references = []; + for (const { kind, pattern, resolve: resolveReference } of referencePatterns) { + for (const match of readme.matchAll(pattern)) { + references.push({ kind, url: match[0], ...resolveReference(match) }); + } + } + return references; +}; + +const main = () => { + const workflows = collectWorkflows(); + const readme = readFileSync(readmePath, "utf8"); + const references = collectReferences(readme); + + trace(`workflows directory: ${workflowsDirectory}`); + for (const workflow of workflows) { + trace(`workflow ${workflow.fileName} -> name ${JSON.stringify(workflow.name)}`); + } + trace(`found ${references.length} workflow reference(s) in README.md`); + + const knownNames = workflows.map((workflow) => workflow.name).filter(Boolean); + const knownFiles = workflows.map((workflow) => workflow.fileName); + + const failures = []; + for (const reference of references) { + const known = reference.by === "name" ? knownNames : knownFiles; + const resolved = known.includes(reference.value); + trace(`${resolved ? "ok" : "FAIL"} ${reference.kind} by ${reference.by}: ${JSON.stringify(reference.value)}`); + if (!resolved) { + failures.push(reference); + } + } + + if (references.length === 0) { + console.error("No GitHub Actions badges found in README.md, the check would pass vacuously."); + process.exit(1); + } + + if (failures.length > 0) { + console.error(`README.md references ${failures.length} workflow(s) that do not exist:\n`); + for (const failure of failures) { + console.error(` ${failure.kind}: ${failure.url}`); + console.error(` referenced workflow ${failure.by}: ${JSON.stringify(failure.value)}`); + } + console.error(`\nAvailable workflow names: ${knownNames.map((name) => JSON.stringify(name)).join(", ")}`); + console.error(`Available workflow files: ${knownFiles.join(", ")}`); + console.error("\nThe segment after /workflows/ is the workflow `name:`, not the file name."); + process.exit(1); + } + + console.log(`All ${references.length} workflow reference(s) in README.md resolve to existing workflows.`); +}; + +main(); diff --git a/.github/scripts/check-readme-badges.test.mjs b/.github/scripts/check-readme-badges.test.mjs new file mode 100644 index 0000000..758ad52 --- /dev/null +++ b/.github/scripts/check-readme-badges.test.mjs @@ -0,0 +1,112 @@ +#!/usr/bin/env node + +/** + * Tests for check-readme-badges.mjs. + * + * Run with: node --test .github/scripts/check-readme-badges.test.mjs + */ + +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { join, dirname, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; + +const scriptPath = join(dirname(fileURLToPath(import.meta.url)), "check-readme-badges.mjs"); +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); + +/** Workflows mirroring the real ones, so the fixtures stay realistic. */ +const workflowFixtures = { + "cpp-test.yml": "name: Test cpp\n", + "csharp.yml": "name: csharp\n", + "deploy-cpp.yml": "name: Deploy new cpp version\n", + "quoted.yml": 'name: "Quoted name"\n', +}; + +/** Runs the check against a throwaway README and workflow directory. */ +const runCheck = (readmeContents) => { + const directory = mkdtempSync(join(tmpdir(), "readme-badges-")); + try { + const workflowsDirectory = join(directory, "workflows"); + mkdirSync(workflowsDirectory); + for (const [fileName, contents] of Object.entries(workflowFixtures)) { + writeFileSync(join(workflowsDirectory, fileName), contents); + } + const readmePath = join(directory, "README.md"); + writeFileSync(readmePath, readmeContents); + + const result = spawnSync( + process.execPath, + [scriptPath, "--readme", readmePath, "--workflows", workflowsDirectory, "--verbose"], + { encoding: "utf8" }, + ); + return { status: result.status, output: `${result.stdout}${result.stderr}` }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}; + +const badge = (path) => `[![Actions Status](https://github.com/linksplatform/Collections.Methods/${path})](https://github.com/linksplatform/Collections.Methods/actions)`; + +test("rejects the badge that broke in linksplatform/Interfaces#141", () => { + const { status, output } = runCheck(badge("workflows/deploy-cpp/badge.svg")); + assert.equal(status, 1); + assert.match(output, /workflow\(s\) that do not exist/); + assert.match(output, /"deploy-cpp"/); +}); + +test("accepts a badge naming an existing workflow", () => { + const { status, output } = runCheck(badge("workflows/Test%20cpp/badge.svg")); + assert.equal(status, 0, output); + assert.match(output, /ok badge \(workflow name\) by name: "Test cpp"/); +}); + +test("accepts the actions/workflows badge form without truncating the file name", () => { + const { status, output } = runCheck(badge("actions/workflows/cpp-test.yml/badge.svg")); + assert.equal(status, 0, output); + assert.match(output, /ok badge \(workflow file\) by file: "cpp-test\.yml"/); + assert.doesNotMatch(output, /cpp-test\.ym"/); +}); + +test("accepts a plain actions/workflows link", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions/workflows/csharp.yml)`); + assert.equal(status, 0, output); + assert.match(output, /ok link \(workflow file\) by file: "csharp\.yml"/); +}); + +test("rejects a link to a workflow file that does not exist", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions/workflows/missing.yml)`); + assert.equal(status, 1); + assert.match(output, /"missing\.yml"/); +}); + +test("decodes + as a space in actions?workflow= links", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions?workflow=Deploy+new+cpp+version)`); + assert.equal(status, 0, output); + assert.match(output, /ok link \(workflow name\) by name: "Deploy new cpp version"/); +}); + +test("decodes %20 as a space in actions?workflow= links", () => { + const { status, output } = runCheck(`[link](https://github.com/linksplatform/Collections.Methods/actions?workflow=Test%20cpp)`); + assert.equal(status, 0, output); + assert.match(output, /ok link \(workflow name\) by name: "Test cpp"/); +}); + +test("reads a quoted workflow name", () => { + const { status, output } = runCheck(badge("workflows/Quoted%20name/badge.svg")); + assert.equal(status, 0, output); + assert.match(output, /ok badge \(workflow name\) by name: "Quoted name"/); +}); + +test("fails when README has no workflow badges at all", () => { + const { status, output } = runCheck("# Collections.Methods\n\nNo badges here.\n"); + assert.equal(status, 1); + assert.match(output, /No GitHub Actions badges found/); +}); + +test("the real README of this repository passes the check", () => { + const result = spawnSync(process.execPath, [scriptPath], { cwd: repositoryRoot, encoding: "utf8" }); + assert.equal(result.status, 0, `${result.stdout}${result.stderr}`); +}); diff --git a/.github/scripts/codeql-workflow-policy.test.mjs b/.github/scripts/codeql-workflow-policy.test.mjs new file mode 100644 index 0000000..a5dcbca --- /dev/null +++ b/.github/scripts/codeql-workflow-policy.test.mjs @@ -0,0 +1,51 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const workflowPath = new URL("../workflows/codeql.yml", import.meta.url); +const workflow = readFileSync(workflowPath, "utf8"); + +test("uses current CodeQL language identifiers and build-free extraction", () => { + assert.match(workflow, /language: \[ 'actions', 'c-cpp', 'csharp' \]/); + assert.match(workflow, /build-mode: none/); + assert.doesNotMatch(workflow, /language: \[ 'cpp'/); + assert.doesNotMatch(workflow, /build-mode: manual/); +}); + +test("does not duplicate the repositories' language build pipelines", () => { + assert.doesNotMatch(workflow, /apt-get/); + assert.doesNotMatch(workflow, /dotnet (?:restore|build)/); + assert.doesNotMatch(workflow, /cmake/); +}); + +test("uses action versions backed by the current Node runtime", () => { + assert.match(workflow, /actions\/checkout@v7/); + assert.match(workflow, /github\/codeql-action\/init@v4/); + assert.match(workflow, /github\/codeql-action\/analyze@v4/); + assert.doesNotMatch(workflow, /actions\/setup-dotnet@/); +}); + +test("pins the runner and disables persisted checkout credentials", () => { + assert.match(workflow, /runs-on: ubuntu-24\.04/); + assert.doesNotMatch(workflow, /runs-on: ubuntu-latest/); + assert.match(workflow, /persist-credentials: false/); +}); + +test("prevents checkout's default-branch warning", () => { + assert.match(workflow, /GIT_CONFIG_COUNT: '1'/); + assert.match(workflow, /GIT_CONFIG_KEY_0: init\.defaultBranch/); + assert.match(workflow, /GIT_CONFIG_VALUE_0: main/); +}); + +test("reviews dependency changes on pull requests", () => { + assert.match(workflow, /actions\/dependency-review-action@v5/); + assert.match(workflow, /fail-on-severity: high/); +}); + +test("turns off the C# feed check that warns about an empty feed set", () => { + // github/codeql#22766: the check logs "No NuGet feeds are reachable" for an + // empty set even when nuget.org is reachable. + assert.match(workflow, /CODEQL_EXTRACTOR_CSHARP_BUILDLESS_NUGET_FEEDS_CHECK: 'false'/); +}); diff --git a/.github/scripts/workflow-policy.test.mjs b/.github/scripts/workflow-policy.test.mjs new file mode 100644 index 0000000..53576f9 --- /dev/null +++ b/.github/scripts/workflow-policy.test.mjs @@ -0,0 +1,148 @@ +#!/usr/bin/env node + +// Repository-wide guards for the CI/CD problems found in linksplatform/Interfaces#150, so a +// fix applied to one workflow cannot regress in another. + +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import test from "node:test"; +import { getJobs } from "./workflow-jobs.mjs"; + +const workflowsDirectory = new URL("../workflows/", import.meta.url); +const workflows = readdirSync(workflowsDirectory) + .filter((name) => /\.ya?ml$/.test(name)) + .map((name) => ({ name, source: readFileSync(new URL(name, workflowsDirectory), "utf8") })); + +const findLines = (pattern) => + workflows.flatMap(({ name, source }) => + source + .split("\n") + .map((line, index) => ({ line, location: `${name}:${index + 1}` })) + .filter(({ line }) => !line.trimStart().startsWith("#") && pattern.test(line)) + .map(({ line, location }) => `${location}: ${line.trim()}`), + ); + +test("finds every workflow", () => { + assert.ok(workflows.length >= 8, `only ${workflows.length} workflows found`); +}); + +test("pins runner images so -latest label migrations cannot change builds", () => { + assert.deepEqual(findLines(/(runs-on|os):\s*[\w-]*-latest/), []); +}); + +test("caps every job that runs on a runner", () => { + const failures = []; + for (const { name, source } of workflows) { + for (const [job, body] of getJobs(source)) { + if (/\n runs-on:/.test(body) && !/\n timeout-minutes:\s*\d+/.test(body)) { + failures.push(`${name}: ${job}`); + } + } + } + assert.deepEqual(failures, []); +}); + +test("declares least-privilege token permissions in every workflow", () => { + const failures = workflows + .filter(({ source }) => !/^permissions:/m.test(source)) + .map(({ name }) => name); + assert.deepEqual(failures, []); +}); + +test("never persists checkout credentials", () => { + const failures = []; + for (const { name, source } of workflows) { + const lines = source.split("\n"); + lines.forEach((line, index) => { + if (line.includes("uses: actions/checkout@")) { + const step = lines.slice(index, index + 8).join("\n"); + if (!/persist-credentials:\s*false/.test(step)) { + failures.push(`${name}:${index + 1}`); + } + } + }); + } + assert.deepEqual(failures, []); +}); + +test("names the default branch so checkout prints no 'Using master' hint", () => { + const missing = workflows + .filter(({ source }) => source.includes("uses: actions/checkout@")) + .filter(({ source }) => !/^env:\n(?: {2}.*\n)*? {2}GIT_CONFIG_KEY_0: init\.defaultBranch\n {2}GIT_CONFIG_VALUE_0: main\n/m.test(source)) + .map(({ name }) => name); + assert.deepEqual(missing, []); +}); + +test("uses no actions that run on the deprecated Node 20 runtime", () => { + assert.deepEqual( + findLines( + /uses:\s*(?:actions\/(?:checkout|setup-dotnet|setup-node|setup-python|cache)@v[1-4]\b|actions\/(?:upload|download)-artifact@v[1-4]\b|ncipollo\/release-action|egor-tensin\/setup-gcc|ahmadnassri\/)/, + ), + [], + ); +}); + +test("pins third-party actions to a full commit hash", () => { + const trusted = /^(?:actions|github)\//; + const failures = findLines(/^\s*(?:-\s*)?uses:\s*[^.\s]/).filter((entry) => { + const reference = /uses:\s*(\S+)/.exec(entry)[1]; + if (reference.startsWith("docker://")) { + return !/@sha256:[0-9a-f]{64}$/.test(reference); + } + return !trusted.test(reference) && !/@[0-9a-f]{40}$/.test(reference); + }); + assert.deepEqual(failures, []); +}); + +test("keeps CI definitions in this repository instead of a mutable @main", () => { + assert.deepEqual(findLines(/uses:\s*linksplatform\/Workflows\//), []); + assert.deepEqual(findLines(/uses:\s*[^#\s]+@(?:main|master)\b/), []); +}); + +test("does not install the nuget CLI that Ubuntu 24.04 no longer ships", () => { + assert.deepEqual(findLines(/apt-get install[^#\n]*\bnuget\b/), []); +}); + +test("runs pull request checks on code changes, not only on edits", () => { + assert.deepEqual(findLines(/^\s*-\s*edited\s*$|types:\s*\[\s*edited\s*\]/), []); +}); + +test("does not trust the spoofable github.actor for bot checks", () => { + assert.deepEqual(findLines(/github\.(?:triggering_)?actor\s*==/), []); +}); + +test("lets cancelled runs stop instead of forcing jobs with always()", () => { + assert.deepEqual(findLines(/\balways\(\)/), []); +}); + +test("lets every workflow supersede stale runs without cancelling a writer", () => { + const missing = workflows + .filter(({ source }) => !/^concurrency:/m.test(source)) + .filter(({ source }) => + [...getJobs(source).values()].some((body) => /\n runs-on:/.test(body) && !/\n concurrency:/.test(body)), + ) + .map(({ name }) => name); + assert.deepEqual(missing, []); + + const writers = workflows + .filter(({ source }) => /^\s+(?:contents|packages|id-token|pages):\s*write/m.test(source)) + .filter(({ source }) => /cancel-in-progress:\s*true/.test(source)) + .map(({ name }) => name); + assert.deepEqual(writers, []); +}); + +test("scans the repository for committed secrets with a pinned scanner", () => { + const secrets = workflows.find(({ name }) => name === "secrets.yml"); + assert.ok(secrets, "secrets.yml is missing"); + assert.match(secrets.source, /secretlint@\d+\.\d+\.\d+/); + assert.match(secrets.source, /@secretlint\/secretlint-rule-preset-recommend@\d+\.\d+\.\d+/); + assert.doesNotMatch(secrets.source, /\n paths:/); +}); + +test("runs the extra zizmor pass offline on purpose, so it prints no fallback warning", () => { + const workflow = workflows.find(({ name }) => name === "workflows.yml").source; + // Without a token zizmor warns "running in offline mode by default"; the + // action step before it already runs the online audits. + assert.match(workflow, /uses: zizmorcore\/zizmor-action@/); + assert.match(workflow, /pipx run zizmor==[\d.]+ --offline /); +}); diff --git a/.github/workflows/AutoMerge.yml b/.github/workflows/AutoMerge.yml index d5c5e0c..0a90560 100644 --- a/.github/workflows/AutoMerge.yml +++ b/.github/workflows/AutoMerge.yml @@ -1,14 +1,48 @@ name: auto-merge +# pull_request_target is required because DEPENDABOT_AUTO_MERGE_TOKEN is an +# Actions secret, and Dependabot's pull_request runs only receive Dependabot +# secrets. No step checks out or executes code from the pull request. on: - pull_request_target: + pull_request_target: # zizmor: ignore[dangerous-triggers] + +permissions: {} + +# github.ref is the base branch for pull_request_target, so the group is keyed +# by pull request; a newer event for the same pull request supersedes an older one. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true jobs: auto-merge: - runs-on: ubuntu-latest + # The pull request author cannot be spoofed by re-running or commenting, + # unlike github.actor. + if: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read steps: - - uses: actions/checkout@v2 - - uses: ahmadnassri/action-dependabot-auto-merge@v2 - with: - target: minor - github-token: ${{ secrets.DEPENDABOT_AUTO_MERGE_TOKEN }} + - name: Read Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + # The previous action posted "@dependabot merge" comments, which GitHub + # removed on 2026-01-27, so it succeeded without merging (linksplatform/Interfaces#150). + - name: Enable auto-merge for patch and minor updates + if: ${{ steps.metadata.outputs.update-type != 'version-update:semver-major' }} + env: + GH_TOKEN: ${{ secrets.DEPENDABOT_AUTO_MERGE_TOKEN }} + PR_URL: ${{ github.event.pull_request.html_url }} + run: | + if [ -z "$GH_TOKEN" ]; then + echo "::error title=Auto-merge token missing::Configure the DEPENDABOT_AUTO_MERGE_TOKEN Actions secret with a token that can merge pull requests." + exit 1 + fi + if [ "$(gh api "repos/$GITHUB_REPOSITORY" --jq .allow_auto_merge)" != true ]; then + echo "::error title=Auto-merge is disabled::Enable 'Allow auto-merge' in Settings > General > Pull Requests, otherwise Dependabot pull requests are never merged." + exit 1 + fi + gh pr merge --auto --merge "$PR_URL" diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..6fa9f1b --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,78 @@ +name: CodeQL + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + schedule: + - cron: '43 3 * * 0' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'actions', 'c-cpp', 'csharp' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: none + queries: security-extended,security-and-quality + + # The C# buildless restore warns "No NuGet feeds are reachable" whenever + # one of its feed sets is empty, although nuget.org, the only feed here, + # is reachable (github/codeql#22766). With the check off it restores from + # nuget.org directly. The variable is read only by the C# extractor. + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + env: + CODEQL_EXTRACTOR_CSHARP_BUILDLESS_NUGET_FEEDS_CHECK: 'false' + with: + category: "/language:${{ matrix.language }}" + + dependency-review: + name: Dependency review + if: ${{ github.event_name == 'pull_request' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Review dependency changes + uses: actions/dependency-review-action@v5 + with: + fail-on-severity: high diff --git a/.github/workflows/readme-badges.yml b/.github/workflows/readme-badges.yml new file mode 100644 index 0000000..3d62fd6 --- /dev/null +++ b/.github/workflows/readme-badges.yml @@ -0,0 +1,46 @@ +name: Check README badges + +on: + push: + branches: + - 'main' + paths: + - 'README.md' + - '.github/workflows/**' + - '.github/scripts/**' + pull_request: + paths: + - 'README.md' + - '.github/workflows/**' + - '.github/scripts/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + check: + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-node@v7 + with: + node-version: '24' + - name: Test the badge check + run: node --test .github/scripts/check-readme-badges.test.mjs + - name: Check that README badges reference existing workflows + run: node .github/scripts/check-readme-badges.mjs --verbose diff --git a/.github/workflows/secrets.yml b/.github/workflows/secrets.yml new file mode 100644 index 0000000..868c6de --- /dev/null +++ b/.github/workflows/secrets.yml @@ -0,0 +1,44 @@ +name: Secrets + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + secretlint: + name: Scan for committed secrets + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: 24 + + # Scans every tracked file, including the experiments and the case study + # logs. The scan is proven able to fail by + # experiments/secretlint-detects-planted-secret.sh. + - name: Check for secrets + run: >- + npx --yes + -p secretlint@13.0.7 + -p @secretlint/secretlint-rule-preset-recommend@13.0.7 + secretlint "**/*" diff --git a/.github/workflows/workflows.yml b/.github/workflows/workflows.yml new file mode 100644 index 0000000..77a7346 --- /dev/null +++ b/.github/workflows/workflows.yml @@ -0,0 +1,85 @@ +name: Workflows + +on: + push: + branches: [main] + paths: + - '.github/**' + pull_request: + branches: [main] + paths: + - '.github/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Superseded pull request runs are cancelled; runs on main finish so a + # release or documentation push that already started is never interrupted. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: init.defaultBranch + GIT_CONFIG_VALUE_0: main + +jobs: + actionlint: + name: Lint workflows + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # The image bundles shellcheck, so every run: block is linted as well. + # Pinned by digest; re-resolve when bumping: + # docker pull rhysd/actionlint: && + # docker inspect --format='{{index .RepoDigests 0}}' rhysd/actionlint: + - name: Lint workflow files + uses: docker://rhysd/actionlint@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 # v1.7.12 + with: + args: -color + + zizmor: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Audit workflow files + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + with: + advanced-security: false + annotations: true + config: .github/zizmor.yml + inputs: .github + min-confidence: medium + version: 1.29.0 + + # Image pinning audits are pedantic-only; this pass keeps them enforced + # without the stylistic findings of the full pedantic persona. The online + # audits already ran in the step above; --offline says so, instead of + # zizmor warning that it fell back to offline mode without a token. + - name: Audit for pedantic-only high-severity findings + run: | + pipx run zizmor==1.29.0 --offline --config .github/zizmor.yml \ + --persona pedantic --min-severity high --min-confidence high \ + .github + + policy: + name: Workflow policy + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Test workflow policies + run: node --test .github/scripts/*workflow-policy.test.mjs diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000..d1092ff --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,13 @@ +# zizmor configuration — https://docs.zizmor.sh/configuration/ +# Adopted from link-foundation/csharp-ai-driven-development-pipeline-template. +rules: + unpinned-uses: + config: + policies: + # These publishers are trusted at tag granularity. Everything else + # must be pinned to a full commit hash (linksplatform/Interfaces#150 replaced + # tj-actions/changed-files, compromised through a mutable tag in + # CVE-2025-30066). + actions/*: ref-pin + github/*: ref-pin + '*': hash-pin diff --git a/.secretlintrc.json b/.secretlintrc.json new file mode 100644 index 0000000..7a1a5df --- /dev/null +++ b/.secretlintrc.json @@ -0,0 +1,7 @@ +{ + "rules": [ + { + "id": "@secretlint/secretlint-rule-preset-recommend" + } + ] +} diff --git a/README.md b/README.md index 84cfe5f..3edb1f5 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -[![Actions Status](https://github.com/linksplatform/Collections.Methods/workflows/CD/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions?workflow=CD) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/93884a3e5b184aafbf9e900369766972)](https://app.codacy.com/gh/linksplatform/Collections.Methods?utm_source=github.com&utm_medium=referral&utm_content=linksplatform/Collections.Methods&utm_campaign=Badge_Grade_Settings) [![CodeFactor](https://www.codefactor.io/repository/github/linksplatform/collections.methods/badge)](https://www.codefactor.io/repository/github/linksplatform/collections.methods) +[![CodeQL](https://github.com/linksplatform/Collections.Methods/actions/workflows/codeql.yml/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions/workflows/codeql.yml) -| [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods) | C# | -|-|-| -| [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods.TemplateLibrary?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods.TemplateLibrary) | __C++__ | +| [![Actions Status](https://github.com/linksplatform/Collections.Methods/workflows/csharp/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions?workflow=csharp) | [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods) | C# | +|-|-|-| +| [![Actions Status](https://github.com/linksplatform/Collections.Methods/workflows/Test%20cpp/badge.svg)](https://github.com/linksplatform/Collections.Methods/actions?workflow=Test%20cpp) | [![NuGet Version and Downloads count](https://img.shields.io/nuget/v/Platform.Collections.Methods.TemplateLibrary?label=nuget&style=flat)](https://www.nuget.org/packages/Platform.Collections.Methods.TemplateLibrary) | __C++__ | # [Collections.Methods](https://github.com/linksplatform/Collections.Methods) @@ -24,3 +24,60 @@ NuGet package: [Platform.Collections.Methods](https://www.nuget.org/packages/Pla ## Dependent libraries * [Platform.Data.Doublets](https://github.com/linksplatform/Data.Doublets) + +## Trees + +| Tree | Balancing | Height | +|-|-|-| +| `SizeBalancedTreeMethods` | Chen's recursive *Maintain* on the way back from every attach and detach | at most the AVL bound 1.44 log₂(n + 2) | +| `RecursionlessSizeBalancedTreeMethods` | the same rotations as the recursive tree, without recursion: the attach path is remembered while descending and only its nodes are maintained | identical trees to `SizeBalancedTreeMethods` | +| `SizedAndThreadedAVLBalancedTreeMethods` | AVL balance factors, threaded leaves | at most the AVL bound | + +Every node `t` of a size balanced tree satisfies Chen's property: +`size(t.left) >= size(t.right.left), size(t.right.right)` and +`size(t.right) >= size(t.left.left), size(t.left.right)`. Trees that an older +version left unbalanced are rebuilt once, in linear time, when an attach or +detach passes more levels than any size balanced tree of their size has. + +## Tests + +The C# and C++ tests run on every pull request and on `main` +([csharp](.github/workflows/csharp.yml), [Test cpp](.github/workflows/cpp-test.yml)). They check +after every attach and detach that the trees keep their sizes, order and +balance property, that the height stays within the AVL bound, that the recursive +and the recursionless tree build identical trees with the minimum number of +rotations, and that every line of the libraries is executed (100% line coverage +for C# and C++). They also run with `ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION`, which +makes every tree validate itself after each change: + +```sh +cd csharp && dotnet test -c Release -p:TreeValidation=true +TREE_VALIDATION=1 BUILD_TYPE=Debug SANITIZERS='address;undefined' cpp/build-and-test.sh +``` + +## Benchmarks + +Benchmarks are noisy on shared runners, so they run only on request: +Actions > [Benchmarks](.github/workflows/benchmarks.yml) > Run workflow. Results are in +the run summary and its artifacts. Locally: + +```sh +cd csharp && dotnet run -c Release --project Platform.Collections.Methods.Benchmarks +BENCHMARKS=1 cpp/build-and-test.sh && cpp/build/bin/Platform.Collections.Methods.Benchmarks +``` + +## Releasing + +A version bump in `csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj` +or `cpp/Platform.Collections.Methods.TemplateLibrary.nuspec` merged to `main` publishes the package to +nuget.org and creates a GitHub release, after the tests passed. Publishing uses +[trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) first: + +1. On nuget.org, add trusted publishing policies for the repository + `linksplatform/Collections.Methods` with the workflows `csharp.yml` and `deploy-cpp.yml`. +2. Set the repository variable `NUGET_USER` to the nuget.org user that owns the policies. + +Without `NUGET_USER` the workflows fall back to the `NUGET_TOKEN` secret (a nuget.org API +key with push scope). A release preflight fails early with an explanation when +neither works. Dependabot pull requests are merged automatically with the +`DEPENDABOT_AUTO_MERGE_TOKEN` secret once "Allow auto-merge" is enabled. diff --git a/experiments/secretlint-detects-planted-secret.sh b/experiments/secretlint-detects-planted-secret.sh new file mode 100755 index 0000000..dc73553 --- /dev/null +++ b/experiments/secretlint-detects-planted-secret.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Proves that the secretlint scan in .github/workflows/secrets.yml is not a +# false negative: a planted, well-formed (but fake) GitHub token must fail it. +set -euo pipefail +cd "$(dirname "$0")/.." +planted="experiments/planted-secret.tmp.txt" +trap 'rm -f "$planted"' EXIT +# Split so this script itself does not contain a token-shaped string. +printf 'token = %s%s\n' "ghp_" "wWPw5k4aXcaT4fNP0UcnZwJUVFk6LO0pINUx" > "$planted" +if npx --yes -p secretlint@13.0.7 -p @secretlint/secretlint-rule-preset-recommend@13.0.7 \ + secretlint "$planted"; then + echo "FAIL: secretlint did not detect the planted token" >&2 + exit 1 +fi +echo "OK: secretlint detected the planted token" From fcd4619f01934e55a137540402b82cead13912e9 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:53:44 +0000 Subject: [PATCH 19/46] Let the trees pay nothing for being inspected LeftRotate and RightRotate are non-virtual again, as on main. The test trees, which inherit from the library trees, now count rotations in the SetLeft and SetRight accessors they implement anyway: a rotation is the only change of links that makes a node the child of its former child. A cross-check run (experiments/detect_rotations_in_setters.py --cross-check) confirmed that the setters detect exactly the rotations the overrides saw. A C# test fails if a rotation becomes virtual, and C++ static_asserts keep the library trees free of virtual functions; the C++ test trees shadow the rotations through CRTP, which resolves them at compile time. --- README.md | 9 +- .../SizeBalancedTreeRotationTests.cpp | 11 +++ cpp/Platform.Collections.Methods.Tests/pch.h | 2 + .../RecursionlessSizeBalancedTree.cs | 44 +++++++--- .../SizeBalancedTree.cs | 44 +++++++--- .../SizeBalancedTreeRotationTests.cs | 15 ++++ .../Trees/SizedBinaryTreeMethodsBase.cs | 4 +- experiments/detect_rotations_in_setters.py | 83 +++++++++++++++++++ 8 files changed, 189 insertions(+), 23 deletions(-) create mode 100644 experiments/detect_rotations_in_setters.py diff --git a/README.md b/README.md index 3edb1f5..47f2586 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,13 @@ cd csharp && dotnet test -c Release -p:TreeValidation=true TREE_VALIDATION=1 BUILD_TYPE=Debug SANITIZERS='address;undefined' cpp/build-and-test.sh ``` +The trees pay nothing for being inspected. The library has no counters, +logs or hooks for tests: the test trees inherit from the library trees and count +rotations and size reads in the node accessors (`GetSize`, `SetLeft`, `SetRight`) +that every tree implements anyway. `LeftRotate` and `RightRotate` stay non-virtual in C#, and in C++ +the test trees shadow them through CRTP, which compiles to direct calls. The +validation mode is a compile-time switch, so it costs nothing when it is off. + ## Benchmarks Benchmarks are noisy on shared runners, so they run only on request: @@ -69,7 +76,7 @@ BENCHMARKS=1 cpp/build-and-test.sh && cpp/build/bin/Platform.Collections.Methods ## Releasing A version bump in `csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj` -or `cpp/Platform.Collections.Methods.TemplateLibrary.nuspec` merged to `main` publishes the package to +or `cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec` merged to `main` publishes the package to nuget.org and creates a GitHub release, after the tests passed. Publishing uses [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) first: diff --git a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp index b6e8ee3..74c3978 100644 --- a/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp +++ b/cpp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cpp @@ -9,6 +9,17 @@ namespace Platform::Collections::Methods::Tests using TreeBalance::Capacity; using TreeBalance::N; + // The trees pay nothing for being inspected: the library trees have no virtual functions, so no table + // pointer and only direct calls. The test trees count rotations and size reads by shadowing LeftRotate, + // RightRotate and GetSize, which the library calls through CRTP and the compiler resolves statically. + using Platform::Collections::Methods::Trees::RecursionlessSizeBalancedTreeMethods; + using Platform::Collections::Methods::Trees::SizeBalancedTreeMethods; + static_assert(!std::is_polymorphic_v, std::uint32_t>>); + static_assert(!std::is_polymorphic_v, std::uint32_t>>); + static_assert(!std::is_polymorphic_v>); + static_assert(!std::is_polymorphic_v>); + static_assert(!std::is_polymorphic_v, std::uint32_t>>); + /// /// Whether inserting the key with a plain binary search tree insertion would break a size balanced tree property. /// Нарушила бы вставка ключа простой вставкой в двоичное дерево поиска свойство дерева, сбалансированного по размеру. diff --git a/cpp/Platform.Collections.Methods.Tests/pch.h b/cpp/Platform.Collections.Methods.Tests/pch.h index e711bc2..ddcf106 100644 --- a/cpp/Platform.Collections.Methods.Tests/pch.h +++ b/cpp/Platform.Collections.Methods.Tests/pch.h @@ -9,6 +9,8 @@ // add headers that you want to pre-compile here +#include + #include #endif //PCH_H diff --git a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs index f46b78e..599e4be 100644 --- a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs @@ -66,18 +66,37 @@ public void SetNode(TElement node, TElement left, TElement right, TElement size) SetSize(node, size); } - protected override TElement LeftRotate(TElement root) + // The library does not pay for inspection: LeftRotate and RightRotate are not virtual, so the + // rotations are recognized in the setters this tree implements anyway. LeftRotate(root) sets the + // right link of root, which held its right child, and right after it makes root the left child of + // that child; RightRotate is the mirror image. No other change of links moves a node below its + // former child, so every rotation is counted once. + private TElement _lastLinkParent = TElement.Zero; + private TElement _lastLinkChild = TElement.Zero; + private bool _lastLinkIsRight; + + private void SetLink(TElement node, TElement child, bool isRight) { - Rotations++; - RotationLog?.Add("L" + root); - return base.LeftRotate(root); + ref var element = ref GetElement(node); + if (_lastLinkParent == child && _lastLinkChild == node && _lastLinkIsRight != isRight && child != TElement.Zero) + { + CountRotation(isRight ? "R" : "L", child); + } + (_lastLinkParent, _lastLinkChild, _lastLinkIsRight) = (node, isRight ? element.Right : element.Left, isRight); + if (isRight) + { + element.Right = child; + } + else + { + element.Left = child; + } } - protected override TElement RightRotate(TElement root) + private void CountRotation(string direction, TElement node) { Rotations++; - RotationLog?.Add("R" + root); - return base.RightRotate(root); + RotationLog?.Add(direction + node); } public RecursionlessSizeBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); @@ -134,11 +153,16 @@ protected override TElement GetSize(TElement node) protected override void PrintNodeValue(TElement node, StringBuilder sb) => sb.Append(node); - protected override void SetLeft(TElement node, TElement left) => GetElement(node).Left = left; + protected override void SetLeft(TElement node, TElement left) => SetLink(node, left, isRight: false); + + protected override void SetRight(TElement node, TElement right) => SetLink(node, right, isRight: true); - protected override void SetRight(TElement node, TElement right) => GetElement(node).Right = right; + protected override void SetSize(TElement node, TElement size) + { + _lastLinkParent = TElement.Zero; + GetElement(node).Size = size; + } - protected override void SetSize(TElement node, TElement size) => GetElement(node).Size = size; private ref TreeElement GetElement(TElement node) => ref _elements[UncheckedConverter.Default.Convert(node)]; } } diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs index 5508a61..eca123d 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs @@ -66,18 +66,37 @@ public void SetNode(TElement node, TElement left, TElement right, TElement size) SetSize(node, size); } - protected override TElement LeftRotate(TElement root) + // The library does not pay for inspection: LeftRotate and RightRotate are not virtual, so the + // rotations are recognized in the setters this tree implements anyway. LeftRotate(root) sets the + // right link of root, which held its right child, and right after it makes root the left child of + // that child; RightRotate is the mirror image. No other change of links moves a node below its + // former child, so every rotation is counted once. + private TElement _lastLinkParent = TElement.Zero; + private TElement _lastLinkChild = TElement.Zero; + private bool _lastLinkIsRight; + + private void SetLink(TElement node, TElement child, bool isRight) { - Rotations++; - RotationLog?.Add("L" + root); - return base.LeftRotate(root); + ref var element = ref GetElement(node); + if (_lastLinkParent == child && _lastLinkChild == node && _lastLinkIsRight != isRight && child != TElement.Zero) + { + CountRotation(isRight ? "R" : "L", child); + } + (_lastLinkParent, _lastLinkChild, _lastLinkIsRight) = (node, isRight ? element.Right : element.Left, isRight); + if (isRight) + { + element.Right = child; + } + else + { + element.Left = child; + } } - protected override TElement RightRotate(TElement root) + private void CountRotation(string direction, TElement node) { Rotations++; - RotationLog?.Add("R" + root); - return base.RightRotate(root); + RotationLog?.Add(direction + node); } public SizeBalancedTree(int capacity) => (_elements, _allocated) = (new TreeElement[capacity], TElement.One); @@ -135,11 +154,16 @@ protected override TElement GetSize(TElement node) protected override void PrintNodeValue(TElement node, StringBuilder sb) => sb.Append(node); - protected override void SetLeft(TElement node, TElement left) => GetElement(node).Left = left; + protected override void SetLeft(TElement node, TElement left) => SetLink(node, left, isRight: false); + + protected override void SetRight(TElement node, TElement right) => SetLink(node, right, isRight: true); - protected override void SetRight(TElement node, TElement right) => GetElement(node).Right = right; + protected override void SetSize(TElement node, TElement size) + { + _lastLinkParent = TElement.Zero; + GetElement(node).Size = size; + } - protected override void SetSize(TElement node, TElement size) => GetElement(node).Size = size; private ref TreeElement GetElement(TElement node) => ref _elements[UncheckedConverter.Default.Convert(node)]; } } diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs index 03757ee..de4e56c 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTreeRotationTests.cs @@ -155,6 +155,21 @@ public void RecursionlessAttachReadsFewerSizes(string workload) /// Every order of attaches and detaches of up to 8 nodes keeps the properties and gives the same tree in both implementations. /// Любой порядок присоединений и отсоединений до 8 узлов сохраняет свойства и даёт одинаковое дерево в обеих реализациях. /// + /// + /// The trees do not pay for being inspected: rotations are direct calls, and the test trees count them in the node accessors instead. + /// Деревья не платят за возможность их проверки: повороты вызываются напрямую, а тестовые деревья считают их в методах доступа к узлам. + /// + [Fact] + public void RotationsAreNotVirtual() + { + foreach (var name in new[] { "LeftRotate", "RightRotate" }) + { + var rotation = typeof(Platform.Collections.Methods.Trees.SizedBinaryTreeMethodsBase).GetMethod(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, new[] { typeof(uint) }); + Assert.NotNull(rotation); + Assert.False(rotation!.IsVirtual, name); + } + } + [Fact] public void EveryOrderOfUpToEightNodesKeepsTheProperties() { diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index 9d7f05f..3c9cb67 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -349,7 +349,7 @@ public abstract class SizedBinaryTreeMethodsBase where TElement: IUn /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected virtual TElement LeftRotate(TElement root) + protected TElement LeftRotate(TElement root) { var right = GetRight(root); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION @@ -393,7 +393,7 @@ protected virtual TElement LeftRotate(TElement root) /// /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected virtual TElement RightRotate(TElement root) + protected TElement RightRotate(TElement root) { var left = GetLeft(root); #if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION diff --git a/experiments/detect_rotations_in_setters.py b/experiments/detect_rotations_in_setters.py new file mode 100644 index 0000000..9e356e9 --- /dev/null +++ b/experiments/detect_rotations_in_setters.py @@ -0,0 +1,83 @@ +"""Move rotation counting of the C# test trees from LeftRotate/RightRotate overrides into SetLeft/SetRight. + +With --cross-check the overrides stay and assert that the setters detected exactly the rotation the +override saw, and that the setters detect nothing outside rotations (run the tests, then rerun without it). +""" +import re +import sys + +cross_check = "--cross-check" in sys.argv +for name in ["SizeBalancedTree", "RecursionlessSizeBalancedTree"]: + path = f"csharp/Platform.Collections.Methods.Tests/{name}.cs" + text = open(path, encoding="utf-8").read() + overrides = re.search(r" protected override TElement LeftRotate.*?\n }\n\n protected override TElement RightRotate.*?\n }\n", text, re.S) + assert overrides, path + check = ''' private bool _inRotation; + + protected override TElement LeftRotate(TElement root) + { + var before = Rotations; + _inRotation = true; + var result = base.LeftRotate(root); + _inRotation = false; + if (Rotations != before + 1 || (RotationLog != null && RotationLog[^1] != "L" + root)) throw new InvalidOperationException("Missed left rotation of " + root); + return result; + } + + protected override TElement RightRotate(TElement root) + { + var before = Rotations; + _inRotation = true; + var result = base.RightRotate(root); + _inRotation = false; + if (Rotations != before + 1 || (RotationLog != null && RotationLog[^1] != "R" + root)) throw new InvalidOperationException("Missed right rotation of " + root); + return result; + } + +''' if cross_check else "" + guard = ''' if (!_inRotation) throw new InvalidOperationException("Rotation detected outside of a rotation: " + direction + node); +''' if cross_check else "" + detector = check + ''' // The library does not pay for inspection: LeftRotate and RightRotate are not virtual, so the + // rotations are recognized in the setters this tree implements anyway. LeftRotate(root) sets the + // right link of root, which held its right child, and right after it makes root the left child of + // that child; RightRotate is the mirror image. No other change of links moves a node below its + // former child, so every rotation is counted once. + private TElement _lastLinkParent = TElement.Zero; + private TElement _lastLinkChild = TElement.Zero; + private bool _lastLinkIsRight; + + private void SetLink(TElement node, TElement child, bool isRight) + { + ref var element = ref GetElement(node); + if (_lastLinkParent == child && _lastLinkChild == node && _lastLinkIsRight != isRight && child != TElement.Zero) + { + CountRotation(isRight ? "R" : "L", child); + } + (_lastLinkParent, _lastLinkChild, _lastLinkIsRight) = (node, isRight ? element.Right : element.Left, isRight); + if (isRight) + { + element.Right = child; + } + else + { + element.Left = child; + } + } + + private void CountRotation(string direction, TElement node) + { +''' + guard + ''' Rotations++; + RotationLog?.Add(direction + node); + } +''' + text = text[:overrides.start()] + detector + text[overrides.end():] + text = text.replace( + " protected override void SetLeft(TElement node, TElement left) => GetElement(node).Left = left;", + " protected override void SetLeft(TElement node, TElement left) => SetLink(node, left, isRight: false);") + text = text.replace( + " protected override void SetRight(TElement node, TElement right) => GetElement(node).Right = right;", + " protected override void SetRight(TElement node, TElement right) => SetLink(node, right, isRight: true);") + text = text.replace( + " protected override void SetSize(TElement node, TElement size) => GetElement(node).Size = size;", + " protected override void SetSize(TElement node, TElement size)\n {\n _lastLinkParent = TElement.Zero;\n GetElement(node).Size = size;\n }\n") + open(path, "w", encoding="utf-8").write(text) From 21cc382e33378c5637b10fe74f2cbfe7ed7a029d Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:56:39 +0000 Subject: [PATCH 20/46] Make the shell scripts executable The csharp test job and the C++ pack job failed with "Permission denied" (exit code 126) because six scripts were committed without the executable bit. A workflow policy test now requires it for every tracked shell script. install-local-conan-dependencies.sh gets a shebang and strict mode. --- .github/scripts/check-cpp-nuget-package.sh | 0 .github/scripts/generate-csharp-pdf.sh | 0 .github/scripts/publish-csharp-docs.sh | 0 .github/scripts/push-nuget-package.sh | 0 .github/scripts/validate-csharp-docs.sh | 0 .github/scripts/validate-csharp-package.sh | 0 .github/scripts/workflow-policy.test.mjs | 11 +++++++++++ cpp/install-local-conan-dependencies.sh | 3 +++ 8 files changed, 14 insertions(+) mode change 100644 => 100755 .github/scripts/check-cpp-nuget-package.sh mode change 100644 => 100755 .github/scripts/generate-csharp-pdf.sh mode change 100644 => 100755 .github/scripts/publish-csharp-docs.sh mode change 100644 => 100755 .github/scripts/push-nuget-package.sh mode change 100644 => 100755 .github/scripts/validate-csharp-docs.sh mode change 100644 => 100755 .github/scripts/validate-csharp-package.sh mode change 100644 => 100755 cpp/install-local-conan-dependencies.sh diff --git a/.github/scripts/check-cpp-nuget-package.sh b/.github/scripts/check-cpp-nuget-package.sh old mode 100644 new mode 100755 diff --git a/.github/scripts/generate-csharp-pdf.sh b/.github/scripts/generate-csharp-pdf.sh old mode 100644 new mode 100755 diff --git a/.github/scripts/publish-csharp-docs.sh b/.github/scripts/publish-csharp-docs.sh old mode 100644 new mode 100755 diff --git a/.github/scripts/push-nuget-package.sh b/.github/scripts/push-nuget-package.sh old mode 100644 new mode 100755 diff --git a/.github/scripts/validate-csharp-docs.sh b/.github/scripts/validate-csharp-docs.sh old mode 100644 new mode 100755 diff --git a/.github/scripts/validate-csharp-package.sh b/.github/scripts/validate-csharp-package.sh old mode 100644 new mode 100755 diff --git a/.github/scripts/workflow-policy.test.mjs b/.github/scripts/workflow-policy.test.mjs index 53576f9..a2ab729 100644 --- a/.github/scripts/workflow-policy.test.mjs +++ b/.github/scripts/workflow-policy.test.mjs @@ -4,6 +4,7 @@ // fix applied to one workflow cannot regress in another. import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import { readdirSync, readFileSync } from "node:fs"; import test from "node:test"; import { getJobs } from "./workflow-jobs.mjs"; @@ -146,3 +147,13 @@ test("runs the extra zizmor pass offline on purpose, so it prints no fallback wa assert.match(workflow, /uses: zizmorcore\/zizmor-action@/); assert.match(workflow, /pipx run zizmor==[\d.]+ --offline /); }); + +test("keeps every shell script executable, since the workflows run them directly", () => { + // A script added without the executable bit fails in CI with "Permission denied" (exit code 126). + const repository = new URL("../../", import.meta.url).pathname; + const failures = execFileSync("git", ["ls-files", "--stage", "--", "*.sh"], { cwd: repository, encoding: "utf8" }) + .split("\n") + .filter((line) => line && !line.startsWith("100755 ")) + .map((line) => line.split("\t")[1]); + assert.deepEqual(failures, []); +}); diff --git a/cpp/install-local-conan-dependencies.sh b/cpp/install-local-conan-dependencies.sh old mode 100644 new mode 100755 index 2bfd5b5..45bafad --- a/cpp/install-local-conan-dependencies.sh +++ b/cpp/install-local-conan-dependencies.sh @@ -1,3 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + git clone https://github.com/linksplatform/conan-center-index cd conan-center-index && cd recipes conan create platform.interfaces/all --version 0.3.41 From ad3539cbd2054d53805ca76b937903d566c5ee34 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 10:56:39 +0000 Subject: [PATCH 21/46] Exclude the CodeQL queries that report the C++ unity builds cpp/include-non-header flags the unity builds of the C++ tests and benchmarks, the linksplatform layout. cpp/unused-static-variable misreads a benchmark function template as a variable, because the buildless extraction does not have the fetched Google Benchmark headers. --- .github/codeql/codeql-config.yml | 18 ++++++++++++++++++ .../scripts/codeql-workflow-policy.test.mjs | 8 ++++++++ .github/workflows/codeql.yml | 1 + 3 files changed, 27 insertions(+) create mode 100644 .github/codeql/codeql-config.yml diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml new file mode 100644 index 0000000..8a9df61 --- /dev/null +++ b/.github/codeql/codeql-config.yml @@ -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 diff --git a/.github/scripts/codeql-workflow-policy.test.mjs b/.github/scripts/codeql-workflow-policy.test.mjs index a5dcbca..0f26e44 100644 --- a/.github/scripts/codeql-workflow-policy.test.mjs +++ b/.github/scripts/codeql-workflow-policy.test.mjs @@ -49,3 +49,11 @@ test("turns off the C# feed check that warns about an empty feed set", () => { // empty set even when nuget.org is reachable. assert.match(workflow, /CODEQL_EXTRACTOR_CSHARP_BUILDLESS_NUGET_FEEDS_CHECK: 'false'/); }); + +test("excludes only the queries that report the unity builds of the C++ tests and benchmarks", () => { + assert.match(workflow, /config-file: \.\/\.github\/codeql\/codeql-config\.yml/); + const config = readFileSync(new URL("../codeql/codeql-config.yml", import.meta.url), "utf8"); + const excluded = [...config.matchAll(/^\s+id: (\S+)$/gm)].map(([, id]) => id); + assert.deepEqual(excluded, ["cpp/include-non-header", "cpp/unused-static-variable"]); + assert.doesNotMatch(config, /paths-ignore|disable-default-queries/); +}); diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 6fa9f1b..524e8e1 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -49,6 +49,7 @@ jobs: languages: ${{ matrix.language }} build-mode: none queries: security-extended,security-and-quality + config-file: ./.github/codeql/codeql-config.yml # The C# buildless restore warns "No NuGet feeds are reachable" whenever # one of its feed sets is empty, although nuget.org, the only feed here, From b13c2781396d6dec299e2dcec02e15070dce167d Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 11:01:57 +0000 Subject: [PATCH 22/46] Let the documentation jobs build the README and the comments of the trees MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docfx builds README.md into the site, which holds only the README and the API pages, so the relative links to the workflows were invalid links and failed the --warningsAsErrors build. They are absolute URLs now. pdflatex stopped at the ≥ in a comment of SizeBalancedTreeMethods. The PDF preamble now maps the mathematical symbols, and a policy test requires a mapping for every character of the C# sources and only absolute links in the README. --- .../scripts/csharp-workflow-policy.test.mjs | 35 +++++++++++++++++++ .github/scripts/generate-csharp-pdf.sh | 16 +++++++++ README.md | 4 +-- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.github/scripts/csharp-workflow-policy.test.mjs b/.github/scripts/csharp-workflow-policy.test.mjs index 7392189..217c440 100644 --- a/.github/scripts/csharp-workflow-policy.test.mjs +++ b/.github/scripts/csharp-workflow-policy.test.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; import test from "node:test"; import { getJobs } from "./workflow-jobs.mjs"; @@ -211,3 +212,37 @@ test("runs the C# benchmarks only on request", () => { // The tests build the whole solution, so the benchmarks keep compiling. assert.match(readFileSync(new URL("./validate-csharp-package.sh", import.meta.url), "utf8"), /dotnet (?:build|test)/); }); + +// pdflatex stops at the first character it has no mapping for. inputenc maps +// Latin-1, Cyrillic and the typographic dashes, quotes and dots; every other +// character of the C# sources needs a \DeclareUnicodeCharacter of its own. +test("maps every character of the C# sources in the PDF preamble", () => { + const script = readFileSync(new URL("./generate-csharp-pdf.sh", import.meta.url), "utf8"); + const declared = new Set([...script.matchAll(/\\DeclareUnicodeCharacter\{([0-9A-F]+)\}/g)].map(([, code]) => Number.parseInt(code, 16))); + const mappedByInputenc = (code) => code < 0x100 || (code >= 0x400 && code <= 0x4ff) || (code >= 0x2013 && code <= 0x2026); + const sources = execFileSync("git", ["ls-files", "-z", "--", "csharp/Platform.Collections.Methods/*.cs", "csharp/Platform.Collections.Methods.Tests/*.cs"], { encoding: "utf8" }) + .split("\0") + .filter(Boolean); + assert.ok(sources.length > 0); + const unmapped = new Set(); + for (const source of sources) { + for (const character of readFileSync(source, "utf8").replace(/^/, "")) { + const code = character.codePointAt(0); + if (!mappedByInputenc(code) && !declared.has(code)) { + unmapped.add(`U+${code.toString(16).toUpperCase().padStart(4, "0")} ${character} in ${source}`); + } + } + } + assert.deepEqual([...unmapped], []); +}); + +// docfx builds README.md into the documentation site, which contains only the +// README and the API pages, so a relative link to any other repository file +// is an invalid link there and fails the --warningsAsErrors build. +test("links the README only to absolute URLs and anchors", () => { + const readme = readFileSync(new URL("../../README.md", import.meta.url), "utf8"); + const relative = [...readme.matchAll(/\]\(([^)\s]+)\)|(?:src|href)="([^"]+)"/g)] + .map(([, markdown, html]) => markdown ?? html) + .filter((target) => !/^(?:https?:|mailto:|#)/.test(target)); + assert.deepEqual(relative, []); +}); diff --git a/.github/scripts/generate-csharp-pdf.sh b/.github/scripts/generate-csharp-pdf.sh index cb445b4..29463c6 100755 --- a/.github/scripts/generate-csharp-pdf.sh +++ b/.github/scripts/generate-csharp-pdf.sh @@ -39,7 +39,23 @@ cat > "$document" <<'LATEX' \makeindex \titlespacing\chapter{0mm}{0mm}{0mm} \titlespacing\section{0mm}{0mm}{0mm} +% inputenc maps Latin-1, Cyrillic and typographic dashes and quotes; the +% mathematical symbols the comments use need a mapping of their own. +\DeclareUnicodeCharacter{2190}{\ensuremath{\leftarrow}} +\DeclareUnicodeCharacter{2192}{\ensuremath{\rightarrow}} +\DeclareUnicodeCharacter{2208}{\ensuremath{\in}} +\DeclareUnicodeCharacter{2211}{\ensuremath{\sum}} +\DeclareUnicodeCharacter{2212}{\ensuremath{-}} +\DeclareUnicodeCharacter{221A}{\ensuremath{\surd}} \DeclareUnicodeCharacter{221E}{\ensuremath{\infty}} +\DeclareUnicodeCharacter{2248}{\ensuremath{\approx}} +\DeclareUnicodeCharacter{2260}{\ensuremath{\neq}} +\DeclareUnicodeCharacter{2264}{\ensuremath{\leq}} +\DeclareUnicodeCharacter{2265}{\ensuremath{\geq}} +\DeclareUnicodeCharacter{230A}{\ensuremath{\lfloor}} +\DeclareUnicodeCharacter{230B}{\ensuremath{\rfloor}} +\DeclareUnicodeCharacter{2308}{\ensuremath{\lceil}} +\DeclareUnicodeCharacter{2309}{\ensuremath{\rceil}} \DeclareUnicodeCharacter{FFFD}{\ensuremath{ }} \begin{document} \sffamily diff --git a/README.md b/README.md index 47f2586..5475009 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ detach passes more levels than any size balanced tree of their size has. ## Tests The C# and C++ tests run on every pull request and on `main` -([csharp](.github/workflows/csharp.yml), [Test cpp](.github/workflows/cpp-test.yml)). They check +([csharp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/csharp.yml), [Test cpp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/cpp-test.yml)). They check after every attach and detach that the trees keep their sizes, order and balance property, that the height stays within the AVL bound, that the recursive and the recursionless tree build identical trees with the minimum number of @@ -65,7 +65,7 @@ validation mode is a compile-time switch, so it costs nothing when it is off. ## Benchmarks Benchmarks are noisy on shared runners, so they run only on request: -Actions > [Benchmarks](.github/workflows/benchmarks.yml) > Run workflow. Results are in +Actions > [Benchmarks](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/benchmarks.yml) > Run workflow. Results are in the run summary and its artifacts. Locally: ```sh From bb17f454da0cb1bb03281a5e2ea5eda27378b80d Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 11:06:36 +0000 Subject: [PATCH 23/46] Resolve the C# sources from the repository root in the PDF preamble test The csharp workflow runs the node tests from csharp/, where the pathspecs matched no file, so the test failed on its own guard. --- .github/scripts/csharp-workflow-policy.test.mjs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/scripts/csharp-workflow-policy.test.mjs b/.github/scripts/csharp-workflow-policy.test.mjs index 217c440..5c5b83a 100644 --- a/.github/scripts/csharp-workflow-policy.test.mjs +++ b/.github/scripts/csharp-workflow-policy.test.mjs @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; import test from "node:test"; import { getJobs } from "./workflow-jobs.mjs"; @@ -219,14 +220,18 @@ test("runs the C# benchmarks only on request", () => { test("maps every character of the C# sources in the PDF preamble", () => { const script = readFileSync(new URL("./generate-csharp-pdf.sh", import.meta.url), "utf8"); const declared = new Set([...script.matchAll(/\\DeclareUnicodeCharacter\{([0-9A-F]+)\}/g)].map(([, code]) => Number.parseInt(code, 16))); + // The workflow runs the tests from csharp/, so pathspecs and files are + // resolved against the repository root, not the working directory. + const repositoryUrl = new URL("../../", import.meta.url); + const repository = fileURLToPath(repositoryUrl); const mappedByInputenc = (code) => code < 0x100 || (code >= 0x400 && code <= 0x4ff) || (code >= 0x2013 && code <= 0x2026); - const sources = execFileSync("git", ["ls-files", "-z", "--", "csharp/Platform.Collections.Methods/*.cs", "csharp/Platform.Collections.Methods.Tests/*.cs"], { encoding: "utf8" }) + const sources = execFileSync("git", ["ls-files", "-z", "--", "csharp/Platform.Collections.Methods/*.cs", "csharp/Platform.Collections.Methods.Tests/*.cs"], { cwd: repository, encoding: "utf8" }) .split("\0") .filter(Boolean); assert.ok(sources.length > 0); const unmapped = new Set(); for (const source of sources) { - for (const character of readFileSync(source, "utf8").replace(/^/, "")) { + for (const character of readFileSync(new URL(source, repositoryUrl), "utf8").replace(/^/, "")) { const code = character.codePointAt(0); if (!mappedByInputenc(code) && !declared.has(code)) { unmapped.add(`U+${code.toString(16).toUpperCase().padStart(4, "0")} ${character} in ${source}`); From 1ad28a590d25cfd210e99af900b6de56a7258f85 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 11:12:11 +0000 Subject: [PATCH 24/46] Validate the documentation pages that DocFX writes for this library The validator came from linksplatform/Interfaces, whose root namespace has types. Here every type is in Platform.Collections.Methods.Lists or .Trees, so DocFX writes no page for the root namespace and the check failed. It now requires the two namespace pages and the pages of both size balanced trees, and a test requires every listed page to name a namespace or public type of the library. --- .github/scripts/validate-csharp-docs.sh | 4 ++- .github/scripts/validate-csharp-docs.test.mjs | 32 +++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/.github/scripts/validate-csharp-docs.sh b/.github/scripts/validate-csharp-docs.sh index 7432608..b72b6b3 100755 --- a/.github/scripts/validate-csharp-docs.sh +++ b/.github/scripts/validate-csharp-docs.sh @@ -6,8 +6,10 @@ site=${1:?Usage: validate-csharp-docs.sh SITE_DIRECTORY} for file in \ index.html \ - api/Platform.Collections.Methods.html \ + api/Platform.Collections.Methods.Lists.html \ + api/Platform.Collections.Methods.Trees.html \ api/Platform.Collections.Methods.Trees.SizeBalancedTreeMethods-1.html \ + api/Platform.Collections.Methods.Trees.RecursionlessSizeBalancedTreeMethods-1.html \ Platform.Collections.Methods.Documentation.pdf \ xrefmap.yml; do if [[ ! -s "$site/$file" ]]; then diff --git a/.github/scripts/validate-csharp-docs.test.mjs b/.github/scripts/validate-csharp-docs.test.mjs index 21b7d40..adcf3e7 100644 --- a/.github/scripts/validate-csharp-docs.test.mjs +++ b/.github/scripts/validate-csharp-docs.test.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node import assert from "node:assert/strict"; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { spawnSync } from "node:child_process"; @@ -28,8 +28,10 @@ const withSite = (files, check, contents = {}) => { const requiredFiles = [ "index.html", - "api/Platform.Collections.Methods.html", + "api/Platform.Collections.Methods.Lists.html", + "api/Platform.Collections.Methods.Trees.html", "api/Platform.Collections.Methods.Trees.SizeBalancedTreeMethods-1.html", + "api/Platform.Collections.Methods.Trees.RecursionlessSizeBalancedTreeMethods-1.html", "xrefmap.yml", "Platform.Collections.Methods.Documentation.pdf", ]; @@ -62,3 +64,29 @@ test("rejects a site with no documentation PDF link", () => { assert.match(stderr, /home page is missing its PDF link/); }, { "index.html": "generated content" }); }); + +// DocFX writes a page only for a namespace that has types and for each type +// (generic types get a - suffix), so a required page that names +// neither can never exist and would fail every documentation build. +test("requires only pages that DocFX generates for the library", () => { + const library = new URL("../../csharp/Platform.Collections.Methods/", import.meta.url); + const pages = new Set(); + for (const file of readdirSync(library, { recursive: true })) { + if (!file.endsWith(".cs") || /(^|\/)(bin|obj)\//.test(file)) { + continue; + } + const source = readFileSync(new URL(file, library), "utf8"); + const namespace = /^\s*namespace\s+([\w.]+)/m.exec(source)?.[1]; + if (!namespace) { + continue; + } + pages.add(`api/${namespace}.html`); + for (const [, type, parameters] of source.matchAll(/\bpublic\s+(?:\w+\s+)*(?:class|struct|interface)\s+(\w+)(?:<([^>]*)>)?/g)) { + pages.add(`api/${namespace}.${type}${parameters ? `-${parameters.split(",").length}` : ""}.html`); + } + } + const script = readFileSync(validator, "utf8"); + const required = [...script.matchAll(/^\s+(api\/\S+\.html)/gm)].map(([, page]) => page); + assert.ok(required.length > 0); + assert.deepEqual(required.filter((page) => !pages.has(page)), []); +}); From caba0d1ec081d5604c03d20337266bfc0204d1f9 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 11:18:16 +0000 Subject: [PATCH 25/46] Link the README to the API documentation PDF and the namespace pages The documentation home page is the README, which had no link to the PDF that DocFX writes, and its namespace link pointed to a page DocFX never writes because the root namespace has no types. Like linksplatform/Interfaces, the README now links the API documentation PDF, and it links the Lists and Trees namespace pages; a policy test keeps both links valid. --- .github/scripts/csharp-workflow-policy.test.mjs | 14 ++++++++++++++ README.md | 4 +++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/scripts/csharp-workflow-policy.test.mjs b/.github/scripts/csharp-workflow-policy.test.mjs index 5c5b83a..3434361 100644 --- a/.github/scripts/csharp-workflow-policy.test.mjs +++ b/.github/scripts/csharp-workflow-policy.test.mjs @@ -251,3 +251,17 @@ test("links the README only to absolute URLs and anchors", () => { .filter((target) => !/^(?:https?:|mailto:|#)/.test(target)); assert.deepEqual(relative, []); }); + +// The documentation home page is the README, and validate-csharp-docs.sh +// requires it to link the PDF that DocFX writes; the namespace links must +// name pages DocFX writes, which it does only for namespaces with types. +test("links the README to the DocFX PDF and to the namespace pages", () => { + const readme = readFileSync(new URL("../../README.md", import.meta.url), "utf8"); + const docfx = JSON.parse(readFileSync(new URL("../../csharp/docfx.json", import.meta.url), "utf8")); + assert.ok(readme.includes(`/csharp/${docfx.build.globalMetadata.pdfFileName})`)); + const validator = readFileSync(new URL("./validate-csharp-docs.sh", import.meta.url), "utf8"); + const pages = new Set([...validator.matchAll(/^\s+(api\/\S+\.html)/gm)].map(([, page]) => page)); + const linked = [...readme.matchAll(/linksplatform\.github\.io\/Collections\.Methods\/csharp\/(api\/[^)]+\.html)\)/g)].map(([, page]) => page); + assert.ok(linked.length > 0); + assert.deepEqual(linked.filter((page) => !pages.has(page)), []); +}); diff --git a/README.md b/README.md index 5475009..b1691ac 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ LinksPlatform's Platform.Collections.Methods Class Library. -Namespace: [Platform.Collections.Methods](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.html) +Namespaces: [Platform.Collections.Methods.Lists](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Lists.html), [Platform.Collections.Methods.Trees](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Trees.html) Forked from: [Konard/LinksPlatform/Platform/Platform.Data.Core/Collections](https://github.com/Konard/LinksPlatform/tree/b6866f278712c317b4c895e27e49f2d0b3fe561f/Platform/Platform.Data.Core/Collections) @@ -19,6 +19,8 @@ NuGet package: [Platform.Collections.Methods](https://www.nuget.org/packages/Pla ## [Documentation](https://linksplatform.github.io/Collections.Methods) [PDF file](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.pdf) with code for e-readers. +The [C# workflow](https://github.com/linksplatform/Collections.Methods/actions/workflows/csharp.yml) builds the DocFX site on every pull request and publishes it from `main`, including the [API documentation PDF](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.Documentation.pdf). + ## Depend on * [Platform.Numbers](https://github.com/linksplatform/Numbers) From 2555c3ebde12d289c78cd352d21b75a18b815532 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 11:27:18 +0000 Subject: [PATCH 26/46] Resolve the Codacy findings of the pull request - The test trees expose Root by reference and their counters as properties instead of public fields. - The list views derive circularity from their base methods instead of an unused member in every list. - The experiment scripts have docstrings in the layout pydocstyle expects. - The README wraps its prose at 80 columns and lists the trees instead of a table with long rows. --- README.md | 90 +++++++++++-------- .../DoublyLinkedLists.cpp | 26 +++--- .../RecursionlessSizeBalancedTree.cs | 14 ++- .../SizeBalancedTree.cs | 14 ++- .../SizedAndThreadedAVLBalancedTree.cs | 14 ++- experiments/detect_rotations_in_setters.py | 5 +- experiments/remove_root_guard.py | 13 ++- 7 files changed, 113 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index b1691ac..9663d35 100644 --- a/README.md +++ b/README.md @@ -10,16 +10,23 @@ LinksPlatform's Platform.Collections.Methods Class Library. -Namespaces: [Platform.Collections.Methods.Lists](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Lists.html), [Platform.Collections.Methods.Trees](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Trees.html) +Namespaces: +[Platform.Collections.Methods.Lists](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Lists.html), +[Platform.Collections.Methods.Trees](https://linksplatform.github.io/Collections.Methods/csharp/api/Platform.Collections.Methods.Trees.html) Forked from: [Konard/LinksPlatform/Platform/Platform.Data.Core/Collections](https://github.com/Konard/LinksPlatform/tree/b6866f278712c317b4c895e27e49f2d0b3fe561f/Platform/Platform.Data.Core/Collections) NuGet package: [Platform.Collections.Methods](https://www.nuget.org/packages/Platform.Collections.Methods) ## [Documentation](https://linksplatform.github.io/Collections.Methods) -[PDF file](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.pdf) with code for e-readers. +[PDF file](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.pdf) +with code for e-readers. -The [C# workflow](https://github.com/linksplatform/Collections.Methods/actions/workflows/csharp.yml) builds the DocFX site on every pull request and publishes it from `main`, including the [API documentation PDF](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.Documentation.pdf). +The +[C# workflow](https://github.com/linksplatform/Collections.Methods/actions/workflows/csharp.yml) +builds the DocFX site on every pull request and publishes it from `main`, +including the +[API documentation PDF](https://linksplatform.github.io/Collections.Methods/csharp/Platform.Collections.Methods.Documentation.pdf). ## Depend on * [Platform.Numbers](https://github.com/linksplatform/Numbers) @@ -29,11 +36,15 @@ The [C# workflow](https://github.com/linksplatform/Collections.Methods/actions/w ## Trees -| Tree | Balancing | Height | -|-|-|-| -| `SizeBalancedTreeMethods` | Chen's recursive *Maintain* on the way back from every attach and detach | at most the AVL bound 1.44 log₂(n + 2) | -| `RecursionlessSizeBalancedTreeMethods` | the same rotations as the recursive tree, without recursion: the attach path is remembered while descending and only its nodes are maintained | identical trees to `SizeBalancedTreeMethods` | -| `SizedAndThreadedAVLBalancedTreeMethods` | AVL balance factors, threaded leaves | at most the AVL bound | +* `SizeBalancedTreeMethods` runs Chen's recursive *Maintain* on the way back + from every attach and detach. Its height is at most the AVL bound + 1.44 log₂(n + 2). +* `RecursionlessSizeBalancedTreeMethods` makes the same rotations as the + recursive tree, without recursion: the attach path is remembered while + descending and only its nodes are maintained. It builds identical trees to + `SizeBalancedTreeMethods`. +* `SizedAndThreadedAVLBalancedTreeMethods` keeps AVL balance factors and + threaded leaves. Its height is at most the AVL bound. Every node `t` of a size balanced tree satisfies Chen's property: `size(t.left) >= size(t.right.left), size(t.right.right)` and @@ -44,31 +55,34 @@ detach passes more levels than any size balanced tree of their size has. ## Tests The C# and C++ tests run on every pull request and on `main` -([csharp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/csharp.yml), [Test cpp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/cpp-test.yml)). They check -after every attach and detach that the trees keep their sizes, order and -balance property, that the height stays within the AVL bound, that the recursive -and the recursionless tree build identical trees with the minimum number of -rotations, and that every line of the libraries is executed (100% line coverage -for C# and C++). They also run with `ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION`, which -makes every tree validate itself after each change: +([csharp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/csharp.yml), +[Test cpp](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/cpp-test.yml)). +They check after every attach and detach that the trees keep their sizes, order +and balance property, that the height stays within the AVL bound, that the +recursive and the recursionless tree build identical trees with the minimum +number of rotations, and that every line of the libraries is executed (100% +line coverage for C# and C++). They also run with +`ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION`, which makes every tree validate itself +after each change: ```sh cd csharp && dotnet test -c Release -p:TreeValidation=true TREE_VALIDATION=1 BUILD_TYPE=Debug SANITIZERS='address;undefined' cpp/build-and-test.sh ``` -The trees pay nothing for being inspected. The library has no counters, -logs or hooks for tests: the test trees inherit from the library trees and count -rotations and size reads in the node accessors (`GetSize`, `SetLeft`, `SetRight`) -that every tree implements anyway. `LeftRotate` and `RightRotate` stay non-virtual in C#, and in C++ -the test trees shadow them through CRTP, which compiles to direct calls. The -validation mode is a compile-time switch, so it costs nothing when it is off. +The trees pay nothing for being inspected. The library has no counters, logs +or hooks for tests: the test trees inherit from the library trees and count +rotations and size reads in the node accessors (`GetSize`, `SetLeft`, +`SetRight`) that every tree implements anyway. `LeftRotate` and `RightRotate` +stay non-virtual in C#, and in C++ the test trees shadow them through CRTP, +which compiles to direct calls. The validation mode is a compile-time switch, +so it costs nothing when it is off. ## Benchmarks -Benchmarks are noisy on shared runners, so they run only on request: -Actions > [Benchmarks](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/benchmarks.yml) > Run workflow. Results are in -the run summary and its artifacts. Locally: +Benchmarks are noisy on shared runners, so they run only on request: Actions > +[Benchmarks](https://github.com/linksplatform/Collections.Methods/blob/main/.github/workflows/benchmarks.yml) +\> Run workflow. Results are in the run summary and its artifacts. Locally: ```sh cd csharp && dotnet run -c Release --project Platform.Collections.Methods.Benchmarks @@ -77,16 +91,22 @@ BENCHMARKS=1 cpp/build-and-test.sh && cpp/build/bin/Platform.Collections.Methods ## Releasing -A version bump in `csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj` -or `cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec` merged to `main` publishes the package to -nuget.org and creates a GitHub release, after the tests passed. Publishing uses -[trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) first: +A version bump in +`csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj` or +`cpp/Platform.Collections.Methods/Platform.Collections.Methods.TemplateLibrary.nuspec` +merged to `main` publishes the package to nuget.org and creates a GitHub +release, after the tests passed. Publishing uses +[trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing) +first: 1. On nuget.org, add trusted publishing policies for the repository - `linksplatform/Collections.Methods` with the workflows `csharp.yml` and `deploy-cpp.yml`. -2. Set the repository variable `NUGET_USER` to the nuget.org user that owns the policies. - -Without `NUGET_USER` the workflows fall back to the `NUGET_TOKEN` secret (a nuget.org API -key with push scope). A release preflight fails early with an explanation when -neither works. Dependabot pull requests are merged automatically with the -`DEPENDABOT_AUTO_MERGE_TOKEN` secret once "Allow auto-merge" is enabled. + `linksplatform/Collections.Methods` with the workflows `csharp.yml` and + `deploy-cpp.yml`. +2. Set the repository variable `NUGET_USER` to the nuget.org user that owns + the policies. + +Without `NUGET_USER` the workflows fall back to the `NUGET_TOKEN` secret (a +nuget.org API key with push scope). A release preflight fails early with an +explanation when neither works. Dependabot pull requests are merged +automatically with the `DEPENDABOT_AUTO_MERGE_TOKEN` secret once "Allow +auto-merge" is enabled. diff --git a/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp index 6e0d357..3f71ba7 100644 --- a/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp +++ b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp @@ -12,9 +12,6 @@ namespace Platform::Collections::Methods::Tests template class AbsoluteCircularDoublyLinkedList : public Platform::Collections::Methods::Lists::AbsoluteCircularDoublyLinkedListMethods, std::uint32_t> { - - public: static constexpr bool IsCircular = true; - public: ListLinks Links; public: std::uint32_t First = 0; public: std::uint32_t Last = 0; @@ -43,9 +40,6 @@ namespace Platform::Collections::Methods::Tests template class AbsoluteOpenDoublyLinkedList : public Platform::Collections::Methods::Lists::AbsoluteOpenDoublyLinkedListMethods, std::uint32_t> { - - public: static constexpr bool IsCircular = false; - public: ListLinks Links; public: std::uint32_t First = 0; public: std::uint32_t Last = 0; @@ -78,9 +72,6 @@ namespace Platform::Collections::Methods::Tests /// template class RelativeCircularDoublyLinkedList : public Platform::Collections::Methods::Lists::RelativeCircularDoublyLinkedListMethods, std::uint32_t> { - - public: static constexpr bool IsCircular = true; - public: ListLinks Links; public: std::uint32_t First[Heads] = { 0 }; public: std::uint32_t Last[Heads] = { 0 }; @@ -113,9 +104,6 @@ namespace Platform::Collections::Methods::Tests /// template class RelativeOpenDoublyLinkedList : public Platform::Collections::Methods::Lists::RelativeOpenDoublyLinkedListMethods, std::uint32_t> { - - public: static constexpr bool IsCircular = false; - public: ListLinks Links; public: std::uint32_t First[Heads] = { 0 }; public: std::uint32_t Last[Heads] = { 0 }; @@ -151,7 +139,11 @@ namespace Platform::Collections::Methods::Tests public: TList* List; public: std::uint32_t Head; - public: bool IsCircular() const { return TList::IsCircular; } + // A list is circular exactly when it is built on one of the circular list methods. + public: static constexpr bool Circular = std::is_base_of_v, TList> + || std::is_base_of_v, TList>; + + public: bool IsCircular() const { return Circular; } public: std::uint32_t First() const { if constexpr (Relative) { return List->First[Head]; } else { return List->First; } } @@ -174,3 +166,11 @@ namespace Platform::Collections::Methods::Tests public: void Detach(std::uint32_t element) { if constexpr (Relative) { List->Detach(Head, element); } else { List->Detach(element); } } }; } + +namespace Platform::Collections::Methods::Tests +{ + static_assert(ListView, false>::Circular); + static_assert(!ListView, false>::Circular); + static_assert(ListView, true>::Circular); + static_assert(!ListView, true>::Circular); +} diff --git a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs index 599e4be..63e0080 100644 --- a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs @@ -19,7 +19,13 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - public TElement Root = TElement.Zero; + private TElement _root = TElement.Zero; + + /// + /// The root of the tree, by reference, so attach and detach can replace it. + /// Корень дерева по ссылке, чтобы присоединение и отсоединение могли его заменить. + /// + public ref TElement Root => ref _root; public TElement Count => GetSizeOrZero(Root); @@ -33,19 +39,19 @@ private struct TreeElement /// The number of rotations made since the counter was last reset. /// Число поворотов, сделанных с момента последнего сброса счётчика. /// - public long Rotations; + public long Rotations { get; set; } /// /// The number of node sizes read since the counter was last reset. /// Число прочитанных размеров узлов с момента последнего сброса счётчика. /// - public long SizeReads; + public long SizeReads { get; set; } /// /// When set, every rotation is recorded as "L" or "R" followed by the node that moved down. /// Если задан, каждый поворот записывается как "L" или "R" и узел, который опустился вниз. /// - public List? RotationLog; + public List? RotationLog { get; set; } public TElement NextOf(TElement node) => GetNext(node); diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs index eca123d..12390ad 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs @@ -19,7 +19,13 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - public TElement Root = TElement.Zero; + private TElement _root = TElement.Zero; + + /// + /// The root of the tree, by reference, so attach and detach can replace it. + /// Корень дерева по ссылке, чтобы присоединение и отсоединение могли его заменить. + /// + public ref TElement Root => ref _root; public TElement Count => GetSizeOrZero(Root); @@ -33,19 +39,19 @@ private struct TreeElement /// The number of rotations made since the counter was last reset. /// Число поворотов, сделанных с момента последнего сброса счётчика. /// - public long Rotations; + public long Rotations { get; set; } /// /// The number of node sizes read since the counter was last reset. /// Число прочитанных размеров узлов с момента последнего сброса счётчика. /// - public long SizeReads; + public long SizeReads { get; set; } /// /// When set, every rotation is recorded as "L" or "R" followed by the node that moved down. /// Если задан, каждый поворот записывается как "L" или "R" и узел, который опустился вниз. /// - public List? RotationLog; + public List? RotationLog { get; set; } public TElement NextOf(TElement node) => GetNext(node); diff --git a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs index f9ac6e6..4ac0643 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs @@ -22,7 +22,13 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - public TElement Root = TElement.Zero; + private TElement _root = TElement.Zero; + + /// + /// The root of the tree, by reference, so attach and detach can replace it. + /// Корень дерева по ссылке, чтобы присоединение и отсоединение могли его заменить. + /// + public ref TElement Root => ref _root; public TElement Count => GetSizeOrZero(Root); @@ -36,19 +42,19 @@ private struct TreeElement /// The number of rotations made since the counter was last reset. /// Число поворотов, сделанных с момента последнего сброса счётчика. ///
- public long Rotations; + public long Rotations { get; set; } /// /// The number of node sizes read since the counter was last reset. /// Число прочитанных размеров узлов с момента последнего сброса счётчика. /// - public long SizeReads; + public long SizeReads { get; set; } /// /// When set, every rotation is recorded as "L" or "R" followed by the node that moved down. /// Если задан, каждый поворот записывается как "L" или "R" и узел, который опустился вниз. /// - public List? RotationLog; + public List? RotationLog { get; set; } public TElement NextOf(TElement node) => GetNext(node); diff --git a/experiments/detect_rotations_in_setters.py b/experiments/detect_rotations_in_setters.py index 9e356e9..76fb047 100644 --- a/experiments/detect_rotations_in_setters.py +++ b/experiments/detect_rotations_in_setters.py @@ -1,4 +1,7 @@ -"""Move rotation counting of the C# test trees from LeftRotate/RightRotate overrides into SetLeft/SetRight. +""" +Move rotation counting of the C# test trees from rotation overrides into the link setters. + +The counting moves from LeftRotate/RightRotate overrides into SetLeft/SetRight. With --cross-check the overrides stay and assert that the setters detected exactly the rotation the override saw, and that the setters detect nothing outside rotations (run the tests, then rerun without it). diff --git a/experiments/remove_root_guard.py b/experiments/remove_root_guard.py index 6279aba..956e493 100644 --- a/experiments/remove_root_guard.py +++ b/experiments/remove_root_guard.py @@ -1,8 +1,17 @@ -"""One-off refactoring helper: removes the unreachable `root != 0` guard of LeftMaintain/RightMaintain -(the position is never empty: it is on a path or a child of a node that was just rotated) and dedents the body.""" +""" +Remove the unreachable `root != 0` guard of LeftMaintain/RightMaintain. + +A one-off refactoring helper. The position is never empty: it is on a path or a +child of a node that was just rotated. The helper also dedents the guarded body. +""" import re, sys def rewrite(path, guard): + """ + Drop the guard line and its braces from both Maintain methods of a file. + + The body inside the braces is dedented by one level and the BOM is kept. + """ lines = open(path, encoding='utf-8-sig').read().split('\n') had_bom = open(path, 'rb').read(3) == b'\xef\xbb\xbf' out, i = [], 0 From fc26de0011fbd3349a2478995bf81cdbb0a16416 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 11:38:00 +0000 Subject: [PATCH 27/46] Resolve the remaining Codacy findings - The test trees keep their root in a readonly one-element array, so Root still returns it by reference. - The list views read the lists through their getters, which cppcheck does not mistake for returning an array address. - The experiment scripts use one-line docstrings, which satisfy both D212 and D213 that Codacy enables. - The README list markers are followed by one space (MD030). --- README.md | 18 +++++++++--------- .../DoublyLinkedLists.cpp | 6 +++--- .../RecursionlessSizeBalancedTree.cs | 5 +++-- .../SizeBalancedTree.cs | 5 +++-- .../SizedAndThreadedAVLBalancedTree.cs | 5 +++-- experiments/detect_rotations_in_setters.py | 14 ++++++-------- experiments/remove_root_guard.py | 15 ++++----------- 7 files changed, 31 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 9663d35..414c88d 100644 --- a/README.md +++ b/README.md @@ -36,15 +36,15 @@ including the ## Trees -* `SizeBalancedTreeMethods` runs Chen's recursive *Maintain* on the way back - from every attach and detach. Its height is at most the AVL bound - 1.44 log₂(n + 2). -* `RecursionlessSizeBalancedTreeMethods` makes the same rotations as the - recursive tree, without recursion: the attach path is remembered while - descending and only its nodes are maintained. It builds identical trees to - `SizeBalancedTreeMethods`. -* `SizedAndThreadedAVLBalancedTreeMethods` keeps AVL balance factors and - threaded leaves. Its height is at most the AVL bound. +* `SizeBalancedTreeMethods` runs Chen's recursive *Maintain* on the way back + from every attach and detach. Its height is at most the AVL bound + 1.44 log₂(n + 2). +* `RecursionlessSizeBalancedTreeMethods` makes the same rotations as the + recursive tree, without recursion: the attach path is remembered while + descending and only its nodes are maintained. It builds identical trees to + `SizeBalancedTreeMethods`. +* `SizedAndThreadedAVLBalancedTreeMethods` keeps AVL balance factors and + threaded leaves. Its height is at most the AVL bound. Every node `t` of a size balanced tree satisfies Chen's property: `size(t.left) >= size(t.right.left), size(t.right.right)` and diff --git a/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp index 3f71ba7..c48992e 100644 --- a/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp +++ b/cpp/Platform.Collections.Methods.Tests/DoublyLinkedLists.cpp @@ -145,11 +145,11 @@ namespace Platform::Collections::Methods::Tests public: bool IsCircular() const { return Circular; } - public: std::uint32_t First() const { if constexpr (Relative) { return List->First[Head]; } else { return List->First; } } + public: std::uint32_t First() const { if constexpr (Relative) { return List->GetFirst(Head); } else { return List->GetFirst(); } } - public: std::uint32_t Last() const { if constexpr (Relative) { return List->Last[Head]; } else { return List->Last; } } + public: std::uint32_t Last() const { if constexpr (Relative) { return List->GetLast(Head); } else { return List->GetLast(); } } - public: std::uint32_t Size() const { if constexpr (Relative) { return List->Size[Head]; } else { return List->Size; } } + public: std::uint32_t Size() const { if constexpr (Relative) { return List->GetSize(Head); } else { return List->GetSize(); } } public: std::uint32_t PreviousOf(std::uint32_t element) const { return List->Links.Previous[element]; } diff --git a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs index 63e0080..9dd446b 100644 --- a/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/RecursionlessSizeBalancedTree.cs @@ -19,13 +19,14 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - private TElement _root = TElement.Zero; + // A one-element array: the field stays readonly while the root it holds changes. + private readonly TElement[] _root = { TElement.Zero }; /// /// The root of the tree, by reference, so attach and detach can replace it. /// Корень дерева по ссылке, чтобы присоединение и отсоединение могли его заменить. /// - public ref TElement Root => ref _root; + public ref TElement Root => ref _root[0]; public TElement Count => GetSizeOrZero(Root); diff --git a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs index 12390ad..ca9b6a1 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizeBalancedTree.cs @@ -19,13 +19,14 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - private TElement _root = TElement.Zero; + // A one-element array: the field stays readonly while the root it holds changes. + private readonly TElement[] _root = { TElement.Zero }; /// /// The root of the tree, by reference, so attach and detach can replace it. /// Корень дерева по ссылке, чтобы присоединение и отсоединение могли его заменить. /// - public ref TElement Root => ref _root; + public ref TElement Root => ref _root[0]; public TElement Count => GetSizeOrZero(Root); diff --git a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs index 4ac0643..5613301 100644 --- a/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs +++ b/csharp/Platform.Collections.Methods.Tests/SizedAndThreadedAVLBalancedTree.cs @@ -22,13 +22,14 @@ private struct TreeElement private readonly TreeElement[] _elements; private TElement _allocated; - private TElement _root = TElement.Zero; + // A one-element array: the field stays readonly while the root it holds changes. + private readonly TElement[] _root = { TElement.Zero }; /// /// The root of the tree, by reference, so attach and detach can replace it. /// Корень дерева по ссылке, чтобы присоединение и отсоединение могли его заменить. /// - public ref TElement Root => ref _root; + public ref TElement Root => ref _root[0]; public TElement Count => GetSizeOrZero(Root); diff --git a/experiments/detect_rotations_in_setters.py b/experiments/detect_rotations_in_setters.py index 76fb047..11e108e 100644 --- a/experiments/detect_rotations_in_setters.py +++ b/experiments/detect_rotations_in_setters.py @@ -1,11 +1,9 @@ -""" -Move rotation counting of the C# test trees from rotation overrides into the link setters. - -The counting moves from LeftRotate/RightRotate overrides into SetLeft/SetRight. - -With --cross-check the overrides stay and assert that the setters detected exactly the rotation the -override saw, and that the setters detect nothing outside rotations (run the tests, then rerun without it). -""" +"""Move rotation counting of the C# test trees into the link setters.""" +# The counting moves from LeftRotate/RightRotate overrides into SetLeft/SetRight. +# +# With --cross-check the overrides stay and assert that the setters detected +# exactly the rotation the override saw, and that the setters detect nothing +# outside rotations (run the tests, then rerun without it). import re import sys diff --git a/experiments/remove_root_guard.py b/experiments/remove_root_guard.py index 956e493..cadb53b 100644 --- a/experiments/remove_root_guard.py +++ b/experiments/remove_root_guard.py @@ -1,17 +1,10 @@ -""" -Remove the unreachable `root != 0` guard of LeftMaintain/RightMaintain. - -A one-off refactoring helper. The position is never empty: it is on a path or a -child of a node that was just rotated. The helper also dedents the guarded body. -""" +"""Remove the unreachable `root != 0` guard of LeftMaintain/RightMaintain.""" +# A one-off refactoring helper. The position is never empty: it is on a path or +# a child of a node that was just rotated. The helper also dedents the body. import re, sys def rewrite(path, guard): - """ - Drop the guard line and its braces from both Maintain methods of a file. - - The body inside the braces is dedented by one level and the BOM is kept. - """ + """Drop the guard and its braces from the Maintain methods, keeping the BOM.""" lines = open(path, encoding='utf-8-sig').read().split('\n') had_bom = open(path, 'rb').read(3) == b'\xef\xbb\xbf' out, i = [], 0 From 5e7db266b0859f016f0f505c7b1687f8ffed3e79 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 16:24:20 +0000 Subject: [PATCH 28/46] Expose the tree internals to inheritors and let the AVL tree reuse its path buffer The tree methods keep their helpers protected instead of private, so an inheritor can observe them without the plain tree paying anything for it. The C# AVL tree allocated a new path array on every attach and detach; it now reuses one buffer per tree, which TreeAllocationTests proves by measuring zero allocated bytes for every tree. --- .../RecursionlessSizeBalancedTreeMethods.h | 22 +++---- .../Trees/SizeBalancedTreeMethods.h | 8 +-- .../SizedAndThreadedAVLBalancedTreeMethods.h | 6 +- .../Trees/SizedBinaryTreeMethodsBase.h | 2 +- .../Platform.Collections.Methods.Tests.csproj | 6 +- .../TreeAllocationTests.cs | 65 +++++++++++++++++++ .../RecursionlessSizeBalancedTreeMethods.cs | 26 ++++---- .../Trees/SizeBalancedTreeMethods.cs | 8 +-- .../SizedAndThreadedAVLBalancedTreeMethods.cs | 19 ++++-- .../Trees/SizedBinaryTreeMethodsBase.cs | 2 +- 10 files changed, 119 insertions(+), 45 deletions(-) create mode 100644 csharp/Platform.Collections.Methods.Tests/TreeAllocationTests.cs diff --git a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h index d7b5824..e43f668 100644 --- a/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.h @@ -11,15 +11,15 @@ /// A step of the path from the root: the parent (0 for the root position), the side of the child and the side that may become too heavy. /// Шаг пути от корня: родитель (0 для позиции корня), сторона потомка и сторона, которая может стать слишком тяжёлой. ///
- private: struct Step + protected: struct Step { TElement Parent; bool IsLeft; bool LeftMayBeHeavy; }; - private: std::vector _path; - private: std::vector _maintenance; + protected: std::vector _path; + protected: std::vector _maintenance; /// /// The same algorithm as SizeBalancedTreeMethods, with explicit stacks instead of recursion, so both build trees of identical shape. The attach also remembers the direction it took at every node of the path, so on the way back up it compares only the size of the grandchild that grew, until a rotation changes the children (see MaintainAttachPath). @@ -133,7 +133,7 @@ this->RebuildIfDeeperThanBalanced(root, passed, size); } - private: void RebuildIfDeeperThanBalanced(TElement* root, int passed, TElement size) + protected: void RebuildIfDeeperThanBalanced(TElement* root, int passed, TElement size) { if (passed > base::GetMaximumBalancedHeight(size)) { @@ -142,7 +142,7 @@ } } - private: TElement* Position(TElement* root, TElement parent, bool isLeft) + protected: TElement* Position(TElement* root, TElement parent, bool isLeft) { if (parent == 0) { @@ -151,7 +151,7 @@ return isLeft ? this->object().GetLeftReference(parent) : this->object().GetRightReference(parent); } - private: void MaintainPath(TElement* root, std::size_t length) + protected: void MaintainPath(TElement* root, std::size_t length) { while (_path.size() > length) { @@ -169,7 +169,7 @@ /// Before the attach the tree was size balanced, and the attach made only one grandchild of each position on the path larger: the one on the path. So while the child on the path has not been rotated, Maintain in the paper can rotate only because of that grandchild, and checking only it gives the same rotations with half of the size comparisons. After a rotation of the child its children are other nodes, so the position is checked fully. The parent of the attached node is skipped: the attached node has no children, so it cannot be too heavy there. /// До присоединения дерево было сбалансировано по размеру, а присоединение увеличило только одного внука каждой позиции пути: того, что на пути. Поэтому, пока потомок на пути не повёрнут, Maintain из статьи может сделать поворот только из-за этого внука, и проверка только его даёт те же повороты за половину сравнений размеров. После поворота потомка его потомками становятся другие узлы, поэтому позиция проверяется полностью. Родитель присоединённого узла пропускается: у присоединённого узла нет потомков, поэтому он не может быть там слишком тяжёлым. /// - private: void MaintainAttachPath(TElement* root) + protected: void MaintainAttachPath(TElement* root) { auto childRotated = false; for (auto i = static_cast(_path.size()) - 2; i >= 0; i--) @@ -190,7 +190,7 @@ /// Restores the size balanced tree properties at the position (Maintain in the paper). /// Восстанавливает свойства дерева, сбалансированного по размеру, в позиции (Maintain в статье). ///
- private: void Maintain(TElement* root, Step step) + protected: void Maintain(TElement* root, Step step) { if (this->Rotate(this->Position(root, step.Parent, step.IsLeft), step.LeftMayBeHeavy)) { @@ -202,7 +202,7 @@ /// Finishes Maintain in the paper after the subtree at the position was rotated. The pending steps run in the same order as the recursive calls of SizeBalancedTreeMethods. /// Завершает Maintain из статьи после того, как поддерево в позиции было повёрнуто. Отложенные шаги выполняются в том же порядке, что и рекурсивные вызовы в SizeBalancedTreeMethods. ///
- private: void MaintainRotated(TElement* root, Step step) + protected: void MaintainRotated(TElement* root, Step step) { _maintenance.clear(); while (true) @@ -230,7 +230,7 @@ /// Rotates the subtree at the position, which is not empty and whose child on the side of the attach is not empty, if the grandchild on the side of the attach is heavier than the other child. /// Поворачивает поддерево в позиции, которая не пуста и потомок которой на стороне присоединения не пуст, если внук на стороне присоединения тяжелее другого потомка. /// - private: bool RotateIfGrandchildIsHeavy(TElement* root, bool leftMayBeHeavy, bool grandchildIsLeft) + protected: bool RotateIfGrandchildIsHeavy(TElement* root, bool leftMayBeHeavy, bool grandchildIsLeft) { if (leftMayBeHeavy) { @@ -275,7 +275,7 @@ /// Rotates the subtree at the position, which is not empty (positions on a path and children of a rotated node always hold nodes), if the specified side is too heavy. /// Поворачивает поддерево в позиции, которая не пуста (позиции на пути и потомки повёрнутого узла всегда содержат узлы), если указанная сторона слишком тяжёлая. /// - private: bool Rotate(TElement* root, bool leftMayBeHeavy) + protected: bool Rotate(TElement* root, bool leftMayBeHeavy) { if (leftMayBeHeavy) { diff --git a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h index 18ccb18..8cfa290 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.h @@ -22,7 +22,7 @@ } } - private: int AttachCounting(TElement* root, TElement node) + protected: int AttachCounting(TElement* root, TElement node) { if (*root == 0) { @@ -55,7 +55,7 @@ } } - private: int DetachCounting(TElement* root, TElement node) + protected: int DetachCounting(TElement* root, TElement node) { if (*root == 0) { @@ -121,7 +121,7 @@ // Maintain(t, false) in the paper: the left side of the subtree may have become too heavy. // The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. - private: void LeftMaintain(TElement* root) + protected: void LeftMaintain(TElement* root) { auto rootLeftNode = this->object().GetLeft(*root); if (rootLeftNode != 0) @@ -154,7 +154,7 @@ // Maintain(t, true) in the paper: the right side of the subtree may have become too heavy. // The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. - private: void RightMaintain(TElement* root) + protected: void RightMaintain(TElement* root) { auto rootRightNode = this->object().GetRight(*root); if (rootRightNode != 0) diff --git a/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h b/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h index 4481c66..9a6d376 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.h @@ -6,7 +6,7 @@ public: using base = SizedBinaryTreeMethodsBase; friend base; - private: inline static const std::int32_t _maxPath = 11 * sizeof(TElement) + 4; + protected: inline static const std::int32_t _maxPath = 11 * sizeof(TElement) + 4; protected: TElement GetRightest(TElement current) { @@ -162,7 +162,7 @@ } } - private: TElement Balance(TElement node) + protected: TElement Balance(TElement node) { { auto rootBalance = this->object().GetBalance(node); @@ -303,7 +303,7 @@ } // Undoes the size changes that the search made on the path, so that a failed attach or detach leaves the tree intact. - private: void UndoSizeChanges(const TElement* path, std::int32_t pathPosition, bool sizesWereIncremented) + protected: void UndoSizeChanges(const TElement* path, std::int32_t pathPosition, bool sizesWereIncremented) { while (--pathPosition > 0) { diff --git a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h index 1db22f7..dfafa3c 100644 --- a/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h +++ b/cpp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.h @@ -122,7 +122,7 @@ } } - private: void Fold(TElement* root, std::uint64_t rotations) + protected: void Fold(TElement* root, std::uint64_t rotations) { auto* position = root; for (std::uint64_t i = 0; i < rotations; i++) diff --git a/csharp/Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj b/csharp/Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj index c46bbc1..a35fd38 100644 --- a/csharp/Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj +++ b/csharp/Platform.Collections.Methods.Tests/Platform.Collections.Methods.Tests.csproj @@ -18,9 +18,13 @@ + + + $(DefineConstants);ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION + + - diff --git a/csharp/Platform.Collections.Methods.Tests/TreeAllocationTests.cs b/csharp/Platform.Collections.Methods.Tests/TreeAllocationTests.cs new file mode 100644 index 0000000..68354f3 --- /dev/null +++ b/csharp/Platform.Collections.Methods.Tests/TreeAllocationTests.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using Platform.Collections.Methods.Trees; +using Xunit; + +namespace Platform.Collections.Methods.Tests +{ + /// + /// Checks that the trees allocate no managed memory while they attach and detach nodes. + /// Проверяет, что деревья не выделяют управляемую память, пока присоединяют и отсоединяют узлы. + /// + public static class TreeAllocationTests + { + private const int Nodes = 1000; + + public static IEnumerable Trees => new[] + { + new object[] { "SizeBalancedTree" }, + new object[] { "RecursionlessSizeBalancedTree" }, + new object[] { "SizedAndThreadedAVLBalancedTree" }, + }; + +#if ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION + [Theory(Skip = "The validation prints and checks every tree, which allocates.")] +#else + [Theory] +#endif + [MemberData(nameof(Trees))] + public static void AttachAndDetachAllocateNothing(string name) + { + var tree = Create(name); + Assert.Equal(0u, AttachAndDetachAll(tree)); + var before = GC.GetAllocatedBytesForCurrentThread(); + var root = AttachAndDetachAll(tree); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.Equal(0u, root); + Assert.Equal(0L, allocated); + } + + private static SizedBinaryTreeMethodsBase Create(string name) => name switch + { + "SizeBalancedTree" => new SizeBalancedTree(Nodes + 1), + "RecursionlessSizeBalancedTree" => new RecursionlessSizeBalancedTree(Nodes + 1), + _ => new SizedAndThreadedAVLBalancedTree(Nodes + 1), + }; + + // Attaches the nodes 1..Nodes and detaches them again; returns the root, which is zero again. + private static uint AttachAndDetachAll(SizedBinaryTreeMethodsBase tree) + { + var root = 0u; + for (var node = 1u; node <= Nodes; node++) + { + tree.Attach(ref root, Scatter(node)); + } + for (var node = 1u; node <= Nodes; node++) + { + tree.Detach(ref root, Scatter(node)); + } + return root; + } + + // 7 and 1000 are coprime, so the nodes come in a scattered but complete order. + private static uint Scatter(uint node) => node * 7 % Nodes + 1; + } +} diff --git a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs index ee0ad60..d03241b 100644 --- a/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/RecursionlessSizeBalancedTreeMethods.cs @@ -52,12 +52,12 @@ public abstract class RecursionlessSizeBalancedTreeMethods : SizedBina /// Whether the left side of the subtree at the position may have become too heavy; otherwise the right side. /// Могла ли левая сторона поддерева в этой позиции стать слишком тяжёлой; иначе правая сторона. /// - private readonly record struct Step(TElement Parent, bool IsLeft, bool LeftMayBeHeavy); + protected readonly record struct Step(TElement Parent, bool IsLeft, bool LeftMayBeHeavy); - private Step[] _path = new Step[64]; - private int _pathLength; + protected Step[] _path = new Step[64]; + protected int _pathLength; // Usually only a few Maintain steps are pending at once (at most 11 in the tests), so this stack starts small and grows when needed. - private Step[] _maintenance = new Step[8]; + protected Step[] _maintenance = new Step[8]; /// /// @@ -213,7 +213,7 @@ protected override void DetachCore(ref TElement root, TElement node) /// Такие пути есть только у деревьев, построенных другим кодом, например старыми версиями этого класса. /// /// - private void RebuildIfDeeperThanBalanced(ref TElement root, int passed, TElement size) + protected void RebuildIfDeeperThanBalanced(ref TElement root, int passed, TElement size) { if (passed > GetMaximumBalancedHeight(size)) { @@ -225,7 +225,7 @@ private void RebuildIfDeeperThanBalanced(ref TElement root, int passed, TElement /// Returns the reference to the specified position: the root reference or the child reference of the parent. /// Возвращает ссылку на указанную позицию: ссылку на корень или ссылку на потомка родителя. /// - private ref TElement Position(ref TElement root, TElement parent, bool isLeft) + protected ref TElement Position(ref TElement root, TElement parent, bool isLeft) { if (parent == TElement.Zero) { @@ -234,7 +234,7 @@ private ref TElement Position(ref TElement root, TElement parent, bool isLeft) return ref isLeft ? ref GetLeftReference(parent) : ref GetRightReference(parent); } - private void PushPath(Step step) + protected void PushPath(Step step) { if (_pathLength == _path.Length) { @@ -247,7 +247,7 @@ private void PushPath(Step step) /// Maintains the positions of the path from the deepest one up to (but not including) the specified path length. /// Поддерживает позиции пути, начиная с самой глубокой и до указанной длины пути (не включая её). /// - private void MaintainPath(ref TElement root, int length) + protected void MaintainPath(ref TElement root, int length) { while (_pathLength > length) { @@ -279,7 +279,7 @@ private void MaintainPath(ref TElement root, int length) /// Родитель присоединённого узла пропускается: у присоединённого узла нет потомков, поэтому он не может быть там слишком тяжёлым. ///
/// - private void MaintainAttachPath(ref TElement root) + protected void MaintainAttachPath(ref TElement root) { var childRotated = false; for (var i = _pathLength - 2; i >= 0; i--) @@ -304,7 +304,7 @@ private void MaintainAttachPath(ref TElement root) /// Восстанавливает свойства дерева, сбалансированного по размеру, в позиции (Maintain в статье). /// /// - private void Maintain(ref TElement root, Step step) + protected void Maintain(ref TElement root, Step step) { if (Rotate(ref Position(ref root, step.Parent, step.IsLeft), step.LeftMayBeHeavy)) { @@ -322,7 +322,7 @@ private void Maintain(ref TElement root, Step step) /// Отложенные шаги выполняются в том же порядке, что и рекурсивные вызовы в . /// /// - private void MaintainRotated(ref TElement root, Step step) + protected void MaintainRotated(ref TElement root, Step step) { var count = 0; while (true) @@ -369,7 +369,7 @@ private void MaintainRotated(ref TElement root, Step step) /// Whether the subtree was rotated. /// Было ли поддерево повёрнуто. /// - private bool RotateIfGrandchildIsHeavy(ref TElement root, bool leftMayBeHeavy, bool grandchildIsLeft) + protected bool RotateIfGrandchildIsHeavy(ref TElement root, bool leftMayBeHeavy, bool grandchildIsLeft) { if (leftMayBeHeavy) { @@ -426,7 +426,7 @@ private bool RotateIfGrandchildIsHeavy(ref TElement root, bool leftMayBeHeavy, b /// Whether the subtree was rotated. /// Было ли поддерево повёрнуто. /// - private bool Rotate(ref TElement root, bool leftMayBeHeavy) + protected bool Rotate(ref TElement root, bool leftMayBeHeavy) { if (leftMayBeHeavy) { diff --git a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs index 87f3d34..586b9bf 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizeBalancedTreeMethods.cs @@ -57,7 +57,7 @@ protected override void AttachCore(ref TElement root, TElement node) } /// The number of nodes of the tree that the path passed before the node was attached. - private int AttachCounting(ref TElement root, TElement node) + protected int AttachCounting(ref TElement root, TElement node) { if (root == TElement.Zero) { @@ -111,7 +111,7 @@ protected override void DetachCore(ref TElement root, TElement node) } /// The number of nodes that the paths to the node and to its replacement passed. - private int DetachCounting(ref TElement root, TElement node) + protected int DetachCounting(ref TElement root, TElement node) { if (root == TElement.Zero) { @@ -187,7 +187,7 @@ private int DetachCounting(ref TElement root, TElement node) /// The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. /// Поддерево никогда не пусто: оно лежит на пути операции или является потомком узла, который только что поднял поворот. /// - private void LeftMaintain(ref TElement root) + protected void LeftMaintain(ref TElement root) { var rootLeftNode = GetLeft(root); if (rootLeftNode != TElement.Zero) @@ -231,7 +231,7 @@ private void LeftMaintain(ref TElement root) /// The subtree is never empty: it is on the path of the operation or is a child of the node that a rotation has just moved up. /// Поддерево никогда не пусто: оно лежит на пути операции или является потомком узла, который только что поднял поворот. /// - private void RightMaintain(ref TElement root) + protected void RightMaintain(ref TElement root) { var rootRightNode = GetRight(root); if (rootRightNode != TElement.Zero) diff --git a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs index 52a2045..b73c277 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedAndThreadedAVLBalancedTreeMethods.cs @@ -17,10 +17,17 @@ namespace Platform.Collections.Methods.Trees /// /// Based on: TreeLib.AVLTreeList. /// Which itself based on: GNOME/glib/gtree. + /// The path buffer belongs to the instance, so one instance must not be used by several threads at once. /// public abstract class SizedAndThreadedAVLBalancedTreeMethods : SizedBinaryTreeMethodsBase where TElement: IUnsignedNumber, IComparisonOperators { - private static readonly int _maxPath = 11 * NumericType.BytesSize + 4; + protected static readonly int _maxPath = 11 * NumericType.BytesSize + 4; + + /// + /// The path from the root that an attach or a detach walks; it is reused, so the operations allocate nothing. Its first element always stays zero. + /// Путь от корня, который проходит присоединение или отсоединение; он используется повторно, поэтому операции ничего не выделяют. Его первый элемент всегда остаётся нулём. + /// + protected readonly TElement[] _path = new TElement[_maxPath]; /// /// @@ -324,14 +331,12 @@ protected override void AttachCore(ref TElement root, TElement node) { unchecked { - // TODO: Check what is faster to use simple array or array from array pool - // TODO: Try to use stackalloc as an optimization (requires code generation, because of generics) #if USEARRAYPOOL var path = ArrayPool.Allocate(MaxPath); var pathPosition = 0; path[pathPosition++] = default; #else - var path = new TElement[_maxPath]; + var path = _path; var pathPosition = 1; #endif var currentNode = root; @@ -431,7 +436,7 @@ protected override void AttachCore(ref TElement root, TElement node) #endif } } - private TElement Balance(TElement node) + protected TElement Balance(TElement node) { unchecked { @@ -644,7 +649,7 @@ protected override TElement GetPrevious(TElement node) /// Отменяет изменения размеров, сделанные поиском на пути, чтобы неудачное присоединение или отсоединение оставляло дерево нетронутым. /// /// - private void UndoSizeChanges(TElement[] path, int pathPosition, bool sizesWereIncremented) + protected void UndoSizeChanges(TElement[] path, int pathPosition, bool sizesWereIncremented) { while (--pathPosition > 0) { @@ -690,7 +695,7 @@ protected override void DetachCore(ref TElement root, TElement node) var pathPosition = 0; path[pathPosition++] = default; #else - var path = new TElement[_maxPath]; + var path = _path; var pathPosition = 1; #endif var currentNode = root; diff --git a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs index 3c9cb67..2920366 100644 --- a/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs +++ b/csharp/Platform.Collections.Methods/Trees/SizedBinaryTreeMethodsBase.cs @@ -779,7 +779,7 @@ protected TElement RebuildComplete(TElement root) return root; } - private void Fold(ref TElement root, ulong rotations) + protected void Fold(ref TElement root, ulong rotations) { ref TElement position = ref root; for (ulong i = 0; i < rotations; i++) From f2173e0ae612a1fbe250db4860d63898d8122f19 Mon Sep 17 00:00:00 2001 From: konard Date: Sun, 29 Nov 2026 16:24:20 +0000 Subject: [PATCH 29/46] Split the test trees into plain trees and inspectable inheritors SizeBalancedTree, RecursionlessSizeBalancedTree and SizedAndThreadedAVLBalancedTree of the tests are now plain storage, as a user of the library would write them. Rotation and size read counting, the rotation log and the inspection helpers live only in the Inspectable* inheritors (C#) and in the InspectableTree CRTP decorator (C++), which the balance, rotation and edge case tests use. Static asserts check that the plain C++ tree is exactly its nodes plus root and count, so nothing is paid for inspection. --- .../InspectableTree.cpp | 134 ++++++++++++++++++ .../RecursionlessSizeBalancedTree.cpp | 130 ++++------------- .../SizeBalancedTree.cpp | 130 ++++------------- .../SizeBalancedTreeRotationTests.cpp | 26 ++-- .../SizedAndThreadedAVLBalancedTree.cpp | 133 +++++------------ .../TreeBalanceTests.cpp | 6 +- .../TreeEdgeCaseTests.cpp | 16 +-- .../Trees.h | 1 + .../DoublyLinkedLists.cs | 8 +- ...nspectableRecursionlessSizeBalancedTree.cs | 98 +++++++++++++ .../InspectableSizeBalancedTree.cs | 98 +++++++++++++ ...pectableSizedAndThreadedAVLBalancedTree.cs | 91 ++++++++++++ .../RecursionlessSizeBalancedTree.cs | 123 +++------------- .../RotationDetector.cs | 36 +++++ .../SizeBalancedTree.cs | 122 +++------------- .../SizeBalancedTreeRotationTests.cs | 24 ++-- .../SizedAndThreadedAVLBalancedTree.cs | 125 ++++------------ .../TreeBalanceTests.cs | 10 +- .../TreeEdgeCaseTests.cs | 22 +-- 19 files changed, 664 insertions(+), 669 deletions(-) create mode 100644 cpp/Platform.Collections.Methods.Tests/InspectableTree.cpp create mode 100644 csharp/Platform.Collections.Methods.Tests/InspectableRecursionlessSizeBalancedTree.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/InspectableSizeBalancedTree.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/InspectableSizedAndThreadedAVLBalancedTree.cs create mode 100644 csharp/Platform.Collections.Methods.Tests/RotationDetector.cs diff --git a/cpp/Platform.Collections.Methods.Tests/InspectableTree.cpp b/cpp/Platform.Collections.Methods.Tests/InspectableTree.cpp new file mode 100644 index 0000000..e346567 --- /dev/null +++ b/cpp/Platform.Collections.Methods.Tests/InspectableTree.cpp @@ -0,0 +1,134 @@ +namespace Platform::Collections::Methods::Tests +{ + /// + /// A test tree that the tests can inspect: it inherits the plain tree TTree, counts rotations and size reads, compares nodes by node >> KeyShift and exposes the protected helpers. Only this inheritor pays for the inspection; the plain trees do not. + /// Тестовое дерево, которое тесты могут исследовать: оно наследует простое дерево TTree, считает повороты и чтения размеров, сравнивает узлы по node >> KeyShift и открывает защищённые вспомогательные методы. За исследование платит только этот наследник; простые деревья не платят. + /// + /// + /// CRTP resolves the library calls at compile time, so shadowing GetSize, LeftRotate and RightRotate here counts every call the library makes without any virtual function. + /// CRTP разрешает вызовы библиотеки во время компиляции, поэтому скрытие GetSize, LeftRotate и RightRotate здесь учитывает каждый вызов библиотеки без виртуальных функций. + /// + template