Skip to content
Merged
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
54 changes: 54 additions & 0 deletions src/Ramstack.HtmxToolkit/Collections/SmallDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,40 @@ public SmallDictionary(IComparer<TKey> comparer)
_comparer = comparer;
}

/// <summary>
/// Initializes a new instance of the <see cref="SmallDictionary{TKey,TValue}"/> class that contains
/// entries copied from the specified collection and uses the specified key comparer.
/// </summary>
/// <param name="collection">The collection whose entries are copied to the new dictionary.</param>
/// <param name="comparer">The comparer to use when comparing keys.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="collection"/> or <paramref name="comparer"/> is <see langword="null"/>.
/// </exception>
public SmallDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IComparer<TKey> comparer) : this(comparer)
{
ArgumentNullException.ThrowIfNull(collection);

if (collection is Dictionary<TKey, TValue> dictionary)
{
_items = new KeyValuePair<TKey, TValue>[dictionary.Count];
foreach (var pair in dictionary)
Add(pair.Key, pair.Value);
}
else if (collection is SmallDictionary<TKey, TValue> small)
{
_count = small._count;
_items = [..small._items];

if (_count > LinearSearchThreshold && !ReferenceEquals(_comparer, small._comparer))
Array.Sort(_items, 0, _count, new KeyValuePairComparer(_comparer));
}
else
{
foreach (var pair in collection)
Add(pair.Key, pair.Value);
}
}

/// <inherited />
public bool ContainsKey(TKey key) =>
IndexOf(key) >= 0;
Expand Down Expand Up @@ -111,6 +145,26 @@ public void Add(TKey key, TValue value)
Insert(~index, key, value);
}

/// <summary>
/// Attempts to add the specified key and value to the dictionary.
/// </summary>
/// <param name="key">The key of the entry to add.</param>
/// <param name="value">The value of the entry to add.</param>
/// <returns>
/// <see langword="true"/> if the key/value pair was added to the dictionary;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is <see langword="null"/>.</exception>
public bool TryAdd(TKey key, TValue value)
{
var index = IndexOf(key);
if (index >= 0)
return false;

Insert(~index, key, value);
return true;
}

/// <inherited />
public bool Remove(TKey key)
{
Expand Down
135 changes: 135 additions & 0 deletions tests/Ramstack.HtmxToolkit.Tests/Collections/SmallDictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,95 @@ public void Constructor_NewInstance_IsEmpty_Writable()
});
}

[Test]
public void Constructor_FromCollection_CopiesEntries()
{
var source = new[]
{
KeyValuePair.Create(1, "one"),
KeyValuePair.Create(2, "two"),
KeyValuePair.Create(3, "three")
};

var dictionary = new SmallDictionary<int, string>(source, Comparer<int>.Default);

Assert.Multiple(() =>
{
Assert.That(dictionary.Count, Is.EqualTo(3));
Assert.That(dictionary, Is.EquivalentTo(source));
Assert.That(dictionary[2], Is.EqualTo("two"));
});
}

[Test]
public void Constructor_FromDictionary_CopiesEntries()
{
var source = new Dictionary<int, string>
{
[1] = "one",
[2] = "two",
[3] = "three"
};

var dictionary = new SmallDictionary<int, string>(source, Comparer<int>.Default);

Assert.Multiple(() =>
{
Assert.That(dictionary.Count, Is.EqualTo(3));
Assert.That(dictionary, Is.EquivalentTo(source));
});
}

[Test]
public void Constructor_FromSmallDictionary_CopiesEntries()
{
var source = CreateDictionary();
source.Add(3, "three");
source.Add(1, "one");
source.Add(2, "two");

var dictionary = new SmallDictionary<int, string>(source, Comparer<int>.Default);

Assert.Multiple(() =>
{
Assert.That(dictionary.Count, Is.EqualTo(3));
Assert.That(dictionary, Is.EquivalentTo(source));
});
}

[Test]
public void Constructor_FromSmallDictionary_WithDifferentComparer_ReSortsEntries()
{
var source = new SmallDictionary<string, int>(StringComparer.Ordinal);
foreach (var key in new[] { "Bravo", "alpha", "Delta", "charlie", "Echo", "foxtrot" })
source.Add(key, source.Count + 1);

var dictionary = new SmallDictionary<string, int>(source, StringComparer.OrdinalIgnoreCase);

Assert.Multiple(() =>
{
Assert.That(dictionary.Count, Is.EqualTo(source.Count));
Assert.That(dictionary, Is.EquivalentTo(source));
Assert.That(dictionary["ALPHA"], Is.EqualTo(source["alpha"]));
Assert.That(dictionary["echo"], Is.EqualTo(source["Echo"]));
Assert.That(dictionary["FOXTROT"], Is.EqualTo(source["foxtrot"]));
});
}

[Test]
public void Constructor_NullCollection_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(
() => new SmallDictionary<int, string>(null!, Comparer<int>.Default));
}

[Test]
public void Constructor_NullComparer_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(
() => new SmallDictionary<int, string>([], null!));
}

[Test]
public void Add_NewKey_StoresEntry_UpdatesAllViews()
{
Expand Down Expand Up @@ -67,6 +156,52 @@ public void Add_NullKey_ThrowsArgumentNullException_PreservesState()
});
}

[Test]
public void TryAdd_NewKey_ReturnsTrue_AddsEntry()
{
var dictionary = new SmallDictionary<int, string>(Comparer<int>.Default);

var added = dictionary.TryAdd(7, "seven");

Assert.Multiple(() =>
{
Assert.That(added, Is.True);
Assert.That(dictionary.Count, Is.EqualTo(1));
Assert.That(dictionary[7], Is.EqualTo("seven"));
});
}

[Test]
public void TryAdd_ExistingKey_ReturnsFalse_PreservesExistingEntry()
{
var dictionary = new SmallDictionary<int, string>(Comparer<int>.Default);
dictionary.Add(7, "original");

var added = dictionary.TryAdd(7, "replacement");

Assert.Multiple(() =>
{
Assert.That(added, Is.False);
Assert.That(dictionary.Count, Is.EqualTo(1));
Assert.That(dictionary[7], Is.EqualTo("original"));
});
}

[Test]
public void TryAdd_NullKey_ThrowsArgumentNullException_PreservesState()
{
var dictionary = new SmallDictionary<string, int>(StringComparer.Ordinal);
dictionary.Add("existing", 1);

Assert.Throws<ArgumentNullException>(() => dictionary.TryAdd(null!, 0));

Assert.Multiple(() =>
{
Assert.That(dictionary.Count, Is.EqualTo(1));
Assert.That(dictionary["existing"], Is.EqualTo(1));
});
}

[Test]
public void Indexer_Get_MissingKey_ThrowsKeyNotFoundException()
{
Expand Down
Loading