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
5 changes: 5 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ public class MyClass : DeepCloneable<MyClass>
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`
- **NativeAOT**: the library builds with `IsAotCompatible` on net8.0 and later, so an AOT or trimming warning fails
the build. A `KeyValuePair` element reached through a generic `T` is cloned by a cloner made with
`MakeGenericType`, which NativeAOT can't make for a value-type key or value. That case is caught and the pair is
copied as it is, and the `IEnumerable<KeyValuePair<TKey, TValue>>` / `ICollection<KeyValuePair<TKey, TValue>>`
overloads clone pairs without reflection (#92). Pinned by `KeyValuePairOverloadTests`
- **Polymorphic Support**: Non-generic `IDeepCloneable` interface enables cloning through base type references
- **Clone Context**: `CloneContext` (internal, thread-static) maps each source to its clone for one top-level `DeepClone()` call or collection extension call. `DeepCloneable.DeepClone()` registers the clone before calling the override, so cycles resolve and shared references stay shared; the outermost scope clears the map

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

namespace ktsu.DeepClone.Test;

using System.Collections.ObjectModel;

/// <summary>
/// Tests for the <see cref="KeyValuePair{TKey, TValue}"/> overloads, which clone pairs without building a cloner by
/// reflection, so they work under NativeAOT for value-type keys and values (ktsu-dev/DeepClone#92).
/// </summary>
[TestClass]
public class KeyValuePairOverloadTests
{
/// <summary>
/// Tests that a pair sequence binds to the pair overload of DeepClone. Before #92 there was none, so a sequence of
/// <c>KeyValuePair&lt;int, T&gt;</c> went through the reflection path that throws under NativeAOT.
/// </summary>
[TestMethod]
public void PairSequence_DeepClone_BindsToThePairOverload()
{
Func<IEnumerable<KeyValuePair<int, SimpleObject>>, IEnumerable<KeyValuePair<int, SimpleObject>>> clone =
DeepCloneContainerExtensions.DeepClone<int, SimpleObject>;

Assert.AreEqual(nameof(DeepCloneContainerExtensions.DeepClone), clone.Method.Name);
Assert.AreEqual(typeof(IEnumerable<KeyValuePair<int, SimpleObject>>), clone.Method.GetParameters()[0].ParameterType);
}

/// <summary>
/// Tests that a pair collection binds to the pair overload of DeepCloneFrom.
/// </summary>
[TestMethod]
public void PairCollection_DeepCloneFrom_BindsToThePairOverload()
{
Action<ICollection<KeyValuePair<int, SimpleObject>>, IEnumerable<KeyValuePair<int, SimpleObject>>> cloneFrom =
DeepCloneContainerExtensions.DeepCloneFrom<int, SimpleObject>;

Assert.AreEqual(typeof(ICollection<KeyValuePair<int, SimpleObject>>), cloneFrom.Method.GetParameters()[0].ParameterType);
}

/// <summary>
/// Tests that the pair overload of DeepClone clones the values of a sequence with value-type keys.
/// </summary>
[TestMethod]
public void PairSequence_DeepClone_ClonesValues()
{
SimpleObject value = new() { Id = 1, Name = "One" };
IEnumerable<KeyValuePair<int, SimpleObject>> source = new Dictionary<int, SimpleObject> { [1] = value }.Select(pair => pair);

KeyValuePair<int, SimpleObject>[] clone = [.. source.DeepClone()];

Assert.HasCount(1, clone);
Assert.AreEqual(1, clone[0].Key);
Assert.AreNotSame(value, clone[0].Value);
Assert.AreEqual("One", clone[0].Value.Name);
}

/// <summary>
/// Tests that the pair overload of DeepClone clones a value shared by two pairs once, so it stays shared.
/// </summary>
[TestMethod]
public void PairSequence_DeepClone_KeepsSharedValuesShared()
{
SimpleObject shared = new() { Id = 1, Name = "Shared" };
KeyValuePair<int, SimpleObject>[] source = [new(1, shared), new(2, shared)];

KeyValuePair<int, SimpleObject>[] clone = [.. ((IEnumerable<KeyValuePair<int, SimpleObject>>)source).DeepClone()];

Assert.AreNotSame(shared, clone[0].Value);
Assert.AreSame(clone[0].Value, clone[1].Value);
}

/// <summary>
/// Tests that the pair overload of DeepClone returns a snapshot that doesn't track later source changes.
/// </summary>
[TestMethod]
public void PairSequence_DeepClone_IsASnapshot()
{
List<KeyValuePair<int, int>> source = [new(1, 2)];

IEnumerable<KeyValuePair<int, int>> clone = ((IEnumerable<KeyValuePair<int, int>>)source).DeepClone();
source.Add(new(3, 4));

Assert.AreEqual(1, clone.Count());

Check warning on line 83 in DeepClone.Test/KeyValuePairOverloadTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.HasCount' instead of 'Assert.AreEqual'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_DeepClone&issues=AaHP_oxRXLp_2ad-3qLq&open=AaHP_oxRXLp_2ad-3qLq&pullRequest=147
}

/// <summary>
/// Tests that the pair overload of DeepClone throws for a null source.
/// </summary>
[TestMethod]
public void PairSequence_DeepClone_ThrowsForNull()
{
IEnumerable<KeyValuePair<int, int>> source = null!;

Assert.ThrowsExactly<ArgumentNullException>(() => source.DeepClone());
}

/// <summary>
/// Tests that a read-only dictionary of value-type keys clones into a list of pairs through the pair overload of
/// DeepCloneFrom, cloning its values.
/// </summary>
[TestMethod]
public void PairCollection_DeepCloneFrom_ClonesValuesFromReadOnlyDictionary()
{
SimpleObject value = new() { Id = 1, Name = "One" };
IReadOnlyDictionary<int, SimpleObject> source = new Dictionary<int, SimpleObject> { [1] = value };
List<KeyValuePair<int, SimpleObject>> dest = [new(9, new SimpleObject())];

dest.DeepCloneFrom(source);

Assert.HasCount(1, dest);
Assert.AreEqual(1, dest[0].Key);
Assert.AreNotSame(value, dest[0].Value);
Assert.AreEqual("One", dest[0].Value.Name);
}

/// <summary>
/// Tests that the pair overload of DeepCloneFrom refuses a read-only destination before cloning.
/// </summary>
[TestMethod]
public void PairCollection_DeepCloneFrom_ThrowsForReadOnlyDestination()
{
ICollection<KeyValuePair<int, int>> dest = new ReadOnlyCollection<KeyValuePair<int, int>>([new(1, 2)]);

Assert.ThrowsExactly<ArgumentException>(() => dest.DeepCloneFrom([new KeyValuePair<int, int>(3, 4)]));
Assert.AreEqual(1, dest.Single().Key);
}

/// <summary>
/// Tests that the pair overload of DeepCloneFrom throws for a null destination or source.
/// </summary>
[TestMethod]
public void PairCollection_DeepCloneFrom_ThrowsForNull()
{
ICollection<KeyValuePair<int, int>> dest = [];

Assert.ThrowsExactly<ArgumentNullException>(() => ((ICollection<KeyValuePair<int, int>>)null!).DeepCloneFrom([]));
Assert.ThrowsExactly<ArgumentNullException>(() => dest.DeepCloneFrom(null!));
}

/// <summary>
/// Tests that a list of pairs, which binds to the <see cref="List{T}"/> overload and so reaches its pairs through a
/// generic element type, still clones each pair's value through the reflection path where it is available (#82).
/// </summary>
[TestMethod]
public void PairList_DeepClone_ClonesValuesThroughTheGenericPath()
{
SimpleObject value = new() { Id = 1, Name = "One" };
List<KeyValuePair<int, SimpleObject>> source = [new(1, value)];

List<KeyValuePair<int, SimpleObject>> clone = source.DeepClone();

Assert.HasCount(1, clone);
Assert.AreNotSame(value, clone[0].Value);
Assert.AreEqual("One", clone[0].Value.Name);
}

/// <summary>
/// Tests that the pair overload of DeepClone hands a source that is itself <see cref="IDeepCloneable"/> to its own
/// DeepClone, as the <see cref="IEnumerable{T}"/> overload does.
/// </summary>
[TestMethod]
public void PairSequence_DeepClone_UsesTheSourcesOwnDeepClone()
{
IEnumerable<KeyValuePair<int, int>> source = new CloneablePairs([new(1, 2)]);

IEnumerable<KeyValuePair<int, int>> clone = source.DeepClone();

Assert.IsInstanceOfType<CloneablePairs>(clone);
Assert.AreNotSame(source, clone);
Assert.AreEqual(2, clone.Single().Value);
}

/// <summary>
/// A sequence of pairs that clones itself.
/// </summary>
/// <param name="pairs">The pairs it holds.</param>
private sealed class CloneablePairs(List<KeyValuePair<int, int>> pairs) : IEnumerable<KeyValuePair<int, int>>, IDeepCloneable
{
public object DeepClone() => new CloneablePairs([.. pairs]);

public IEnumerator<KeyValuePair<int, int>> GetEnumerator() => pairs.GetEnumerator();

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}

/// <summary>
/// Tests that a dictionary still binds to the dictionary overloads rather than the pair overloads, so it keeps its
/// type and comparer.
/// </summary>
[TestMethod]
public void Dictionary_StillBindsToDictionaryOverloads()
{
Dictionary<string, int> source = new(StringComparer.OrdinalIgnoreCase) { ["a"] = 1 };
Dictionary<string, int> dest = new(StringComparer.OrdinalIgnoreCase);

Dictionary<string, int> clone = source.DeepClone();
dest.DeepCloneFrom(source);

Assert.AreSame(StringComparer.OrdinalIgnoreCase, clone.Comparer);
Assert.AreEqual(1, dest["A"]);
}
}
5 changes: 5 additions & 0 deletions DeepClone/DeepClone.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
<Sdk Name="Microsoft.NET.Sdk" />
<Sdk Name="ktsu.Sdk" />

<!-- Fails the build on an AOT or trimming warning, such as the IL3050 that let ktsu-dev/DeepClone#92 ship. -->
<PropertyGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Polyfill" PrivateAssets="All" />
</ItemGroup>
Expand Down
113 changes: 105 additions & 8 deletions DeepClone/DeepCloneContainerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
#if NET
using System.Collections.Immutable;
Expand Down Expand Up @@ -55,7 +56,7 @@
/// Also 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 59 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 59 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 59 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);

Expand All @@ -73,6 +74,40 @@
ReplaceContents(dest, clones);
}

/// <summary>
/// Deep clones key-value pairs from a source sequence into a destination collection of pairs.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="dest">The destination collection to clone into.</param>
/// <param name="source">The source pairs to clone from.</param>
/// <remarks>
/// This behaves like <see cref="DeepCloneFrom{T}(ICollection{T}, IEnumerable{T})"/>, cloning each pair's key and
/// value. It binds when the pairs' key and value types are known where it is called, such as an
/// <see cref="IReadOnlyDictionary{TKey, TValue}"/> cloned into a <see cref="List{T}"/> of pairs, so the pairs are
/// cloned without building a cloner by reflection, which NativeAOT can't do for value-type keys or values
/// (ktsu-dev/DeepClone#92).
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if dest or source is null.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="dest"/> is read-only.</exception>
public static void DeepCloneFrom<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> dest, IEnumerable<KeyValuePair<TKey, TValue>> source)
{
Ensure.NotNull(dest);

Ensure.NotNull(source);

if (dest.IsReadOnly)
{
throw new ArgumentException("The destination collection is read-only, so it can't be cloned into.", nameof(dest));
}

EnsureSameComparer(dest, source);

KeyValuePair<TKey, TValue>[] clones = CloneAllPairs(source);

ReplaceContents(dest, clones);
}

/// <summary>
/// Deep clones items from a source sequence into a destination array of the same length, element by element.
/// </summary>
Expand Down Expand Up @@ -363,7 +398,7 @@
}

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

Check warning on line 401 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 401 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 @@ -535,7 +570,7 @@
/// <returns>The cloner, or <see langword="null"/>.</returns>
internal static IBoxedCloner? For(Type runtimeType) =>
IsKeyValuePair(runtimeType)
? Cloners.GetOrAdd(runtimeType, static type => (IBoxedCloner)CreatePairCloner(type.GetGenericArguments()))
? Cloners.GetOrAdd(runtimeType, static type => (IBoxedCloner?)CreatePairCloner(type.GetGenericArguments()))
: null;
}

Expand All @@ -548,13 +583,50 @@
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>);

/// <summary>
/// Creates the <see cref="PairElementCloner{TKey, TValue}"/> for a pair's key and value types. This is the one
/// place a pair cloner is made from reflected type arguments.
/// Creates the <see cref="PairElementCloner{TKey, TValue}"/> for a pair's key and value types, or returns
/// <see langword="null"/> when the runtime can't make that instantiation.
/// </summary>
/// <param name="pairArguments">The key and value types.</param>
/// <returns>The cloner.</returns>
private static object CreatePairCloner(Type[] pairArguments) =>
Activator.CreateInstance(typeof(PairElementCloner<,>).MakeGenericType(pairArguments))!;
/// <returns>The cloner, or <see langword="null"/>.</returns>
/// <remarks>
/// Under NativeAOT, <see cref="Type.MakeGenericType(Type[])"/> throws <see cref="NotSupportedException"/> for an
/// instantiation the compiler didn't generate, which is any pair with a value-type key or value. Thrown from
/// <see cref="PairCloner{T}"/>'s initializer, that became a <see cref="TypeInitializationException"/> that broke
/// every later clone of the element type (ktsu-dev/DeepClone#92). Such a pair is now copied as it is, as it
/// was before #82, and this returns <see langword="null"/>. The pair overloads, such as
/// <see cref="DeepClone{TKey, TValue}(IEnumerable{KeyValuePair{TKey, TValue}})"/>, clone it without reflection.
/// </remarks>
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "An instantiation the runtime can't make is caught, and the pair is then copied as it is (ktsu-dev/DeepClone#92).")]
private static object? CreatePairCloner(Type[] pairArguments)
{
try
{
return Activator.CreateInstance(typeof(PairElementCloner<,>).MakeGenericType(pairArguments));
}
catch (NotSupportedException)
{
return null;
}
}

/// <summary>
/// Creates the <see cref="NullablePairElementCloner{TKey, TValue}"/> for a pair's key and value types, or returns
/// <see langword="null"/> when the runtime can't make that instantiation, as <see cref="CreatePairCloner"/> does.
/// </summary>
/// <param name="pairArguments">The key and value types.</param>
/// <returns>The cloner, or <see langword="null"/>.</returns>
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "An instantiation the runtime can't make is caught, and the pair is then copied as it is (ktsu-dev/DeepClone#92).")]
private static object? CreateNullablePairCloner(Type[] pairArguments)

Check warning on line 619 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Move this method inside 'PairCloner'.

Check warning on line 619 in DeepClone/DeepCloneContainerExtensions.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Move this method inside 'PairCloner'.

Check warning on line 619 in DeepClone/DeepCloneContainerExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Move this method inside 'PairCloner'.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_DeepClone&issues=AaHP_o5ZXLp_2ad-3qLr&open=AaHP_o5ZXLp_2ad-3qLr&pullRequest=147
{
try
{
return Activator.CreateInstance(typeof(NullablePairElementCloner<,>).MakeGenericType(pairArguments));
}
catch (NotSupportedException)
{
return null;
}
}

/// <summary>
/// Caches, per element type, the cloner that clones it as a key-value pair.
Expand All @@ -573,12 +645,12 @@
{
if (IsKeyValuePair(typeof(T)))
{
return (IElementCloner<T>)CreatePairCloner(typeof(T).GetGenericArguments());
return (IElementCloner<T>?)CreatePairCloner(typeof(T).GetGenericArguments());
}

Type? underlying = Nullable.GetUnderlyingType(typeof(T));
return underlying is not null && IsKeyValuePair(underlying)
? (IElementCloner<T>)Activator.CreateInstance(typeof(NullablePairElementCloner<,>).MakeGenericType(underlying.GetGenericArguments()))!
? (IElementCloner<T>?)CreateNullablePairCloner(underlying.GetGenericArguments())
: null;
}
}
Expand Down Expand Up @@ -607,7 +679,7 @@
/// so the clone keeps the source's type and its other fields rather than becoming a list of cloned items.
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if source is null.</exception>
public static IEnumerable<T> DeepClone<T>(this IEnumerable<T> source)

Check warning on line 682 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 682 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 682 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 All @@ -619,6 +691,31 @@
return [.. CloneAll(source)];
}

/// <summary>
/// Deep clones a sequence of key-value pairs.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="source">The source pairs to clone.</param>
/// <returns>A snapshot of the pairs, each holding a deep clone of its key and value.</returns>
/// <remarks>
/// This behaves like <see cref="DeepClone{T}(IEnumerable{T})"/>. It binds when the pairs' key and value types are
/// known where it is called, so the pairs are cloned without building a cloner by reflection, which NativeAOT
/// can't do for value-type keys or values (ktsu-dev/DeepClone#92).
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if source is null.</exception>
public static IEnumerable<KeyValuePair<TKey, TValue>> DeepClone<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
{
Ensure.NotNull(source);

if (source is IDeepCloneable cloneable)
{
return (IEnumerable<KeyValuePair<TKey, TValue>>)cloneable.DeepClone();
}

return [.. CloneAllPairs(source)];
}

/// <summary>
/// Deep clones a dictionary.
/// </summary>
Expand Down
Loading