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

Implement IList<T> on Enumerable.Cast<T> for IList #97956

Merged
merged 4 commits into from
Feb 23, 2024
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
24 changes: 16 additions & 8 deletions src/libraries/System.Linq/System.Linq.sln
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
Microsoft Visual Studio Solution File, Format Version 12.00

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.34618.27
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{AF1B1B01-A4EC-45F4-AE51-CC1FA7892181}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Collections", "..\System.Collections\ref\System.Collections.csproj", "{3A8560D8-0E79-4BDE-802A-C96C7FE98258}"
Expand Down Expand Up @@ -35,11 +39,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8CA90AB2-58B
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{84E98F7C-FA2B-4048-AB7C-9FCDEA9CD37E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "tools\gen", "{34793393-0347-438D-A832-2476F33C1BE3}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{34793393-0347-438D-A832-2476F33C1BE3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "tools\src", "{F8F69023-9ACD-4979-A710-39D16377AEEE}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F8F69023-9ACD-4979-A710-39D16377AEEE}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "tools\ref", "{18C4E23D-AB0F-45E5-A6A1-A741F6462E85}"
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{18C4E23D-AB0F-45E5-A6A1-A741F6462E85}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{0ADC596A-5B2E-4E5F-B5B5-DEB65A6C7E9D}"
EndProject
Expand Down Expand Up @@ -111,24 +115,28 @@ Global
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{AF1B1B01-A4EC-45F4-AE51-CC1FA7892181} = {E291F4BF-7B8B-45AD-88F5-FB8B8380C126}
{80A4051B-4A36-4A8B-BA43-A5AB8AA959F3} = {E291F4BF-7B8B-45AD-88F5-FB8B8380C126}
{3A8560D8-0E79-4BDE-802A-C96C7FE98258} = {7C5B49B9-F7D9-41FB-A8FA-94328BDDCCD1}
{7E4C1F09-B4F2-470E-9E7B-2C386E93D657} = {7C5B49B9-F7D9-41FB-A8FA-94328BDDCCD1}
{D3160C37-FC48-4907-8F4A-F584ED12B275} = {7C5B49B9-F7D9-41FB-A8FA-94328BDDCCD1}
{14B966BB-CE23-4432-ADBB-89974389AC1D} = {8CA90AB2-58B9-45E7-A684-EDB60C6924B0}
{80A4051B-4A36-4A8B-BA43-A5AB8AA959F3} = {E291F4BF-7B8B-45AD-88F5-FB8B8380C126}
{9A13A12F-C924-43AF-94AF-6F1B33582D27} = {84E98F7C-FA2B-4048-AB7C-9FCDEA9CD37E}
{4BEC631E-B5FD-453F-82A0-C95C461798EA} = {84E98F7C-FA2B-4048-AB7C-9FCDEA9CD37E}
{C8F0459C-15D5-4624-8CE4-E93ADF96A28C} = {84E98F7C-FA2B-4048-AB7C-9FCDEA9CD37E}
{D3160C37-FC48-4907-8F4A-F584ED12B275} = {7C5B49B9-F7D9-41FB-A8FA-94328BDDCCD1}
{E0CA3ED5-EE6C-4F7C-BCE7-EFB1D64A9CD1} = {34793393-0347-438D-A832-2476F33C1BE3}
{3EFB74E7-616A-48C1-B43B-3F89AA5013E6} = {34793393-0347-438D-A832-2476F33C1BE3}
{34793393-0347-438D-A832-2476F33C1BE3} = {0ADC596A-5B2E-4E5F-B5B5-DEB65A6C7E9D}
{28ABC524-ACEE-4183-A64A-49E3DC830595} = {F8F69023-9ACD-4979-A710-39D16377AEEE}
{721DB3D9-8221-424E-BE29-084CDD20D26E} = {F8F69023-9ACD-4979-A710-39D16377AEEE}
{F8F69023-9ACD-4979-A710-39D16377AEEE} = {0ADC596A-5B2E-4E5F-B5B5-DEB65A6C7E9D}
{E19B8772-2DBD-4274-8190-F3CC0242A1C0} = {18C4E23D-AB0F-45E5-A6A1-A741F6462E85}
{34793393-0347-438D-A832-2476F33C1BE3} = {0ADC596A-5B2E-4E5F-B5B5-DEB65A6C7E9D}
{F8F69023-9ACD-4979-A710-39D16377AEEE} = {0ADC596A-5B2E-4E5F-B5B5-DEB65A6C7E9D}
{18C4E23D-AB0F-45E5-A6A1-A741F6462E85} = {0ADC596A-5B2E-4E5F-B5B5-DEB65A6C7E9D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A4970D79-BF1C-4343-9070-B409DBB69F93}
EndGlobalSection
GlobalSection(SharedMSBuildProjectFiles) = preSolution
..\..\tools\illink\src\ILLink.Shared\ILLink.Shared.projitems*{3efb74e7-616a-48c1-b43b-3f89aa5013e6}*SharedItemsImports = 5
..\..\tools\illink\src\ILLink.Shared\ILLink.Shared.projitems*{721db3d9-8221-424e-be29-084cdd20d26e}*SharedItemsImports = 5
EndGlobalSection
EndGlobal
1 change: 1 addition & 0 deletions src/libraries/System.Linq/src/System.Linq.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

