// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace System.Linq { public static partial class AsyncEnumerable { public static IAsyncEnumerable Repeat(TResult element, int count) { if (count < 0) throw Error.ArgumentOutOfRange(nameof(count)); return new RepeatAsyncIterator(element, count); } private sealed class RepeatAsyncIterator : AsyncIterator, IAsyncIListProvider { private readonly TResult _element; private readonly int _count; private int _remaining; public RepeatAsyncIterator(TResult element, int count) { _element = element; _count = count; } public override AsyncIteratorBase Clone() => new RepeatAsyncIterator(_element, _count); public Task GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken) => Task.FromResult(_count); public Task ToArrayAsync(CancellationToken cancellationToken) { var res = new TResult[_count]; for (var i = 0; i < _count; i++) { res[i] = _element; } return Task.FromResult(res); } public Task> ToListAsync(CancellationToken cancellationToken) { var res = new List(_count); for (var i = 0; i < _count; i++) { res.Add(_element); } return Task.FromResult(res); } protected override async ValueTask 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; } } } }