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

Add CopyTo operator #964

Closed
wants to merge 4 commits into from
Closed
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
144 changes: 144 additions & 0 deletions MoreLinq.Test/CopyToTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2009 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

namespace MoreLinq.Test
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NUnit.Framework;

[TestFixture]
public class CopyToTest
{
[Test]
public void ThrowsOnNegativeIndex()
{
Assert.That(
() => new BreakingSequence<int>().CopyTo(Array.Empty<int>(), -1),
Throws.TypeOf<ArgumentOutOfRangeException>());
}

[Test]
public void ThrowsOnTooMuchDataForArray()
{
Assert.That(
() => MoreEnumerable.From(() => 1).CopyTo(Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => Enumerable.Range(1, 1).CopyTo(Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => new List<int> { 1 }.AsEnumerable().CopyTo(Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => new List<int> { 1 }.AsReadOnly().AsEnumerable().CopyTo(Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
}

[Test]
public void ThrowsOnTooMuchDataForIListArray()
{
Assert.That(
() => MoreEnumerable.From(() => 1).CopyTo((IList<int>)Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => Enumerable.Range(1, 1).CopyTo((IList<int>)Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => new List<int> { 1 }.AsEnumerable().CopyTo((IList<int>)Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => new List<int> { 1 }.AsReadOnly().AsEnumerable().CopyTo((IList<int>)Array.Empty<int>()),
Throws.TypeOf<ArgumentException>());
}

[Test]
public void CopiesDataToArray()
{
var array = new int[4];

using var xs = TestingSequence.Of(1);
var cnt = xs.CopyTo(array);
array.AssertSequenceEqual(1, 0, 0, 0);
Assert.That(cnt, Is.EqualTo(1));

cnt = new List<int> { 2 }.AsEnumerable().CopyTo(array, 1);
array.AssertSequenceEqual(1, 2, 0, 0);
Assert.That(cnt, Is.EqualTo(1));

cnt = Enumerable.Range(3, 1).CopyTo(array, 2);
array.AssertSequenceEqual(1, 2, 3, 0);
Assert.That(cnt, Is.EqualTo(1));

cnt = new[] { 4, }.AsEnumerable().CopyTo(array, 3);
array.AssertSequenceEqual(1, 2, 3, 4);
Assert.That(cnt, Is.EqualTo(1));
}

[Test]
public void CopiesDataToList()
{
var list = new List<int>();

var cnt = new[] { 1, }.AsEnumerable().CopyTo(list);
list.AssertSequenceEqual(1);
Assert.That(cnt, Is.EqualTo(1));

using (var xs = TestingSequence.Of(2))
{
cnt = xs.CopyTo(list, 1);
list.AssertSequenceEqual(1, 2);
Assert.That(cnt, Is.EqualTo(1));
}

using (var xs = TestingSequence.Of(3, 4))
{
cnt = xs.AsEnumerable().CopyTo(list, 1);
list.AssertSequenceEqual(1, 3, 4);
Assert.That(cnt, Is.EqualTo(2));
}
}

[Test]
public void CopiesDataToIList()
{
var list = new Collection<int>();

using (var xs = TestingSequence.Of(1))
{
var cnt = xs.CopyTo(list);
list.AssertSequenceEqual(1);
Assert.That(cnt, Is.EqualTo(1));
}

using (var xs = TestingSequence.Of(2))
{
var cnt = xs.CopyTo(list, 1);
list.AssertSequenceEqual(1, 2);
Assert.That(cnt, Is.EqualTo(1));
}

using (var xs = TestingSequence.Of(3, 4))
{
var cnt = xs.CopyTo(list, 1);
list.AssertSequenceEqual(1, 3, 4);
Assert.That(cnt, Is.EqualTo(2));
}
}
}
}
3 changes: 3 additions & 0 deletions MoreLinq.Test/NullArgumentTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ public class Enumerable<T> : IEnumerable<T?>

#pragma warning disable CA1812 // Avoid uninstantiated internal classes

public sealed class List<T> : System.Collections.Generic.List<T>
{ }

public sealed class OrderedEnumerable<T> : Enumerable<T>, System.Linq.IOrderedEnumerable<T?>
{
public System.Linq.IOrderedEnumerable<T?> CreateOrderedEnumerable<TKey>(Func<T, TKey> keySelector, IComparer<TKey>? comparer, bool descending)
Expand Down
172 changes: 172 additions & 0 deletions MoreLinq/CopyTo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2023 Turning Code, LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

namespace MoreLinq
{
using System;
using System.Collections.Generic;

static partial class MoreEnumerable
{
/// <summary>
/// Copies the contents of a sequence into a provided array.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements of <paramref name="source"/></typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="array">The array that is the destination of the elements copied from <paramref
/// name="source"/>.</param>
/// <returns>The number of elements actually copied.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="array"/> is not long enough to hold the data from
/// sequence.</exception>
/// <remarks>
/// <para>
/// All data from <paramref name="source"/> will be copied to <paramref name="array"/> if possible. If <paramref
/// name="source"/> is shorter than <paramref name="array"/>, then any remaining elements will be untouched. If
/// <paramref name="source"/> is longer than <paramref name="array"/>, then an exception will be thrown.
/// </para>
/// <para>
/// This operator executes immediately.
/// </para>
/// </remarks>
public static int CopyTo<TSource>(this IEnumerable<TSource> source, TSource[] array)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (array == null) throw new ArgumentNullException(nameof(array));

return CopyTo(source, array, 0);
}

static int CopyTo<TSource>(IEnumerable<TSource> source, TSource[] array, int index)
{
if (source is TSource[] arr)
{
arr.CopyTo(array, index);
return arr.Length;
}
else if (source is ICollection<TSource> coll)
{
coll.CopyTo(array, index);
return coll.Count;
}
else if (source.TryAsCollectionLike() is CollectionLike<TSource> c)
{
if (c.Count + index > array.Length)
throw new ArgumentException("Destination is not long enough.", nameof(array));

var i = index;
foreach (var el in source)
array[i++] = el;

return i - index;
}
else
{
var i = index;
foreach (var el in source)
{
if (i >= array.Length)
throw new ArgumentException("Destination is not long enough.", nameof(array));

array[i++] = el;
}

return i - index;
}
}

/// <summary>
/// Copies the contents of a sequence into a provided list.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements of <paramref name="source"/></typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="list">The list that is the destination of the elements copied from <paramref
/// name="source"/>.</param>
/// <returns>The number of elements actually copied.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is <see langword="null"/>.</exception>
/// <remarks>
/// <para>
/// All data from <paramref name="source"/> will be copied to <paramref name="list"/>, starting at position 0.
/// </para>
/// <para>
/// This operator executes immediately.
/// </para>
/// </remarks>
public static int CopyTo<TSource>(this IEnumerable<TSource> source, IList<TSource> list)
{
return source.CopyTo(list, 0);
}

/// <summary>
/// Copies the contents of a sequence into a provided list.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements of <paramref name="source"/></typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="list">The list that is the destination of the elements copied from <paramref
/// name="source"/>.</param>
/// <param name="index">The position in <paramref name="list"/> at which to start copying data</param>
/// <returns>The number of elements actually copied.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is <see langword="null"/>.</exception>
/// <remarks>
/// <para>
/// All data from <paramref name="source"/> will be copied to <paramref name="list"/>, starting at position
/// <paramref name="index"/>.
/// </para>
/// <para>
/// This operator executes immediately.
/// </para>
/// </remarks>
public static int CopyTo<TSource>(this IEnumerable<TSource> source, IList<TSource> list, int index)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (list == null) throw new ArgumentNullException(nameof(list));
if (index < 0) throw new ArgumentOutOfRangeException(nameof(index));

if (list is TSource[] array)
{
return CopyTo(source, array, index);
}
else

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡You don't need the else statement here, because there is no more instruction after it.

{
#if NET6_0_OR_GREATER
if (list is List<TSource> l
&& source.TryAsCollectionLike() is CollectionLike<TSource> c)
{
l.EnsureCapacity(c.Count + index);
}
#endif

var i = index;
foreach (var el in source)
{
if (i < list.Count)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Sometimes you use { } and sometimes you don't use it in if statement. Adopt a single code style.

list[i] = el;
else
list.Add(el);
i++;
}

return i - index;
}
}
}
}
Loading