<ItemGroup Condition="'$(OptimizeForSize)' != true">
<Compile Include="System\Linq\AppendPrepend.SpeedOpt.cs" />
<Compile Include="System\Linq\Cast.SpeedOpt.cs" />
<Compile Include="System\Linq\Concat.SpeedOpt.cs" />
<Compile Include="System\Linq\DefaultIfEmpty.SpeedOpt.cs" />
<Compile Include="System\Linq\Distinct.SpeedOpt.cs" />
Expand Down
122 changes: 122 additions & 0 deletions src/libraries/System.Linq/src/System/Linq/Cast.SpeedOpt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections;
using System.Collections.Generic;

namespace System.Linq
{
public static partial class Enumerable
{
private sealed partial class CastICollectionIterator<TResult> : IPartition<TResult>
{
public int GetCount(bool onlyIfCheap) => _source.Count;

public TResult[] ToArray()
{
TResult[] array = new TResult[_source.Count];

int index = 0;
foreach (TResult item in _source)
{
array[index++] = item;
}

return array;
}

public List<TResult> ToList()
{
List<TResult> list = new(_source.Count);

foreach (TResult item in _source)
{
list.Add(item);
}

return list;
}

public TResult? TryGetElementAt(int index, out bool found)
{
if (index >= 0)
{
IEnumerator e = _source.GetEnumerator();
try
{
while (e.MoveNext())
{
if (index == 0)
{
found = true;
return (TResult)e.Current;
}

index--;
}
}
finally
{
(e as IDisposable)?.Dispose();
}
}

found = false;
return default;
}

public TResult? TryGetFirst(out bool found)
{
IEnumerator e = _source.GetEnumerator();
try
{
if (e.MoveNext())
{
found = true;
return (TResult)e.Current;
}
}
finally
{
(e as IDisposable)?.Dispose();
}

found = false;
return default;
}

public TResult? TryGetLast(out bool found)
{
IEnumerator e = _source.GetEnumerator();
try
{
if (e.MoveNext())
{
TResult last = (TResult)e.Current;
while (e.MoveNext())
{
last = (TResult)e.Current;
}

found = true;
return last;
}

found = false;
return default;
}
finally
{
(e as IDisposable)?.Dispose();
}
}

public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
new SelectIPartitionIterator<TResult, TResult2>(this, selector);

public IPartition<TResult>? Skip(int count) => new EnumerablePartition<TResult>(this, count, -1);

public IPartition<TResult>? Take(int count) => new EnumerablePartition<TResult>(this, 0, count - 1);
}
}
}
47 changes: 47 additions & 0 deletions src/libraries/System.Linq/src/System/Linq/Cast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

