Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
bin/
obj/

ConcurrentCollections.xml
ConcurrentCollections.xml
*.coverage
.claude/settings.local.json
coverage.xml
60 changes: 60 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

ConcurrentHashSet is a thread-safe hash-based set (`ConcurrentHashSet<T>`) for .NET, modeled after `ConcurrentDictionary`. It lives in the `ConcurrentCollections` namespace with assembly name `ConcurrentCollections`. Published as the `ConcurrentHashSet` NuGet package.

## Build Commands

```bash
# Build (solution is under src/)
dotnet build src/ConcurrentCollections.sln -c Release

# Build specific framework target
dotnet build src/ConcurrentHashSet/ConcurrentHashSet.csproj -f netstandard2.0 -c Release
```

NuGet package is auto-generated on build (`GeneratePackageOnBuild=True`) and output to `src/ConcurrentHashSet/bin/Release/`.

## Test Commands

Tests use TUnit framework (`src/ConcurrentHashSet.Tests/`). TUnit uses Microsoft.Testing.Platform (not VSTest), so on .NET 10+ use `dotnet run`:

```bash
# Run all tests
dotnet run --project src/ConcurrentHashSet.Tests/ConcurrentHashSet.Tests.csproj -c Release

# On .NET 9 SDK, dotnet test also works
dotnet test src/ConcurrentHashSet.Tests/ConcurrentHashSet.Tests.csproj -c Release
```

## Build Constraints

Defined in `src/Directory.Build.props`:
- **TreatWarningsAsErrors** is enabled — all warnings are build errors
- **Nullable reference types** are enabled
- **Latest C# language version** is used

## Target Frameworks

Multi-targets: `netstandard1.0`, `netstandard2.0`, `net461`. Code uses conditional compilation (`#if`) for nullable attribute polyfills on older targets (see `NullableAttributes.cs`).

## Architecture

The entire implementation is in two files under `src/ConcurrentHashSet/`:

- **ConcurrentHashSet.cs** (~900 lines) — The single public type `ConcurrentHashSet<T>` implementing `IReadOnlyCollection<T>` and `ICollection<T>`. Uses lock-per-segment concurrency with linked-list buckets, mirroring `ConcurrentDictionary`'s internal design. Contains three nested types:
- `Tables` (private class) — holds bucket array, lock array, and per-lock counts
- `Node` (private class) — linked list node with cached hashcode
- `Enumerator` (public struct) — allocation-free enumerator using a state machine with goto-based transitions

- **NullableAttributes.cs** — Polyfill for `MaybeNullWhenAttribute`, conditionally compiled only for targets lacking it.

## Key Design Decisions

- Concurrency model: lock-per-segment (up to 1024 locks), with `Volatile.Read/Write` for lock-free reads in hot paths like `Contains` and `TryGetValue`
- No set operations (union, intersect, etc.) — only per-item operations (`Add`, `TryRemove`, `Contains`, `TryGetValue`)
- Struct enumerator avoids heap allocation; does not snapshot — allows concurrent modification during iteration
- Default concurrency level is `Environment.ProcessorCount`; default capacity is 31 buckets
26 changes: 26 additions & 0 deletions src/ConcurrentCollections.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,42 @@ VisualStudioVersion = 15.0.26228.9
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConcurrentHashSet", "ConcurrentHashSet\ConcurrentHashSet.csproj", "{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConcurrentHashSet.Tests", "ConcurrentHashSet.Tests\ConcurrentHashSet.Tests.csproj", "{4820316A-E280-4829-A2EE-FA74C52DEB0B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Debug|x64.ActiveCfg = Debug|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Debug|x64.Build.0 = Debug|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Debug|x86.ActiveCfg = Debug|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Debug|x86.Build.0 = Debug|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Release|Any CPU.Build.0 = Release|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Release|x64.ActiveCfg = Release|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Release|x64.Build.0 = Release|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Release|x86.ActiveCfg = Release|Any CPU
{58063048-C7B0-4F4D-B27E-1ED5F9789AF7}.Release|x86.Build.0 = Release|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Debug|x64.ActiveCfg = Debug|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Debug|x64.Build.0 = Debug|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Debug|x86.ActiveCfg = Debug|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Debug|x86.Build.0 = Debug|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Release|Any CPU.Build.0 = Release|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Release|x64.ActiveCfg = Release|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Release|x64.Build.0 = Release|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Release|x86.ActiveCfg = Release|Any CPU
{4820316A-E280-4829-A2EE-FA74C52DEB0B}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
205 changes: 205 additions & 0 deletions src/ConcurrentHashSet.Tests/CollectionInterfaceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
using ConcurrentCollections;
using System.Collections;

namespace ConcurrentHashSet.Tests;

public class ICollectionAddTests
{
[Test]
public async Task ICollection_Add_Adds_Item()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(42);

await Assert.That(set.Count).IsEqualTo(1);
await Assert.That(set.Contains(42)).IsTrue();
}

[Test]
public async Task ICollection_Add_Duplicate_Does_Not_Throw()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(42);
set.Add(42); // Should not throw, just silently ignores

await Assert.That(set.Count).IsEqualTo(1);
}
}

