Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[API Proposal]: Create array from array type #88620

Merged
merged 26 commits into from
Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,7 @@ public static Attribute Instantiate(this CustomAttributeData cad)
IList<CustomAttributeTypedArgument>? typedElements = (IList<CustomAttributeTypedArgument>?)(typedArgument.Value);
if (typedElements == null)
return null;
Type? elementType = argumentType.GetElementType();
Array array = Array.CreateInstance(elementType, typedElements.Count);
Array array = Array.CreateInstanceFromArrayType(argumentType, typedElements.Count);
AlexRadch marked this conversation as resolved.
Show resolved Hide resolved
for (int i = 0; i < typedElements.Count; i++)
{
object? elementValue = typedElements[i].Convert();
Expand Down
67 changes: 35 additions & 32 deletions src/libraries/System.Private.CoreLib/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

<!--
Microsoft ResX Schema
Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -376,7 +376,7 @@
<data name="Arg_FormatException" xml:space="preserve">
<value>One of the identified items was in an invalid format.</value>
</data>
<data name= "Arg_GenericArgumentsAfterArrayOrPointerType" xml:space="preserve">
<data name="Arg_GenericArgumentsAfterArrayOrPointerType" xml:space="preserve">
<value>Generic arguments after array spec or pointer type.</value>
</data>
<data name="Arg_GenericParameter" xml:space="preserve">
Expand Down Expand Up @@ -1080,7 +1080,7 @@
<data name="Argument_FieldDoesNotBelongToConstructorClass" xml:space="preserve">
<value>Field '{0}' does not belong to the same class as the constructor.</value>
</data>
<data name="Argument_FieldDoesNotHaveAValidType" xml:space="preserve">
<data name="Argument_FieldDoesNotHaveAValidType" xml:space="preserve">
<value>Field '{0}' does not have a valid type.</value>
</data>
<data name="Argument_FieldDoesNotHaveAValidValue" xml:space="preserve">
Expand Down Expand Up @@ -1496,7 +1496,7 @@
<value>Path cannot be the empty string or all whitespace.</value>
</data>
<data name="Argument_ParameterHasUnmatchedArgumentValue" xml:space="preserve">
<value>Value of argument {0} does not match parameter type: {1} -> {2}.</value>
<value>Value of argument {0} does not match parameter type: {1} -&gt; {2}.</value>
</data>
<data name="Argument_ParameterInvalidType" xml:space="preserve">
<value>Parameter {0} does not have a valid type.</value>
Expand Down Expand Up @@ -3762,7 +3762,7 @@
<value>"Property '{0}' does not have a setter.</value>
</data>
<data name="Argument_PropertyUnmatchingPropertyType" xml:space="preserve">
<value>"Value of property '{0}' does not match property type: '{1}' -> '{2}'.</value>
<value>"Value of property '{0}' does not match property type: '{1}' -&gt; '{2}'.</value>
</data>
<data name="AssemblyDependencyResolver_FailedToLoadHostpolicy" xml:space="preserve">
<value>Cannot load hostpolicy library. AssemblyDependencyResolver is currently only supported if the runtime is hosted through hostpolicy library.</value>
Expand Down Expand Up @@ -4235,4 +4235,7 @@
<data name="OutOfMemory_StringTooLong" xml:space="preserve">
<value>String length exceeded supported range.</value>
</data>
</root>
<data name="Arg_MustBeArrayType" xml:space="preserve">
<value>Type must be a array type.</value>
AlexRadch marked this conversation as resolved.
Show resolved Hide resolved
</data>
</root>
68 changes: 68 additions & 0 deletions src/libraries/System.Private.CoreLib/src/System/Array.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,74 @@ public static Array CreateInstance(Type elementType, params long[] lengths)
return CreateInstance(elementType, intLengths);
}

public static unsafe Array CreateInstanceFromArrayType(Type arrayType, int length)
AlexRadch marked this conversation as resolved.
Show resolved Hide resolved
{
ArgumentNullException.ThrowIfNull(arrayType);
ArgumentOutOfRangeException.ThrowIfNegative(length);

if (!arrayType.IsArray)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeArrayType, ExceptionArgument.arrayType);

RuntimeType t = (arrayType.GetElementType()!.UnderlyingSystemType as RuntimeType)!;
Debug.Assert(t is not null, $"CreateInstanceFromArrayType can not get underlying system type for \"{arrayType}\"");
AlexRadch marked this conversation as resolved.
Show resolved Hide resolved

return InternalCreate(t, 1, &length, null);
}

public static unsafe Array CreateInstanceFromArrayType(Type arrayType, params int[] lengths)
{
ArgumentNullException.ThrowIfNull(arrayType);
ArgumentNullException.ThrowIfNull(lengths);
if (lengths.Length == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);

if (!arrayType.IsArray)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeArrayType, ExceptionArgument.arrayType);

