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
6 changes: 5 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ public class MyClass : DeepCloneable<MyClass>

- **CRTP Pattern**: Enables type-safe cloning without casting in inheritance hierarchies
- **Factory Method**: `CreateInstance()` separates object creation from property copying
- **Extension Methods**: `DeepCloneFrom()` handles in-place collection cloning; `DeepClone()` returns new collections
- **Extension Methods**: `DeepCloneFrom()` handles in-place collection cloning; `DeepClone()` returns new collections.
`DeepClone()` keeps the source's comparer, while `DeepCloneFrom()` keeps the destination's, so `DeepCloneFrom()`
throws `ArgumentException` when a `HashSet`, `SortedSet`, `Dictionary`, `SortedDictionary` or `SortedList` source
uses a different comparer from a destination of the same kind (#139). `StringComparer.Ordinal` and the default
string comparer count as the same. Pinned by `DeepCloneFromComparerTests`
- **Polymorphic Support**: Non-generic `IDeepCloneable` interface enables cloning through base type references

## Project Structure
Expand Down
155 changes: 155 additions & 0 deletions DeepClone.Test/DeepCloneFromComparerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.DeepClone.Test;

/// <summary>
/// Tests that <c>DeepCloneFrom</c> refuses a source whose comparer differs from the destination's, instead of producing
/// a clone that drops elements, reorders them or misses lookups (ktsu-dev/DeepClone#139).
/// </summary>
[TestClass]
public class DeepCloneFromComparerTests
{
private sealed class Settings : DeepCloneable<Settings>
{
public HashSet<string> Tags { get; set; } = new(StringComparer.OrdinalIgnoreCase);

protected override Settings CreateInstance() => new();

protected override void DeepClone(Settings clone) => clone.Tags.DeepCloneFrom(Tags);
}

private static readonly int[] DescendingOrder = [3, 2, 1];

private static readonly Comparer<int> Descending = Comparer<int>.Create((x, y) => y.CompareTo(x));

/// <summary>
/// The issue's repro: a reassigned ordinal source set cloned into the clone's case-insensitive set.
/// </summary>
[TestMethod]
public void ReassignedSourceSet_DeepClone_ThrowsInsteadOfDroppingElements()
{
Settings source = new() { Tags = ["a", "A"] };

ArgumentException exception = Assert.ThrowsExactly<ArgumentException>(source.DeepClone);

Assert.Contains("DeepClone()", exception.Message);
}

/// <summary>
/// Tests that a case-insensitive source set refuses an ordinal destination, which would keep both "a" and "A" apart.
/// </summary>
[TestMethod]
public void HashSet_DifferentComparer_ThrowsAndLeavesDestinationUnchanged()
{
HashSet<string> dest = ["keep"];
HashSet<string> source = new(StringComparer.OrdinalIgnoreCase) { "a" };

Assert.ThrowsExactly<ArgumentException>(() => dest.DeepCloneFrom(source));

Assert.HasCount(1, dest);
Assert.Contains("keep", dest);
}

/// <summary>
/// Tests that a descending source set refuses an ascending destination, which would reverse its order.
/// </summary>
[TestMethod]
public void SortedSet_DifferentComparer_Throws()
{
SortedSet<int> dest = [];
SortedSet<int> source = new(Descending) { 1, 2, 3 };

Assert.ThrowsExactly<ArgumentException>(() => dest.DeepCloneFrom(source));
Assert.IsEmpty(dest);
}

/// <summary>
/// Tests that a case-insensitive source dictionary refuses an ordinal destination, whose lookups would miss.
/// </summary>
[TestMethod]
public void Dictionary_DifferentComparer_Throws()
{
Dictionary<string, int> dest = [];
Dictionary<string, int> source = new(StringComparer.OrdinalIgnoreCase) { ["key"] = 1 };

Assert.ThrowsExactly<ArgumentException>(() => dest.DeepCloneFrom(source));
Assert.IsEmpty(dest);
}

/// <summary>
/// Tests that a descending source sorted dictionary refuses an ascending destination.
/// </summary>
[TestMethod]
public void SortedDictionary_DifferentComparer_Throws()
{
SortedDictionary<int, string> dest = [];
SortedDictionary<int, string> source = new(Descending) { [1] = "a", [2] = "b" };

Assert.ThrowsExactly<ArgumentException>(() => dest.DeepCloneFrom(source));
Assert.IsEmpty(dest);
}

/// <summary>
/// Tests that a descending source sorted list refuses an ascending destination.
/// </summary>
[TestMethod]
public void SortedList_DifferentComparer_Throws()
{
SortedList<int, string> dest = [];
SortedList<int, string> source = new(Descending) { [1] = "a", [2] = "b" };

Assert.ThrowsExactly<ArgumentException>(() => dest.DeepCloneFrom(source));
Assert.IsEmpty(dest);
}

/// <summary>
/// Tests that matching comparers still clone, keeping the destination's (and so the source's) behaviour.
/// </summary>
[TestMethod]
public void SameComparer_Clones()
{
HashSet<string> dest = new(StringComparer.OrdinalIgnoreCase);
HashSet<string> source = new(StringComparer.OrdinalIgnoreCase) { "a" };
SortedSet<int> sortedDest = new(Descending);
SortedSet<int> sortedSource = new(Descending) { 1, 2, 3 };

dest.DeepCloneFrom(source);
sortedDest.DeepCloneFrom(sortedSource);

Assert.Contains("A", dest);
CollectionAssert.AreEqual(DescendingOrder, sortedDest.ToArray());

Check warning on line 120 in DeepClone.Test/DeepCloneFromComparerTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.AreSequenceEqual' instead of 'CollectionAssert.AreEqual'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_DeepClone&issues=AaHG_Tp6IaQfhV6A_3Nk&open=AaHG_Tp6IaQfhV6A_3Nk&pullRequest=142
}

/// <summary>
/// Tests that an explicit <see cref="StringComparer.Ordinal"/> and the default string comparer, which compare the
/// same way, are not reported as a mismatch.
/// </summary>
[TestMethod]
public void OrdinalAndDefaultStringComparers_Clone()
{
HashSet<string> dest = [];
HashSet<string> source = new(StringComparer.Ordinal) { "a", "A" };
Dictionary<string, int> mapDest = new(StringComparer.Ordinal);
Dictionary<string, int> mapSource = new() { ["a"] = 1 };

dest.DeepCloneFrom(source);
mapDest.DeepCloneFrom(mapSource);

Assert.HasCount(2, dest);
Assert.AreEqual(1, mapDest["a"]);
}

/// <summary>
/// Tests that a destination of a different kind from the source is filled as before, with no comparer check.
/// </summary>
[TestMethod]
public void DifferentKinds_Clone()
{
HashSet<string> dest = new(StringComparer.OrdinalIgnoreCase);
List<string> source = ["a"];

dest.DeepCloneFrom(source);

Assert.Contains("A", dest);
}
}
124 changes: 124 additions & 0 deletions DeepClone/DeepCloneContainerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,26 @@
/// var clonedList = new List&lt;MyType&gt;();
/// clonedList.DeepCloneFrom(originalList);
/// </code>
/// <para>
/// The destination keeps its own comparer. A <see cref="HashSet{T}"/> or <see cref="SortedSet{T}"/> source whose
/// comparer differs from the destination's would clone into a collection that drops elements or orders them
/// differently, so that case throws instead. Assign <c>dest = source.DeepClone()</c> for a settable property,
/// which keeps the source's comparer, and keep <c>DeepCloneFrom</c> for get-only ones.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if dest or source is null.</exception>
/// <exception cref="ArgumentException">
/// Thrown, before <paramref name="dest"/> is changed, if both are <see cref="HashSet{T}"/> or both are
/// <see cref="SortedSet{T}"/> and their comparers differ.
/// </exception>
public static void DeepCloneFrom<T>(this ICollection<T> dest, IEnumerable<T> source)

Check warning on line 53 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepCloneFrom' method overloads should be adjacent.

Check warning on line 53 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepCloneFrom' method overloads should be adjacent.

Check warning on line 53 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepCloneFrom' method overloads should be adjacent.

Check warning on line 53 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepCloneFrom' method overloads should be adjacent.
{
Ensure.NotNull(dest);

Ensure.NotNull(source);

EnsureSameComparer(dest, source);

T[] items = [.. source];
T[] clones = new T[items.Length];
for (int i = 0; i < items.Length; i++)
Expand Down Expand Up @@ -75,15 +87,28 @@
/// var clonedDict = new Dictionary&lt;KeyType, ValueType&gt;();
/// clonedDict.DeepCloneFrom(originalDict);
/// </code>
/// <para>
/// The destination keeps its own key comparer. A <see cref="Dictionary{TKey, TValue}"/>,
/// <see cref="SortedDictionary{TKey, TValue}"/> or <see cref="SortedList{TKey, TValue}"/> source whose comparer
/// differs from the destination's would clone into a dictionary whose lookups miss or whose order changes, so that
/// case throws instead. Assign <c>dest = source.DeepClone()</c> for a settable property, which keeps the source's
/// comparer, and keep <c>DeepCloneFrom</c> for get-only ones.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if dest or source is null.</exception>
/// <exception cref="ArgumentException">
/// Thrown, before <paramref name="dest"/> is changed, if both are the same one of those dictionary kinds and their
/// comparers differ.
/// </exception>
public static void DeepCloneFrom<TKey, TValue>(this IDictionary<TKey, TValue> dest, IDictionary<TKey, TValue> source)
where TKey : notnull
{
Ensure.NotNull(dest);

Ensure.NotNull(source);

EnsureSameComparer(dest, source);

KeyValuePair<TKey, TValue>[] items = [.. source];
KeyValuePair<TKey, TValue>[] clones = new KeyValuePair<TKey, TValue>[items.Length];
for (int i = 0; i < items.Length; i++)
Expand All @@ -94,6 +119,105 @@
ReplaceContents(dest, clones);
}

/// <summary>
/// Throws when <paramref name="dest"/> and <paramref name="source"/> are the same comparer-holding collection kind
/// with different comparers, since filling one from the other would silently change the clone (ktsu-dev/DeepClone#139).
/// </summary>
/// <typeparam name="T">The type of objects in the collections.</typeparam>
/// <param name="dest">The destination collection.</param>
/// <param name="source">The source collection.</param>
private static void EnsureSameComparer<T>(ICollection<T> dest, IEnumerable<T> source)
{
object? destComparer;
object? sourceComparer;
string kind;
switch (dest)
{
case HashSet<T> destSet when source is HashSet<T> sourceSet:
(destComparer, sourceComparer, kind) = (destSet.Comparer, sourceSet.Comparer, "HashSet");
break;
case SortedSet<T> destSet when source is SortedSet<T> sourceSet:
(destComparer, sourceComparer, kind) = (destSet.Comparer, sourceSet.Comparer, "SortedSet");
break;
default:
return;
}

if (!ComparersMatch<T>(destComparer, sourceComparer))
{
throw new ArgumentException(ComparerMismatchMessage(kind, destComparer, sourceComparer), nameof(source));
}
}

/// <summary>
/// Throws when <paramref name="dest"/> and <paramref name="source"/> are the same comparer-holding dictionary kind
/// with different key comparers, since filling one from the other would silently change the clone (ktsu-dev/DeepClone#139).
/// </summary>
/// <typeparam name="TKey">The type of keys in the dictionaries.</typeparam>
/// <typeparam name="TValue">The type of values in the dictionaries.</typeparam>
/// <param name="dest">The destination dictionary.</param>
/// <param name="source">The source dictionary.</param>
private static void EnsureSameComparer<TKey, TValue>(IDictionary<TKey, TValue> dest, IDictionary<TKey, TValue> source)
where TKey : notnull
{
object? destComparer;
object? sourceComparer;
string kind;
switch (dest)
{
case Dictionary<TKey, TValue> destMap when source is Dictionary<TKey, TValue> sourceMap:
(destComparer, sourceComparer, kind) = (destMap.Comparer, sourceMap.Comparer, "Dictionary");
break;
case SortedDictionary<TKey, TValue> destMap when source is SortedDictionary<TKey, TValue> sourceMap:
(destComparer, sourceComparer, kind) = (destMap.Comparer, sourceMap.Comparer, "SortedDictionary");
break;
case SortedList<TKey, TValue> destMap when source is SortedList<TKey, TValue> sourceMap:
(destComparer, sourceComparer, kind) = (destMap.Comparer, sourceMap.Comparer, "SortedList");
break;
default:
return;
}

if (!ComparersMatch<TKey>(destComparer, sourceComparer))
{
throw new ArgumentException(ComparerMismatchMessage(kind, destComparer, sourceComparer), nameof(source));
}
}

/// <summary>
/// Reports whether two comparers compare the same way.
/// </summary>
/// <typeparam name="T">The type the comparers compare.</typeparam>
/// <param name="destComparer">The destination's comparer.</param>
/// <param name="sourceComparer">The source's comparer.</param>
/// <returns><see langword="true"/> if they are equal once normalized.</returns>
private static bool ComparersMatch<T>(object? destComparer, object? sourceComparer) =>
Equals(Normalize<T>(destComparer), Normalize<T>(sourceComparer));

/// <summary>
/// Builds the message for a comparer mismatch, naming both comparers and the fix.
/// </summary>
/// <param name="kind">The collection kind.</param>
/// <param name="destComparer">The destination's comparer.</param>
/// <param name="sourceComparer">The source's comparer.</param>
/// <returns>The message.</returns>
private static string ComparerMismatchMessage(string kind, object? destComparer, object? sourceComparer) =>
$"The source {kind} uses comparer {sourceComparer?.GetType().Name ?? "null"} but the destination uses " +
$"{destComparer?.GetType().Name ?? "null"}, so DeepCloneFrom would produce a clone that behaves differently " +
"from its source. Assign dest = source.DeepClone() instead, which keeps the source's comparer.";

/// <summary>
/// Maps <see cref="StringComparer.Ordinal"/> to the default string equality comparer, which compares the same way,
/// so a set built with one and a set built with the other are not reported as a mismatch.
/// </summary>
/// <typeparam name="T">The type the comparer compares.</typeparam>
/// <param name="comparer">The comparer to normalize.</param>
/// <returns>The comparer, or the default equality comparer when the two are equivalent.</returns>
private static object? Normalize<T>(object? comparer) =>
typeof(T) == typeof(string) && ReferenceEquals(comparer, StringComparer.Ordinal)
? EqualityComparer<string>.Default
: comparer;

/// <summary>
/// Replaces the contents of <paramref name="dest"/> with <paramref name="items"/>, restoring the original
/// contents if an <see cref="ICollection{T}.Add"/> throws part-way through.
Expand Down Expand Up @@ -207,7 +331,7 @@
}

dest.Clear();
if (clones.Length > 0)

Check warning on line 334 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Change this condition so that it does not always evaluate to 'True'.

Check warning on line 334 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Change this condition so that it does not always evaluate to 'True'.

Check warning on line 334 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Change this condition so that it does not always evaluate to 'True'.
{
dest.PushRange(clones);
}
Expand Down Expand Up @@ -346,7 +470,7 @@
/// </code>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if source is null.</exception>
public static IEnumerable<T> DeepClone<T>(this IEnumerable<T> source)

Check warning on line 473 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepClone' method overloads should be adjacent.

Check warning on line 473 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepClone' method overloads should be adjacent.

Check warning on line 473 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

All 'DeepClone' method overloads should be adjacent.
{
Ensure.NotNull(source);

Expand Down
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ public class ComplexObject : DeepCloneable<ComplexObject>
public string? Name { get; set; }
public List<ItemObject> Items { get; set; } = new();
public Dictionary<string, DataObject> DataMapping { get; set; } = new();
public HashSet<int> UniqueIds { get; set; } = new();
public HashSet<string> Tags { get; } = new(StringComparer.OrdinalIgnoreCase);

protected override ComplexObject CreateInstance() => new ComplexObject();

Expand All @@ -537,13 +537,16 @@ public class ComplexObject : DeepCloneable<ComplexObject>

clone.Name = Name;

// Use DeepCloneFrom for all collections - this handles cloning correctly
clone.Items.DeepCloneFrom(Items);
clone.DataMapping.DeepCloneFrom(DataMapping);

// Even for value type collections, DeepCloneFrom can be used for consistency
// This is equivalent to copying each element manually
clone.UniqueIds.DeepCloneFrom(UniqueIds);
// For a settable collection property, assign a clone. DeepClone() keeps the source's
// comparer, so the clone behaves like the source even if the property was reassigned
// (by a deserializer, say) to a collection with a different comparer.
clone.Items = Items.DeepClone();
clone.DataMapping = DataMapping.DeepClone();

// For a get-only property, fill the clone's own collection in place. The clone keeps
// its own comparer, so DeepCloneFrom throws ArgumentException if a HashSet, SortedSet,
// Dictionary, SortedDictionary or SortedList source uses a different comparer.
clone.Tags.DeepCloneFrom(Tags);
}
}

Expand Down
Loading