From d536bc27bc0631a9cee39099821349800fcd4d54 Mon Sep 17 00:00:00 2001 From: Roger Leblanc Date: Tue, 9 Oct 2018 21:22:37 -0400 Subject: [PATCH] ToArray and tests --- ShittyLINQ/ToArray.cs | 63 +++++++++++++++++++++++++++++++++ ShittyLinqTests/ToArrayTests.cs | 35 ++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 ShittyLINQ/ToArray.cs create mode 100644 ShittyLinqTests/ToArrayTests.cs diff --git a/ShittyLINQ/ToArray.cs b/ShittyLINQ/ToArray.cs new file mode 100644 index 0000000..747d43d --- /dev/null +++ b/ShittyLINQ/ToArray.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; + +namespace ShittyLINQ +{ + public static partial class Extensions + { + public static TSource[] ToArray(this IEnumerable source) + { + if (source == null) throw new ArgumentNullException(); + return new Buffer(source).ToArray(); + } + } + + internal struct Buffer + { + internal TElement[] items; + internal int count; + internal Buffer(IEnumerable source) + { + TElement[] items = null; + int count = 0; + ICollection collection = source as ICollection; + if (collection != null) + { + count = collection.Count; + if (count > 0) + { + items = new TElement[count]; + collection.CopyTo(items, 0); + } + } + else + { + foreach (TElement item in source) + { + if (items == null) + { + items = new TElement[4]; + } + else if (items.Length == count) + { + TElement[] newItems = new TElement[checked(count * 2)]; + Array.Copy(items, 0, newItems, 0, count); + items = newItems; + } + items[count] = item; + count++; + } + } + this.items = items; + this.count = count; + } + internal TElement[] ToArray() + { + if (count == 0) return new TElement[0]; + if (items.Length == count) return items; + TElement[] result = new TElement[count]; + Array.Copy(items, 0, result, 0, count); + return result; + } + } +} \ No newline at end of file diff --git a/ShittyLinqTests/ToArrayTests.cs b/ShittyLinqTests/ToArrayTests.cs new file mode 100644 index 0000000..d4577dc --- /dev/null +++ b/ShittyLinqTests/ToArrayTests.cs @@ -0,0 +1,35 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using ShittyLINQ; +using ShittyTests.TestHelpers; +using System; +using System.Collections.Generic; + +namespace ShittyTests +{ + [TestClass] + public class ToArrayTests + { + [TestMethod] + public void ToArray_SequenceIsNull() + { + IEnumerable nums = null; + Assert.ThrowsException(() => nums.ToArray()); + } + + [TestMethod] + public void ToArray_SequenceEquals() + { + IEnumerable expected = new List { 0, 1, 2 }; + int[] actual = expected.ToArray(); + TestHelper.AssertCollectionsAreSame(expected, actual); + } + + [TestMethod] + public void ToArray_SequenceIsEmpty() + { + IEnumerable expected = new List(); + int[] actual = expected.ToArray(); + TestHelper.AssertCollectionsAreSame(expected, actual); + } + } +} \ No newline at end of file