RuntimeType t = (arrayType.GetElementType()!.UnderlyingSystemType as RuntimeType)!;
Debug.Assert(t is not null, $"CreateInstanceFromArrayType can not get underlying system type for \"{arrayType}\"");

// Check to make sure the lengths are all non-negative. Note that we check this here to give
// a good exception message if they are not; however we check this again inside the execution
// engine's low level allocation function after having made a copy of the array to prevent a
// malicious caller from mutating the array after this check.
for (int i = 0; i < lengths.Length; i++)
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);

fixed (int* pLengths = &lengths[0])
return InternalCreate(t, lengths.Length, pLengths, null);
}

public static unsafe Array CreateInstanceFromArrayType(Type arrayType, int[] lengths, int[] lowerBounds)
{
ArgumentNullException.ThrowIfNull(arrayType);
ArgumentNullException.ThrowIfNull(lengths);
ArgumentNullException.ThrowIfNull(lowerBounds);
if (lengths.Length != lowerBounds.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds);
if (lengths.Length == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);

if (!arrayType.IsArray)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeArrayType, ExceptionArgument.arrayType);

RuntimeType t = (arrayType.GetElementType()!.UnderlyingSystemType as RuntimeType)!;
Debug.Assert(t is not null, $"CreateInstanceFromArrayType can not get underlying system type for \"{arrayType}\"");

// Check to make sure the lengths are all non-negative. Note that we check this here to give
// a good exception message if they are not; however we check this again inside the execution
// engine's low level allocation function after having made a copy of the array to prevent a
// malicious caller from mutating the array after this check.
for (int i = 0; i < lengths.Length; i++)
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);

fixed (int* pLengths = &lengths[0])
fixed (int* pLowerBounds = &lowerBounds[0])
return InternalCreate(t, lengths.Length, pLengths, pLowerBounds);
}

public static void Copy(Array sourceArray, Array destinationArray, long length)
{
int ilength = (int)length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,8 @@ private static string GetArgumentName(ExceptionArgument argument)
return "overlapped";
case ExceptionArgument.minimumBytes:
return "minimumBytes";
case ExceptionArgument.arrayType:
return "arrayType";
default:
Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum.");
return "";
Expand Down Expand Up @@ -1147,6 +1149,8 @@ private static string GetResourceString(ExceptionResource resource)
return SR.Format_UnclosedFormatItem;
case ExceptionResource.Format_ExpectedAsciiDigit:
return SR.Format_ExpectedAsciiDigit;
case ExceptionResource.Arg_MustBeArrayType:
return SR.Arg_MustBeArrayType;
default:
Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum.");
return "";
Expand Down Expand Up @@ -1258,6 +1262,7 @@ internal enum ExceptionArgument
anyOf,
overlapped,
minimumBytes,
arrayType,
}

//
Expand Down Expand Up @@ -1343,5 +1348,6 @@ internal enum ExceptionResource
Format_UnexpectedClosingBrace,
Format_UnclosedFormatItem,
Format_ExpectedAsciiDigit,
Arg_MustBeArrayType,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -572,8 +572,7 @@ private static void SetCollectionObjectWithCollectionMember([NotNull] ref object
}
else
{
Type elementType = collectionType.GetElementType()!;
a = Array.CreateInstance(elementType, collectionMember.Count);
a = Array.CreateInstanceFromArrayType(collectionType, collectionMember.Count);
jkotas marked this conversation as resolved.
Show resolved Hide resolved
}

for (int i = 0; i < collectionMember.Count; i++)
Expand Down
3 changes: 3 additions & 0 deletions src/libraries/System.Runtime/ref/System.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,9 @@ public void CopyTo(System.Array array, long index) { }
public static System.Array CreateInstance(System.Type elementType, int[] lengths, int[] lowerBounds) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("The code for an array of the specified type might not be available.")]
public static System.Array CreateInstance(System.Type elementType, params long[] lengths) { throw null; }
public static System.Array CreateInstanceFromArrayType(System.Type arrayType, int length) { throw null; }
public static System.Array CreateInstanceFromArrayType(System.Type arrayType, params int[] lengths) { throw null; }
public static System.Array CreateInstanceFromArrayType(System.Type arrayType, int[] lengths, int[] lowerBounds) { throw null; }
public static T[] Empty<T>() { throw null; }
public static bool Exists<T>(T[] array, System.Predicate<T> match) { throw null; }
public static void Fill<T>(T[] array, T value) { }
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Runtime/tests/Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ private static Type RefEmitType()
private sealed class NonRuntimeType : MockType
{
public sealed override Type UnderlyingSystemType => this;
protected sealed override bool IsArrayImpl() => false;
}
}
}
Loading