Expression tree cloner can now clone multi-dimensional arrays

git-svn-id: file:///srv/devel/repo-conversion/nusu@232 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2012-02-04 14:22:59 +00:00
parent 1307976597
commit 79063f59c1
2 changed files with 394 additions and 193 deletions

View File

@ -27,33 +27,43 @@ using NUnit.Framework;
namespace Nuclex.Support.Cloning { namespace Nuclex.Support.Cloning {
/// <summary>Unit Test for the expression tree-based cloner</summary> /// <summary>Unit Test for the expression tree-based cloner</summary>
[TestFixture] [TestFixture]
public class ExpressionTreeClonerTest : CloneFactoryTest { public class ExpressionTreeClonerTest : CloneFactoryTest {
/// <summary>Initializes a new unit test suite for the reflection cloner</summary> /// <summary>Initializes a new unit test suite for the reflection cloner</summary>
public ExpressionTreeClonerTest() { public ExpressionTreeClonerTest() {
this.cloneFactory = new ExpressionTreeCloner(); this.cloneFactory = new ExpressionTreeCloner();
} }
/// <summary>Verifies that clones of primitive types can be created</summary> /// <summary>Verifies that clones of primitive types can be created</summary>
[Test] [Test]
public void PrimitiveTypesCanBeCloned() { public void PrimitiveTypesCanBeCloned() {
int original = 12345; int original = 12345;
int clone = this.cloneFactory.DeepClone(original, false); int clone = this.cloneFactory.DeepClone(original, false);
Assert.AreEqual(original, clone); Assert.AreEqual(original, clone);
} }
/// <summary>Verifies that shallow clones of arrays can be made</summary> /// <summary>Verifies that shallow clones of arrays can be made</summary>
[Test] [Test]
public void ReferenceTypesCanBeCloned() { public void ReferenceTypesCanBeCloned() {
var original = new TestReferenceType() { TestField = 123, TestProperty = 456 }; var original = new TestReferenceType() { TestField = 123, TestProperty = 456 };
TestReferenceType clone = this.cloneFactory.DeepClone(original, false); TestReferenceType clone = this.cloneFactory.DeepClone(original, false);
Assert.AreNotSame(original, clone); Assert.AreNotSame(original, clone);
Assert.AreEqual(original.TestField, clone.TestField); Assert.AreEqual(original.TestField, clone.TestField);
Assert.AreEqual(original.TestProperty, clone.TestProperty); Assert.AreEqual(original.TestProperty, clone.TestProperty);
} }
/// <summary>Verifies that shallow clones of arrays can be made</summary>
[Test]
public void PrimitiveArraysCanBeCloned() {
var original = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] clone = this.cloneFactory.DeepClone(original, false);
Assert.AreNotSame(original, clone);
CollectionAssert.AreEqual(original, clone);
}
#if false #if false
/// <summary>Verifies that shallow clones of arrays can be made</summary> /// <summary>Verifies that shallow clones of arrays can be made</summary>
@ -66,20 +76,22 @@ namespace Nuclex.Support.Cloning {
Assert.AreSame(original[0], clone[0]); Assert.AreSame(original[0], clone[0]);
} }
//#endif #endif
/// <summary>Verifies that deep clones of arrays can be made</summary> /// <summary>Verifies that deep clones of arrays can be made</summary>
[Test] [Test]
public void DeepClonesOfArraysCanBeMade() { public void DeepClonesOfArraysCanBeMade() {
var original = new TestReferenceType[] { var original = new TestReferenceType[,] {
new TestReferenceType() { TestField = 123, TestProperty = 456 } {
new TestReferenceType() { TestField = 123, TestProperty = 456 }
}
}; };
TestReferenceType[] clone = this.cloneFactory.DeepClone(original, false); TestReferenceType[,] clone = this.cloneFactory.DeepClone(original, false);
Assert.AreNotSame(original[0], clone[0]); Assert.AreNotSame(original[0, 0], clone[0, 0]);
Assert.AreEqual(original[0].TestField, clone[0].TestField); //Assert.AreEqual(original[0,0].TestField, clone[0,0].TestField);
Assert.AreEqual(original[0].TestProperty, clone[0].TestProperty); //Assert.AreEqual(original[0,0].TestProperty, clone[0,0].TestProperty);
} }
//#if false #if false
/// <summary>Verifies that deep clones of a generic list can be made</summary> /// <summary>Verifies that deep clones of a generic list can be made</summary>
[Test] [Test]
public void GenericListsCanBeCloned() { public void GenericListsCanBeCloned() {
@ -180,10 +192,10 @@ namespace Nuclex.Support.Cloning {
} }
#endif #endif
/// <summary>Clone factory being tested</summary> /// <summary>Clone factory being tested</summary>
private ICloneFactory cloneFactory; private ICloneFactory cloneFactory;
} }
} // namespace Nuclex.Support.Cloning } // namespace Nuclex.Support.Cloning

