瀏覽代碼

Hand-rolling Repeat iterator.

Bart De Smet 8 年之前
父節點
當前提交
5d3b50c6fb
共有 1 個文件被更改,包括 44 次插入1 次删除
  1. 44 1
      Ix.NET/Source/System.Linq.Async/System/Linq/Operators/Repeat.cs

+ 44 - 1
Ix.NET/Source/System.Linq.Async/System/Linq/Operators/Repeat.cs

@@ -3,7 +3,6 @@
 // See the LICENSE file in the project root for more information. 
 
 using System.Collections.Generic;
-using System.Diagnostics;
 using System.Threading.Tasks;
 
 namespace System.Linq
@@ -17,5 +16,49 @@ namespace System.Linq
 
             return Enumerable.Repeat(element, count).ToAsyncEnumerable();
         }
+
+        private sealed class RepeatAsyncIterator<TResult> : AsyncIterator<TResult>
+        {
+            private readonly TResult element;
+            private readonly int count;
+            private int remaining;
+
+            public RepeatAsyncIterator(TResult element, int count)
+            {
+                this.element = element;
+                this.count = count;
+            }
+
+            public override AsyncIterator<TResult> Clone() => new RepeatAsyncIterator<TResult>(element, count);
+
+            protected override async Task<bool> MoveNextCore()
+            {
+                switch (state)
+                {
+                    case AsyncIteratorState.Allocated:
+                        remaining = count;
+
+                        if (remaining > 0)
+                        {
+                            current = element;
+                        }
+
+                        state = AsyncIteratorState.Iterating;
+
+                        goto case AsyncIteratorState.Iterating;
+
+                    case AsyncIteratorState.Iterating:
+                        if (remaining-- != 0)
+                        {
+                            return true;
+                        }
+
+                        break;
+                }
+
+                await DisposeAsync().ConfigureAwait(false);
+                return false;
+            }
+        }
     }
 }