openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Utility/PageResultEnumerator.cs
75lines · modecode
| 1 | using System; |
| 2 | using System.ClientModel; |
| 3 | using System.Collections; |
| 4 | using System.Collections.Generic; |
| 5 | using System.Threading.Tasks; |
| 6 | |
| 7 | #nullable enable |
| 8 | |
| 9 | namespace OpenAI; |
| 10 | |
| 11 | internal abstract class PageResultEnumerator : IAsyncEnumerator<ClientResult>, IEnumerator<ClientResult> |
| 12 | { |
| 13 | private ClientResult? _current; |
| 14 | private bool _hasNext = true; |
| 15 | |
| 16 | public ClientResult Current => _current!; |
| 17 | |
| 18 | public abstract Task<ClientResult> GetFirstAsync(); |
| 19 | |
| 20 | public abstract ClientResult GetFirst(); |
| 21 | |
| 22 | public abstract Task<ClientResult> GetNextAsync(ClientResult result); |
| 23 | |
| 24 | public abstract ClientResult GetNext(ClientResult result); |
| 25 | |
| 26 | public abstract bool HasNext(ClientResult result); |
| 27 | |
| 28 | object IEnumerator.Current => ((IEnumerator<ClientResult>)this).Current; |
| 29 | |
| 30 | public bool MoveNext() |
| 31 | { |
| 32 | if (!_hasNext) |
| 33 | { |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | if (_current == null) |
| 38 | { |
| 39 | _current = GetFirst(); |
| 40 | } |
| 41 | else |
| 42 | { |
| 43 | _current = GetNext(_current); |
| 44 | } |
| 45 | |
| 46 | _hasNext = HasNext(_current); |
| 47 | return true; |
| 48 | } |
| 49 | |
| 50 | void IEnumerator.Reset() => _current = null; |
| 51 | |
| 52 | void IDisposable.Dispose() { } |
| 53 | |
| 54 | public async ValueTask<bool> MoveNextAsync() |
| 55 | { |
| 56 | if (!_hasNext) |
| 57 | { |
| 58 | return false; |
| 59 | } |
| 60 | |
| 61 | if (_current == null) |
| 62 | { |
| 63 | _current = await GetFirstAsync().ConfigureAwait(false); |
| 64 | } |
| 65 | else |
| 66 | { |
| 67 | _current = await GetNextAsync(_current).ConfigureAwait(false); |
| 68 | } |
| 69 | |
| 70 | _hasNext = HasNext(_current); |
| 71 | return true; |
| 72 | } |
| 73 | |
| 74 | ValueTask IAsyncDisposable.DisposeAsync() => default; |
| 75 | } |