namespace System.Linq
{
Expand Down Expand Up @@ -45,6 +46,11 @@ public static IEnumerable<
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}

if (source is ICollection collection)
{
return new CastICollectionIterator<TResult>(collection);
}

return CastIterator<TResult>(source);
}

Expand All @@ -55,5 +61,46 @@ private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
yield return (TResult)obj;
}
}

[DebuggerDisplay("Count = {Count}")]
private sealed partial class CastICollectionIterator<TResult>(ICollection source) : Iterator<TResult>
{
private readonly ICollection _source = source;
private IEnumerator? _enumerator;

public override Iterator<TResult> Clone() => new CastICollectionIterator<TResult>(_source);

public override bool MoveNext()
{
switch (_state)
{
case 1:
_enumerator = _source.GetEnumerator();
_state = 2;
goto case 2;

case 2:
Debug.Assert(_enumerator != null);
if (_enumerator.MoveNext())
{
_current = (TResult)_enumerator.Current;
return true;
}

Dispose();
break;
}

return false;
}

public override void Dispose()
{
(_enumerator as IDisposable)?.Dispose();
_enumerator = null;

base.Dispose();
}
}
}
}
97 changes: 96 additions & 1 deletion src/libraries/System.Linq/tests/CastTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using Xunit;

Expand Down Expand Up @@ -235,5 +234,101 @@ public void ForcedToEnumeratorDoesntEnumerate()
var en = iterator as IEnumerator<string>;
Assert.False(en != null && en.MoveNext());
}

[Fact]
public void TargetTypeIsSourceType_Nop()
{
object[] values = new string[] { "hello", "world" };
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
Assert.Same(values, values.Cast<string>());
}

[Fact]
public void CastOnMultidimensionalArraySucceeds()
{
Array array = Array.CreateInstance(typeof(int), 2, 3);
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
array.SetValue(i * 3 + j, i, j);
}
}

int[] result = array.Cast<int>().ToArray();
for (int i = 0; i < 6; i++)
{
Assert.Equal(i, result[i]);
}
}

[Fact]
public void CastCountReturnsExpectedLength()
{
object[] objects = new object[] { "hello", "world" };
Assert.Equal(2, objects.Cast<string>().Count());
}

[Fact]
public void CastFirstReturnsFirstElement()
{
object[] objects = new object[] { "hello", "world" };
Assert.Equal("hello", objects.Cast<string>().First());
}

[Fact]
public void CastFirstOnEmptySequenceThrows()
{
object[] objects = Array.Empty<object>();
Assert.Throws<InvalidOperationException>(() => objects.Cast<string>().First());
}

[Fact]
public void CastLastReturnsLastElement()
{
object[] objects = new object[] { "hello", "world" };
Assert.Equal("world", objects.Cast<string>().Last());
}

[Fact]
public void CastElementAtReturnsExpectedElement()
{
object[] objects = new object[] { "hello", "world" };
Assert.Equal("world", objects.Cast<string>().ElementAt(1));
}

[Fact]
public void CastElementAtOutOfRangeThrows()
{
object[] objects = new object[] { "hello", "world" };
Assert.Throws<ArgumentOutOfRangeException>(() => objects.Cast<string>().ElementAt(2));
}

[Fact]
public void CastLastOnEmptySequenceThrows()
{
object[] objects = Array.Empty<object>();
Assert.Throws<InvalidOperationException>(() => objects.Cast<string>().Last());
}

[Fact]
public void CastSelectProcessesEachElement()
{
object[] objects = new object[] { "hello", "world!" };
Assert.Equal(new[] { 5, 6 }, objects.Cast<string>().Select(s => s.Length));
}

[Fact]
public void CastSkipSkipsElements()
{
object[] objects = new object[] { "hello", "there", "world" };
Assert.Equal(new[] { "world" }, objects.Cast<string>().Skip(2));
}

[Fact]
public void CastTakeTakesElements()
{
object[] objects = new object[] { "hello", "there", "world" };
Assert.Equal(new[] { "hello", "there" }, objects.Cast<string>().Take(2));
}
}
}
Loading