public class ICollectionRemoveTests
{
[Test]
public async Task ICollection_Remove_Existing_Returns_True()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(42);

await Assert.That(set.Remove(42)).IsTrue();
}

[Test]
public async Task ICollection_Remove_NonExisting_Returns_False()
{
ICollection<int> set = new ConcurrentHashSet<int>();

await Assert.That(set.Remove(42)).IsFalse();
}
}

public class IsReadOnlyTests
{
[Test]
public async Task IsReadOnly_Returns_False()
{
ICollection<int> set = new ConcurrentHashSet<int>();

await Assert.That(set.IsReadOnly).IsFalse();
}
}

public class CopyToTests
{
[Test]
public async Task CopyTo_Copies_All_Items()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);

var array = new int[3];
set.CopyTo(array, 0);

// Items may not be in insertion order, but all must be present
var sorted = array.OrderBy(x => x).ToArray();
await Assert.That(sorted[0]).IsEqualTo(1);
await Assert.That(sorted[1]).IsEqualTo(2);
await Assert.That(sorted[2]).IsEqualTo(3);
}

[Test]
public async Task CopyTo_With_Offset()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(10);
set.Add(20);

var array = new int[5];
set.CopyTo(array, 2);

// First two should be 0 (default), items at indices 2-3
await Assert.That(array[0]).IsEqualTo(0);
await Assert.That(array[1]).IsEqualTo(0);

var copied = array.Skip(2).Where(x => x != 0).OrderBy(x => x).ToArray();
await Assert.That(copied).Contains(10);
await Assert.That(copied).Contains(20);
}

[Test]
public async Task CopyTo_Null_Array_Throws()
{
ICollection<int> set = new ConcurrentHashSet<int>();

await Assert.That(() => set.CopyTo(null!, 0))
.Throws<ArgumentNullException>();
}

[Test]
public async Task CopyTo_Negative_Index_Throws()
{
ICollection<int> set = new ConcurrentHashSet<int>();

await Assert.That(() => set.CopyTo(new int[5], -1))
.Throws<ArgumentOutOfRangeException>();
}

[Test]
public async Task CopyTo_Insufficient_Space_Throws()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);

await Assert.That(() => set.CopyTo(new int[2], 0))
.Throws<ArgumentException>();
}

[Test]
public async Task CopyTo_Insufficient_Space_Due_To_Offset_Throws()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(1);
set.Add(2);

await Assert.That(() => set.CopyTo(new int[3], 2))
.Throws<ArgumentException>();
}

[Test]
public async Task CopyTo_Empty_Set_Does_Nothing()
{
ICollection<int> set = new ConcurrentHashSet<int>();
var array = new int[] { 99, 99, 99 };
set.CopyTo(array, 0);

await Assert.That(array[0]).IsEqualTo(99);
await Assert.That(array[1]).IsEqualTo(99);
await Assert.That(array[2]).IsEqualTo(99);
}

[Test]
public async Task CopyTo_Exact_Size_Array()
{
ICollection<int> set = new ConcurrentHashSet<int>();
set.Add(1);
set.Add(2);

var array = new int[2];
set.CopyTo(array, 0);

var sorted = array.OrderBy(x => x).ToArray();
await Assert.That(sorted[0]).IsEqualTo(1);
await Assert.That(sorted[1]).IsEqualTo(2);
}
}

public class IEnumerableInterfaceTests
{
[Test]
public async Task IEnumerable_Generic_GetEnumerator_Works()
{
var set = new ConcurrentHashSet<int>(new[] { 1, 2, 3 });
IEnumerable<int> enumerable = set;

var items = new List<int>();
foreach (var item in enumerable)
{
items.Add(item);
}

await Assert.That(items.Count).IsEqualTo(3);
await Assert.That(items).Contains(1);
await Assert.That(items).Contains(2);
await Assert.That(items).Contains(3);
}

[Test]
public async Task IEnumerable_NonGeneric_GetEnumerator_Works()
{
var set = new ConcurrentHashSet<int>(new[] { 1, 2, 3 });
IEnumerable enumerable = set;

var items = new List<int>();
foreach (int item in enumerable)
{
items.Add(item);
}

await Assert.That(items.Count).IsEqualTo(3);
await Assert.That(items).Contains(1);
await Assert.That(items).Contains(2);
await Assert.That(items).Contains(3);
}
}
Loading