View File

@ -28,174 +28,363 @@ using System.Collections.Generic;
namespace Nuclex.Support.Cloning { namespace Nuclex.Support.Cloning {
/// <summary>An action that takes its arguments as references to a structure</summary> /// <summary>An action that takes its arguments as references to a structure</summary>
/// <typeparam name="TFirst">Type of the first argument to the method</typeparam> /// <typeparam name="TFirst">Type of the first argument to the method</typeparam>
/// <typeparam name="TSecond">Type of the second argument to the method</typeparam> /// <typeparam name="TSecond">Type of the second argument to the method</typeparam>
/// <param name="first">First argument to the method</param> /// <param name="first">First argument to the method</param>
/// <param name="second">Second argument to the method</param> /// <param name="second">Second argument to the method</param>
public delegate void ReferenceAction<TFirst, TSecond>(ref TFirst first, ref TSecond second) public delegate void ReferenceAction<TFirst, TSecond>(ref TFirst first, ref TSecond second)
where TFirst : struct where TFirst : struct
where TSecond : struct; where TSecond : struct;
/// <summary> /// <summary>
/// Cloning factory which uses expression trees to improve performance when cloning /// Cloning factory which uses expression trees to improve performance when cloning
/// is a high-frequency action. /// is a high-frequency action.
/// </summary> /// </summary>
public class ExpressionTreeCloner : ICloneFactory { public class ExpressionTreeCloner : ICloneFactory {
/// <summary>Initializes the static members of the expression tree cloner</summary> /// <summary>Initializes the static members of the expression tree cloner</summary>
static ExpressionTreeCloner() { static ExpressionTreeCloner() {
shallowCloners = new ConcurrentDictionary<Type, Delegate>(); shallowCloners = new ConcurrentDictionary<Type, Delegate>();
deepCloners = new ConcurrentDictionary<Type, Delegate>(); deepCloners = new ConcurrentDictionary<Type, Delegate>();
} }
/// <summary> /// <summary>
/// Creates a deep clone of the specified object, also creating clones of all /// Creates a deep clone of the specified object, also creating clones of all
/// child objects being referenced /// child objects being referenced
/// </summary> /// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam> /// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param> /// <param name="objectToClone">Object that will be cloned</param>
/// <param name="usePropertyBasedClone"> /// <param name="usePropertyBasedClone">
/// Whether to clone the object based on its properties only /// Whether to clone the object based on its properties only
/// </param> /// </param>
/// <returns>A deep clone of the provided object</returns> /// <returns>A deep clone of the provided object</returns>
public static TCloned DeepClone<TCloned>( public static TCloned DeepClone<TCloned>(
TCloned objectToClone, bool usePropertyBasedClone TCloned objectToClone, bool usePropertyBasedClone
) { ) {
if(usePropertyBasedClone) { if(usePropertyBasedClone) {
throw new NotImplementedException("Not implemented yet"); throw new NotImplementedException("Not implemented yet");
} else { } else {
Func<TCloned, TCloned> cloner = getOrCreateDeepFieldBasedCloner<TCloned>(); Func<TCloned, TCloned> cloner = getOrCreateDeepFieldBasedCloner<TCloned>();
return cloner(objectToClone); return cloner(objectToClone);
} }
} }
/// <summary> /// <summary>
/// Creates a shallow clone of the specified object, reusing any referenced objects /// Creates a shallow clone of the specified object, reusing any referenced objects
/// </summary> /// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam> /// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param> /// <param name="objectToClone">Object that will be cloned</param>
/// <param name="usePropertyBasedClone"> /// <param name="usePropertyBasedClone">
/// Whether to clone the object based on its properties only /// Whether to clone the object based on its properties only
/// </param> /// </param>
/// <returns>A shallow clone of the provided object</returns> /// <returns>A shallow clone of the provided object</returns>
public static TCloned ShallowClone<TCloned>( public static TCloned ShallowClone<TCloned>(
TCloned objectToClone, bool usePropertyBasedClone TCloned objectToClone, bool usePropertyBasedClone
) { ) {
throw new NotImplementedException("Not implemented yet"); throw new NotImplementedException("Not implemented yet");
} }
/// <summary> /// <summary>
/// Creates a deep clone of the specified object, also creating clones of all /// Creates a deep clone of the specified object, also creating clones of all
/// child objects being referenced /// child objects being referenced
/// </summary> /// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam> /// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param> /// <param name="objectToClone">Object that will be cloned</param>
/// <param name="usePropertyBasedClone"> /// <param name="usePropertyBasedClone">
/// Whether to clone the object based on its properties only /// Whether to clone the object based on its properties only
/// </param> /// </param>
/// <returns>A deep clone of the provided object</returns> /// <returns>A deep clone of the provided object</returns>
TCloned ICloneFactory.DeepClone<TCloned>( TCloned ICloneFactory.DeepClone<TCloned>(
TCloned objectToClone, bool usePropertyBasedClone TCloned objectToClone, bool usePropertyBasedClone
) { ) {
return ExpressionTreeCloner.DeepClone<TCloned>(objectToClone, usePropertyBasedClone); return ExpressionTreeCloner.DeepClone<TCloned>(objectToClone, usePropertyBasedClone);
} }
/// <summary> /// <summary>
/// Creates a shallow clone of the specified object, reusing any referenced objects /// Creates a shallow clone of the specified object, reusing any referenced objects
/// </summary> /// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam> /// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param> /// <param name="objectToClone">Object that will be cloned</param>
/// <param name="usePropertyBasedClone"> /// <param name="usePropertyBasedClone">
/// Whether to clone the object based on its properties only /// Whether to clone the object based on its properties only
/// </param> /// </param>
/// <returns>A shallow clone of the provided object</returns> /// <returns>A shallow clone of the provided object</returns>
TCloned ICloneFactory.ShallowClone<TCloned>( TCloned ICloneFactory.ShallowClone<TCloned>(
TCloned objectToClone, bool usePropertyBasedClone TCloned objectToClone, bool usePropertyBasedClone
) { ) {
return ExpressionTreeCloner.ShallowClone<TCloned>(objectToClone, usePropertyBasedClone); return ExpressionTreeCloner.ShallowClone<TCloned>(objectToClone, usePropertyBasedClone);
} }
/// <summary> /// <summary>
/// Retrieves the existing clone method for the specified type or compiles one if /// Retrieves the existing clone method for the specified type or compiles one if
/// none exists for the type yet /// none exists for the type yet
/// </summary> /// </summary>
/// <typeparam name="TCloned">Type for which a clone method will be retrieved</typeparam> /// <typeparam name="TCloned">Type for which a clone method will be retrieved</typeparam>
/// <returns>The clone method for the specified type</returns> /// <returns>The clone method for the specified type</returns>
private static Func<TCloned, TCloned> getOrCreateDeepFieldBasedCloner<TCloned>() { private static Func<TCloned, TCloned> getOrCreateDeepFieldBasedCloner<TCloned>() {
Type clonedType = typeof(TCloned); Type clonedType = typeof(TCloned);
Delegate clonerAsDelegate; Delegate clonerAsDelegate;
if(deepCloners.TryGetValue(clonedType, out clonerAsDelegate)) { if(deepCloners.TryGetValue(clonedType, out clonerAsDelegate)) {
return (Func<TCloned, TCloned>)clonerAsDelegate; return (Func<TCloned, TCloned>)clonerAsDelegate;
} else { } else {
Func<TCloned, TCloned> cloner = createDeepFieldBasedCloner<TCloned>(); Func<TCloned, TCloned> cloner = createDeepFieldBasedCloner<TCloned>();
deepCloners.TryAdd(clonedType, cloner); deepCloners.TryAdd(clonedType, cloner);
return cloner; return cloner;
} }
} }
/// <summary>Compiles a method that creates a clone of an object</summary> /// <summary>
/// <typeparam name="TCloned">Type for which a clone method will be created</typeparam> /// Generates state transfer expressions to copy an array of primitive types
/// <returns>A method that clones an object of the provided type</returns> /// </summary>
private static Func<TCloned, TCloned> createDeepFieldBasedCloner<TCloned>() { /// <param name="clonedType">Type of array that will be cloned</param>
Type clonedType = typeof(TCloned); /// <param name="original">Variable expression for the original array</param>
/// <param name="variables">Receives variables used by the transfer expressions</param>
/// <param name="transferExpressions">Receives the generated transfer expressions</param>
private static void generatePrimitiveArrayTransferExpressions(
Type clonedType,
ParameterExpression original,
ICollection<ParameterExpression> variables,
ICollection<Expression> transferExpressions
) {
// We need a temporary variable because the IfThen expression is not suitable
// for returning values
ParameterExpression clone = Expression.Variable(clonedType, "clone");
variables.Add(clone);
ParameterExpression original = Expression.Parameter(typeof(TCloned), "original"); // If the array referenced by 'original' is not null, call Array.Clone() on it
ParameterExpression clone = Expression.Variable(typeof(TCloned), "clone"); // and assign the result to our temporary variable
MethodInfo arrayCloneMethodInfo = typeof(Array).GetMethod("Clone");
transferExpressions.Add(
Expression.IfThen(
Expression.NotEqual(original, Expression.Constant(null)),
Expression.Assign(
clone,
Expression.Convert(
Expression.Call(original, arrayCloneMethodInfo),
clonedType
)
)
)
);
var transferExpressions = new List<Expression>(); // Set the return value to the temporary variable
transferExpressions.Add(clone);
}
if(clonedType.IsPrimitive || (clonedType == typeof(string))) { /// <summary>
transferExpressions.Add(original); // primitives are copied on assignment /// Generates state transfer expressions to copy an array of complex types
} else if(clonedType.IsArray) { /// </summary>
Type elementType = clonedType.GetElementType(); /// <param name="clonedType">Type of array that will be cloned</param>
if(elementType.IsPrimitive || (elementType == typeof(string))) { /// <param name="original">Variable expression for the original array</param>
MethodInfo arrayCloneMethodInfo = typeof(Array).GetMethod("Clone"); /// <param name="variables">Receives variables used by the transfer expressions</param>
transferExpressions.Add( /// <param name="transferExpressions">Receives the generated transfer expressions</param>
Expression.Convert( private static void generateComplexArrayTransferExpressions(
Expression.Call(original, arrayCloneMethodInfo), Type clonedType,
clonedType ParameterExpression original,
) IList<ParameterExpression> variables,
); ICollection<Expression> transferExpressions
} else { ) {
} // We need a temporary variable because the IfThen expression is not suitable
// for returning values
ParameterExpression clone = Expression.Variable(clonedType, "clone");
variables.Add(clone);
} else { int dimensionCount = clonedType.GetArrayRank();
transferExpressions.Add(Expression.Assign(clone, Expression.New(clonedType))); int baseVariableIndex = variables.Count;
var arrayTransferExpressions = new List<Expression>();
Type elementType = clonedType.GetElementType();
FieldInfo[] fieldInfos = clonedType.GetFields( // Retrieve the length of each of the array's dimensions
BindingFlags.Public | BindingFlags.NonPublic | MethodInfo arrayGetLengthMethodInfo = typeof(Array).GetMethod("GetLength");
BindingFlags.Instance | BindingFlags.FlattenHierarchy for(int index = 0; index < dimensionCount; ++index) {
); ParameterExpression length = Expression.Variable(typeof(int));
variables.Add(length);
arrayTransferExpressions.Add(
Expression.Assign(
length,
Expression.Call(original, arrayGetLengthMethodInfo, Expression.Constant(index))
)
);
}
for(int index = 0; index < fieldInfos.Length; ++index) { // Create a new array of identical size
FieldInfo fieldInfo = fieldInfos[index]; switch(dimensionCount) {
Type fieldType = fieldInfo.FieldType; case 1: {
MethodInfo arrayCreateInstanceMethodInfo = typeof(Array).GetMethod(
"CreateInstance", new Type[] { typeof(Type), typeof(int) }
);
arrayTransferExpressions.Add(
Expression.Assign(
clone,
Expression.Convert(
Expression.Call(
arrayCreateInstanceMethodInfo,
Expression.Constant(elementType),
variables[baseVariableIndex]
),
clonedType
)
)
);
break;
}
case 2: {
MethodInfo arrayCreateInstanceMethodInfo = typeof(Array).GetMethod(
"CreateInstance", new Type[] { typeof(Type), typeof(int), typeof(int) }
);
arrayTransferExpressions.Add(
Expression.Assign(
clone,
Expression.Convert(
Expression.Call(
arrayCreateInstanceMethodInfo,
Expression.Constant(elementType),
variables[baseVariableIndex],
variables[baseVariableIndex + 1]
),
clonedType
)
)
);
break;
}
case 3: {
MethodInfo arrayCreateInstanceMethodInfo = typeof(Array).GetMethod(
"CreateInstance", new Type[] { typeof(Type), typeof(int), typeof(int), typeof(int) }
);
arrayTransferExpressions.Add(
Expression.Assign(
clone,
Expression.Convert(
Expression.Call(
arrayCreateInstanceMethodInfo,
Expression.Constant(elementType),
variables[baseVariableIndex],
variables[baseVariableIndex + 1],
variables[baseVariableIndex + 2]
),
clonedType
)
)
);
break;
}
default: {
throw new InvalidOperationException("Unsupported array dimension count");
}
if(fieldType.IsPrimitive) { }
transferExpressions.Add(
Expression.Assign(
Expression.Field(clone, fieldInfo),
Expression.Field(original, fieldInfo)
)
);
}
}
transferExpressions.Add(clone); // Only execute the array transfer expressions if the array is not null
} transferExpressions.Add(
Expression.IfThen(
Expression.NotEqual(original, Expression.Constant(null)),
Expression.Block(arrayTransferExpressions)
)
);
Expression<Func<TCloned, TCloned>> expression = // Set the return value to the temporary variable
Expression.Lambda<Func<TCloned, TCloned>>( transferExpressions.Add(clone);
Expression.Block( }
new[] { clone },
transferExpressions
),
original
);
return expression.Compile(); /// <summary>Generates state transfer expressions to copy a complex type</summary>
} /// <param name="clonedType">Complex type that will be cloned</param>
/// <param name="original">Variable expression for the original instance</param>
/// <param name="variables">Receives variables used by the transfer expressions</param>
/// <param name="transferExpressions">Receives the generated transfer expressions</param>
private static void generateComplexTypeTransferExpressions(
Type clonedType,
ParameterExpression original,
ICollection<ParameterExpression> variables,
ICollection<Expression> transferExpressions
) {
// We need a temporary variable because the IfThen expression is not suitable
// for returning values
ParameterExpression clone = Expression.Variable(clonedType, "clone");
variables.Add(clone);
var complexTransferExpressions = new List<Expression>();
complexTransferExpressions.Add(Expression.Assign(clone, Expression.New(clonedType)));
FieldInfo[] fieldInfos = clonedType.GetFields(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.FlattenHierarchy
);
for(int index = 0; index < fieldInfos.Length; ++index) {
FieldInfo fieldInfo = fieldInfos[index];
Type fieldType = fieldInfo.FieldType;
if(fieldType.IsPrimitive) {
complexTransferExpressions.Add(
Expression.Assign(
Expression.Field(clone, fieldInfo),
Expression.Field(original, fieldInfo)
)
);
}
}
transferExpressions.Add(
Expression.IfThen(
Expression.NotEqual(original, Expression.Constant(null)),
Expression.Block(complexTransferExpressions)
)
);
// Set the return value to the temporary variable
transferExpressions.Add(clone);
}
/// <summary>Compiles a method that creates a clone of an object</summary>
/// <typeparam name="TCloned">Type for which a clone method will be created</typeparam>
/// <returns>A method that clones an object of the provided type</returns>
private static Func<TCloned, TCloned> createDeepFieldBasedCloner<TCloned>() {
Type clonedType = typeof(TCloned);
ParameterExpression original = Expression.Parameter(typeof(TCloned), "original");
ParameterExpression clone = Expression.Variable(typeof(TCloned), "clone");
var transferExpressions = new List<Expression>();
var variables = new List<ParameterExpression>();
if(clonedType.IsPrimitive || (clonedType == typeof(string))) {
transferExpressions.Add(original); // primitives are copied on assignment
} else if(clonedType.IsArray) {
Type elementType = clonedType.GetElementType();
if(elementType.IsPrimitive || (elementType == typeof(string))) {
generatePrimitiveArrayTransferExpressions(
clonedType, original, variables, transferExpressions
);
} else {
generateComplexArrayTransferExpressions(
clonedType, original, variables, transferExpressions
);
}
} else {
generateComplexTypeTransferExpressions(
clonedType, original, variables, transferExpressions
);
}
Expression<Func<TCloned, TCloned>> expression;
if(variables.Count > 0) {
expression = Expression.Lambda<Func<TCloned, TCloned>>(
Expression.Block(variables, transferExpressions), original
);
} else if(transferExpressions.Count == 1) {
expression = Expression.Lambda<Func<TCloned, TCloned>>(
transferExpressions[0], original
);
} else {
expression = Expression.Lambda<Func<TCloned, TCloned>>(
Expression.Block(transferExpressions), original
);
}
return expression.Compile();
}
#if false #if false
/// <summary> /// <summary>
@ -274,12 +463,12 @@ namespace Nuclex.Support.Cloning {
} }
#endif #endif
/// <summary>Compiled cloners that perform shallow clone operations</summary> /// <summary>Compiled cloners that perform shallow clone operations</summary>
private static ConcurrentDictionary<Type, Delegate> shallowCloners; private static ConcurrentDictionary<Type, Delegate> shallowCloners;
/// <summary>Compiled cloners that perform deep clone operations</summary> /// <summary>Compiled cloners that perform deep clone operations</summary>
private static ConcurrentDictionary<Type, Delegate> deepCloners; private static ConcurrentDictionary<Type, Delegate> deepCloners;
} }
} // namespace Nuclex.Support.Cloning } // namespace Nuclex.Support.Cloning