-
-
Notifications
You must be signed in to change notification settings - Fork 410
Expand file tree
/
Copy pathAsyncEnumerableWriteAdapter.cs
More file actions
86 lines (73 loc) · 2.87 KB
/
AsyncEnumerableWriteAdapter.cs
File metadata and controls
86 lines (73 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
namespace MiniExcelLib.Core.WriteAdapters;
internal sealed class AsyncEnumerableWriteAdapter<T>(IAsyncEnumerable<T> values, MiniExcelBaseConfiguration configuration) : IMiniExcelWriteAdapterAsync, IAsyncDisposable
{
private readonly IAsyncEnumerable<T> _values = values;
private readonly MiniExcelBaseConfiguration _configuration = configuration;
private IAsyncEnumerator<T>? _enumerator;
private bool _empty;
private bool _disposed = false;
public async Task<List<MiniExcelColumnInfo>?> GetColumnsAsync()
{
if (CustomPropertyHelper.TryGetTypeColumnInfo(typeof(T), _configuration, out var props))
{
return props;
}
_enumerator = _values.GetAsyncEnumerator();
if (!await _enumerator.MoveNextAsync().ConfigureAwait(false))
{
_empty = true;
return null;
}
return CustomPropertyHelper.GetColumnInfoFromValue(_enumerator.Current, _configuration);
}
public async IAsyncEnumerable<IAsyncEnumerable<CellWriteInfo>> GetRowsAsync(List<MiniExcelColumnInfo> props, [EnumeratorCancellation] CancellationToken cancellationToken)
{
if (_empty)
{
yield break;
}
if (_enumerator is null)
{
_enumerator = _values.GetAsyncEnumerator(cancellationToken);
if (!await _enumerator.MoveNextAsync().ConfigureAwait(false))
{
yield break;
}
}
do
{
cancellationToken.ThrowIfCancellationRequested();
yield return GetRowValuesAsync(_enumerator.Current, props);
}
while (await _enumerator.MoveNextAsync().ConfigureAwait(false));
}
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
private static async IAsyncEnumerable<CellWriteInfo> GetRowValuesAsync(T currentValue, List<MiniExcelColumnInfo> props)
#pragma warning restore CS1998
{
var column = 0;
foreach (var prop in props)
{
column++;
if (prop is null)
continue;
yield return currentValue switch
{
IDictionary<string, object> genericDictionary => new CellWriteInfo(genericDictionary[prop.Key.ToString()], column, prop),
IDictionary dictionary => new CellWriteInfo(dictionary[prop.Key], column, prop),
_ => new CellWriteInfo(prop.Property.GetValue(currentValue), column, prop)
};
}
}
public async ValueTask DisposeAsync()
{
if (!_disposed)
{
if (_enumerator is not null)
{
await _enumerator.DisposeAsync().ConfigureAwait(false);
}
_disposed = true;
}
}
}