diff --git a/src/UniTask.NetCore/NetCore/UniTask.AsValueTask.cs b/src/UniTask.NetCore/NetCore/UniTask.AsValueTask.cs new file mode 100644 index 0000000..834968a --- /dev/null +++ b/src/UniTask.NetCore/NetCore/UniTask.AsValueTask.cs @@ -0,0 +1,123 @@ +#pragma warning disable 0649 + +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; + +namespace Cysharp.Threading.Tasks +{ + public static class UniTaskValueTaskExtensions + { + public static ValueTask AsValueTask(this UniTask task) + { + ref var core = ref Unsafe.As(ref task); + if (core.source == null) + { + return default; + } + + return new ValueTask(new UniTaskValueTaskSource(core.source), core.token); + } + + public static ValueTask AsValueTask(this UniTask task) + { + ref var core = ref Unsafe.As, UniTaskToValueTask>(ref task); + if (core.source == null) + { + return new ValueTask(core.result); + } + + return new ValueTask(new UniTaskValueTaskSource(core.source), core.token); + } + + struct UniTaskToValueTask + { + public IUniTaskSource source; + public short token; + } + + class UniTaskValueTaskSource : IValueTaskSource + { + readonly IUniTaskSource source; + + public UniTaskValueTaskSource(IUniTaskSource source) + { + this.source = source; + } + + public void GetResult(short token) + { + source.GetResult(token); + } + + public ValueTaskSourceStatus GetStatus(short token) + { + var status = source.GetStatus(token); + switch (status) + { + case UniTaskStatus.Pending: + return ValueTaskSourceStatus.Pending; + case UniTaskStatus.Succeeded: + return ValueTaskSourceStatus.Succeeded; + case UniTaskStatus.Faulted: + return ValueTaskSourceStatus.Faulted; + case UniTaskStatus.Canceled: + return ValueTaskSourceStatus.Canceled; + default: + return (ValueTaskSourceStatus)status; + } + } + + public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) + { + source.OnCompleted(continuation, state, token); + } + } + + struct UniTaskToValueTask + { + public IUniTaskSource source; + public T result; + public short token; + } + + class UniTaskValueTaskSource : IValueTaskSource + { + readonly IUniTaskSource source; + + public UniTaskValueTaskSource(IUniTaskSource source) + { + this.source = source; + } + + public T GetResult(short token) + { + return source.GetResult(token); + } + + public ValueTaskSourceStatus GetStatus(short token) + { + var status = source.GetStatus(token); + switch (status) + { + case UniTaskStatus.Pending: + return ValueTaskSourceStatus.Pending; + case UniTaskStatus.Succeeded: + return ValueTaskSourceStatus.Succeeded; + case UniTaskStatus.Faulted: + return ValueTaskSourceStatus.Faulted; + case UniTaskStatus.Canceled: + return ValueTaskSourceStatus.Canceled; + default: + return (ValueTaskSourceStatus)status; + } + } + + public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) + { + source.OnCompleted(continuation, state, token); + } + } + } +} diff --git a/src/UniTask.NetCore/NetCore/UniTask.Run.cs b/src/UniTask.NetCore/NetCore/UniTask.Run.cs new file mode 100644 index 0000000..16fe48a --- /dev/null +++ b/src/UniTask.NetCore/NetCore/UniTask.Run.cs @@ -0,0 +1,112 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + /// Run action on the threadPool and return to current SynchronizationContext if configureAwait = true. + public static async UniTask Run(Action action, bool configureAwait = true) + { + if (configureAwait) + { + var current = SynchronizationContext.Current; + await UniTask.SwitchToThreadPool(); + try + { + action(); + } + finally + { + if (current != null) + { + await UniTask.SwitchToSynchronizationContext(current); + } + } + } + else + { + await UniTask.SwitchToThreadPool(); + action(); + } + } + + /// Run action on the threadPool and return to current SynchronizationContext if configureAwait = true. + public static async UniTask Run(Action action, object state, bool configureAwait = true) + { + if (configureAwait) + { + var current = SynchronizationContext.Current; + await UniTask.SwitchToThreadPool(); + try + { + action(state); + } + finally + { + if (current != null) + { + await UniTask.SwitchToSynchronizationContext(current); + } + } + } + else + { + await UniTask.SwitchToThreadPool(); + action(state); + } + } + + /// Run action on the threadPool and return to current SynchronizationContext if configureAwait = true. + public static async UniTask Run(Func func, bool configureAwait = true) + { + if (configureAwait) + { + var current = SynchronizationContext.Current; + await UniTask.SwitchToThreadPool(); + try + { + return func(); + } + finally + { + if (current != null) + { + await UniTask.SwitchToSynchronizationContext(current); + } + } + } + else + { + await UniTask.SwitchToThreadPool(); + return func(); + } + } + + /// Run action on the threadPool and return to current SynchronizationContext if configureAwait = true. + public static async UniTask Run(Func func, object state, bool configureAwait = true) + { + if (configureAwait) + { + var current = SynchronizationContext.Current; + await UniTask.SwitchToThreadPool(); + try + { + return func(state); + } + finally + { + if (current != null) + { + await UniTask.SwitchToSynchronizationContext(current); + } + } + } + else + { + await UniTask.SwitchToThreadPool(); + return func(state); + } + } + } +} \ No newline at end of file diff --git a/src/UniTask.NetCore/NetCore/UniTask.Yield.cs b/src/UniTask.NetCore/NetCore/UniTask.Yield.cs new file mode 100644 index 0000000..1931f4e --- /dev/null +++ b/src/UniTask.NetCore/NetCore/UniTask.Yield.cs @@ -0,0 +1,55 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public partial struct UniTask + { + public static UniTask.YieldAwaitable Yield() + { + return default; + } + + public readonly struct YieldAwaitable + { + public Awaiter GetAwaiter() + { + return default; + } + + public readonly struct Awaiter : ICriticalNotifyCompletion + { + static readonly SendOrPostCallback SendOrPostCallbackDelegate = Continuation; + static readonly WaitCallback WaitCallbackDelegate = Continuation; + + public bool IsCompleted => false; + + public void GetResult() { } + + public void OnCompleted(Action continuation) + { + UnsafeOnCompleted(continuation); + } + + public void UnsafeOnCompleted(Action continuation) + { + var syncContext = SynchronizationContext.Current; + if (syncContext != null) + { + syncContext.Post(SendOrPostCallbackDelegate, continuation); + } + else + { + ThreadPool.UnsafeQueueUserWorkItem(WaitCallbackDelegate, continuation); + } + } + + static void Continuation(object state) + { + ((Action)state).Invoke(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask.NetCore/UniTask.NetCore.csproj b/src/UniTask.NetCore/UniTask.NetCore.csproj index 512edf9..d335bd7 100644 --- a/src/UniTask.NetCore/UniTask.NetCore.csproj +++ b/src/UniTask.NetCore/UniTask.NetCore.csproj @@ -7,25 +7,11 @@ - + + + + + diff --git a/src/UniTask.NetCoreSandbox/Program.cs b/src/UniTask.NetCoreSandbox/Program.cs index d982b12..24807f2 100644 --- a/src/UniTask.NetCoreSandbox/Program.cs +++ b/src/UniTask.NetCoreSandbox/Program.cs @@ -1,46 +1,241 @@ using Cysharp.Threading.Tasks; + +using System.Linq; using System; +using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; +using System.Collections; +using System.Text; +using System.Text.RegularExpressions; +using System.Runtime.CompilerServices; +using Cysharp.Threading.Tasks.Linq; +using System.Reactive.Linq; +using System.Reactive.Concurrency; namespace NetCoreSandbox { class Program { + static string FlattenGenArgs(Type type) + { + if (type.IsGenericType) + { + var t = string.Join(", ", type.GetGenericArguments().Select(x => FlattenGenArgs(x))); + return Regex.Replace(type.Name, "`.+", "") + "<" + t + ">"; + } + //x.ReturnType.GetGenericArguments() + else + { + return type.Name; + } + } + + static async IAsyncEnumerable FooAsync([EnumeratorCancellation]CancellationToken cancellationToken = default) + { + yield return 1; + await Task.Delay(10, cancellationToken); + } + static async Task Main(string[] args) { - Console.WriteLine("Foo"); - var v = await outer().AsTask(); + await foreach (var item in UniTaskAsyncEnumerable.Range(1, 10) + .SelectAwait(x => UniTask.Run(() => x)) + .TakeLast(6) + + + + ) + { + + Console.WriteLine(item); + } + + + // AsyncEnumerable.Range(1, 10).GroupBy(x=>x).Select(x=>x.first + + + + //Enumerable.Range(1,10).ToHashSet( + - Console.WriteLine("Bar:" + v); } - static async UniTask outer() + + + void Foo() { - //await Task.WhenAll(); - //var foo = await Task.WhenAny(Array.Empty>()); + // AsyncEnumerable.Range(1,10).Do( + + // AsyncEnumerable.t + + var sb = new StringBuilder(); + sb.AppendLine(@"using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ +"); + + + + var chako = typeof(AsyncEnumerable).GetMethods() + .OrderBy(x => x.Name) + .Select(x => + { + var ret = FlattenGenArgs(x.ReturnType); + + + var generics = string.Join(", ", x.GetGenericArguments().Select(x => x.Name)); + + if (x.GetParameters().Length == 0) return ""; + + var self = x.GetParameters().First(); + if (x.GetCustomAttributes(typeof(ExtensionAttribute), true).Length == 0) + { + return ""; + } + + var arg1Type = FlattenGenArgs(x.GetParameters().First().ParameterType); + + var others = string.Join(", ", x.GetParameters().Skip(1).Select(y => FlattenGenArgs(y.ParameterType) + " " + y.Name)); + + if (!string.IsNullOrEmpty(others)) + { + others = ", " + others; + } + + var template = $"public static {ret} {x.Name}<{generics}>(this {arg1Type} {self.Name}{others})"; + + + + return template.Replace("ValueTask", "UniTask").Replace("IAsyncEnumerable", "IUniTaskAsyncEnumerable").Replace("<>", ""); + }) + .Where(x => x != "") + .Select(x => x + "\r\n{\r\n throw new NotImplementedException();\r\n}") + .ToArray(); + + var huga = string.Join("\r\n\r\n", chako); + + + + + foreach (var item in typeof(AsyncEnumerable).GetMethods().Select(x => x.Name).Distinct()) + { + if (item.EndsWith("AwaitAsync") || item.EndsWith("AwaitWithCancellationAsync") || item.EndsWith("WithCancellation")) + { + continue; + } + + var item2 = item.Replace("Async", ""); + item2 = item2.Replace("Await", ""); + + var format = @" + internal sealed class {0} + {{ + }} +"; + + sb.Append(string.Format(format, item2)); + + } + + sb.Append("}"); + + + Console.WriteLine(sb.ToString()); + - await UniTask.WhenAny(new UniTask[0]); - return 10; - //var v = await DoAsync(); - //return v; } - static async UniTask DoAsync() + public static async IAsyncEnumerable AsyncGen() { - var tcs = new UniTaskCompletionSource(); - - tcs.TrySetResult(100); - - - var v = await tcs.Task; - - return v; + await UniTask.SwitchToThreadPool(); + yield return 10; + await UniTask.SwitchToThreadPool(); + yield return 100; } - - } + + class MyEnumerable : IEnumerable + { + public IEnumerator GetEnumerator() + { + return new MyEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + } + + class MyEnumerator : IEnumerator + { + public int Current => throw new NotImplementedException(); + + object IEnumerator.Current => throw new NotImplementedException(); + + public void Dispose() + { + Console.WriteLine("Called Dispose"); + } + + public bool MoveNext() + { + throw new NotImplementedException(); + } + + public void Reset() + { + throw new NotImplementedException(); + } + } + + + + public class MyClass + { + public CustomAsyncEnumerator GetAsyncEnumerator() + { + //IAsyncEnumerable + return new CustomAsyncEnumerator(); + } + } + + + public struct CustomAsyncEnumerator + { + int count; + + public T Current + { + get + { + return default; + } + } + + public UniTask MoveNextAsync() + { + if (count++ == 3) + { + return UniTask.FromResult(false); + //return false; + } + return UniTask.FromResult(true); + } + + public UniTask DisposeAsync() + { + return default; + } + } + + + } diff --git a/src/UniTask.NetCoreSandbox/UniTask.NetCoreSandbox.csproj b/src/UniTask.NetCoreSandbox/UniTask.NetCoreSandbox.csproj index 86d58b5..c7cf11b 100644 --- a/src/UniTask.NetCoreSandbox/UniTask.NetCoreSandbox.csproj +++ b/src/UniTask.NetCoreSandbox/UniTask.NetCoreSandbox.csproj @@ -6,6 +6,11 @@ NetCoreSandbox + + + + + diff --git a/src/UniTask.NetCoreTests/Linq/Aggregate.cs b/src/UniTask.NetCoreTests/Linq/Aggregate.cs new file mode 100644 index 0000000..61ac6f7 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Aggregate.cs @@ -0,0 +1,496 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading.Tasks; +using Xunit; + +namespace NetCoreTests.Linq +{ + public class Aggregate + { + [Theory] + [InlineData(0, 10)] + [InlineData(0, 1)] + [InlineData(10, 0)] + [InlineData(1, 11)] + public async Task Sum(int start, int count) + { + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).SumAsync(); + var ys = Enumerable.Range(start, count).Sum(); + xs.Should().Be(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).SumAsync(x => x * 2); + var ys = Enumerable.Range(start, count).Sum(x => x * 2); + xs.Should().Be(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).SumAwaitAsync(x => UniTask.Run(() => x)); + var ys = Enumerable.Range(start, count).Sum(x => x); + xs.Should().Be(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).SumAwaitCancellationAsync((x, _) => UniTask.Run(() => x)); + var ys = Enumerable.Range(start, count).Sum(x => x); + xs.Should().Be(ys); + } + } + + public static IEnumerable array1 = new object[][] + { + new object[]{new int[] { 1, 10, 100 } }, + new object[]{new int?[] { 1, null, 100 } }, + new object[]{new float[] { 1, 10, 100 } }, + new object[]{new float?[] { 1, null, 100 } }, + new object[]{new double[] { 1, 10, 100 } }, + new object[]{new double?[] { 1, null, 100 } }, + new object[]{new decimal[] { 1, 10, 100 } }, + new object[]{new decimal?[] { 1, null, 100 } }, + }; + + [Theory] + [MemberData(nameof(array1))] + public async Task Average(T arr) + { + switch (arr) + { + case int[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case int?[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case float[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case float?[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case double[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case double?[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case decimal[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + case decimal?[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().AverageAsync(); + var ys = array.Average(); + xs.Should().Be(ys); + } + break; + default: + break; + } + } + + + public static IEnumerable array2 = new object[][] + { + new object[]{new int[] { } }, + new object[]{new int[] { 5 } }, + new object[]{new int[] { 5, 10, 100 } }, + new object[]{new int[] { 10, 5,100 } }, + new object[]{new int[] { 100, 10, 5 } }, + + new object[]{new int?[] { } }, + new object[]{new int?[] { 5 } }, + new object[]{new int?[] { null, null, null } }, + new object[]{new int?[] { null, 5, 10, 100 } }, + new object[]{new int?[] { 10, 5,100, null } }, + new object[]{new int?[] { 100, 10, 5 } }, + + new object[]{new X[] { } }, + new object[]{new X[] { new X(5) } }, + new object[]{new X[] { new X(5), new X(10), new X(100) } }, + new object[]{new X[] { new X(10),new X( 5),new X(100) } }, + new object[]{new X[] { new X(100), new X(10),new X(5) } }, + + new object[]{new XX[] { } }, + new object[]{new XX[] { new XX(new X(5)) } }, + new object[]{new XX[] { new XX(new X(5)), new XX(new X(10)), new XX(new X(100)) } }, + new object[]{new XX[] { new XX(new X(10)),new XX(new X( 5)),new XX(new X(100)) } }, + new object[]{new XX[] { new XX(new X(100)), new XX(new X(10)),new XX(new X(5)) } }, + }; + + [Theory] + [MemberData(nameof(array2))] + public async Task Min(T arr) + { + switch (arr) + { + case int[] array: + { + { + if (array.Length == 0) + { + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().MinAsync()); + Assert.Throws(() => array.Min()); + } + else + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(); + var ys = array.Min(); + xs.Should().Be(ys); + } + } + { + if (array.Length == 0) + { + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().MinAsync(x => x * 2)); + Assert.Throws(() => array.Min(x => x * 2)); + } + else + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(x => x * 2); + var ys = array.Min(x => x * 2); + xs.Should().Be(ys); + } + } + } + break; + case int?[] array: + { + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(); + var ys = array.Min(); + xs.Should().Be(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(x => x); + var ys = array.Min(x => x); + xs.Should().Be(ys); + } + } + break; + case X[] array: + { + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(); + var ys = array.Min(); + xs.Should().Be(ys); + } + { + + if (array.Length == 0) + { + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().MinAsync(x => x.Value)); + Assert.Throws(() => array.Min(x => x.Value)); + } + else + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(x => x.Value); + var ys = array.Min(x => x.Value); + xs.Should().Be(ys); + } + } + } + break; + case XX[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().MinAsync(x => x.Value); + var ys = array.Min(x => x.Value); + xs.Should().Be(ys); + } + break; + default: + break; + } + } + + + + [Theory] + [MemberData(nameof(array2))] + public async Task Max(T arr) + { + switch (arr) + { + case int[] array: + { + { + if (array.Length == 0) + { + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().MaxAsync()); + Assert.Throws(() => array.Max()); + } + else + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(); + var ys = array.Max(); + xs.Should().Be(ys); + } + } + { + if (array.Length == 0) + { + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().MaxAsync(x => x * 2)); + Assert.Throws(() => array.Max(x => x * 2)); + } + else + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(x => x * 2); + var ys = array.Max(x => x * 2); + xs.Should().Be(ys); + } + } + } + break; + case int?[] array: + { + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(); + var ys = array.Max(); + xs.Should().Be(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(x => x); + var ys = array.Max(x => x); + xs.Should().Be(ys); + } + } + break; + case X[] array: + { + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(); + var ys = array.Max(); + xs.Should().Be(ys); + } + { + + if (array.Length == 0) + { + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().MaxAsync(x => x.Value)); + Assert.Throws(() => array.Max(x => x.Value)); + } + else + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(x => x.Value); + var ys = array.Max(x => x.Value); + xs.Should().Be(ys); + } + } + } + break; + case XX[] array: + { + var xs = await array.ToUniTaskAsyncEnumerable().MaxAsync(x => x.Value); + var ys = array.Max(x => x.Value); + xs.Should().Be(ys); + } + break; + default: + break; + } + } + + public class XX + { + public readonly X Value; + + public XX(X value) + { + this.Value = value; + } + } + + public class X : IComparable + { + public readonly int Value; + + public X(int value) + { + Value = value; + } + + public int CompareTo([AllowNull] X other) + { + return Comparer.Default.Compare(Value, other.Value); + } + } + + + [Theory] + [InlineData(0, 10)] + [InlineData(0, 1)] + [InlineData(10, 0)] + [InlineData(1, 11)] + public async Task Count(int start, int count) + { + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).CountAsync(); + var ys = Enumerable.Range(start, count).Count(); + xs.Should().Be(ys); + } + + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).CountAsync(x => x % 2 == 0); + var ys = Enumerable.Range(start, count).Count(x => x % 2 == 0); + xs.Should().Be(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).LongCountAsync(); + var ys = Enumerable.Range(start, count).LongCount(); + xs.Should().Be(ys); + } + + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).LongCountAsync(x => x % 2 == 0); + var ys = Enumerable.Range(start, count).LongCount(x => x % 2 == 0); + xs.Should().Be(ys); + } + } + + + [Fact] + public async Task AggregateTest1() + { + // 0 + await Assert.ThrowsAsync(async () => await new int[] { }.ToUniTaskAsyncEnumerable().AggregateAsync((x, y) => x + y)); + Assert.Throws(() => new int[] { }.Aggregate((x, y) => x + y)); + + // 1 + { + var a = await Enumerable.Range(1, 1).ToUniTaskAsyncEnumerable().AggregateAsync((x, y) => x + y); + var b = Enumerable.Range(1, 1).Aggregate((x, y) => x + y); + a.Should().Be(b); + } + + // 2 + { + var a = await Enumerable.Range(1, 2).ToUniTaskAsyncEnumerable().AggregateAsync((x, y) => x + y); + var b = Enumerable.Range(1, 2).Aggregate((x, y) => x + y); + a.Should().Be(b); + } + + // 10 + { + var a = await Enumerable.Range(1, 10).ToUniTaskAsyncEnumerable().AggregateAsync((x, y) => x + y); + var b = Enumerable.Range(1, 10).Aggregate((x, y) => x + y); + a.Should().Be(b); + } + } + + [Fact] + public async Task AggregateTest2() + { + // 0 + { + var a = await Enumerable.Range(1, 1).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y); + var b = Enumerable.Range(1, 1).Aggregate(1000, (x, y) => x + y); + a.Should().Be(b); + } + + // 1 + { + var a = await Enumerable.Range(1, 1).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y); + var b = Enumerable.Range(1, 1).Aggregate(1000, (x, y) => x + y); + a.Should().Be(b); + } + + // 2 + { + var a = await Enumerable.Range(1, 2).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y); + var b = Enumerable.Range(1, 2).Aggregate(1000, (x, y) => x + y); + a.Should().Be(b); + } + + // 10 + { + var a = await Enumerable.Range(1, 10).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y); + var b = Enumerable.Range(1, 10).Aggregate(1000, (x, y) => x + y); + a.Should().Be(b); + } + } + + [Fact] + public async Task AggregateTest3() + { + // 0 + { + var a = await Enumerable.Range(1, 1).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y, x => (x * 99).ToString()); + var b = Enumerable.Range(1, 1).Aggregate(1000, (x, y) => x + y, x => (x * 99).ToString()); + a.Should().Be(b); + } + + // 1 + { + var a = await Enumerable.Range(1, 1).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y, x => (x * 99).ToString()); + var b = Enumerable.Range(1, 1).Aggregate(1000, (x, y) => x + y, x => (x * 99).ToString()); + a.Should().Be(b); + } + + // 2 + { + var a = await Enumerable.Range(1, 2).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y, x => (x * 99).ToString()); + var b = Enumerable.Range(1, 2).Aggregate(1000, (x, y) => x + y, x => (x * 99).ToString()); + a.Should().Be(b); + } + + // 10 + { + var a = await Enumerable.Range(1, 10).ToUniTaskAsyncEnumerable().AggregateAsync(1000, (x, y) => x + y, x => (x * 99).ToString()); + var b = Enumerable.Range(1, 10).Aggregate(1000, (x, y) => x + y, x => (x * 99).ToString()); + a.Should().Be(b); + } + } + + [Fact] + public async Task ForEach() + { + var list = new List(); + await Enumerable.Range(1, 10).ToUniTaskAsyncEnumerable().ForEachAsync(x => + { + list.Add(x); + }); + + list.Should().BeEquivalentTo(Enumerable.Range(1, 10)); + + var list2 = new List<(int, int)>(); + await Enumerable.Range(5, 10).ToUniTaskAsyncEnumerable().ForEachAsync((index, x) => + { + list2.Add((index, x)); + }); + + var list3 = Enumerable.Range(5, 10).Select((index, x) => (index, x)).ToArray(); + list2.Should().BeEquivalentTo(list3); + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/AllAny.cs b/src/UniTask.NetCoreTests/Linq/AllAny.cs new file mode 100644 index 0000000..541c3db --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/AllAny.cs @@ -0,0 +1,112 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class AllAny + { + [Theory] + [InlineData(0, 0)] + [InlineData(1, 1)] + [InlineData(1, 2)] + [InlineData(1, 3)] + [InlineData(0, 10)] + [InlineData(0, 11)] + public async Task AllTest(int start, int count) + { + var range = Enumerable.Range(start, count); + var x = await range.ToUniTaskAsyncEnumerable().AllAsync(x => x % 2 == 0); + var y = range.All(x => x % 2 == 0); + + x.Should().Be(y); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(1, 1)] + [InlineData(1, 2)] + [InlineData(1, 3)] + [InlineData(0, 10)] + [InlineData(0, 11)] + public async Task AnyTest(int start, int count) + { + var range = Enumerable.Range(start, count); + { + var x = await range.ToUniTaskAsyncEnumerable().AnyAsync(); + var y = range.Any(); + + x.Should().Be(y); + } + { + var x = await range.ToUniTaskAsyncEnumerable().AnyAsync(x => x % 2 == 0); + var y = range.Any(x => x % 2 == 0); + + x.Should().Be(y); + } + } + + [Theory] + [InlineData(0, 0)] + [InlineData(1, 1)] + [InlineData(1, 2)] + [InlineData(1, 3)] + [InlineData(0, 10)] + [InlineData(0, 11)] + public async Task ContainsTest(int start, int count) + { + var range = Enumerable.Range(start, count); + foreach (var c in Enumerable.Range(0, 15)) + { + var x = await range.ToUniTaskAsyncEnumerable().ContainsAsync(c); + var y = range.Contains(c); + x.Should().Be(y); + } + } + + [Fact] + public async Task SequenceEqual() + { + // empty and empty + (await new int[0].ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[0].ToUniTaskAsyncEnumerable())).Should().BeTrue(); + (new int[0].SequenceEqual(new int[0])).Should().BeTrue(); + + // empty and exists + (await new int[0].ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1 }.ToUniTaskAsyncEnumerable())).Should().BeFalse(); + (new int[0].SequenceEqual(new int[] { 1 })).Should().BeFalse(); + + // exists and empty + (await new int[] { 1 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[0].ToUniTaskAsyncEnumerable())).Should().BeFalse(); + (new int[] { 1 }.SequenceEqual(new int[] { })).Should().BeFalse(); + + // samelength same value + (await new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable())).Should().BeTrue(); + (new int[] { 1, 2, 3 }.SequenceEqual(new int[] { 1, 2, 3 })).Should().BeTrue(); + + // samelength different value(first) + (await new int[] { 5, 2, 3 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable())).Should().BeFalse(); + + // samelength different value(middle) + (await new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1, 5, 3 }.ToUniTaskAsyncEnumerable())).Should().BeFalse(); + + // samelength different value(last) + (await new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1, 2, 5 }.ToUniTaskAsyncEnumerable())).Should().BeFalse(); + + // left is long + (await new int[] { 1, 2, 3, 4 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable())).Should().BeFalse(); + (new int[] { 1, 2, 3, 4 }.SequenceEqual(new int[] { 1, 2, 3 })).Should().BeFalse(); + + // right is long + (await new int[] { 1, 2, 3 }.ToUniTaskAsyncEnumerable().SequenceEqualAsync(new int[] { 1, 2, 3, 4 }.ToUniTaskAsyncEnumerable())).Should().BeFalse(); + (new int[] { 1, 2, 3 }.SequenceEqual(new int[] { 1, 2, 3, 4 })).Should().BeFalse(); + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/Concat.cs b/src/UniTask.NetCoreTests/Linq/Concat.cs new file mode 100644 index 0000000..5b1a3d2 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Concat.cs @@ -0,0 +1,144 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class Concat + { + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(0, 2)] + [InlineData(0, 10)] + public async Task Append(int start, int count) + { + var xs = await Enumerable.Range(start, count).ToUniTaskAsyncEnumerable().Append(99).ToArrayAsync(); + var ys = Enumerable.Range(start, count).Append(99).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task AppendThrow() + { + var xs = UniTaskTestException.ThrowImmediate().Append(99).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + + var ys = UniTaskTestException.ThrowAfter().Append(99).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await ys); + + var zs = UniTaskTestException.ThrowInMoveNext().Append(99).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await zs); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(0, 2)] + [InlineData(0, 10)] + public async Task Prepend(int start, int count) + { + var xs = await Enumerable.Range(start, count).ToUniTaskAsyncEnumerable().Prepend(99).ToArrayAsync(); + var ys = Enumerable.Range(start, count).Prepend(99).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task PrependThrow() + { + var xs = UniTaskTestException.ThrowImmediate().Prepend(99).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + + var ys = UniTaskTestException.ThrowAfter().Prepend(99).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await ys); + + var zs = UniTaskTestException.ThrowInMoveNext().Prepend(99).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await zs); + } + + public static IEnumerable array1 = new object[][] + { + new object[] { (0, 0), (0, 0) }, // empty + empty + new object[] { (0, 1), (0, 0) }, // 1 + empty + new object[] { (0, 0), (0, 1) }, // empty + 1 + new object[] { (0, 5), (0, 0) }, // 5 + empty + new object[] { (0, 0), (0, 5) }, // empty + 5 + new object[] { (0, 5), (0, 5) }, // 5 + 5 + }; + + [Theory] + [MemberData(nameof(array1))] + public async Task ConcatTest((int, int) left, (int, int) right) + { + var l = Enumerable.Range(left.Item1, left.Item2); + var r = Enumerable.Range(right.Item1, right.Item2); + + var xs = await l.ToUniTaskAsyncEnumerable().Concat(r.ToUniTaskAsyncEnumerable()).ToArrayAsync(); + var ys = l.Concat(r).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task ConcatThrow() + { + { + var xs = UniTaskTestException.ThrowImmediate().Concat(UniTaskAsyncEnumerable.Range(1, 10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + + var ys = UniTaskTestException.ThrowAfter().Concat(UniTaskAsyncEnumerable.Range(1, 10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await ys); + + var zs = UniTaskTestException.ThrowInMoveNext().Concat(UniTaskAsyncEnumerable.Range(1, 10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await zs); + } + { + var xs = UniTaskAsyncEnumerable.Range(1, 10).Concat(UniTaskTestException.ThrowImmediate()).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + + var ys = UniTaskAsyncEnumerable.Range(1, 10).Concat(UniTaskTestException.ThrowAfter()).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await ys); + + var zs = UniTaskAsyncEnumerable.Range(1, 10).Concat(UniTaskTestException.ThrowInMoveNext()).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await zs); + } + } + + [Fact] + public async Task DefaultIfEmpty() + { + { + var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().DefaultIfEmpty(99).ToArrayAsync(); + var ys = Enumerable.Range(1, 0).DefaultIfEmpty(99).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await Enumerable.Range(1, 1).ToUniTaskAsyncEnumerable().DefaultIfEmpty(99).ToArrayAsync(); + var ys = Enumerable.Range(1, 1).DefaultIfEmpty(99).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await Enumerable.Range(1, 10).ToUniTaskAsyncEnumerable().DefaultIfEmpty(99).ToArrayAsync(); + var ys = Enumerable.Range(1, 10).DefaultIfEmpty(99).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + // Throw + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.DefaultIfEmpty().ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/Convert.cs b/src/UniTask.NetCoreTests/Linq/Convert.cs new file mode 100644 index 0000000..0e3d4b9 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Convert.cs @@ -0,0 +1,196 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + +namespace NetCoreTests.Linq +{ + public class Convert + { + [Fact] + public async Task ToAsyncEnumerable() + { + { + var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToArrayAsync(); + + xs.Length.Should().Be(100); + } + { + var xs = await Enumerable.Empty().ToUniTaskAsyncEnumerable().ToArrayAsync(); + + xs.Length.Should().Be(0); + } + } + + + [Fact] + public async Task ToObservable() + { + { + var xs = await UniTaskAsyncEnumerable.Range(1, 10).ToObservable().ToArray(); + xs.Should().BeEquivalentTo(Enumerable.Range(1, 10)); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, 0).ToObservable().ToArray(); + xs.Should().BeEquivalentTo(Enumerable.Range(1, 0)); + } + } + + + [Fact] + public async Task ToAsyncEnumerableTask() + { + var t = Task.FromResult(100); + var xs = await t.ToUniTaskAsyncEnumerable().ToArrayAsync(); + + xs.Length.Should().Be(1); + xs[0].Should().Be(100); + } + + [Fact] + public async Task ToAsyncEnumerableUniTask() + { + var t = UniTask.FromResult(100); + var xs = await t.ToUniTaskAsyncEnumerable().ToArrayAsync(); + + xs.Length.Should().Be(1); + xs[0].Should().Be(100); + } + + [Fact] + public async Task ToAsyncEnumerableObservable() + { + { + var xs = await Observable.Range(1, 100).ToUniTaskAsyncEnumerable().ToArrayAsync(); + var ys = await Observable.Range(1, 100).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + { + var xs = await Observable.Range(1, 100, ThreadPoolScheduler.Instance).ToUniTaskAsyncEnumerable().ToArrayAsync(); + var ys = await Observable.Range(1, 100, ThreadPoolScheduler.Instance).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + { + var xs = await Observable.Empty(ThreadPoolScheduler.Instance).ToUniTaskAsyncEnumerable().ToArrayAsync(); + var ys = await Observable.Empty(ThreadPoolScheduler.Instance).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task ToDictionary() + { + { + var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x); + var ys = Enumerable.Range(1, 100).ToDictionary(x => x); + + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + { + var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x); + var ys = Enumerable.Range(1, 0).ToDictionary(x => x); + + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + { + var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x, x => x * 2); + var ys = Enumerable.Range(1, 100).ToDictionary(x => x, x => x * 2); + + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + { + var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x, x => x * 2); + var ys = Enumerable.Range(1, 0).ToDictionary(x => x, x => x * 2); + + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + } + + [Fact] + public async Task ToLookup() + { + var arr = new[] { 1, 4, 10, 10, 4, 5, 10, 9 }; + { + var xs = await arr.ToUniTaskAsyncEnumerable().ToLookupAsync(x => x); + var ys = arr.ToLookup(x => x); + + xs.Count.Should().Be(ys.Count); + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + foreach (var key in xs.Select(x => x.Key)) + { + xs[key].Should().BeEquivalentTo(ys[key]); + } + } + { + var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToLookupAsync(x => x); + var ys = Enumerable.Range(1, 0).ToLookup(x => x); + + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + { + var xs = await arr.ToUniTaskAsyncEnumerable().ToLookupAsync(x => x, x => x * 2); + var ys = arr.ToLookup(x => x, x => x * 2); + + xs.Count.Should().Be(ys.Count); + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + foreach (var key in xs.Select(x => x.Key)) + { + xs[key].Should().BeEquivalentTo(ys[key]); + } + } + { + var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToLookupAsync(x => x, x => x * 2); + var ys = Enumerable.Range(1, 0).ToLookup(x => x, x => x * 2); + + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + } + + [Fact] + public async Task ToList() + { + { + var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToListAsync(); + var ys = Enumerable.Range(1, 100).ToList(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await Enumerable.Empty().ToUniTaskAsyncEnumerable().ToListAsync(); + var ys = Enumerable.Empty().ToList(); + + xs.Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task ToHashSet() + { + { + var xs = await new[] { 1, 20, 4, 5, 20, 4, 6 }.ToUniTaskAsyncEnumerable().ToHashSetAsync(); + var ys = new[] { 1, 20, 4, 5, 20, 4, 6 }.ToHashSet(); + + xs.OrderBy(x => x).Should().BeEquivalentTo(ys.OrderBy(x => x)); + } + { + var xs = await Enumerable.Empty().ToUniTaskAsyncEnumerable().ToHashSetAsync(); + var ys = Enumerable.Empty().ToHashSet(); + + xs.Should().BeEquivalentTo(ys); + } + } + } + + +} diff --git a/src/UniTask.NetCoreTests/Linq/Factory.cs b/src/UniTask.NetCoreTests/Linq/Factory.cs new file mode 100644 index 0000000..fb753e6 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Factory.cs @@ -0,0 +1,66 @@ +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Xunit; + +namespace NetCoreTests.Linq +{ + public class Factory + { + [Theory] + [InlineData(0, 10)] + [InlineData(0, 0)] + [InlineData(1, 5)] + [InlineData(1, 0)] + [InlineData(0, 11)] + [InlineData(1, 11)] + public async Task RangeTest(int start, int count) + { + var xs = await UniTaskAsyncEnumerable.Range(start, count).ToArrayAsync(); + var ys = Enumerable.Range(start, count).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Theory] + [InlineData("foo", 0)] + [InlineData("bar", 1)] + [InlineData("baz", 3)] + [InlineData("foobar", 10)] + [InlineData("foobarbaz", 11)] + public async Task RepeatTest(string value, int count) + { + var xs = await UniTaskAsyncEnumerable.Repeat(value, count).ToArrayAsync(); + var ys = Enumerable.Repeat(value, count).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task EmptyTest() + { + var xs = await UniTaskAsyncEnumerable.Empty().ToArrayAsync(); + var ys = Enumerable.Empty().ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Theory] + [InlineData(100)] + [InlineData((string)null)] + [InlineData("foo")] + public async Task ReturnTest(T value) + { + var xs = await UniTaskAsyncEnumerable.Return(value).ToArrayAsync(); + + xs.Length.Should().Be(1); + xs[0].Should().Be(value); + } + + } + + +} diff --git a/src/UniTask.NetCoreTests/Linq/Filtering.cs b/src/UniTask.NetCoreTests/Linq/Filtering.cs new file mode 100644 index 0000000..c9fdd97 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Filtering.cs @@ -0,0 +1,118 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class Filtering + { + [Fact] + public async Task Where() + { + var range = Enumerable.Range(1, 10); + var src = range.ToUniTaskAsyncEnumerable(); + + { + var a = await src.Where(x => x % 2 == 0).ToArrayAsync(); + var expected = range.Where(x => x % 2 == 0).ToArray(); + a.Should().BeEquivalentTo(expected); + } + { + var a = await src.Where((x, i) => (x + i) % 2 == 0).ToArrayAsync(); + var expected = range.Where((x, i) => (x + i) % 2 == 0).ToArray(); + a.Should().BeEquivalentTo(expected); + } + { + var a = await src.WhereAwait(x => UniTask.Run(() => x % 2 == 0)).ToArrayAsync(); + var b = await src.WhereAwait(x => UniTask.FromResult(x % 2 == 0)).ToArrayAsync(); + var expected = range.Where(x => x % 2 == 0).ToArray(); + a.Should().BeEquivalentTo(expected); + b.Should().BeEquivalentTo(expected); + } + { + var a = await src.WhereAwait((x, i) => UniTask.Run(() => (x + i) % 2 == 0)).ToArrayAsync(); + var b = await src.WhereAwait((x, i) => UniTask.FromResult((x + i) % 2 == 0)).ToArrayAsync(); + var expected = range.Where((x, i) => (x + i) % 2 == 0).ToArray(); + a.Should().BeEquivalentTo(expected); + b.Should().BeEquivalentTo(expected); + } + } + + + [Fact] + public async Task WhereException() + { + foreach (var item in UniTaskTestException.Throws()) + { + { + var xs = item.Where(x => x % 2 == 0).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.Where((x, i) => x % 2 == 0).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.WhereAwait(x => UniTask.FromResult(x % 2 == 0)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.WhereAwait((x, i) => UniTask.FromResult(x % 2 == 0)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } + + [Fact] + public async Task OfType() + { + var data = new object[] { 0, null, 10, 30, null, "foo", 99 }; + + var a = await data.ToUniTaskAsyncEnumerable().OfType().ToArrayAsync(); + var b = data.OfType().ToArray(); + + a.Should().BeEquivalentTo(b); + } + + + [Fact] + public async Task OfTypeException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Select(x => (object)x).OfType().ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Fact] + public async Task Cast() + { + var data = new object[] { 0, 10, 30, 99 }; + + var a = await data.ToUniTaskAsyncEnumerable().Cast().ToArrayAsync(); + var b = data.Cast().ToArray(); + + a.Should().BeEquivalentTo(b); + } + + + [Fact] + public async Task CastException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Select(x => (object)x).Cast().ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/FirstLast.cs b/src/UniTask.NetCoreTests/Linq/FirstLast.cs new file mode 100644 index 0000000..185ae35 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/FirstLast.cs @@ -0,0 +1,258 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + +namespace NetCoreTests.Linq +{ + public class FirstLast + { + [Fact] + public async Task FirstTest() + { + { + await Assert.ThrowsAsync(async () => await Enumerable.Empty().ToUniTaskAsyncEnumerable().FirstAsync()); + Assert.Throws(() => Enumerable.Empty().First()); + + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().FirstAsync(); + var y = new[] { 99 }.First(); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().FirstAsync(x => x % 98 == 0)); + Assert.Throws(() => array.First(x => x % 98 == 0)); + + var x = await array.ToUniTaskAsyncEnumerable().FirstAsync(x => x % 2 == 0); + var y = array.First(x => x % 2 == 0); + x.Should().Be(y); + } + + { + var x = await Enumerable.Empty().ToUniTaskAsyncEnumerable().FirstOrDefaultAsync(); + var y = Enumerable.Empty().FirstOrDefault(); + x.Should().Be(y); + } + { + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().FirstOrDefaultAsync(); + var y = new[] { 99 }.FirstOrDefault(); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + var x = await array.ToUniTaskAsyncEnumerable().FirstOrDefaultAsync(x => x % 98 == 0); + var y = array.FirstOrDefault(x => x % 98 == 0); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + var x = await array.ToUniTaskAsyncEnumerable().FirstAsync(x => x % 2 == 0); + var y = array.FirstOrDefault(x => x % 2 == 0); + x.Should().Be(y); + } + } + + [Fact] + public async Task LastTest() + { + { + await Assert.ThrowsAsync(async () => await Enumerable.Empty().ToUniTaskAsyncEnumerable().LastAsync()); + Assert.Throws(() => Enumerable.Empty().Last()); + + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().LastAsync(); + var y = new[] { 99 }.Last(); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().LastAsync(x => x % 98 == 0)); + Assert.Throws(() => array.Last(x => x % 98 == 0)); + + var x = await array.ToUniTaskAsyncEnumerable().LastAsync(x => x % 2 == 0); + var y = array.Last(x => x % 2 == 0); + x.Should().Be(y); + } + + { + var x = await Enumerable.Empty().ToUniTaskAsyncEnumerable().LastOrDefaultAsync(); + var y = Enumerable.Empty().LastOrDefault(); + x.Should().Be(y); + } + { + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().LastOrDefaultAsync(); + var y = new[] { 99 }.LastOrDefault(); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + var x = await array.ToUniTaskAsyncEnumerable().LastOrDefaultAsync(x => x % 98 == 0); + var y = array.LastOrDefault(x => x % 98 == 0); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + var x = await array.ToUniTaskAsyncEnumerable().LastOrDefaultAsync(x => x % 2 == 0); + var y = array.LastOrDefault(x => x % 2 == 0); + x.Should().Be(y); + } + } + + [Fact] + public async Task SingleTest() + { + { + await Assert.ThrowsAsync(async () => await Enumerable.Empty().ToUniTaskAsyncEnumerable().SingleAsync()); + Assert.Throws(() => Enumerable.Empty().Single()); + + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().SingleAsync(); + var y = new[] { 99 }.Single(); + x.Should().Be(y); + + var array = new[] { 99, 11, 135, 10, 144, 800 }; + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().SingleAsync()); + Assert.Throws(() => array.Single()); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + // not found + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().SingleAsync(x => x % 999 == 0)); + Assert.Throws(() => array.Single(x => x % 999 == 0)); + // found multi + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().SingleAsync(x => x % 2 == 0)); + Assert.Throws(() => array.Single(x => x % 2 == 0)); + + { + var x = await array.ToUniTaskAsyncEnumerable().SingleAsync(x => x % 144 == 0); + var y = array.Single(x => x % 144 == 0); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().SingleAsync(x => x % 800 == 0); + var y = array.Single(x => x % 800 == 0); + x.Should().Be(y); + } + } + + { + { + var x = await Enumerable.Empty().ToUniTaskAsyncEnumerable().SingleOrDefaultAsync(); + var y = Enumerable.Empty().SingleOrDefault(); + x.Should().Be(y); + } + { + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().SingleOrDefaultAsync(); + var y = new[] { 99 }.SingleOrDefault(); + x.Should().Be(y); + + var array = new[] { 99, 11, 135, 10, 144, 800 }; + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().SingleOrDefaultAsync()); + Assert.Throws(() => array.SingleOrDefault()); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + // not found + { + var x = await array.ToUniTaskAsyncEnumerable().SingleOrDefaultAsync(x => x % 999 == 0); + var y = array.SingleOrDefault(x => x % 999 == 0); + x.Should().Be(y); + } + // found multi + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().SingleOrDefaultAsync(x => x % 2 == 0)); + Assert.Throws(() => array.SingleOrDefault(x => x % 2 == 0)); + + // normal + { + var x = await array.ToUniTaskAsyncEnumerable().SingleOrDefaultAsync(x => x % 144 == 0); + var y = array.SingleOrDefault(x => x % 144 == 0); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().SingleOrDefaultAsync(x => x % 800 == 0); + var y = array.SingleOrDefault(x => x % 800 == 0); + x.Should().Be(y); + } + } + } + } + + + [Fact] + public async Task ElementAtTest() + { + { + await Assert.ThrowsAsync(async () => await Enumerable.Empty().ToUniTaskAsyncEnumerable().ElementAtAsync(0)); + Assert.Throws(() => Enumerable.Empty().ElementAt(0)); + + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().ElementAtAsync(0); + var y = new[] { 99 }.ElementAt(0); + x.Should().Be(y); + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + await Assert.ThrowsAsync(async () => await array.ToUniTaskAsyncEnumerable().ElementAtAsync(10)); + Assert.Throws(() => array.ElementAt(10)); + + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtAsync(0); + var y = array.ElementAt(0); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtAsync(3); + var y = array.ElementAt(3); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtAsync(5); + var y = array.ElementAt(5); + x.Should().Be(y); + } + } + + + { + { + var x = await Enumerable.Empty().ToUniTaskAsyncEnumerable().ElementAtOrDefaultAsync(0); + var y = Enumerable.Empty().ElementAtOrDefault(0); + x.Should().Be(y); + } + { + var x = await new[] { 99 }.ToUniTaskAsyncEnumerable().ElementAtOrDefaultAsync(0); + var y = new[] { 99 }.ElementAtOrDefault(0); + x.Should().Be(y); + } + } + { + var array = new[] { 99, 11, 135, 10, 144, 800 }; + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtOrDefaultAsync(10); + var y = array.ElementAtOrDefault(10); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtOrDefaultAsync(0); + var y = array.ElementAtOrDefault(0); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtOrDefaultAsync(3); + var y = array.ElementAtOrDefault(3); + x.Should().Be(y); + } + { + var x = await array.ToUniTaskAsyncEnumerable().ElementAtOrDefaultAsync(5); + var y = array.ElementAtOrDefault(5); + x.Should().Be(y); + } + } + } + } + + +} diff --git a/src/UniTask.NetCoreTests/Linq/Joins.cs b/src/UniTask.NetCoreTests/Linq/Joins.cs new file mode 100644 index 0000000..48fd120 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Joins.cs @@ -0,0 +1,253 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class Joins + { + static int rd; + + static UniTask RandomRun(T value) + { + if (Interlocked.Increment(ref rd) % 2 == 0) + { + return UniTask.Run(() => value); + } + else + { + return UniTask.FromResult(value); + } + } + + [Fact] + public async Task Join() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + + var xs = await outer.ToUniTaskAsyncEnumerable().Join(inner.ToUniTaskAsyncEnumerable(), x => x, x => x, (x, y) => (x, y)).ToArrayAsync(); + var ys = outer.Join(inner, x => x, x => x, (x, y) => (x, y)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + + [Fact] + public async Task JoinThrow() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + foreach (var item in UniTaskTestException.Throws()) + { + var xs = outer.ToUniTaskAsyncEnumerable().Join(item, x => x, x => x, (x, y) => x + y).ToArrayAsync(); + var ys = item.Join(inner.ToUniTaskAsyncEnumerable(), x => x, x => x, (x, y) => x + y).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + } + + [Fact] + public async Task JoinAwait() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + + var xs = await outer.ToUniTaskAsyncEnumerable().JoinAwait(inner.ToUniTaskAsyncEnumerable(), x => RandomRun(x), x => RandomRun(x), (x, y) => RandomRun((x, y))).ToArrayAsync(); + var ys = outer.Join(inner, x => x, x => x, (x, y) => (x, y)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + + [Fact] + public async Task JoinAwaitThrow() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + foreach (var item in UniTaskTestException.Throws()) + { + var xs = outer.ToUniTaskAsyncEnumerable().JoinAwait(item, x => RandomRun(x), x => RandomRun(x), (x, y) => RandomRun(x + y)).ToArrayAsync(); + var ys = item.Join(inner.ToUniTaskAsyncEnumerable(), x => x, x => x, (x, y) => x + y).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + } + + [Fact] + public async Task JoinAwaitCt() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + + var xs = await outer.ToUniTaskAsyncEnumerable().JoinAwaitWithCancellation(inner.ToUniTaskAsyncEnumerable(), (x, _) => RandomRun(x), (x, _) => RandomRun(x), (x, y, _) => RandomRun((x, y))).ToArrayAsync(); + var ys = outer.Join(inner, x => x, x => x, (x, y) => (x, y)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + + [Fact] + public async Task JoinAwaitCtThrow() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + foreach (var item in UniTaskTestException.Throws()) + { + var xs = outer.ToUniTaskAsyncEnumerable().JoinAwaitWithCancellation(item, (x, _) => RandomRun(x), (x, _) => RandomRun(x), (x, y, _) => RandomRun(x + y)).ToArrayAsync(); + var ys = item.JoinAwaitWithCancellation(inner.ToUniTaskAsyncEnumerable(), (x, _) => RandomRun(x), (x, _) => RandomRun(x), (x, y, _) => RandomRun(x + y)).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + } + + + [Fact] + public async Task GroupBy() + { + var arr = new[] { 1, 4, 10, 10, 4, 5, 10, 9 }; + { + var xs = await arr.ToUniTaskAsyncEnumerable().GroupBy(x => x).ToArrayAsync(); + var ys = arr.GroupBy(x => x).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + + { + var xs = await arr.ToUniTaskAsyncEnumerable().GroupBy(x => x, (key, xs) => (key, xs.ToArray())).ToArrayAsync(); + var ys = arr.GroupBy(x => x, (key, xs) => (key, xs.ToArray())).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.OrderBy(x => x.key).SelectMany(x => x.Item2).Should().BeEquivalentTo(ys.OrderBy(x => x.key).SelectMany(x => x.Item2)); + } + + { + var xs = await arr.ToUniTaskAsyncEnumerable().GroupByAwait(x => RandomRun(x)).ToArrayAsync(); + var ys = arr.GroupBy(x => x).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + + { + var xs = await arr.ToUniTaskAsyncEnumerable().GroupByAwait(x => RandomRun(x), (key, xs) => RandomRun((key, xs.ToArray()))).ToArrayAsync(); + var ys = arr.GroupBy(x => x, (key, xs) => (key, xs.ToArray())).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.OrderBy(x => x.key).SelectMany(x => x.Item2).Should().BeEquivalentTo(ys.OrderBy(x => x.key).SelectMany(x => x.Item2)); + } + + { + var xs = await arr.ToUniTaskAsyncEnumerable().GroupByAwaitWithCancellation((x, _) => RandomRun(x)).ToArrayAsync(); + var ys = arr.GroupBy(x => x).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.OrderBy(x => x.Key).Should().BeEquivalentTo(ys.OrderBy(x => x.Key)); + } + + { + var xs = await arr.ToUniTaskAsyncEnumerable().GroupByAwaitWithCancellation((x, _) => RandomRun(x), (key, xs, _) => RandomRun((key, xs.ToArray()))).ToArrayAsync(); + var ys = arr.GroupBy(x => x, (key, xs) => (key, xs.ToArray())).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.OrderBy(x => x.key).SelectMany(x => x.Item2).Should().BeEquivalentTo(ys.OrderBy(x => x.key).SelectMany(x => x.Item2)); + } + } + + + + + [Fact] + public async Task GroupByThrow() + { + var arr = new[] { 1, 4, 10, 10, 4, 5, 10, 9 }; + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.GroupBy(x => x).ToArrayAsync(); + var ys = item.GroupByAwait(x => RandomRun(x)).ToArrayAsync(); + var zs = item.GroupByAwaitWithCancellation((x, _) => RandomRun(x)).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + await Assert.ThrowsAsync(async () => await zs); + } + } + + + + [Fact] + public async Task GroupJoin() + { + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }; + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }; + + { + var xs = await outer.ToUniTaskAsyncEnumerable().GroupJoin(inner.ToUniTaskAsyncEnumerable(), x => x, x => x, (x, y) => (x, string.Join(", ", y))).ToArrayAsync(); + var ys = outer.GroupJoin(inner, x => x, x => x, (x, y) => (x, string.Join(", ", y))).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await outer.ToUniTaskAsyncEnumerable().GroupJoinAwait(inner.ToUniTaskAsyncEnumerable(), x => RandomRun(x), x => RandomRun(x), (x, y) => RandomRun((x, string.Join(", ", y)))).ToArrayAsync(); + var ys = outer.GroupJoin(inner, x => x, x => x, (x, y) => (x, string.Join(", ", y))).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await outer.ToUniTaskAsyncEnumerable().GroupJoinAwaitWithCancellation(inner.ToUniTaskAsyncEnumerable(), (x, _) => RandomRun(x), (x, _) => RandomRun(x), (x, y, _) => RandomRun((x, string.Join(", ", y)))).ToArrayAsync(); + var ys = outer.GroupJoin(inner, x => x, x => x, (x, y) => (x, string.Join(", ", y))).ToArray(); + + xs.Length.Should().Be(ys.Length); + xs.Should().BeEquivalentTo(ys); + } + } + + + [Fact] + public async Task GroupJoinThrow() + { + + var outer = new[] { 1, 2, 4, 5, 8, 10, 14, 4, 8, 1, 2, 10 }.ToUniTaskAsyncEnumerable(); + var inner = new[] { 1, 2, 1, 2, 1, 14, 2 }.ToUniTaskAsyncEnumerable(); + + foreach (var item in UniTaskTestException.Throws()) + { + { + var xs = item.GroupJoin(outer, x => x, x => x, (x, y) => x).ToArrayAsync(); + var ys = inner.GroupJoin(item, x => x, x => x, (x, y) => x).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + { + var xs = item.GroupJoinAwait(outer, x => RandomRun(x), x => RandomRun(x), (x, y) => RandomRun(x)).ToArrayAsync(); + var ys = inner.GroupJoinAwait(item, x => RandomRun(x), x => RandomRun(x), (x, y) => RandomRun(x)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + { + var xs = item.GroupJoinAwaitWithCancellation(outer, (x, _) => RandomRun(x), (x, _) => RandomRun(x), (x, y, _) => RandomRun(x)).ToArrayAsync(); + var ys = inner.GroupJoinAwaitWithCancellation(item, (x, _) => RandomRun(x), (x, _) => RandomRun(x), (x, y, _) => RandomRun(x)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + } + } + + + } +} diff --git a/src/UniTask.NetCoreTests/Linq/Paging.cs b/src/UniTask.NetCoreTests/Linq/Paging.cs new file mode 100644 index 0000000..cfea04b --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Paging.cs @@ -0,0 +1,285 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class Paging + { + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(9, 0)] + [InlineData(9, 1)] + [InlineData(9, 5)] + [InlineData(9, 9)] + [InlineData(9, 15)] + public async Task Skip(int collection, int skipCount) + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).Skip(skipCount).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).Skip(skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task SkipException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Skip(5).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(9, 0)] + [InlineData(9, 1)] + [InlineData(9, 5)] + [InlineData(9, 9)] + [InlineData(9, 15)] + public async Task SkipLast(int collection, int skipCount) + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipLast(skipCount).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipLast(skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task SkipLastException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipLast(5).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(9, 0)] + [InlineData(9, 1)] + [InlineData(9, 5)] + [InlineData(9, 9)] + [InlineData(9, 15)] + public async Task TakeLast(int collection, int takeCount) + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeLast(takeCount).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeLast(takeCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task TakeLastException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeLast(5).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(9, 0)] + [InlineData(9, 1)] + [InlineData(9, 5)] + [InlineData(9, 9)] + [InlineData(9, 15)] + public async Task Take(int collection, int takeCount) + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).Take(takeCount).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).Take(takeCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task TakeException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Take(5).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(9, 0)] + [InlineData(9, 1)] + [InlineData(9, 5)] + [InlineData(9, 9)] + [InlineData(9, 15)] + public async Task SkipWhile(int collection, int skipCount) + { + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipWhile(x => x < skipCount).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipWhile(x => x < skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipWhile((x, i) => x < (skipCount - i)).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipWhile((x, i) => x < (skipCount - i)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipWhileAwait(x => UniTask.Run(() => x < skipCount)).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipWhile(x => x < skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipWhileAwait((x, i) => UniTask.Run(() => x < (skipCount - i))).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipWhile((x, i) => x < (skipCount - i)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipWhileAwaitWithCancellation((x, _) => UniTask.Run(() => x < skipCount)).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipWhile(x => x < skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).SkipWhileAwaitWithCancellation((x, i, _) => UniTask.Run(() => x < (skipCount - i))).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).SkipWhile((x, i) => x < (skipCount - i)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task SkipWhileException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipWhile(x => x < 2).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipWhile((x, i) => x < 2).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipWhileAwait((x) => UniTask.Run(() => x < 2)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipWhileAwait((x, i) => UniTask.Run(() => x < 2)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipWhileAwaitWithCancellation((x, _) => UniTask.Run(() => x < 2)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SkipWhileAwaitWithCancellation((x, i, _) => UniTask.Run(() => x < 2)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(9, 0)] + [InlineData(9, 1)] + [InlineData(9, 5)] + [InlineData(9, 9)] + [InlineData(9, 15)] + public async Task TakeWhile(int collection, int skipCount) + { + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeWhile(x => x < skipCount).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeWhile(x => x < skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeWhile((x, i) => x < (skipCount - i)).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeWhile((x, i) => x < (skipCount - i)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeWhileAwait(x => UniTask.Run(() => x < skipCount)).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeWhile(x => x < skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeWhileAwait((x, i) => UniTask.Run(() => x < (skipCount - i))).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeWhile((x, i) => x < (skipCount - i)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeWhileAwaitWithCancellation((x, _) => UniTask.Run(() => x < skipCount)).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeWhile(x => x < skipCount).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, collection).TakeWhileAwaitWithCancellation((x, i, _) => UniTask.Run(() => x < (skipCount - i))).ToArrayAsync(); + var ys = Enumerable.Range(1, collection).TakeWhile((x, i) => x < (skipCount - i)).ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task TakeWhileException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeWhile(x => x < 5).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeWhile((x, i) => x < 5).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeWhileAwait((x) => UniTask.Run(() => x < 5)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeWhileAwait((x, i) => UniTask.Run(() => x < 5)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeWhileAwaitWithCancellation((x, _) => UniTask.Run(() => x < 5)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.TakeWhileAwaitWithCancellation((x, i, _) => UniTask.Run(() => x < 5)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/Projection.cs b/src/UniTask.NetCoreTests/Linq/Projection.cs new file mode 100644 index 0000000..ec652ac --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Projection.cs @@ -0,0 +1,323 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class Projection + { + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(0, 2)] + [InlineData(0, 10)] + public async Task Reverse(int start, int count) + { + var xs = await Enumerable.Range(start, count).ToUniTaskAsyncEnumerable().Reverse().ToArrayAsync(); + var ys = Enumerable.Range(start, count).Reverse().ToArray(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task ReverseException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Reverse().ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(9)] + public async Task Select(int count) + { + { + var xs = await UniTaskAsyncEnumerable.Range(1, count).Select(x => x * x).ToArrayAsync(); + var ys = Enumerable.Range(1, count).Select(x => x * x).ToArray(); + xs.Should().BeEquivalentTo(ys); + + var zs = await UniTaskAsyncEnumerable.Range(1, count).SelectAwait((x) => UniTask.Run(() => x * x)).ToArrayAsync(); + zs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, count).Select((x, i) => x * x * i).ToArrayAsync(); + var ys = Enumerable.Range(1, count).Select((x, i) => x * x * i).ToArray(); + xs.Should().BeEquivalentTo(ys); + + var zs = await UniTaskAsyncEnumerable.Range(1, count).SelectAwait((x, i) => UniTask.Run(() => x * x * i)).ToArrayAsync(); + zs.Should().BeEquivalentTo(ys); + } + } + + + [Fact] + public async Task SelectException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Select(x => UniTaskAsyncEnumerable.Range(0, 1)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + + // await + + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SelectAwait(x => UniTask.Run(() => UniTaskAsyncEnumerable.Range(0, 1))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + + // cancel + + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SelectAwaitWithCancellation((x, _) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(0, 1))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + + [Theory] + [InlineData(0, 9)] // empty + exists + [InlineData(9, 0)] // exists + empty + [InlineData(9, 9)] // exists + exists + public async Task SelectMany(int leftCount, int rightCount) + { + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectMany(x => UniTaskAsyncEnumerable.Range(99, rightCount * x)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany(x => Enumerable.Range(99, rightCount * x)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectMany((i, x) => UniTaskAsyncEnumerable.Range(99 * i, rightCount * x)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany((i, x) => Enumerable.Range(99 * i, rightCount * x)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectMany(x => UniTaskAsyncEnumerable.Range(99, rightCount * x), (x, y) => x * y).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany(x => Enumerable.Range(99, rightCount * x), (x, y) => x * y).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectMany((i, x) => UniTaskAsyncEnumerable.Range(99 * i, rightCount * x), (x, y) => x * y).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany((i, x) => Enumerable.Range(99 * i, rightCount * x), (x, y) => x * y).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + + // await + + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwait(x => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99, rightCount * x))).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany(x => Enumerable.Range(99, rightCount * x)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwait((i, x) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99 * i, rightCount * x))).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany((i, x) => Enumerable.Range(99 * i, rightCount * x)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwait(x => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99, rightCount * x)), (x, y) => UniTask.Run(() => x * y)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany(x => Enumerable.Range(99, rightCount * x), (x, y) => x * y).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwait((i, x) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99 * i, rightCount * x)), (x, y) => UniTask.Run(() => x * y)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany((i, x) => Enumerable.Range(99 * i, rightCount * x), (x, y) => x * y).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + + // with cancel + + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwaitWithCancellation((x, _) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99, rightCount * x))).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany(x => Enumerable.Range(99, rightCount * x)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwaitWithCancellation((i, x, _) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99 * i, rightCount * x))).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany((i, x) => Enumerable.Range(99 * i, rightCount * x)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwaitWithCancellation((x, _) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99, rightCount * x)), (x, y, _) => UniTask.Run(() => x * y)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany(x => Enumerable.Range(99, rightCount * x), (x, y) => x * y).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).SelectManyAwaitWithCancellation((i, x, _) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(99 * i, rightCount * x)), (x, y, _) => UniTask.Run(() => x * y)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).SelectMany((i, x) => Enumerable.Range(99 * i, rightCount * x), (x, y) => x * y).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task SelectManyException() + { + // error + exists + // exists + error + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SelectMany(x => UniTaskAsyncEnumerable.Range(0, 1)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Range(0, 1).SelectMany(x => item).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + + // await + + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SelectManyAwait(x => UniTask.Run(() => UniTaskAsyncEnumerable.Range(0, 1))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Range(0, 1).SelectManyAwait(x => UniTask.Run(() => item)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + + // with c + + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.SelectManyAwaitWithCancellation((x, _) => UniTask.Run(() => UniTaskAsyncEnumerable.Range(0, 1))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Range(0, 1).SelectManyAwaitWithCancellation((x, _) => UniTask.Run(() => item)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + + + [Theory] + [InlineData(0, 9)] // empty + exists + [InlineData(9, 0)] // exists + empty + [InlineData(9, 9)] // same + [InlineData(9, 4)] // leftlong + [InlineData(4, 9)] // rightlong + public async Task Zip(int leftCount, int rightCount) + { + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).Zip(UniTaskAsyncEnumerable.Range(99, rightCount)).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).Zip(Enumerable.Range(99, rightCount)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).ZipAwait(UniTaskAsyncEnumerable.Range(99, rightCount), (x, y) => UniTask.Run(() => (x, y))).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).Zip(Enumerable.Range(99, rightCount)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await UniTaskAsyncEnumerable.Range(1, leftCount).ZipAwaitWithCancellation(UniTaskAsyncEnumerable.Range(99, rightCount), (x, y, _) => UniTask.Run(() => (x, y))).ToArrayAsync(); + var ys = Enumerable.Range(1, leftCount).Zip(Enumerable.Range(99, rightCount)).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + } + [Fact] + public async Task ZipException() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Zip(UniTaskAsyncEnumerable.Range(1, 10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Range(1, 10).Zip(item).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + + // a + + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.ZipAwait(UniTaskAsyncEnumerable.Range(1, 10), (x, y) => UniTask.Run(() => (x, y))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Range(1, 10).ZipAwait(item, (x, y) => UniTask.Run(() => (x, y))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + + // c + + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.ZipAwaitWithCancellation(UniTaskAsyncEnumerable.Range(1, 10), (x, y, c) => UniTask.Run(() => (x, y))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Range(1, 10).ZipAwaitWithCancellation(item, (x, y, c) => UniTask.Run(() => (x, y))).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Theory] + // [InlineData(0, 0)] + [InlineData(0, 3)] + [InlineData(9, 1)] + [InlineData(9, 2)] + [InlineData(9, 3)] + [InlineData(17, 3)] + [InlineData(17, 16)] + [InlineData(17, 17)] + [InlineData(17, 27)] + public async Task Buffer(int rangeCount, int bufferCount) + { + var xs = await UniTaskAsyncEnumerable.Range(0, rangeCount).Buffer(bufferCount).Select(x => string.Join(",", x)).ToArrayAsync(); + var ys = await AsyncEnumerable.Range(0, rangeCount).Buffer(bufferCount).Select(x => string.Join(",", x)).ToArrayAsync(); + + xs.Should().BeEquivalentTo(ys); + } + + [Theory] + // [InlineData(0, 0)] + [InlineData(0, 3, 2)] + [InlineData(9, 1, 1)] + [InlineData(9, 2, 3)] + [InlineData(9, 3, 4)] + [InlineData(17, 3, 3)] + [InlineData(17, 16, 5)] + [InlineData(17, 17, 19)] + public async Task BufferSkip(int rangeCount, int bufferCount, int skipCount) + { + var xs = await UniTaskAsyncEnumerable.Range(0, rangeCount).Buffer(bufferCount, skipCount).Select(x => string.Join(",", x)).ToArrayAsync(); + var ys = await AsyncEnumerable.Range(0, rangeCount).Buffer(bufferCount, skipCount).Select(x => string.Join(",", x)).ToArrayAsync(); + + xs.Should().BeEquivalentTo(ys); + } + + [Fact] + public async Task BufferError() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Buffer(3).ToArrayAsync(); + var ys = item.Buffer(3, 2).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + await Assert.ThrowsAsync(async () => await ys); + } + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/Sets.cs b/src/UniTask.NetCoreTests/Linq/Sets.cs new file mode 100644 index 0000000..6d3c45c --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Sets.cs @@ -0,0 +1,193 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class Sets + { + public static IEnumerable array1 = new object[][] + { + new object[] { new int[] { } }, // empty + new object[] { new int[] { 1, 2, 3 } }, // no dup + new object[] { new int[] { 1, 2, 3, 3, 4, 5, 2 } }, // dup + }; + + public static IEnumerable array2 = new object[][] + { + new object[] { new int[] { } }, // empty + new object[] { new int[] { 1, 2 } }, + new object[] { new int[] { 1, 2, 4, 5, 9 } }, // dup + }; + + [Theory] + [MemberData(nameof(array1))] + public async Task Distinct(int[] array) + { + var ys = array.Distinct().ToArray(); + { + (await array.ToUniTaskAsyncEnumerable().Distinct().ToArrayAsync()).Should().BeEquivalentTo(ys); + (await array.ToUniTaskAsyncEnumerable().Distinct(x => x).ToArrayAsync()).Should().BeEquivalentTo(ys); + (await array.ToUniTaskAsyncEnumerable().DistinctAwait(x => UniTask.Run(() => x)).ToArrayAsync()).Should().BeEquivalentTo(ys); + (await array.ToUniTaskAsyncEnumerable().DistinctAwaitWithCancellation((x, _) => UniTask.Run(() => x)).ToArrayAsync()).Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task DistinctThrow() + { + foreach (var item in UniTaskTestException.Throws()) + { + { + var xs = item.Distinct().ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.Distinct(x => x).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.DistinctAwait(x => UniTask.Run(() => x)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.DistinctAwaitWithCancellation((x, _) => UniTask.Run(() => x)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } + + [Theory] + [MemberData(nameof(array1))] + public async Task DistinctUntilChanged(int[] array) + { + var ys = await array.ToAsyncEnumerable().DistinctUntilChanged().ToArrayAsync(); + { + (await array.ToUniTaskAsyncEnumerable().DistinctUntilChanged().ToArrayAsync()).Should().BeEquivalentTo(ys); + (await array.ToUniTaskAsyncEnumerable().DistinctUntilChanged(x => x).ToArrayAsync()).Should().BeEquivalentTo(ys); + (await array.ToUniTaskAsyncEnumerable().DistinctUntilChangedAwait(x => UniTask.Run(() => x)).ToArrayAsync()).Should().BeEquivalentTo(ys); + (await array.ToUniTaskAsyncEnumerable().DistinctUntilChangedAwaitWithCancellation((x, _) => UniTask.Run(() => x)).ToArrayAsync()).Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task DistinctUntilChangedThrow() + { + foreach (var item in UniTaskTestException.Throws()) + { + { + var xs = item.DistinctUntilChanged().ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.DistinctUntilChanged(x => x).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.DistinctUntilChangedAwait(x => UniTask.Run(() => x)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + { + var xs = item.DistinctUntilChangedAwaitWithCancellation((x, _) => UniTask.Run(() => x)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } + + + [Fact] + public async Task Except() + { + foreach (var a1 in array1.First().Cast()) + { + foreach (var a2 in array2.First().Cast()) + { + var xs = await a1.ToUniTaskAsyncEnumerable().Except(a2.ToUniTaskAsyncEnumerable()).ToArrayAsync(); + var ys = a1.Except(a2).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + } + } + + [Fact] + public async Task ExceptThrow() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Except(UniTaskAsyncEnumerable.Return(10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Return(10).Except(item).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Fact] + public async Task Intersect() + { + foreach (var a1 in array1.First().Cast()) + { + foreach (var a2 in array2.First().Cast()) + { + var xs = await a1.ToUniTaskAsyncEnumerable().Intersect(a2.ToUniTaskAsyncEnumerable()).ToArrayAsync(); + var ys = a1.Intersect(a2).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + } + } + + [Fact] + public async Task IntersectThrow() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Intersect(UniTaskAsyncEnumerable.Return(10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Return(10).Intersect(item).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + + [Fact] + public async Task Union() + { + foreach (var a1 in array1.First().Cast()) + { + foreach (var a2 in array2.First().Cast()) + { + var xs = await a1.ToUniTaskAsyncEnumerable().Union(a2.ToUniTaskAsyncEnumerable()).ToArrayAsync(); + var ys = a1.Union(a2).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + } + } + + [Fact] + public async Task UnionThrow() + { + foreach (var item in UniTaskTestException.Throws()) + { + var xs = item.Union(UniTaskAsyncEnumerable.Return(10)).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + foreach (var item in UniTaskTestException.Throws()) + { + var xs = UniTaskAsyncEnumerable.Return(10).Union(item).ToArrayAsync(); + await Assert.ThrowsAsync(async () => await xs); + } + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/Sort.cs b/src/UniTask.NetCoreTests/Linq/Sort.cs new file mode 100644 index 0000000..673e697 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/Sort.cs @@ -0,0 +1,221 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using FluentAssertions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Concurrency; +using System.Reactive.Linq; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + + +namespace NetCoreTests.Linq +{ + public class SortCheck + { + public int Age { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + + public override string ToString() + { + return (Age, FirstName, LastName).ToString(); + } + } + + public class Sort + { + static int rd; + + static UniTask RandomRun(T value) + { + if (Interlocked.Increment(ref rd) % 2 == 0) + { + return UniTask.Run(() => value); + } + else + { + return UniTask.FromResult(value); + } + } + static UniTask RandomRun(T value, CancellationToken ct) + { + if (Interlocked.Increment(ref rd) % 2 == 0) + { + return UniTask.Run(() => value); + } + else + { + return UniTask.FromResult(value); + } + } + + [Fact] + public async Task OrderBy() + { + var array = new[] { 1, 99, 32, 4, 536, 7, 8 }; + { + var xs = await array.ToUniTaskAsyncEnumerable().OrderBy(x => x).ToArrayAsync(); + var ys = array.OrderBy(x => x).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().OrderByDescending(x => x).ToArrayAsync(); + var ys = array.OrderByDescending(x => x).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().OrderByAwait(RandomRun).ToArrayAsync(); + var ys = array.OrderBy(x => x).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwait(RandomRun).ToArrayAsync(); + var ys = array.OrderByDescending(x => x).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().OrderByAwaitWithCancellation(RandomRun).ToArrayAsync(); + var ys = array.OrderBy(x => x).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + { + var xs = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwaitWithCancellation(RandomRun).ToArrayAsync(); + var ys = array.OrderByDescending(x => x).ToArray(); + xs.Should().BeEquivalentTo(ys); + } + } + + [Fact] + public async Task ThenBy() + { + var array = new[] + { + new SortCheck { Age = 99, FirstName = "ABC", LastName = "DEF" }, + new SortCheck { Age = 49, FirstName = "ABC", LastName = "DEF" }, + new SortCheck { Age = 49, FirstName = "ABC", LastName = "ZKH" }, + new SortCheck { Age = 12, FirstName = "ABC", LastName = "DEF" }, + new SortCheck { Age = 49, FirstName = "ABC", LastName = "MEF" }, + new SortCheck { Age = 12, FirstName = "QQQ", LastName = "DEF" }, + new SortCheck { Age = 19, FirstName = "ZKN", LastName = "DEF" }, + new SortCheck { Age = 39, FirstName = "APO", LastName = "REF" }, + new SortCheck { Age = 59, FirstName = "ABC", LastName = "DEF" }, + new SortCheck { Age = 99, FirstName = "DBC", LastName = "DEF" }, + new SortCheck { Age = 99, FirstName = "DBC", LastName = "MEF" }, + }; + { + var a = array.OrderBy(x => x.Age).ThenBy(x => x.FirstName).ThenBy(x => x.LastName).ToArray(); + var b = array.OrderBy(x => x.Age).ThenBy(x => x.FirstName).ThenByDescending(x => x.LastName).ToArray(); + var c = array.OrderBy(x => x.Age).ThenByDescending(x => x.FirstName).ThenBy(x => x.LastName).ToArray(); + var d = array.OrderBy(x => x.Age).ThenByDescending(x => x.FirstName).ThenByDescending(x => x.LastName).ToArray(); + var e = array.OrderByDescending(x => x.Age).ThenBy(x => x.FirstName).ThenBy(x => x.LastName).ToArray(); + var f = array.OrderByDescending(x => x.Age).ThenBy(x => x.FirstName).ThenByDescending(x => x.LastName).ToArray(); + var g = array.OrderByDescending(x => x.Age).ThenByDescending(x => x.FirstName).ThenBy(x => x.LastName).ToArray(); + var h = array.OrderByDescending(x => x.Age).ThenByDescending(x => x.FirstName).ThenByDescending(x => x.LastName).ToArray(); + + { + var a2 = await array.ToUniTaskAsyncEnumerable().OrderBy(x => x.Age).ThenBy(x => x.FirstName).ThenBy(x => x.LastName).ToArrayAsync(); + var b2 = await array.ToUniTaskAsyncEnumerable().OrderBy(x => x.Age).ThenBy(x => x.FirstName).ThenByDescending(x => x.LastName).ToArrayAsync(); + var c2 = await array.ToUniTaskAsyncEnumerable().OrderBy(x => x.Age).ThenByDescending(x => x.FirstName).ThenBy(x => x.LastName).ToArrayAsync(); + var d2 = await array.ToUniTaskAsyncEnumerable().OrderBy(x => x.Age).ThenByDescending(x => x.FirstName).ThenByDescending(x => x.LastName).ToArrayAsync(); + var e2 = await array.ToUniTaskAsyncEnumerable().OrderByDescending(x => x.Age).ThenBy(x => x.FirstName).ThenBy(x => x.LastName).ToArrayAsync(); + var f2 = await array.ToUniTaskAsyncEnumerable().OrderByDescending(x => x.Age).ThenBy(x => x.FirstName).ThenByDescending(x => x.LastName).ToArrayAsync(); + var g2 = await array.ToUniTaskAsyncEnumerable().OrderByDescending(x => x.Age).ThenByDescending(x => x.FirstName).ThenBy(x => x.LastName).ToArrayAsync(); + var h2 = await array.ToUniTaskAsyncEnumerable().OrderByDescending(x => x.Age).ThenByDescending(x => x.FirstName).ThenByDescending(x => x.LastName).ToArrayAsync(); + + a.Should().BeEquivalentTo(a2); + b.Should().BeEquivalentTo(b2); + c.Should().BeEquivalentTo(c2); + d.Should().BeEquivalentTo(d2); + e.Should().BeEquivalentTo(e2); + f.Should().BeEquivalentTo(f2); + g.Should().BeEquivalentTo(g2); + h.Should().BeEquivalentTo(h2); + } + { + var a2 = await array.ToUniTaskAsyncEnumerable().OrderByAwait(x => RandomRun(x.Age)).ThenByAwait(x => RandomRun(x.FirstName)).ThenByAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var b2 = await array.ToUniTaskAsyncEnumerable().OrderByAwait(x => RandomRun(x.Age)).ThenByAwait(x => RandomRun(x.FirstName)).ThenByDescendingAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var c2 = await array.ToUniTaskAsyncEnumerable().OrderByAwait(x => RandomRun(x.Age)).ThenByDescendingAwait(x => RandomRun(x.FirstName)).ThenByAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var d2 = await array.ToUniTaskAsyncEnumerable().OrderByAwait(x => RandomRun(x.Age)).ThenByDescendingAwait(x => RandomRun(x.FirstName)).ThenByDescendingAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var e2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwait(x => RandomRun(x.Age)).ThenByAwait(x => RandomRun(x.FirstName)).ThenByAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var f2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwait(x => RandomRun(x.Age)).ThenByAwait(x => RandomRun(x.FirstName)).ThenByDescendingAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var g2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwait(x => RandomRun(x.Age)).ThenByDescendingAwait(x => RandomRun(x.FirstName)).ThenByAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + var h2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwait(x => RandomRun(x.Age)).ThenByDescendingAwait(x => RandomRun(x.FirstName)).ThenByDescendingAwait(x => RandomRun(x.LastName)).ToArrayAsync(); + + a.Should().BeEquivalentTo(a2); + b.Should().BeEquivalentTo(b2); + c.Should().BeEquivalentTo(c2); + d.Should().BeEquivalentTo(d2); + e.Should().BeEquivalentTo(e2); + f.Should().BeEquivalentTo(f2); + g.Should().BeEquivalentTo(g2); + h.Should().BeEquivalentTo(h2); + } + { + var a2 = await array.ToUniTaskAsyncEnumerable().OrderByAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var b2 = await array.ToUniTaskAsyncEnumerable().OrderByAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var c2 = await array.ToUniTaskAsyncEnumerable().OrderByAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var d2 = await array.ToUniTaskAsyncEnumerable().OrderByAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var e2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var f2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var g2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + var h2 = await array.ToUniTaskAsyncEnumerable().OrderByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.Age)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.FirstName)).ThenByDescendingAwaitWithCancellation((x, ct) => RandomRun(x.LastName)).ToArrayAsync(); + + a.Should().BeEquivalentTo(a2); + b.Should().BeEquivalentTo(b2); + c.Should().BeEquivalentTo(c2); + d.Should().BeEquivalentTo(d2); + e.Should().BeEquivalentTo(e2); + f.Should().BeEquivalentTo(f2); + g.Should().BeEquivalentTo(g2); + h.Should().BeEquivalentTo(h2); + } + } + } + + + [Fact] + public async Task Throws() + { + foreach (var item in UniTaskTestException.Throws()) + { + { + var a = item.OrderBy(x => x).ToArrayAsync(); + var b = item.OrderByDescending(x => x).ToArrayAsync(); + var c = item.OrderBy(x => x).ThenBy(x => x).ToArrayAsync(); + var d = item.OrderBy(x => x).ThenByDescending(x => x).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await a); + await Assert.ThrowsAsync(async () => await b); + await Assert.ThrowsAsync(async () => await c); + await Assert.ThrowsAsync(async () => await d); + } + { + var a = item.OrderByAwait(RandomRun).ToArrayAsync(); + var b = item.OrderByDescendingAwait(RandomRun).ToArrayAsync(); + var c = item.OrderByAwait(RandomRun).ThenByAwait(RandomRun).ToArrayAsync(); + var d = item.OrderByAwait(RandomRun).ThenByDescendingAwait(RandomRun).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await a); + await Assert.ThrowsAsync(async () => await b); + await Assert.ThrowsAsync(async () => await c); + await Assert.ThrowsAsync(async () => await d); + } + { + var a = item.OrderByAwaitWithCancellation(RandomRun).ToArrayAsync(); + var b = item.OrderByDescendingAwaitWithCancellation(RandomRun).ToArrayAsync(); + var c = item.OrderByAwaitWithCancellation(RandomRun).ThenByAwaitWithCancellation(RandomRun).ToArrayAsync(); + var d = item.OrderByAwaitWithCancellation(RandomRun).ThenByDescendingAwaitWithCancellation(RandomRun).ToArrayAsync(); + + await Assert.ThrowsAsync(async () => await a); + await Assert.ThrowsAsync(async () => await b); + await Assert.ThrowsAsync(async () => await c); + await Assert.ThrowsAsync(async () => await d); + } + } + + } + } +} diff --git a/src/UniTask.NetCoreTests/Linq/_Exception.cs b/src/UniTask.NetCoreTests/Linq/_Exception.cs new file mode 100644 index 0000000..e28c513 --- /dev/null +++ b/src/UniTask.NetCoreTests/Linq/_Exception.cs @@ -0,0 +1,126 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Linq; +using System; +using System.Collections.Generic; +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace NetCoreTests.Linq +{ + public class UniTaskTestException : Exception + { + public static IUniTaskAsyncEnumerable ThrowImmediate() + { + return UniTaskAsyncEnumerable.Throw(new UniTaskTestException()); + } + public static IUniTaskAsyncEnumerable ThrowAfter() + { + return new ThrowAfter(new UniTaskTestException()); + } + public static IUniTaskAsyncEnumerable ThrowInMoveNext() + { + return new ThrowIn(new UniTaskTestException()); + } + + + public static IEnumerable> Throws(int count = 3) + { + yield return ThrowImmediate(); + yield return ThrowAfter(); + yield return ThrowInMoveNext(); + yield return UniTaskAsyncEnumerable.Range(1, count).Concat(ThrowImmediate()); + yield return UniTaskAsyncEnumerable.Range(1, count).Concat(ThrowAfter()); + yield return UniTaskAsyncEnumerable.Range(1, count).Concat(ThrowInMoveNext()); + } + } + + internal class ThrowIn : IUniTaskAsyncEnumerable + { + readonly Exception exception; + + public ThrowIn(Exception exception) + { + this.exception = exception; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(exception, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly Exception exception; + CancellationToken cancellationToken; + + public Enumerator(Exception exception, CancellationToken cancellationToken) + { + this.exception = exception; + this.cancellationToken = cancellationToken; + } + + public TValue Current => default; + + public UniTask MoveNextAsync() + { + ExceptionDispatchInfo.Capture(exception).Throw(); + return new UniTask(false); + } + + public UniTask DisposeAsync() + { + return default; + } + } + } + + internal class ThrowAfter : IUniTaskAsyncEnumerable + { + readonly Exception exception; + + public ThrowAfter(Exception exception) + { + this.exception = exception; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(exception, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly Exception exception; + CancellationToken cancellationToken; + + public Enumerator(Exception exception, CancellationToken cancellationToken) + { + this.exception = exception; + this.cancellationToken = cancellationToken; + } + + public TValue Current => default; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + var tcs = new UniTaskCompletionSource(); + + var awaiter = UniTask.Yield().GetAwaiter(); + awaiter.UnsafeOnCompleted(() => + { + Thread.Sleep(1); + tcs.TrySetException(exception); + }); + + return tcs.Task; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} diff --git a/src/UniTask.NetCoreTests/UniTask.NetCoreTests.csproj b/src/UniTask.NetCoreTests/UniTask.NetCoreTests.csproj index 3c86681..aa0765b 100644 --- a/src/UniTask.NetCoreTests/UniTask.NetCoreTests.csproj +++ b/src/UniTask.NetCoreTests/UniTask.NetCoreTests.csproj @@ -1,4 +1,4 @@ - + netcoreapp3.1 @@ -9,10 +9,20 @@ - - - - + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/src/UniTask.NetCoreTests/UnitTest1.cs b/src/UniTask.NetCoreTests/UnitTest1.cs deleted file mode 100644 index 1d51046..0000000 --- a/src/UniTask.NetCoreTests/UnitTest1.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using Xunit; - -namespace UniTask.NetCoreTests -{ - public class UnitTest1 - { - [Fact] - public void Test1() - { - - } - } -} diff --git a/src/UniTask/Assets/Plugins/UniTask/IAsyncEnumerable.cs b/src/UniTask/Assets/Plugins/UniTask/IAsyncEnumerable.cs new file mode 100644 index 0000000..6807908 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/IAsyncEnumerable.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Cysharp.Threading.Tasks +{ + public interface IUniTaskAsyncEnumerable + { + IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default); + } + + public interface IUniTaskAsyncEnumerator : IUniTaskAsyncDisposable + { + T Current { get; } + UniTask MoveNextAsync(); + } + + public interface IUniTaskAsyncDisposable + { + UniTask DisposeAsync(); + } + + public interface IUniTaskOrderedAsyncEnumerable : IUniTaskAsyncEnumerable + { + IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func keySelector, IComparer comparer, bool descending); + IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending); + IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending); + } + + //public interface IUniTaskAsyncGrouping : IUniTaskAsyncEnumerable + //{ + // TKey Key { get; } + //} + + public static class UniTaskAsyncEnumerableExtensions + { + public static UniTaskCancelableAsyncEnumerable WithCancellation(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + return new UniTaskCancelableAsyncEnumerable(source, cancellationToken); + } + } + + [StructLayout(LayoutKind.Auto)] + public readonly struct UniTaskCancelableAsyncEnumerable + { + private readonly IUniTaskAsyncEnumerable enumerable; + private readonly CancellationToken cancellationToken; + + internal UniTaskCancelableAsyncEnumerable(IUniTaskAsyncEnumerable enumerable, CancellationToken cancellationToken) + { + this.enumerable = enumerable; + this.cancellationToken = cancellationToken; + } + + public Enumerator GetAsyncEnumerator() + { + return new Enumerator(enumerable.GetAsyncEnumerator(cancellationToken)); + } + + [StructLayout(LayoutKind.Auto)] + public readonly struct Enumerator + { + private readonly IUniTaskAsyncEnumerator enumerator; + + internal Enumerator(IUniTaskAsyncEnumerator enumerator) + { + this.enumerator = enumerator; + } + + public T Current => enumerator.Current; + + public UniTask MoveNextAsync() + { + return enumerator.MoveNextAsync(); + } + + + public UniTask DisposeAsync() + { + return enumerator.DisposeAsync(); + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/IAsyncEnumerable.cs.meta b/src/UniTask/Assets/Plugins/UniTask/IAsyncEnumerable.cs.meta new file mode 100644 index 0000000..12f0fe5 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/IAsyncEnumerable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b20cf9f02ac585948a4372fa4ee06504 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Internal/Error.cs b/src/UniTask/Assets/Plugins/UniTask/Internal/Error.cs index c02e541..5c7bc93 100644 --- a/src/UniTask/Assets/Plugins/UniTask/Internal/Error.cs +++ b/src/UniTask/Assets/Plugins/UniTask/Internal/Error.cs @@ -20,6 +20,24 @@ namespace Cysharp.Threading.Tasks.Internal throw new ArgumentNullException(paramName); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception ArgumentOutOfRange(string paramName) + { + return new ArgumentOutOfRangeException(paramName); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception NoElements() + { + return new InvalidOperationException("Source sequence doesn't contain any elements."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Exception MoreThanOneElement() + { + return new InvalidOperationException("Source sequence contains more than one element."); + } + [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentException(string message) { diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq.meta b/src/UniTask/Assets/Plugins/UniTask/Linq.meta new file mode 100644 index 0000000..1dcbc32 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4cc94a232b1c1154b8084bdda29c3484 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Aggregate.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Aggregate.cs new file mode 100644 index 0000000..723a010 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Aggregate.cs @@ -0,0 +1,318 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AggregateAsync(this IUniTaskAsyncEnumerable source, Func accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.InvokeAsync(source, accumulator, cancellationToken); + } + + public static UniTask AggregateAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.InvokeAsync(source, seed, accumulator, cancellationToken); + } + + public static UniTask AggregateAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, Func resultSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + Error.ThrowArgumentNullException(accumulator, nameof(resultSelector)); + + return Aggregate.InvokeAsync(source, seed, accumulator, resultSelector, cancellationToken); + } + + public static UniTask AggregateAwaitAsync(this IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.InvokeAsync(source, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.InvokeAsync(source, seed, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + Error.ThrowArgumentNullException(accumulator, nameof(resultSelector)); + + return Aggregate.InvokeAsync(source, seed, accumulator, resultSelector, cancellationToken); + } + + public static UniTask AggregateAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.InvokeAsync(source, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + + return Aggregate.InvokeAsync(source, seed, accumulator, cancellationToken); + } + + public static UniTask AggregateAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(accumulator, nameof(accumulator)); + Error.ThrowArgumentNullException(accumulator, nameof(resultSelector)); + + return Aggregate.InvokeAsync(source, seed, accumulator, resultSelector, cancellationToken); + } + } + + internal static class Aggregate + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + throw Error.NoElements(); + } + + while (await e.MoveNextAsync()) + { + value = accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func accumulator, Func resultSelector, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = accumulator(value, e.Current); + } + return resultSelector(value); + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // with async + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + throw Error.NoElements(); + } + + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current); + } + return await resultSelector(value); + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + + // with cancellation + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + throw Error.NoElements(); + } + + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current, cancellationToken); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current, cancellationToken); + } + return value; + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TAccumulate seed, Func> accumulator, Func> resultSelector, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TAccumulate value = seed; + while (await e.MoveNextAsync()) + { + value = await accumulator(value, e.Current, cancellationToken); + } + return await resultSelector(value, cancellationToken); + + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Aggregate.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Aggregate.cs.meta new file mode 100644 index 0000000..837df4a --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Aggregate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5dc68c05a4228c643937f6ebd185bcca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/All.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/All.cs new file mode 100644 index 0000000..b8fb003 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/All.cs @@ -0,0 +1,108 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AllAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return All.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask AllAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return All.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask AllAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return All.InvokeAsync(source, predicate, cancellationToken); + } + } + + internal static class All + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (!predicate(e.Current)) + { + return false; + } + } + + return true; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (!await predicate(e.Current)) + { + return false; + } + } + + return true; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (!await predicate(e.Current, cancellationToken)) + { + return false; + } + } + + return true; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/All.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/All.cs.meta new file mode 100644 index 0000000..d378ff0 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/All.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7271437e0033af2448b600ee248924dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Any.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Any.cs new file mode 100644 index 0000000..cf3cbfa --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Any.cs @@ -0,0 +1,136 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AnyAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Any.InvokeAsync(source, cancellationToken); + } + + public static UniTask AnyAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Any.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask AnyAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Any.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask AnyAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Any.InvokeAsync(source, predicate, cancellationToken); + } + } + + internal static class Any + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + if (await e.MoveNextAsync()) + { + return true; + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (predicate(e.Current)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current, cancellationToken)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Any.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Any.cs.meta new file mode 100644 index 0000000..1070bcc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Any.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2b2e65745263994fbe34f3e0ec8eb12 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/AppendPrepend.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/AppendPrepend.cs new file mode 100644 index 0000000..960e113 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/AppendPrepend.cs @@ -0,0 +1,148 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Append(this IUniTaskAsyncEnumerable source, TSource element) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new AppendPrepend(source, element, true); + } + + public static IUniTaskAsyncEnumerable Prepend(this IUniTaskAsyncEnumerable source, TSource element) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new AppendPrepend(source, element, true); + } + } + + internal sealed class AppendPrepend : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly TSource element; + readonly bool append; // or prepend + + public AppendPrepend(IUniTaskAsyncEnumerable source, TSource element, bool append) + { + this.source = source; + this.element = element; + this.append = append; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, element, append, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + enum State : byte + { + None, + RequirePrepend, + RequireAppend, + Completed + } + + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly TSource element; + CancellationToken cancellationToken; + + State state; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, TSource element, bool append, CancellationToken cancellationToken) + { + this.source = source; + this.element = element; + this.state = append ? State.RequireAppend : State.RequirePrepend; + this.cancellationToken = cancellationToken; + } + + public TSource Current { get; private set; } + + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (enumerator == null) + { + if (state == State.RequireAppend) + { + Current = element; + state = State.None; + return CompletedTasks.True; + } + + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + if (state == State.Completed) + { + return CompletedTasks.False; + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + + if (awaiter.IsCompleted) + { + MoveNextCoreDelegate(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + if (self.state == State.RequireAppend) + { + self.state = State.Completed; + self.Current = self.element; + self.completionSource.TrySetResult(true); + } + else + { + self.state = State.Completed; + self.completionSource.TrySetResult(false); + } + } + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/AppendPrepend.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/AppendPrepend.cs.meta new file mode 100644 index 0000000..6d2ee04 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/AppendPrepend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3268ec424b8055f45aa2a26d17c80468 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/AsUniTaskAsyncEnumerable.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/AsUniTaskAsyncEnumerable.cs new file mode 100644 index 0000000..c00452e --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/AsUniTaskAsyncEnumerable.cs @@ -0,0 +1,10 @@ +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable AsUniTaskAsyncEnumerable(this IUniTaskAsyncEnumerable source) + { + return source; + } + } +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/AsUniTaskAsyncEnumerable.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/AsUniTaskAsyncEnumerable.cs.meta new file mode 100644 index 0000000..90f6207 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/AsUniTaskAsyncEnumerable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69866e262589ea643bbc62a1d696077a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/AsyncEnumeratorBase.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/AsyncEnumeratorBase.cs new file mode 100644 index 0000000..3f3ba2f --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/AsyncEnumeratorBase.cs @@ -0,0 +1,410 @@ +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public abstract class MoveNextSource : IUniTaskSource + { + protected UniTaskCompletionSourceCore completionSource; + + public bool GetResult(short token) + { + return completionSource.GetResult(token); + } + + public UniTaskStatus GetStatus(short token) + { + return completionSource.GetStatus(token); + } + + public void OnCompleted(Action continuation, object state, short token) + { + completionSource.OnCompleted(continuation, state, token); + } + + public UniTaskStatus UnsafeGetStatus() + { + return completionSource.UnsafeGetStatus(); + } + + void IUniTaskSource.GetResult(short token) + { + completionSource.GetResult(token); + } + + protected bool TryGetResult(UniTask.Awaiter awaiter, out T result) + { + try + { + result = awaiter.GetResult(); + return true; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + result = default; + return false; + } + } + + protected bool TryGetResult(UniTask.Awaiter awaiter) + { + try + { + awaiter.GetResult(); + return true; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return false; + } + } + } + + public abstract class AsyncEnumeratorBase : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action moveNextCallbackDelegate = MoveNextCallBack; + + readonly IUniTaskAsyncEnumerable source; + protected CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter sourceMoveNext; + + public AsyncEnumeratorBase(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + // abstract + + /// + /// If return value is false, continue source.MoveNext. + /// + protected abstract bool TryMoveNextCore(bool sourceHasCurrent, out bool result); + + // Util + protected TSource SourceCurrent => enumerator.Current; + + // IUniTaskAsyncEnumerator + + public TResult Current { get; protected set; } + + public UniTask MoveNextAsync() + { + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + if (!OnFirstIteration()) + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + protected virtual bool OnFirstIteration() + { + return false; + } + + protected void SourceMoveNext() + { + CONTINUE: + sourceMoveNext = enumerator.MoveNextAsync().GetAwaiter(); + if (sourceMoveNext.IsCompleted) + { + bool result = false; + try + { + if (!TryMoveNextCore(sourceMoveNext.GetResult(), out result)) + { + goto CONTINUE; + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (cancellationToken.IsCancellationRequested) + { + completionSource.TrySetCanceled(cancellationToken); + } + else + { + completionSource.TrySetResult(result); + } + } + else + { + sourceMoveNext.SourceOnCompleted(moveNextCallbackDelegate, this); + } + } + + static void MoveNextCallBack(object state) + { + var self = (AsyncEnumeratorBase)state; + bool result; + try + { + if (!self.TryMoveNextCore(self.sourceMoveNext.GetResult(), out result)) + { + self.SourceMoveNext(); + return; + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(result); + } + } + + // if require additional resource to dispose, override and call base.DisposeAsync. + public virtual UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + + public abstract class AsyncEnumeratorAwaitSelectorBase : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action moveNextCallbackDelegate = MoveNextCallBack; + static readonly Action setCurrentCallbackDelegate = SetCurrentCallBack; + + + readonly IUniTaskAsyncEnumerable source; + protected CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter sourceMoveNext; + + UniTask.Awaiter resultAwaiter; + + public AsyncEnumeratorAwaitSelectorBase(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + // abstract + + protected abstract UniTask TransformAsync(TSource sourceCurrent); + protected abstract bool TrySetCurrentCore(TAwait awaitResult, out bool terminateIteration); + + // Util + protected TSource SourceCurrent { get; private set; } + + protected (bool waitCallback, bool requireNextIteration) ActionCompleted(bool trySetCurrentResult, out bool moveNextResult) + { + if (trySetCurrentResult) + { + moveNextResult = true; + return (false, false); + } + else + { + moveNextResult = default; + return (false, true); + } + } + protected (bool waitCallback, bool requireNextIteration) WaitAwaitCallback(out bool moveNextResult) { moveNextResult = default; return (true, false); } + protected (bool waitCallback, bool requireNextIteration) IterateFinished(out bool moveNextResult) { moveNextResult = false; return (false, false); } + + // IUniTaskAsyncEnumerator + + public TResult Current { get; protected set; } + + public UniTask MoveNextAsync() + { + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + protected void SourceMoveNext() + { + CONTINUE: + sourceMoveNext = enumerator.MoveNextAsync().GetAwaiter(); + if (sourceMoveNext.IsCompleted) + { + bool result = false; + try + { + (bool waitCallback, bool requireNextIteration) = TryMoveNextCore(sourceMoveNext.GetResult(), out result); + + if (waitCallback) + { + return; + } + + if (requireNextIteration) + { + goto CONTINUE; + } + else + { + completionSource.TrySetResult(result); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + else + { + sourceMoveNext.SourceOnCompleted(moveNextCallbackDelegate, this); + } + } + + (bool waitCallback, bool requireNextIteration) TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + SourceCurrent = enumerator.Current; + var task = TransformAsync(SourceCurrent); + if (UnwarapTask(task, out var taskResult)) + { + var currentResult = TrySetCurrentCore(taskResult, out var terminateIteration); + if (terminateIteration) + { + return IterateFinished(out result); + } + + return ActionCompleted(currentResult, out result); + } + else + { + return WaitAwaitCallback(out result); + } + } + + return IterateFinished(out result); + } + + protected bool UnwarapTask(UniTask taskResult, out TAwait result) + { + resultAwaiter = taskResult.GetAwaiter(); + + if (resultAwaiter.IsCompleted) + { + result = resultAwaiter.GetResult(); + return true; + } + else + { + resultAwaiter.SourceOnCompleted(setCurrentCallbackDelegate, this); + result = default; + return false; + } + } + + static void MoveNextCallBack(object state) + { + var self = (AsyncEnumeratorAwaitSelectorBase)state; + bool result = false; + try + { + (bool waitCallback, bool requireNextIteration) = self.TryMoveNextCore(self.sourceMoveNext.GetResult(), out result); + + if (waitCallback) + { + return; + } + + if (requireNextIteration) + { + self.SourceMoveNext(); + return; + } + else + { + self.completionSource.TrySetResult(result); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + + static void SetCurrentCallBack(object state) + { + var self = (AsyncEnumeratorAwaitSelectorBase)state; + + bool doneSetCurrent; + bool terminateIteration; + try + { + var result = self.resultAwaiter.GetResult(); + doneSetCurrent = self.TrySetCurrentCore(result, out terminateIteration); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + if (doneSetCurrent) + { + self.completionSource.TrySetResult(true); + } + else + { + if (terminateIteration) + { + self.completionSource.TrySetResult(false); + } + else + { + self.SourceMoveNext(); + } + } + } + } + + // if require additional resource to dispose, override and call base.DisposeAsync. + public virtual UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/AsyncEnumeratorBase.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/AsyncEnumeratorBase.cs.meta new file mode 100644 index 0000000..a4e96dc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/AsyncEnumeratorBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 01ba1d3b17e13fb4c95740131c7e6e19 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Average.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.cs new file mode 100644 index 0000000..975fba8 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.cs @@ -0,0 +1,1524 @@ +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask AverageAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + } + + internal static class Average + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64 sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += e.Current; + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int32? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Int64? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (double)sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Single? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return (float)(sum / count); + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Double? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + Decimal? sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum / count; + } + + } +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Average.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.cs.meta new file mode 100644 index 0000000..8f60dfc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58499f95012fb3c47bb7bcbc5862e562 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Average.tt b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.tt new file mode 100644 index 0000000..003094e --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.tt @@ -0,0 +1,237 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".cs" #> +<# + var types = new[] + { + (typeof(int), "double"), + (typeof(long), "double"), + (typeof(float),"float"), + (typeof(double),"double"), + (typeof(decimal),"decimal"), + + (typeof(int?),"double?"), + (typeof(long?),"double?"), + (typeof(float?),"float?"), + (typeof(double?),"double?"), + (typeof(decimal?),"decimal?"), + }; + + Func IsNullable = x => x.IsGenericType; + Func ElementType = x => IsNullable(x) ? x.GetGenericArguments()[0] : x; + Func TypeName = x => IsNullable(x) ? x.GetGenericArguments()[0].Name + "?" : x.Name; + Func WithSuffix = x => IsNullable(x) ? ".GetValueOrDefault()" : ""; + Func CalcResult = x => { var e = ElementType(x); return (e == typeof(int) || e == typeof(long)) ? "(double)sum / count" : (e == typeof(float)) ? "(float)(sum / count)" : "sum / count"; }; +#> +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { +<# foreach(var (t, ret) in types) { #> + public static UniTask<<#= ret #>> AverageAsync(this IUniTaskAsyncEnumerable<<#= TypeName(t) #>> source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Average.InvokeAsync(source, cancellationToken); + } + + public static UniTask<<#= ret #>> AverageAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask<<#= ret #>> AverageAwaitAsync(this IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask<<#= ret #>> AverageAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Average.InvokeAsync(source, selector, cancellationToken); + } + +<# } #> + } + + internal static class Average + { +<# foreach(var (t, ret) in types) { #> + public static async UniTask<<#= ret #>> InvokeAsync(IUniTaskAsyncEnumerable<<#= TypeName(t) #>> source, CancellationToken cancellationToken) + { + long count = 0; + <#= TypeName(t) #> sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { +<# if (IsNullable(t)) { #> + var v = e.Current; + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } +<# } else { #> + checked + { + sum += e.Current; + count++; + } +<# } #> + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return <#= CalcResult(t) #>; + } + + public static async UniTask<<#= ret #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + long count = 0; + <#= TypeName(t) #> sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { +<# if (IsNullable(t)) { #> + var v = selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } +<# } else { #> + checked + { + sum += selector(e.Current); + count++; + } +<# } #> + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return <#= CalcResult(t) #>; + } + + public static async UniTask<<#= ret #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken) + { + long count = 0; + <#= TypeName(t) #> sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { +<# if (IsNullable(t)) { #> + var v = await selector(e.Current); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } +<# } else { #> + checked + { + sum += await selector(e.Current); + count++; + } +<# } #> + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return <#= CalcResult(t) #>; + } + + public static async UniTask<<#= ret #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken) + { + long count = 0; + <#= TypeName(t) #> sum = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { +<# if (IsNullable(t)) { #> + var v = await selector(e.Current, cancellationToken); + if (v.HasValue) + { + checked + { + sum += v.Value; + count++; + } + } +<# } else { #> + checked + { + sum += await selector(e.Current, cancellationToken); + count++; + } +<# } #> + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return <#= CalcResult(t) #>; + } + +<# } #> + } +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Average.tt.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.tt.meta new file mode 100644 index 0000000..e0a43fd --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Average.tt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 84bce45768c171d4490153eb08630a98 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Buffer.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Buffer.cs new file mode 100644 index 0000000..f29af41 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Buffer.cs @@ -0,0 +1,340 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable> Buffer(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + if (count <= 0) throw Error.ArgumentOutOfRange(nameof(count)); + + return new Buffer(source, count); + } + + public static IUniTaskAsyncEnumerable> Buffer(this IUniTaskAsyncEnumerable source, Int32 count, Int32 skip) + { + Error.ThrowArgumentNullException(source, nameof(source)); + if (count <= 0) throw Error.ArgumentOutOfRange(nameof(count)); + if (skip <= 0) throw Error.ArgumentOutOfRange(nameof(skip)); + + return new BufferSkip(source, count, skip); + } + } + + internal sealed class Buffer : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public Buffer(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, count, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator> + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + bool continueNext; + + bool completed; + List buffer; + + public Enumerator(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + } + + public IList Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + buffer = new List(count); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + if (completed) + { + if (buffer != null && buffer.Count > 0) + { + var ret = buffer; + buffer = null; + Current = ret; + completionSource.TrySetResult(true); + return; + } + else + { + completionSource.TrySetResult(false); + return; + } + } + + try + { + + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.buffer.Add(self.enumerator.Current); + + if (self.buffer.Count == self.count) + { + self.Current = self.buffer; + self.buffer = new List(self.count); + self.continueNext = false; + self.completionSource.TrySetResult(true); + return; + } + else + { + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.completed = true; + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + + internal sealed class BufferSkip : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + readonly int skip; + + public BufferSkip(IUniTaskAsyncEnumerable source, int count, int skip) + { + this.source = source; + this.count = count; + this.skip = skip; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, count, skip, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator> + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + readonly int skip; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + bool continueNext; + + bool completed; + Queue> buffers; + int index = 0; + + public Enumerator(IUniTaskAsyncEnumerable source, int count, int skip, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.skip = skip; + this.cancellationToken = cancellationToken; + } + + public IList Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + buffers = new Queue>(); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + if (completed) + { + if (buffers.Count > 0) + { + Current = buffers.Dequeue(); + completionSource.TrySetResult(true); + return; + } + else + { + completionSource.TrySetResult(false); + return; + } + } + + try + { + + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.index++ % self.skip == 0) + { + self.buffers.Enqueue(new List(self.count)); + } + + var item = self.enumerator.Current; + foreach (var buffer in self.buffers) + { + buffer.Add(item); + } + + if (self.buffers.Count > 0 && self.buffers.Peek().Count == self.count) + { + self.Current = self.buffers.Dequeue(); + self.continueNext = false; + self.completionSource.TrySetResult(true); + return; + } + else + { + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.completed = true; + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Buffer.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Buffer.cs.meta new file mode 100644 index 0000000..e7154e4 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Buffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 951310243334a3148a7872977cb31c5c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Cast.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Cast.cs new file mode 100644 index 0000000..9a27f72 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Cast.cs @@ -0,0 +1,53 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Cast(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Cast(source); + } + } + + internal sealed class Cast : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public Cast(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + public Enumerator(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + Current = (TResult)SourceCurrent; + result = true; + return true; + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Cast.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Cast.cs.meta new file mode 100644 index 0000000..913b043 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Cast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edebeae8b61352b428abe9ce8f3fc71a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Concat.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Concat.cs new file mode 100644 index 0000000..45aab70 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Concat.cs @@ -0,0 +1,162 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Concat(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Concat(first, second); + } + } + + internal sealed class Concat : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + + public Concat(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + this.first = first; + this.second = second; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(first, second, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + enum IteratingState + { + IteratingFirst, + IteratingSecond, + Complete + } + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + CancellationToken cancellationToken; + + IteratingState iteratingState; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.cancellationToken = cancellationToken; + this.iteratingState = IteratingState.IteratingFirst; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (iteratingState == IteratingState.Complete) return CompletedTasks.False; + + completionSource.Reset(); + StartIterate(); + return new UniTask(this, completionSource.Version); + } + + void StartIterate() + { + if (enumerator == null) + { + if (iteratingState == IteratingState.IteratingFirst) + { + enumerator = first.GetAsyncEnumerator(cancellationToken); + } + else if (iteratingState == IteratingState.IteratingSecond) + { + enumerator = second.GetAsyncEnumerator(cancellationToken); + } + } + + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (awaiter.IsCompleted) + { + MoveNextCoreDelegate(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + if (self.iteratingState == IteratingState.IteratingFirst) + { + self.RunSecondAfterDisposeAsync().Forget(); + return; + } + + self.iteratingState = IteratingState.Complete; + self.completionSource.TrySetResult(false); + } + } + } + + async UniTaskVoid RunSecondAfterDisposeAsync() + { + try + { + await enumerator.DisposeAsync(); + enumerator = null; + awaiter = default; + iteratingState = IteratingState.IteratingSecond; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + + StartIterate(); + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Concat.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Concat.cs.meta new file mode 100644 index 0000000..6bfcf31 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Concat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7cb9e19c449127a459851a135ce7d527 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Contains.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Contains.cs new file mode 100644 index 0000000..e38601c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Contains.cs @@ -0,0 +1,50 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ContainsAsync(this IUniTaskAsyncEnumerable source, TSource value, CancellationToken cancellationToken = default) + { + return ContainsAsync(source, value, EqualityComparer.Default, cancellationToken); + } + + public static UniTask ContainsAsync(this IUniTaskAsyncEnumerable source, TSource value, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return Contains.InvokeAsync(source, value, comparer, cancellationToken); + } + } + + internal static class Contains + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, TSource value, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (comparer.Equals(value, e.Current)) + { + return true; + } + } + + return false; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Contains.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Contains.cs.meta new file mode 100644 index 0000000..9bd414b --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Contains.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36ab06d30f3223048b4f676e05431a7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Count.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Count.cs new file mode 100644 index 0000000..1cdcda3 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Count.cs @@ -0,0 +1,144 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask CountAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Count.InvokeAsync(source, cancellationToken); + } + + public static UniTask CountAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Count.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask CountAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Count.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask CountAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Count.InvokeAsync(source, predicate, cancellationToken); + } + } + + internal static class Count + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked { count++; } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + var count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current, cancellationToken)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Count.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Count.cs.meta new file mode 100644 index 0000000..35db332 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Count.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e606d38eed688574bb2ba89d983cc9bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/DefaultIfEmpty.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/DefaultIfEmpty.cs new file mode 100644 index 0000000..e8d3662 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/DefaultIfEmpty.cs @@ -0,0 +1,140 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable DefaultIfEmpty(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new DefaultIfEmpty(source, default); + } + + public static IUniTaskAsyncEnumerable DefaultIfEmpty(this IUniTaskAsyncEnumerable source, TSource defaultValue) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new DefaultIfEmpty(source, defaultValue); + } + } + + internal sealed class DefaultIfEmpty : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly TSource defaultValue; + + public DefaultIfEmpty(IUniTaskAsyncEnumerable source, TSource defaultValue) + { + this.source = source; + this.defaultValue = defaultValue; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, defaultValue, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + enum IteratingState : byte + { + Empty, + Iterating, + Completed + } + + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly TSource defaultValue; + CancellationToken cancellationToken; + + IteratingState iteratingState; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, TSource defaultValue, CancellationToken cancellationToken) + { + this.source = source; + this.defaultValue = defaultValue; + this.cancellationToken = cancellationToken; + + this.iteratingState = IteratingState.Empty; + } + + public TSource Current { get; private set; } + + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (iteratingState == IteratingState.Completed) + { + return CompletedTasks.False; + } + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.iteratingState = IteratingState.Iterating; + self.Current = self.enumerator.Current; + self.completionSource.TrySetResult(true); + } + else + { + if (self.iteratingState == IteratingState.Empty) + { + self.iteratingState = IteratingState.Completed; + + self.Current = self.defaultValue; + self.completionSource.TrySetResult(true); + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/DefaultIfEmpty.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/DefaultIfEmpty.cs.meta new file mode 100644 index 0000000..5aa5993 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/DefaultIfEmpty.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 19e437c039ad7e1478dbce1779ef8660 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Distinct.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Distinct.cs new file mode 100644 index 0000000..2868fcd --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Distinct.cs @@ -0,0 +1,277 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source) + { + return Distinct(source, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Distinct(source, comparer); + } + + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source, Func keySelector) + { + return Distinct(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Distinct(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Distinct(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctAwait(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctAwait(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctAwaitWithCancellation(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctAwaitCancellation(source, keySelector, comparer); + } + } + + internal sealed class Distinct : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly IEqualityComparer comparer; + + public Distinct(IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + this.source = source; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly HashSet set; + + public Enumerator(IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (set.Add(v)) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class Distinct : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly IEqualityComparer comparer; + + public Distinct(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly HashSet set; + readonly Func keySelector; + + public Enumerator(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + this.keySelector = keySelector; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (set.Add(keySelector(v))) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class DistinctAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly HashSet set; + readonly Func> keySelector; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + this.keySelector = keySelector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return keySelector(sourceCurrent); + } + + protected override bool TrySetCurrentCore(TKey awaitResult, out bool terminateIteration) + { + if (set.Add(awaitResult)) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = false; + return false; + } + } + } + } + + internal sealed class DistinctAwaitCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctAwaitCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly HashSet set; + readonly Func> keySelector; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.set = new HashSet(comparer); + this.keySelector = keySelector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return keySelector(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(TKey awaitResult, out bool terminateIteration) + { + if (set.Add(awaitResult)) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = false; + return false; + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Distinct.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Distinct.cs.meta new file mode 100644 index 0000000..61804b7 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Distinct.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f09903be66e5d943b243d7c19cb3811 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/DistinctUntilChanged.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/DistinctUntilChanged.cs new file mode 100644 index 0000000..4f25336 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/DistinctUntilChanged.cs @@ -0,0 +1,297 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source) + { + return DistinctUntilChanged(source, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChanged(source, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source, Func keySelector) + { + return DistinctUntilChanged(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChanged(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChanged(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctUntilChangedAwait(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChangedAwait(source, keySelector, comparer); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + return DistinctUntilChangedAwaitWithCancellation(source, keySelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable DistinctUntilChangedAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new DistinctUntilChangedAwaitCancellation(source, keySelector, comparer); + } + } + + internal sealed class DistinctUntilChanged : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly IEqualityComparer comparer; + + public DistinctUntilChanged(IUniTaskAsyncEnumerable source, IEqualityComparer comparer) + { + this.source = source; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly IEqualityComparer comparer; + TSource prev; + bool first; + + public Enumerator(IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.comparer = comparer; + this.first = true; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (first || !comparer.Equals(prev, v)) + { + first = false; + Current = prev = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class DistinctUntilChanged : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly IEqualityComparer comparer; + + public DistinctUntilChanged(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly IEqualityComparer comparer; + readonly Func keySelector; + TKey prev; + bool first; + + public Enumerator(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.comparer = comparer; + this.keySelector = keySelector; + this.first = true; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + var key = keySelector(v); + if (first || !comparer.Equals(prev, key)) + { + first = false; + prev = key; + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class DistinctUntilChangedAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctUntilChangedAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly IEqualityComparer comparer; + readonly Func> keySelector; + TKey prev; + bool first; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.comparer = comparer; + this.keySelector = keySelector; + this.first = true; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return keySelector(sourceCurrent); + } + + protected override bool TrySetCurrentCore(TKey key, out bool terminateIteration) + { + if (first || !comparer.Equals(prev, key)) + { + first = false; + prev = key; + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = false; + return false; + } + } + } + } + + internal sealed class DistinctUntilChangedAwaitCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly IEqualityComparer comparer; + + public DistinctUntilChangedAwaitCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly IEqualityComparer comparer; + readonly Func> keySelector; + TKey prev; + bool first; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.comparer = comparer; + this.keySelector = keySelector; + this.first = true; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return keySelector(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(TKey key, out bool terminateIteration) + { + if (first || !comparer.Equals(prev, key)) + { + first = false; + prev = key; + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = false; + return false; + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/DistinctUntilChanged.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/DistinctUntilChanged.cs.meta new file mode 100644 index 0000000..84cddf8 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/DistinctUntilChanged.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0351f6767df7e644b935d4d599968162 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Do.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Do.cs new file mode 100644 index 0000000..9cb3f41 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Do.cs @@ -0,0 +1,256 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Internal; +using Cysharp.Threading.Tasks.Linq; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return source.Do(onNext, null, null); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext, Action onError) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return source.Do(onNext, onError, null); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return source.Do(onNext, null, onCompleted); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return new Do(source, onNext, onError, onCompleted); + } + + public static IUniTaskAsyncEnumerable Do(this IUniTaskAsyncEnumerable source, IObserver observer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(observer, nameof(observer)); + + return source.Do(observer.OnNext, observer.OnError, observer.OnCompleted); // alloc delegate. + } + + // not yet impl. + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext, Func onError) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwait(this IUniTaskAsyncEnumerable source, Func onNext, Func onError, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext, Func onError) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + + //public static IUniTaskAsyncEnumerable DoAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func onNext, Func onError, Func onCompleted) + //{ + // throw new NotImplementedException(); + //} + } + + internal sealed class Do : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Action onNext; + readonly Action onError; + readonly Action onCompleted; + + public Do(IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted) + { + this.source = source; + this.onNext = onNext; + this.onError = onError; + this.onCompleted = onCompleted; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, onNext, onError, onCompleted, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly Action onNext; + readonly Action onError; + readonly Action onCompleted; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, Action onNext, Action onError, Action onCompleted, CancellationToken cancellationToken) + { + this.source = source; + this.onNext = onNext; + this.onError = onError; + this.onCompleted = onCompleted; + this.cancellationToken = cancellationToken; + } + + public TSource Current { get; private set; } + + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + bool isCompleted = false; + try + { + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + isCompleted = awaiter.IsCompleted; + } + catch (Exception ex) + { + CallTrySetExceptionAfterNotification(ex); + return new UniTask(this, completionSource.Version); + } + + if (isCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + void CallTrySetExceptionAfterNotification(Exception ex) + { + if (onError != null) + { + try + { + onError(ex); + } + catch (Exception ex2) + { + completionSource.TrySetException(ex2); + return; + } + } + + completionSource.TrySetException(ex); + } + + bool TryGetResultWithNotification(UniTask.Awaiter awaiter, out T result) + { + try + { + result = awaiter.GetResult(); + return true; + } + catch (Exception ex) + { + CallTrySetExceptionAfterNotification(ex); + result = default; + return false; + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResultWithNotification(self.awaiter, out var result)) + { + if (result) + { + var v = self.enumerator.Current; + + if (self.onNext != null) + { + try + { + self.onNext(v); + } + catch (Exception ex) + { + self.CallTrySetExceptionAfterNotification(ex); + } + } + + self.Current = v; + self.completionSource.TrySetResult(true); + } + else + { + if (self.onCompleted != null) + { + try + { + self.onCompleted(); + } + catch (Exception ex) + { + self.CallTrySetExceptionAfterNotification(ex); + return; + } + } + + self.completionSource.TrySetResult(false); + } + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } + +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Do.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Do.cs.meta new file mode 100644 index 0000000..766bbb5 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Do.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd83c8e12dedf75409b829b93146d130 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ElementAt.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ElementAt.cs new file mode 100644 index 0000000..03450f4 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ElementAt.cs @@ -0,0 +1,58 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ElementAtAsync(this IUniTaskAsyncEnumerable source, int index, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return ElementAt.InvokeAsync(source, index, cancellationToken, false); + } + + public static UniTask ElementAtOrDefaultAsync(this IUniTaskAsyncEnumerable source, int index, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return ElementAt.InvokeAsync(source, index, cancellationToken, true); + } + } + + internal static class ElementAt + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, int index, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int i = 0; + while (await e.MoveNextAsync()) + { + if (i++ == index) + { + return e.Current; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.ArgumentOutOfRange(nameof(index)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ElementAt.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ElementAt.cs.meta new file mode 100644 index 0000000..fb0850b --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ElementAt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c835bd2dd8555234c8919c7b8ef3b69a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Empty.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Empty.cs new file mode 100644 index 0000000..2b4adea --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Empty.cs @@ -0,0 +1,47 @@ +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Empty() + { + return Cysharp.Threading.Tasks.Linq.Empty.Instance; + } + } + + internal class Empty : IUniTaskAsyncEnumerable + { + public static readonly IUniTaskAsyncEnumerable Instance = new Empty(); + + Empty() + { + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return Enumerator.Instance; + } + + class Enumerator : IUniTaskAsyncEnumerator + { + public static readonly IUniTaskAsyncEnumerator Instance = new Enumerator(); + + Enumerator() + { + } + + public T Current => default; + + public UniTask MoveNextAsync() + { + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Empty.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Empty.cs.meta new file mode 100644 index 0000000..bfa577a --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Empty.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fa123ad6258abb4184721b719a13810 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Except.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Except.cs new file mode 100644 index 0000000..28e565a --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Except.cs @@ -0,0 +1,116 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Except(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Except(first, second, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Except(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Except(first, second, comparer); + } + } + + internal sealed class Except : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly IEqualityComparer comparer; + + public Except(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + this.first = first; + this.second = second; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(first, second, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + static Action HashSetAsyncCoreDelegate = HashSetAsyncCore; + + readonly IEqualityComparer comparer; + readonly IUniTaskAsyncEnumerable second; + + HashSet set; + UniTask>.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(first, cancellationToken) + { + this.second = second; + this.comparer = comparer; + } + + protected override bool OnFirstIteration() + { + if (set != null) return false; + + awaiter = second.ToHashSetAsync(cancellationToken).GetAwaiter(); + if (awaiter.IsCompleted) + { + set = awaiter.GetResult(); + SourceMoveNext(); + } + else + { + awaiter.SourceOnCompleted(HashSetAsyncCoreDelegate, this); + } + + return true; + } + + static void HashSetAsyncCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.set = result; + self.SourceMoveNext(); + } + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + if (set.Add(v)) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Except.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Except.cs.meta new file mode 100644 index 0000000..f61a1aa --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Except.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38c1c4129f59dcb49a5b864eaf4ec63c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/First.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/First.cs new file mode 100644 index 0000000..9cbb2e0 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/First.cs @@ -0,0 +1,200 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask FirstAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return First.InvokeAsync(source, cancellationToken, false); + } + + public static UniTask FirstAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask FirstAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask FirstAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask FirstOrDefaultAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return First.InvokeAsync(source, cancellationToken, true); + } + + public static UniTask FirstOrDefaultAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.InvokeAsync(source, predicate, cancellationToken, true); + } + + public static UniTask FirstOrDefaultAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.InvokeAsync(source, predicate, cancellationToken, true); + } + + public static UniTask FirstOrDefaultAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return First.InvokeAsync(source, predicate, cancellationToken, true); + } + } + + internal static class First + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + if (await e.MoveNextAsync()) + { + return e.Current; + } + else + { + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (predicate(v)) + { + return v; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v)) + { + return v; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v, cancellationToken)) + { + return v; + } + } + + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/First.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/First.cs.meta new file mode 100644 index 0000000..6924307 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/First.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 417946e97e9eed84db6f840f57037ca6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ForEach.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ForEach.cs new file mode 100644 index 0000000..600426c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ForEach.cs @@ -0,0 +1,177 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ForEachAsync(this IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.InvokeAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAsync(this IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.InvokeAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.InvokeAwaitAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.InvokeAwaitAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.InvokeAwaitWithCancellationAsync(source, action, cancellationToken); + } + + public static UniTask ForEachAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(action, nameof(action)); + + return Cysharp.Threading.Tasks.Linq.ForEach.InvokeAwaitWithCancellationAsync(source, action, cancellationToken); + } + } + + internal static class ForEach + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + action(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Action action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int index = 0; + while (await e.MoveNextAsync()) + { + action(e.Current, checked(index++)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAwaitAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + await action(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAwaitAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int index = 0; + while (await e.MoveNextAsync()) + { + await action(e.Current, checked(index++)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + await action(e.Current, cancellationToken); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAwaitWithCancellationAsync(IUniTaskAsyncEnumerable source, Func action, CancellationToken cancellationToken) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + int index = 0; + while (await e.MoveNextAsync()) + { + await action(e.Current, checked(index++), cancellationToken); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ForEach.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ForEach.cs.meta new file mode 100644 index 0000000..5317756 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ForEach.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca8d7f8177ba16140920af405aea3fd4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/GroupBy.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupBy.cs new file mode 100644 index 0000000..d3fb03c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupBy.cs @@ -0,0 +1,911 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + // Ix-Async returns IGrouping but it is competely waste, use standard IGrouping. + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + return new GroupBy(source, keySelector, x => x, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, x => x, comparer); + } + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + return new GroupBy(source, keySelector, elementSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, elementSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func, TResult> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupBy(source, keySelector, x => x, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, x => x, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupBy(source, keySelector, elementSelector, resultSelector, EqualityComparer.Default); + } + public static IUniTaskAsyncEnumerable GroupBy(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupBy(source, keySelector, elementSelector, resultSelector, comparer); + } + + // await + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), comparer); + } + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + return new GroupByAwait(source, keySelector, elementSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, elementSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwait(source, keySelector, elementSelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, x => UniTask.FromResult(x), resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwait(source, keySelector, elementSelector, resultSelector, comparer); + } + + // with ct + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), comparer); + } + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable> GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, CancellationToken, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, (x, _) => UniTask.FromResult(x), resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + return new GroupByAwaitWithCancellation(source, keySelector, elementSelector, resultSelector, comparer); + } + } + + internal sealed class GroupBy : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly IEqualityComparer comparer; + + public GroupBy(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, elementSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public Enumerator(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public IGrouping Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + Current = groupEnumerator.Current as IGrouping; + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupBy : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + + public GroupBy(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, elementSelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + readonly Func keySelector; + readonly Func elementSelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public Enumerator(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + var current = groupEnumerator.Current; + Current = resultSelector(current.Key, current); + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwait : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + + public GroupByAwait(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, elementSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public IGrouping Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + Current = groupEnumerator.Current as IGrouping; + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupByAwait(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, elementSelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + UniTask.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + var current = groupEnumerator.Current; + + awaiter = resultSelector(current.Key, current).GetAwaiter(); + if (awaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + awaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + static void ResultSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwaitWithCancellation : IUniTaskAsyncEnumerable> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + + public GroupByAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, elementSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator> + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public IGrouping Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitWithCancellationAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + Current = groupEnumerator.Current as IGrouping; + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + public UniTask DisposeAsync() + { + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } + + internal sealed class GroupByAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupByAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, keySelector, elementSelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable source; + readonly Func> keySelector; + readonly Func> elementSelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + IEnumerator> groupEnumerator; + UniTask.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (groupEnumerator == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + var lookup = await source.ToLookupAwaitWithCancellationAsync(keySelector, elementSelector, comparer, cancellationToken); + groupEnumerator = lookup.GetEnumerator(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + if (groupEnumerator.MoveNext()) + { + var current = groupEnumerator.Current; + + awaiter = resultSelector(current.Key, current, cancellationToken).GetAwaiter(); + if (awaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + awaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + completionSource.TrySetResult(false); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + } + + static void ResultSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + if (groupEnumerator != null) + { + groupEnumerator.Dispose(); + } + + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/GroupBy.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupBy.cs.meta new file mode 100644 index 0000000..1489701 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupBy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2de80df1cc8a1240ab0ee7badd334d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/GroupJoin.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupJoin.cs new file mode 100644 index 0000000..1978ac2 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupJoin.cs @@ -0,0 +1,606 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable GroupJoin(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupJoin(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new GroupJoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new GroupJoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new GroupJoinWithCancellationAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable GroupJoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new GroupJoinWithCancellationAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + } + + internal sealed class GroupJoin : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + + public GroupJoin(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func, TResult> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + + + public Enumerator(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func, TResult> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + lookup = await inner.ToLookupAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + var outer = self.enumerator.Current; + var key = self.outerKeySelector(outer); + var values = self.lookup[key]; + + self.Current = self.resultSelector(outer, values); + self.completionSource.TrySetResult(true); + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class GroupJoinAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupJoinAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + readonly static Action OuterKeySelectCoreDelegate = OuterKeySelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + TOuter outerValue; + UniTask.Awaiter awaiter; + UniTask.Awaiter outerKeyAwaiter; + UniTask.Awaiter resultAwaiter; + + + public Enumerator(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + lookup = await inner.ToLookupAwaitAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + try + { + + self.outerValue = self.enumerator.Current; + self.outerKeyAwaiter = self.outerKeySelector(self.outerValue).GetAwaiter(); + if (self.outerKeyAwaiter.IsCompleted) + { + OuterKeySelectCore(self); + } + else + { + self.outerKeyAwaiter.SourceOnCompleted(OuterKeySelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void OuterKeySelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var result)) + { + try + { + var values = self.lookup[result]; + self.resultAwaiter = self.resultSelector(self.outerValue, values).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultSelectCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + } + + static void ResultSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class GroupJoinWithCancellationAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + + public GroupJoinWithCancellationAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + readonly static Action ResultSelectCoreDelegate = ResultSelectCore; + readonly static Action OuterKeySelectCoreDelegate = OuterKeySelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func, CancellationToken, UniTask> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + TOuter outerValue; + UniTask.Awaiter awaiter; + UniTask.Awaiter outerKeyAwaiter; + UniTask.Awaiter resultAwaiter; + + + public Enumerator(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func, CancellationToken, UniTask> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateLookup().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateLookup() + { + try + { + lookup = await inner.ToLookupAwaitWithCancellationAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + MoveNextCore(this); + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + try + { + + self.outerValue = self.enumerator.Current; + self.outerKeyAwaiter = self.outerKeySelector(self.outerValue, self.cancellationToken).GetAwaiter(); + if (self.outerKeyAwaiter.IsCompleted) + { + OuterKeySelectCore(self); + } + else + { + self.outerKeyAwaiter.SourceOnCompleted(OuterKeySelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void OuterKeySelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var result)) + { + try + { + var values = self.lookup[result]; + self.resultAwaiter = self.resultSelector(self.outerValue, values, self.cancellationToken).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultSelectCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + } + + static void ResultSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/GroupJoin.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupJoin.cs.meta new file mode 100644 index 0000000..f171ed1 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/GroupJoin.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7bf7759d03bf3f64190d3ae83b182c2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Intersect.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Intersect.cs new file mode 100644 index 0000000..897caa1 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Intersect.cs @@ -0,0 +1,117 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Intersect(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return new Intersect(first, second, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Intersect(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Intersect(first, second, comparer); + } + } + + internal sealed class Intersect : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly IEqualityComparer comparer; + + public Intersect(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + this.first = first; + this.second = second; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(first, second, comparer, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + static Action HashSetAsyncCoreDelegate = HashSetAsyncCore; + + readonly IEqualityComparer comparer; + readonly IUniTaskAsyncEnumerable second; + + HashSet set; + UniTask>.Awaiter awaiter; + + public Enumerator(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken) + + : base(first, cancellationToken) + { + this.second = second; + this.comparer = comparer; + } + + protected override bool OnFirstIteration() + { + if (set != null) return false; + + awaiter = second.ToHashSetAsync(cancellationToken).GetAwaiter(); + if (awaiter.IsCompleted) + { + set = awaiter.GetResult(); + SourceMoveNext(); + } + else + { + awaiter.SourceOnCompleted(HashSetAsyncCoreDelegate, this); + } + + return true; + } + + static void HashSetAsyncCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + self.set = result; + self.SourceMoveNext(); + } + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + var v = SourceCurrent; + + if (set.Remove(v)) + { + Current = v; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Intersect.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Intersect.cs.meta new file mode 100644 index 0000000..28cf8e3 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Intersect.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93999a70f5d57134bbe971f3e988c4f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Join.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Join.cs new file mode 100644 index 0000000..bfdf779 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Join.cs @@ -0,0 +1,722 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Join(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Join(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new Join(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable JoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new JoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable JoinAwait(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new JoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + + public static IUniTaskAsyncEnumerable JoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new JoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable JoinAwaitWithCancellation(this IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(outer, nameof(outer)); + Error.ThrowArgumentNullException(inner, nameof(inner)); + Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); + Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new JoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); + } + } + + internal sealed class Join : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func resultSelector; + readonly IEqualityComparer comparer; + + public Join(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func outerKeySelector; + readonly Func innerKeySelector; + readonly Func resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + TOuter currentOuterValue; + IEnumerator valueEnumerator; + + bool continueNext; + + public Enumerator(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateInnerHashSet().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateInnerHashSet() + { + try + { + lookup = await inner.ToLookupAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + LOOP: + if (valueEnumerator != null) + { + if (valueEnumerator.MoveNext()) + { + Current = resultSelector(currentOuterValue, valueEnumerator.Current); + goto TRY_SET_RESULT_TRUE; + } + else + { + valueEnumerator.Dispose(); + valueEnumerator = null; + } + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + + return; + + TRY_SET_RESULT_TRUE: + completionSource.TrySetResult(true); + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.currentOuterValue = self.enumerator.Current; + var key = self.outerKeySelector(self.currentOuterValue); + self.valueEnumerator = self.lookup[key].GetEnumerator(); + + if (self.continueNext) + { + return; + } + else + { + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + if (valueEnumerator != null) + { + valueEnumerator.Dispose(); + } + + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class JoinAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + + public JoinAwait(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + static readonly Action OuterSelectCoreDelegate = OuterSelectCore; + static readonly Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + TOuter currentOuterValue; + IEnumerator valueEnumerator; + + UniTask.Awaiter resultAwaiter; + UniTask.Awaiter outerKeyAwaiter; + + bool continueNext; + + public Enumerator(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateInnerHashSet().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateInnerHashSet() + { + try + { + lookup = await inner.ToLookupAwaitAsync(innerKeySelector, comparer, cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + LOOP: + if (valueEnumerator != null) + { + if (valueEnumerator.MoveNext()) + { + resultAwaiter = resultSelector(currentOuterValue, valueEnumerator.Current).GetAwaiter(); + if (resultAwaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + valueEnumerator.Dispose(); + valueEnumerator = null; + } + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.currentOuterValue = self.enumerator.Current; + + self.outerKeyAwaiter = self.outerKeySelector(self.currentOuterValue).GetAwaiter(); + + if (self.outerKeyAwaiter.IsCompleted) + { + OuterSelectCore(self); + } + else + { + self.continueNext = false; + self.outerKeyAwaiter.SourceOnCompleted(OuterSelectCoreDelegate, self); + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + static void OuterSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var key)) + { + self.valueEnumerator = self.lookup[key].GetEnumerator(); + + if (self.continueNext) + { + return; + } + else + { + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + static void ResultSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + if (valueEnumerator != null) + { + valueEnumerator.Dispose(); + } + + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + + internal sealed class JoinAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + + public JoinAwaitWithCancellation(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + static readonly Action OuterSelectCoreDelegate = OuterSelectCore; + static readonly Action ResultSelectCoreDelegate = ResultSelectCore; + + readonly IUniTaskAsyncEnumerable outer; + readonly IUniTaskAsyncEnumerable inner; + readonly Func> outerKeySelector; + readonly Func> innerKeySelector; + readonly Func> resultSelector; + readonly IEqualityComparer comparer; + CancellationToken cancellationToken; + + ILookup lookup; + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + TOuter currentOuterValue; + IEnumerator valueEnumerator; + + UniTask.Awaiter resultAwaiter; + UniTask.Awaiter outerKeyAwaiter; + + bool continueNext; + + public Enumerator(IUniTaskAsyncEnumerable outer, IUniTaskAsyncEnumerable inner, Func> outerKeySelector, Func> innerKeySelector, Func> resultSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + this.outer = outer; + this.inner = inner; + this.outerKeySelector = outerKeySelector; + this.innerKeySelector = innerKeySelector; + this.resultSelector = resultSelector; + this.comparer = comparer; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + completionSource.Reset(); + + if (lookup == null) + { + CreateInnerHashSet().Forget(); + } + else + { + SourceMoveNext(); + } + return new UniTask(this, completionSource.Version); + } + + async UniTaskVoid CreateInnerHashSet() + { + try + { + lookup = await inner.ToLookupAwaitWithCancellationAsync(innerKeySelector, comparer, cancellationToken: cancellationToken); + enumerator = outer.GetAsyncEnumerator(cancellationToken); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + SourceMoveNext(); + } + + void SourceMoveNext() + { + try + { + LOOP: + if (valueEnumerator != null) + { + if (valueEnumerator.MoveNext()) + { + resultAwaiter = resultSelector(currentOuterValue, valueEnumerator.Current, cancellationToken).GetAwaiter(); + if (resultAwaiter.IsCompleted) + { + ResultSelectCore(this); + } + else + { + resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, this); + } + return; + } + else + { + valueEnumerator.Dispose(); + valueEnumerator = null; + } + } + + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + self.currentOuterValue = self.enumerator.Current; + + self.outerKeyAwaiter = self.outerKeySelector(self.currentOuterValue, self.cancellationToken).GetAwaiter(); + + if (self.outerKeyAwaiter.IsCompleted) + { + OuterSelectCore(self); + } + else + { + self.continueNext = false; + self.outerKeyAwaiter.SourceOnCompleted(OuterSelectCoreDelegate, self); + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + static void OuterSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.outerKeyAwaiter, out var key)) + { + self.valueEnumerator = self.lookup[key].GetEnumerator(); + + if (self.continueNext) + { + return; + } + else + { + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + static void ResultSelectCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public UniTask DisposeAsync() + { + if (valueEnumerator != null) + { + valueEnumerator.Dispose(); + } + + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + + return default; + } + } + } + +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Join.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Join.cs.meta new file mode 100644 index 0000000..3ab1015 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Join.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc4ff8cb6d7c9a64896f2f082124d6b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Last.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Last.cs new file mode 100644 index 0000000..430aedb --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Last.cs @@ -0,0 +1,240 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask LastAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Last.InvokeAsync(source, cancellationToken, false); + } + + public static UniTask LastAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask LastAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask LastAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask LastOrDefaultAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Last.InvokeAsync(source, cancellationToken, true); + } + + public static UniTask LastOrDefaultAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.InvokeAsync(source, predicate, cancellationToken, true); + } + + public static UniTask LastOrDefaultAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.InvokeAsync(source, predicate, cancellationToken, true); + } + + public static UniTask LastOrDefaultAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return Last.InvokeAsync(source, predicate, cancellationToken, true); + } + } + + internal static class Last + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + if (await e.MoveNextAsync()) + { + value = e.Current; + } + else + { + if (defaultIfEmpty) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + + while (await e.MoveNextAsync()) + { + value = e.Current; + } + return value; + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (predicate(v)) + { + found = true; + value = v; + } + } + + if (defaultIfEmpty) + { + return value; + } + else + { + if (found) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v)) + { + found = true; + value = v; + } + } + + if (defaultIfEmpty) + { + return value; + } + else + { + if (found) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v, cancellationToken)) + { + found = true; + value = v; + } + } + + if (defaultIfEmpty) + { + return value; + } + else + { + if (found) + { + return value; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Last.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Last.cs.meta new file mode 100644 index 0000000..edfa124 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Last.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0ccc93be1387fa4a975f06310127c11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/LongCount.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/LongCount.cs new file mode 100644 index 0000000..4460061 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/LongCount.cs @@ -0,0 +1,144 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask LongCountAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return LongCount.InvokeAsync(source, cancellationToken); + } + + public static UniTask LongCountAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return LongCount.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask LongCountAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return LongCount.InvokeAsync(source, predicate, cancellationToken); + } + + public static UniTask LongCountAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return LongCount.InvokeAsync(source, predicate, cancellationToken); + } + } + + internal static class LongCount + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + checked { count++; } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + { + long count = 0; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + if (await predicate(e.Current, cancellationToken)) + { + checked { count++; } + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return count; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/LongCount.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/LongCount.cs.meta new file mode 100644 index 0000000..862c2bc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/LongCount.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 198b39e58ced3ab4f97ccbe0916787d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Max.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Max.cs new file mode 100644 index 0000000..703226d --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Max.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + } + + internal static partial class Max + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + TSource value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (comparer.Compare(value, x) < 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Max.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Max.cs.meta new file mode 100644 index 0000000..2125edf --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Max.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c8a118a6b664c441820b8a87d7f6e28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Min.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Min.cs new file mode 100644 index 0000000..c54aaf9 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Min.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + } + + internal static partial class Min + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + TSource value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + TResult value = default; + var comparer = Comparer.Default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + return value; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (comparer.Compare(value, x) > 0) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Min.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Min.cs.meta new file mode 100644 index 0000000..91378dc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Min.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57ac9da21d3457849a8e45548290a508 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.cs new file mode 100644 index 0000000..61f4c7f --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.cs @@ -0,0 +1,3763 @@ +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Min.InvokeAsync(source, cancellationToken); + } + + public static UniTask MinAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MinAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Min.InvokeAsync(source, selector, cancellationToken); + } + + } + + internal static partial class Min + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value > x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + } + + public static partial class UniTaskAsyncEnumerable + { + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Max.InvokeAsync(source, cancellationToken); + } + + public static UniTask MaxAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask MaxAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Max.InvokeAsync(source, selector, cancellationToken); + } + + } + + internal static partial class Max + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + + goto NEXT_LOOP; + } + + throw Error.NoElements(); + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); + if(value == null) continue; + + goto NEXT_LOOP; + } + + return default; + + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); + if( x == null) continue; + if (value < x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + } + +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.cs.meta new file mode 100644 index 0000000..3856b65 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d6da02d9ab970e4999daf7147d98e36 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.tt b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.tt new file mode 100644 index 0000000..ef4f0f8 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.tt @@ -0,0 +1,262 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".cs" #> +<# + var types = new[] + { + typeof(int), + typeof(long), + typeof(float), + typeof(double), + typeof(decimal), + + typeof(int?), + typeof(long?), + typeof(float?), + typeof(double?), + typeof(decimal?), + }; + + Func IsNullable = x => x.IsGenericType; + Func TypeName = x => IsNullable(x) ? x.GetGenericArguments()[0].Name + "?" : x.Name; + Func WithSuffix = x => IsNullable(x) ? ".GetValueOrDefault()" : ""; +#> +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ +<# foreach(var (minMax, op) in new[]{("Min",">"), ("Max", "<")}) { #> + public static partial class UniTaskAsyncEnumerable + { +<# foreach(var t in types) { #> + public static UniTask<<#= TypeName(t) #>> <#= minMax #>Async(this IUniTaskAsyncEnumerable<<#= TypeName(t) #>> source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return <#= minMax #>.InvokeAsync(source, cancellationToken); + } + + public static UniTask<<#= TypeName(t) #>> <#= minMax #>Async(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return <#= minMax #>.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask<<#= TypeName(t) #>> <#= minMax #>AwaitAsync(this IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return <#= minMax #>.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask<<#= TypeName(t) #>> <#= minMax #>AwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return <#= minMax #>.InvokeAsync(source, selector, cancellationToken); + } + +<# } #> + } + + internal static partial class <#= minMax #> + { +<# foreach(var t in types) { #> + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable<<#= TypeName(t) #>> source, CancellationToken cancellationToken) + { + <#= TypeName(t) #> value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = e.Current; +<# if (IsNullable(t)) { #> + if(value == null) continue; +<# } #> + goto NEXT_LOOP; + } + +<# if (IsNullable(t)) { #> + return default; +<# } else { #> + throw Error.NoElements(); +<# } #> + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = e.Current; +<# if (IsNullable(t)) { #> + if( x == null) continue; +<# } #> + if (value <#= op #> x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + <#= TypeName(t) #> value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = selector(e.Current); +<# if (IsNullable(t)) { #> + if(value == null) continue; +<# } #> + goto NEXT_LOOP; + } + +<# if (IsNullable(t)) { #> + return default; +<# } else { #> + throw Error.NoElements(); +<# } #> + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = selector(e.Current); +<# if (IsNullable(t)) { #> + if( x == null) continue; +<# } #> + if (value <#= op #> x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken) + { + <#= TypeName(t) #> value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current); +<# if (IsNullable(t)) { #> + if(value == null) continue; +<# } #> + goto NEXT_LOOP; + } + +<# if (IsNullable(t)) { #> + return default; +<# } else { #> + throw Error.NoElements(); +<# } #> + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current); +<# if (IsNullable(t)) { #> + if( x == null) continue; +<# } #> + if (value <#= op #> x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken) + { + <#= TypeName(t) #> value = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + value = await selector(e.Current, cancellationToken); +<# if (IsNullable(t)) { #> + if(value == null) continue; +<# } #> + goto NEXT_LOOP; + } + +<# if (IsNullable(t)) { #> + return default; +<# } else { #> + throw Error.NoElements(); +<# } #> + NEXT_LOOP: + + while (await e.MoveNextAsync()) + { + var x = await selector(e.Current, cancellationToken); +<# if (IsNullable(t)) { #> + if( x == null) continue; +<# } #> + if (value <#= op #> x) + { + value = x; + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return value; + } + +<# } #> + } + +<# } #> +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.tt.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.tt.meta new file mode 100644 index 0000000..f77d718 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/MinMax.tt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 18108e9feb2ec40498df573cfef2ea15 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Never.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Never.cs new file mode 100644 index 0000000..a735812 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Never.cs @@ -0,0 +1,56 @@ +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Never() + { + return Cysharp.Threading.Tasks.Linq.Never.Instance; + } + } + + internal class Never : IUniTaskAsyncEnumerable + { + public static readonly IUniTaskAsyncEnumerable Instance = new Never(); + + Never() + { + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + CancellationToken cancellationToken; + + public Enumerator(CancellationToken cancellationToken) + { + this.cancellationToken = cancellationToken; + } + + public T Current => default; + + public UniTask MoveNextAsync() + { + var tcs = new UniTaskCompletionSource(); + + cancellationToken.Register(state => + { + var task = (UniTaskCompletionSource)state; + task.TrySetCanceled(cancellationToken); + }, tcs); + + return tcs.Task; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Never.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Never.cs.meta new file mode 100644 index 0000000..ba9d358 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Never.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b307c3d3be71a94da251564bcdefa3d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/OfType.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/OfType.cs new file mode 100644 index 0000000..213cc98 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/OfType.cs @@ -0,0 +1,61 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable OfType(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new OfType(source); + } + } + + internal sealed class OfType : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public OfType(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + public Enumerator(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (SourceCurrent is TResult castCurent) + { + Current = castCurent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/OfType.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/OfType.cs.meta new file mode 100644 index 0000000..6ace53f --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/OfType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 111ffe87a7d700442a9ef5af554b252c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/OrderBy.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/OrderBy.cs new file mode 100644 index 0000000..740c0e2 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/OrderBy.cs @@ -0,0 +1,556 @@ +using Cysharp.Threading.Tasks; +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + #region OrderBy_OrderByDescending + + public static IUniTaskOrderedAsyncEnumerable OrderBy(this IUniTaskAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerable(source, keySelector, Comparer.Default, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderBy(this IUniTaskAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerable(source, keySelector, comparer, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, Comparer.Default, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, comparer, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, Comparer.Default, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, comparer, false, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescending(this IUniTaskAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerable(source, keySelector, Comparer.Default, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescending(this IUniTaskAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerable(source, keySelector, comparer, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwait(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, Comparer.Default, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwait(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwait(source, keySelector, comparer, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, Comparer.Default, true, null); + } + + public static IUniTaskOrderedAsyncEnumerable OrderByDescendingAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, comparer, true, null); + } + + #endregion + + #region ThenBy_ThenByDescending + + public static IUniTaskOrderedAsyncEnumerable ThenBy(this IUniTaskOrderedAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenBy(this IUniTaskOrderedAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, false); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescending(this IUniTaskOrderedAsyncEnumerable source, Func keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescending(this IUniTaskOrderedAsyncEnumerable source, Func keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwait(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return source.CreateOrderedEnumerable(keySelector, Comparer.Default, true); + } + + public static IUniTaskOrderedAsyncEnumerable ThenByDescendingAwaitWithCancellation(this IUniTaskOrderedAsyncEnumerable source, Func> keySelector, IComparer comparer) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return source.CreateOrderedEnumerable(keySelector, comparer, true); + } + + #endregion + } + + internal abstract class AsyncEnumerableSorter + { + internal abstract UniTask ComputeKeysAsync(TElement[] elements, int count); + + internal abstract int CompareKeys(int index1, int index2); + + internal async UniTask SortAsync(TElement[] elements, int count) + { + await ComputeKeysAsync(elements, count); + + int[] map = new int[count]; + for (int i = 0; i < count; i++) map[i] = i; + QuickSort(map, 0, count - 1); + return map; + } + + void QuickSort(int[] map, int left, int right) + { + do + { + int i = left; + int j = right; + int x = map[i + ((j - i) >> 1)]; + do + { + while (i < map.Length && CompareKeys(x, map[i]) > 0) i++; + while (j >= 0 && CompareKeys(x, map[j]) < 0) j--; + if (i > j) break; + if (i < j) + { + int temp = map[i]; + map[i] = map[j]; + map[j] = temp; + } + i++; + j--; + } while (i <= j); + if (j - left <= right - i) + { + if (left < j) QuickSort(map, left, j); + left = i; + } + else + { + if (i < right) QuickSort(map, i, right); + right = j; + } + } while (left < right); + } + } + + internal class SyncSelectorAsyncEnumerableSorter : AsyncEnumerableSorter + { + readonly Func keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly AsyncEnumerableSorter next; + TKey[] keys; + + internal SyncSelectorAsyncEnumerableSorter(Func keySelector, IComparer comparer, bool descending, AsyncEnumerableSorter next) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.next = next; + } + + internal override async UniTask ComputeKeysAsync(TElement[] elements, int count) + { + keys = new TKey[count]; + for (int i = 0; i < count; i++) keys[i] = keySelector(elements[i]); + if (next != null) await next.ComputeKeysAsync(elements, count); + } + + internal override int CompareKeys(int index1, int index2) + { + int c = comparer.Compare(keys[index1], keys[index2]); + if (c == 0) + { + if (next == null) return index1 - index2; + return next.CompareKeys(index1, index2); + } + return descending ? -c : c; + } + } + + internal class AsyncSelectorEnumerableSorter : AsyncEnumerableSorter + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly AsyncEnumerableSorter next; + TKey[] keys; + + internal AsyncSelectorEnumerableSorter(Func> keySelector, IComparer comparer, bool descending, AsyncEnumerableSorter next) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.next = next; + } + + internal override async UniTask ComputeKeysAsync(TElement[] elements, int count) + { + keys = new TKey[count]; + for (int i = 0; i < count; i++) keys[i] = await keySelector(elements[i]); + if (next != null) await next.ComputeKeysAsync(elements, count); + } + + internal override int CompareKeys(int index1, int index2) + { + int c = comparer.Compare(keys[index1], keys[index2]); + if (c == 0) + { + if (next == null) return index1 - index2; + return next.CompareKeys(index1, index2); + } + return descending ? -c : c; + } + } + + internal class AsyncSelectorWithCancellationEnumerableSorter : AsyncEnumerableSorter + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly AsyncEnumerableSorter next; + CancellationToken cancellationToken; + TKey[] keys; + + internal AsyncSelectorWithCancellationEnumerableSorter(Func> keySelector, IComparer comparer, bool descending, AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.next = next; + this.cancellationToken = cancellationToken; + } + + internal override async UniTask ComputeKeysAsync(TElement[] elements, int count) + { + keys = new TKey[count]; + for (int i = 0; i < count; i++) keys[i] = await keySelector(elements[i], cancellationToken); + if (next != null) await next.ComputeKeysAsync(elements, count); + } + + internal override int CompareKeys(int index1, int index2) + { + int c = comparer.Compare(keys[index1], keys[index2]); + if (c == 0) + { + if (next == null) return index1 - index2; + return next.CompareKeys(index1, index2); + } + return descending ? -c : c; + } + } + + internal abstract class OrderedAsyncEnumerable : IUniTaskOrderedAsyncEnumerable + { + protected readonly IUniTaskAsyncEnumerable source; + + public OrderedAsyncEnumerable(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func keySelector, IComparer comparer, bool descending) + { + return new OrderedAsyncEnumerable(source, keySelector, comparer, descending, this); + } + + public IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending) + { + return new OrderedAsyncEnumerableAwait(source, keySelector, comparer, descending, this); + } + + public IUniTaskOrderedAsyncEnumerable CreateOrderedEnumerable(Func> keySelector, IComparer comparer, bool descending) + { + return new OrderedAsyncEnumerableAwaitWithCancellation(source, keySelector, comparer, descending, this); + } + + internal abstract AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken); + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(this, cancellationToken); + } + + class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + protected readonly OrderedAsyncEnumerable parent; + CancellationToken cancellationToken; + TElement[] buffer; + int[] map; + int index; + + public Enumerator(OrderedAsyncEnumerable parent, CancellationToken cancellationToken) + { + this.parent = parent; + this.cancellationToken = cancellationToken; + } + + public TElement Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (map == null) + { + completionSource.Reset(); + CreateSortSource().Forget(); + return new UniTask(this, completionSource.Version); + } + + if (index < buffer.Length) + { + Current = buffer[map[index++]]; + return CompletedTasks.True; + } + else + { + return CompletedTasks.False; + } + } + + async UniTaskVoid CreateSortSource() + { + try + { + buffer = await parent.source.ToArrayAsync(); + if (buffer.Length == 0) + { + completionSource.TrySetResult(false); + return; + } + + var sorter = parent.GetAsyncEnumerableSorter(null, cancellationToken); + map = await sorter.SortAsync(buffer, buffer.Length); + sorter = null; + + // set first value + Current = buffer[map[index++]]; + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + completionSource.TrySetResult(true); + } + + public UniTask DisposeAsync() + { + return default; + } + } + } + + internal class OrderedAsyncEnumerable : OrderedAsyncEnumerable + { + readonly Func keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly OrderedAsyncEnumerable parent; + + public OrderedAsyncEnumerable(IUniTaskAsyncEnumerable source, Func keySelector, IComparer comparer, bool descending, OrderedAsyncEnumerable parent) + : base(source) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.parent = parent; + } + + internal override AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + AsyncEnumerableSorter sorter = new SyncSelectorAsyncEnumerableSorter(keySelector, comparer, descending, next); + if (parent != null) sorter = parent.GetAsyncEnumerableSorter(sorter, cancellationToken); + return sorter; + } + } + + internal class OrderedAsyncEnumerableAwait : OrderedAsyncEnumerable + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly OrderedAsyncEnumerable parent; + + public OrderedAsyncEnumerableAwait(IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer, bool descending, OrderedAsyncEnumerable parent) + : base(source) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.parent = parent; + } + + internal override AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + AsyncEnumerableSorter sorter = new AsyncSelectorEnumerableSorter(keySelector, comparer, descending, next); + if (parent != null) sorter = parent.GetAsyncEnumerableSorter(sorter, cancellationToken); + return sorter; + } + } + + internal class OrderedAsyncEnumerableAwaitWithCancellation : OrderedAsyncEnumerable + { + readonly Func> keySelector; + readonly IComparer comparer; + readonly bool descending; + readonly OrderedAsyncEnumerable parent; + + public OrderedAsyncEnumerableAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> keySelector, IComparer comparer, bool descending, OrderedAsyncEnumerable parent) + : base(source) + { + this.keySelector = keySelector; + this.comparer = comparer; + this.descending = descending; + this.parent = parent; + } + + internal override AsyncEnumerableSorter GetAsyncEnumerableSorter(AsyncEnumerableSorter next, CancellationToken cancellationToken) + { + AsyncEnumerableSorter sorter = new AsyncSelectorWithCancellationEnumerableSorter(keySelector, comparer, descending, next, cancellationToken); + if (parent != null) sorter = parent.GetAsyncEnumerableSorter(sorter, cancellationToken); + return sorter; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/OrderBy.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/OrderBy.cs.meta new file mode 100644 index 0000000..5c6b3e4 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/OrderBy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 413883ceff8546143bdf200aafa4b8f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Range.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Range.cs new file mode 100644 index 0000000..09c1f17 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Range.cs @@ -0,0 +1,75 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Range(int start, int count) + { + if (count < 0) throw Error.ArgumentOutOfRange(nameof(count)); + + var end = (long)start + count - 1L; + if (end > int.MaxValue) throw Error.ArgumentOutOfRange(nameof(count)); + + if (count == 0) UniTaskAsyncEnumerable.Empty(); + + return new Cysharp.Threading.Tasks.Linq.Range(start, count); + } + } + + internal class Range : IUniTaskAsyncEnumerable + { + readonly int start; + readonly int end; + + public Range(int start, int count) + { + this.start = start; + this.end = start + count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(start, end, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly int start; + readonly int end; + int current; + CancellationToken cancellationToken; + + public Enumerator(int start, int end, CancellationToken cancellationToken) + { + this.start = start; + this.end = end; + this.cancellationToken = cancellationToken; + + this.current = start - 1; + } + + public int Current => current; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + current++; + + if (current != end) + { + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Range.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Range.cs.meta new file mode 100644 index 0000000..36272fc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Range.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d826418a813498648b10542d0a5fb173 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Repeat.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Repeat.cs new file mode 100644 index 0000000..e74ddc2 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Repeat.cs @@ -0,0 +1,68 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Repeat(TElement element, int count) + { + if (count < 0) throw Error.ArgumentOutOfRange(nameof(count)); + + return new Repeat(element, count); + } + } + + internal class Repeat : IUniTaskAsyncEnumerable + { + readonly TElement element; + readonly int count; + + public Repeat(TElement element, int count) + { + this.element = element; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(element, count, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly TElement element; + readonly int count; + int remaining; + CancellationToken cancellationToken; + + public Enumerator(TElement element, int count, CancellationToken cancellationToken) + { + this.element = element; + this.count = count; + this.cancellationToken = cancellationToken; + + this.remaining = count; + } + + public TElement Current => element; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (remaining-- != 0) + { + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Repeat.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Repeat.cs.meta new file mode 100644 index 0000000..693d579 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Repeat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3819a3925165a674d80ee848c8600379 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Return.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Return.cs new file mode 100644 index 0000000..b5364d4 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Return.cs @@ -0,0 +1,63 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Return(TValue value) + { + return new Return(value); + } + } + + internal class Return : IUniTaskAsyncEnumerable + { + readonly TValue value; + + public Return(TValue value) + { + this.value = value; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(value, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly TValue value; + CancellationToken cancellationToken; + + bool called; + + public Enumerator(TValue value, CancellationToken cancellationToken) + { + this.value = value; + this.cancellationToken = cancellationToken; + this.called = false; + } + + public TValue Current => value; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (!called) + { + called = true; + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Return.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Return.cs.meta new file mode 100644 index 0000000..ad264d0 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Return.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4313cd8ecf705e44f9064ce46e293c2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Reverse.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Reverse.cs new file mode 100644 index 0000000..4a553ca --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Reverse.cs @@ -0,0 +1,76 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Reverse(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + return new Reverse(source); + } + } + + internal sealed class Reverse : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + + public Reverse(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + readonly IUniTaskAsyncEnumerable source; + CancellationToken cancellationToken; + + TSource[] array; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public TSource Current { get; private set; } + + // after consumed array, don't use await so allow async(not require UniTaskCompletionSourceCore). + public async UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (array == null) + { + array = await source.ToArrayAsync(cancellationToken); + index = array.Length - 1; + } + + if (index != -1) + { + Current = array[index]; + --index; + return true; + } + else + { + return false; + } + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Reverse.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Reverse.cs.meta new file mode 100644 index 0000000..4a28306 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Reverse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2769e65c729b4f4ca6af9826d9c7b90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Select.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Select.cs new file mode 100644 index 0000000..d541fda --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Select.cs @@ -0,0 +1,307 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Select(this IUniTaskAsyncEnumerable source, Func selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.Select(source, selector); + } + + public static IUniTaskAsyncEnumerable Select(this IUniTaskAsyncEnumerable source, Func selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectInt(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwait(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectAwait(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwait(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectAwaitInt(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectAwaitCancellation(source, selector); + } + + public static IUniTaskAsyncEnumerable SelectAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new Cysharp.Threading.Tasks.Linq.SelectAwaitIntCancellation(source, selector); + } + } + + internal sealed class Select : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func selector; + + public Select(IUniTaskAsyncEnumerable source, Func selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorBase + { + readonly Func selector; + + public Enumerator(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.selector = selector; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + Current = selector(SourceCurrent); + result = true; + return true; + } + else + { + result = false; + return true; + } + } + } + } + + internal sealed class SelectInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func selector; + + public SelectInt(IUniTaskAsyncEnumerable source, Func selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorBase + { + readonly Func selector; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.selector = selector; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + Current = selector(SourceCurrent, checked(index++)); + result = true; + return true; + } + else + { + result = false; + return true; + } + } + } + } + + internal sealed class SelectAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectAwait(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> selector; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.selector = selector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return selector(sourceCurrent); + } + + protected override bool TrySetCurrentCore(TResult awaitResult, out bool terminateIteration) + { + Current = awaitResult; + terminateIteration= false; + return true; + } + } + } + + internal sealed class SelectAwaitInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectAwaitInt(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> selector; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.selector = selector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return selector(sourceCurrent, checked(index++)); + } + + protected override bool TrySetCurrentCore(TResult awaitResult, out bool terminateIteration) + { + Current = awaitResult; + terminateIteration= false; + return true; + } + } + } + + internal sealed class SelectAwaitCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectAwaitCancellation(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> selector; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.selector = selector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return selector(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(TResult awaitResult, out bool terminateIteration) + { + Current = awaitResult; + terminateIteration= false; + return true; + } + } + } + + internal sealed class SelectAwaitIntCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector; + + public SelectAwaitIntCancellation(IUniTaskAsyncEnumerable source, Func> selector) + { + this.source = source; + this.selector = selector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> selector; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.selector = selector; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return selector(sourceCurrent, checked(index++), cancellationToken); + } + + protected override bool TrySetCurrentCore(TResult awaitResult, out bool terminateIteration) + { + Current = awaitResult; + terminateIteration= false; + return true; + } + } + } + +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Select.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Select.cs.meta new file mode 100644 index 0000000..476e972 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Select.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc68e598ca44a134b988dfaf5e53bfba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SelectMany.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/SelectMany.cs new file mode 100644 index 0000000..d286441 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SelectMany.cs @@ -0,0 +1,886 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectMany(source, selector, (x, y) => y); + } + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectMany(source, selector, (x, y) => y); + } + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> collectionSelector, Func resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectMany(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectMany(this IUniTaskAsyncEnumerable source, Func> collectionSelector, Func resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectMany(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwait(source, selector, (x, y) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwait(source, selector, (x, y) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwait(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwait(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwait(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwaitWithCancellation(source, selector, (x, y, c) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> selector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new SelectManyAwaitWithCancellation(source, selector, (x, y, c) => UniTask.FromResult(y)); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwaitWithCancellation(source, collectionSelector, resultSelector); + } + + public static IUniTaskAsyncEnumerable SelectManyAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func>> collectionSelector, Func> resultSelector) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(collectionSelector, nameof(collectionSelector)); + + return new SelectManyAwaitWithCancellation(source, collectionSelector, resultSelector); + } + } + + internal sealed class SelectMany : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> selector1; + readonly Func> selector2; + readonly Func resultSelector; + + public SelectMany(IUniTaskAsyncEnumerable source, Func> selector, Func resultSelector) + { + this.source = source; + this.selector1 = selector; + this.selector2 = null; + this.resultSelector = resultSelector; + } + + public SelectMany(IUniTaskAsyncEnumerable source, Func> selector, Func resultSelector) + { + this.source = source; + this.selector1 = null; + this.selector2 = selector; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector1, selector2, resultSelector, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action sourceMoveNextCoreDelegate = SourceMoveNextCore; + static readonly Action selectedSourceMoveNextCoreDelegate = SeletedSourceMoveNextCore; + static readonly Action selectedEnumeratorDisposeAsyncCoreDelegate = SelectedEnumeratorDisposeAsyncCore; + + readonly IUniTaskAsyncEnumerable source; + + readonly Func> selector1; + readonly Func> selector2; + readonly Func resultSelector; + CancellationToken cancellationToken; + + TSource sourceCurrent; + int sourceIndex; + IUniTaskAsyncEnumerator sourceEnumerator; + IUniTaskAsyncEnumerator selectedEnumerator; + UniTask.Awaiter sourceAwaiter; + UniTask.Awaiter selectedAwaiter; + UniTask.Awaiter selectedDisposeAsyncAwaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> selector1, Func> selector2, Func resultSelector, CancellationToken cancellationToken) + { + this.source = source; + this.selector1 = selector1; + this.selector2 = selector2; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + // iterate selected field + if (selectedEnumerator != null) + { + MoveNextSelected(); + } + else + { + // iterate source field + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + } + MoveNextSource(); + } + + return new UniTask(this, completionSource.Version); + } + + void MoveNextSource() + { + try + { + sourceAwaiter = sourceEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (sourceAwaiter.IsCompleted) + { + SourceMoveNextCore(this); + } + else + { + sourceAwaiter.SourceOnCompleted(sourceMoveNextCoreDelegate, this); + } + } + + void MoveNextSelected() + { + try + { + selectedAwaiter = selectedEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (selectedAwaiter.IsCompleted) + { + SeletedSourceMoveNextCore(this); + } + else + { + selectedAwaiter.SourceOnCompleted(selectedSourceMoveNextCoreDelegate, this); + } + } + + static void SourceMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.sourceAwaiter, out var result)) + { + if (result) + { + try + { + self.sourceCurrent = self.sourceEnumerator.Current; + if (self.selector1 != null) + { + self.selectedEnumerator = self.selector1(self.sourceCurrent).GetAsyncEnumerator(self.cancellationToken); + } + else + { + self.selectedEnumerator = self.selector2(self.sourceCurrent, checked(self.sourceIndex++)).GetAsyncEnumerator(self.cancellationToken); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + self.MoveNextSelected(); // iterated selected source. + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SeletedSourceMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.selectedAwaiter, out var result)) + { + if (result) + { + try + { + self.Current = self.resultSelector(self.sourceCurrent, self.selectedEnumerator.Current); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + self.completionSource.TrySetResult(true); + } + else + { + // dispose selected source and try iterate source. + try + { + self.selectedDisposeAsyncAwaiter = self.selectedEnumerator.DisposeAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + if (self.selectedDisposeAsyncAwaiter.IsCompleted) + { + SelectedEnumeratorDisposeAsyncCore(self); + } + else + { + self.selectedDisposeAsyncAwaiter.SourceOnCompleted(selectedEnumeratorDisposeAsyncCoreDelegate, self); + } + } + } + } + + static void SelectedEnumeratorDisposeAsyncCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.selectedDisposeAsyncAwaiter)) + { + self.selectedEnumerator = null; + self.selectedAwaiter = default; + + self.MoveNextSource(); // iterate next source + } + } + + public async UniTask DisposeAsync() + { + if (selectedEnumerator != null) + { + await selectedEnumerator.DisposeAsync(); + } + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class SelectManyAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + + public SelectManyAwait(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = selector; + this.selector2 = null; + this.resultSelector = resultSelector; + } + + public SelectManyAwait(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = null; + this.selector2 = selector; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector1, selector2, resultSelector, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action sourceMoveNextCoreDelegate = SourceMoveNextCore; + static readonly Action selectedSourceMoveNextCoreDelegate = SeletedSourceMoveNextCore; + static readonly Action selectedEnumeratorDisposeAsyncCoreDelegate = SelectedEnumeratorDisposeAsyncCore; + static readonly Action selectorAwaitCoreDelegate = SelectorAwaitCore; + static readonly Action resultSelectorAwaitCoreDelegate = ResultSelectorAwaitCore; + + readonly IUniTaskAsyncEnumerable source; + + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + CancellationToken cancellationToken; + + TSource sourceCurrent; + int sourceIndex; + IUniTaskAsyncEnumerator sourceEnumerator; + IUniTaskAsyncEnumerator selectedEnumerator; + UniTask.Awaiter sourceAwaiter; + UniTask.Awaiter selectedAwaiter; + UniTask.Awaiter selectedDisposeAsyncAwaiter; + + // await additional + UniTask>.Awaiter collectionSelectorAwaiter; + UniTask.Awaiter resultSelectorAwaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, Func>> selector1, Func>> selector2, Func> resultSelector, CancellationToken cancellationToken) + { + this.source = source; + this.selector1 = selector1; + this.selector2 = selector2; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + // iterate selected field + if (selectedEnumerator != null) + { + MoveNextSelected(); + } + else + { + // iterate source field + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + } + MoveNextSource(); + } + + return new UniTask(this, completionSource.Version); + } + + void MoveNextSource() + { + try + { + sourceAwaiter = sourceEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (sourceAwaiter.IsCompleted) + { + SourceMoveNextCore(this); + } + else + { + sourceAwaiter.SourceOnCompleted(sourceMoveNextCoreDelegate, this); + } + } + + void MoveNextSelected() + { + try + { + selectedAwaiter = selectedEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (selectedAwaiter.IsCompleted) + { + SeletedSourceMoveNextCore(this); + } + else + { + selectedAwaiter.SourceOnCompleted(selectedSourceMoveNextCoreDelegate, this); + } + } + + static void SourceMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.sourceAwaiter, out var result)) + { + if (result) + { + try + { + self.sourceCurrent = self.sourceEnumerator.Current; + + if (self.selector1 != null) + { + self.collectionSelectorAwaiter = self.selector1(self.sourceCurrent).GetAwaiter(); + } + else + { + self.collectionSelectorAwaiter = self.selector2(self.sourceCurrent, checked(self.sourceIndex++)).GetAwaiter(); + } + + if (self.collectionSelectorAwaiter.IsCompleted) + { + SelectorAwaitCore(self); + } + else + { + self.collectionSelectorAwaiter.SourceOnCompleted(selectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SeletedSourceMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.selectedAwaiter, out var result)) + { + if (result) + { + try + { + self.resultSelectorAwaiter = self.resultSelector(self.sourceCurrent, self.selectedEnumerator.Current).GetAwaiter(); + if (self.resultSelectorAwaiter.IsCompleted) + { + ResultSelectorAwaitCore(self); + } + else + { + self.resultSelectorAwaiter.SourceOnCompleted(resultSelectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + // dispose selected source and try iterate source. + try + { + self.selectedDisposeAsyncAwaiter = self.selectedEnumerator.DisposeAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + if (self.selectedDisposeAsyncAwaiter.IsCompleted) + { + SelectedEnumeratorDisposeAsyncCore(self); + } + else + { + self.selectedDisposeAsyncAwaiter.SourceOnCompleted(selectedEnumeratorDisposeAsyncCoreDelegate, self); + } + } + } + } + + static void SelectedEnumeratorDisposeAsyncCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.selectedDisposeAsyncAwaiter)) + { + self.selectedEnumerator = null; + self.selectedAwaiter = default; + + self.MoveNextSource(); // iterate next source + } + } + + static void SelectorAwaitCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.collectionSelectorAwaiter, out var result)) + { + self.selectedEnumerator = result.GetAsyncEnumerator(self.cancellationToken); + self.MoveNextSelected(); // iterated selected source. + } + } + + static void ResultSelectorAwaitCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultSelectorAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public async UniTask DisposeAsync() + { + if (selectedEnumerator != null) + { + await selectedEnumerator.DisposeAsync(); + } + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class SelectManyAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + + public SelectManyAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = selector; + this.selector2 = null; + this.resultSelector = resultSelector; + } + + public SelectManyAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func>> selector, Func> resultSelector) + { + this.source = source; + this.selector1 = null; + this.selector2 = selector; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, selector1, selector2, resultSelector, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action sourceMoveNextCoreDelegate = SourceMoveNextCore; + static readonly Action selectedSourceMoveNextCoreDelegate = SeletedSourceMoveNextCore; + static readonly Action selectedEnumeratorDisposeAsyncCoreDelegate = SelectedEnumeratorDisposeAsyncCore; + static readonly Action selectorAwaitCoreDelegate = SelectorAwaitCore; + static readonly Action resultSelectorAwaitCoreDelegate = ResultSelectorAwaitCore; + + readonly IUniTaskAsyncEnumerable source; + + readonly Func>> selector1; + readonly Func>> selector2; + readonly Func> resultSelector; + CancellationToken cancellationToken; + + TSource sourceCurrent; + int sourceIndex; + IUniTaskAsyncEnumerator sourceEnumerator; + IUniTaskAsyncEnumerator selectedEnumerator; + UniTask.Awaiter sourceAwaiter; + UniTask.Awaiter selectedAwaiter; + UniTask.Awaiter selectedDisposeAsyncAwaiter; + + // await additional + UniTask>.Awaiter collectionSelectorAwaiter; + UniTask.Awaiter resultSelectorAwaiter; + + public Enumerator(IUniTaskAsyncEnumerable source, Func>> selector1, Func>> selector2, Func> resultSelector, CancellationToken cancellationToken) + { + this.source = source; + this.selector1 = selector1; + this.selector2 = selector2; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + // iterate selected field + if (selectedEnumerator != null) + { + MoveNextSelected(); + } + else + { + // iterate source field + if (sourceEnumerator == null) + { + sourceEnumerator = source.GetAsyncEnumerator(cancellationToken); + } + MoveNextSource(); + } + + return new UniTask(this, completionSource.Version); + } + + void MoveNextSource() + { + try + { + sourceAwaiter = sourceEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (sourceAwaiter.IsCompleted) + { + SourceMoveNextCore(this); + } + else + { + sourceAwaiter.SourceOnCompleted(sourceMoveNextCoreDelegate, this); + } + } + + void MoveNextSelected() + { + try + { + selectedAwaiter = selectedEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + return; + } + + if (selectedAwaiter.IsCompleted) + { + SeletedSourceMoveNextCore(this); + } + else + { + selectedAwaiter.SourceOnCompleted(selectedSourceMoveNextCoreDelegate, this); + } + } + + static void SourceMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.sourceAwaiter, out var result)) + { + if (result) + { + try + { + self.sourceCurrent = self.sourceEnumerator.Current; + + if (self.selector1 != null) + { + self.collectionSelectorAwaiter = self.selector1(self.sourceCurrent, self.cancellationToken).GetAwaiter(); + } + else + { + self.collectionSelectorAwaiter = self.selector2(self.sourceCurrent, checked(self.sourceIndex++), self.cancellationToken).GetAwaiter(); + } + + if (self.collectionSelectorAwaiter.IsCompleted) + { + SelectorAwaitCore(self); + } + else + { + self.collectionSelectorAwaiter.SourceOnCompleted(selectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SeletedSourceMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.selectedAwaiter, out var result)) + { + if (result) + { + try + { + self.resultSelectorAwaiter = self.resultSelector(self.sourceCurrent, self.selectedEnumerator.Current, self.cancellationToken).GetAwaiter(); + if (self.resultSelectorAwaiter.IsCompleted) + { + ResultSelectorAwaitCore(self); + } + else + { + self.resultSelectorAwaiter.SourceOnCompleted(resultSelectorAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + } + else + { + // dispose selected source and try iterate source. + try + { + self.selectedDisposeAsyncAwaiter = self.selectedEnumerator.DisposeAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + if (self.selectedDisposeAsyncAwaiter.IsCompleted) + { + SelectedEnumeratorDisposeAsyncCore(self); + } + else + { + self.selectedDisposeAsyncAwaiter.SourceOnCompleted(selectedEnumeratorDisposeAsyncCoreDelegate, self); + } + } + } + } + + static void SelectedEnumeratorDisposeAsyncCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.selectedDisposeAsyncAwaiter)) + { + self.selectedEnumerator = null; + self.selectedAwaiter = default; + + self.MoveNextSource(); // iterate next source + } + } + + static void SelectorAwaitCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.collectionSelectorAwaiter, out var result)) + { + self.selectedEnumerator = result.GetAsyncEnumerator(self.cancellationToken); + self.MoveNextSelected(); // iterated selected source. + } + } + + static void ResultSelectorAwaitCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultSelectorAwaiter, out var result)) + { + self.Current = result; + self.completionSource.TrySetResult(true); + } + } + + public async UniTask DisposeAsync() + { + if (selectedEnumerator != null) + { + await selectedEnumerator.DisposeAsync(); + } + if (sourceEnumerator != null) + { + await sourceEnumerator.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SelectMany.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/SelectMany.cs.meta new file mode 100644 index 0000000..a8dbbaf --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SelectMany.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d81862f0eb12680479ccaaf2ac319d24 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SequenceEqual.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/SequenceEqual.cs new file mode 100644 index 0000000..ccef8b6 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SequenceEqual.cs @@ -0,0 +1,87 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask SequenceEqualAsync(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, CancellationToken cancellationToken = default) + { + return SequenceEqualAsync(first, second, EqualityComparer.Default, cancellationToken); + } + + public static UniTask SequenceEqualAsync(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return SequenceEqual.InvokeAsync(first, second, comparer, cancellationToken); + } + } + + internal static class SequenceEqual + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var e1 = first.GetAsyncEnumerator(cancellationToken); + try + { + var e2 = second.GetAsyncEnumerator(cancellationToken); + try + { + while (true) + { + if (await e1.MoveNextAsync()) + { + if (await e2.MoveNextAsync()) + { + if (comparer.Equals(e1.Current, e2.Current)) + { + continue; + } + else + { + return false; + } + } + else + { + // e2 is finished, but e1 has value + return false; + } + } + else + { + // e1 is finished, e2? + if (await e2.MoveNextAsync()) + { + return false; + } + else + { + return true; + } + } + } + } + finally + { + if (e2 != null) + { + await e2.DisposeAsync(); + } + } + } + finally + { + if (e1 != null) + { + await e1.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SequenceEqual.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/SequenceEqual.cs.meta new file mode 100644 index 0000000..ee2b75c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SequenceEqual.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b382772aba6128842928cdb6b2e034b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Single.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Single.cs new file mode 100644 index 0000000..512eb88 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Single.cs @@ -0,0 +1,230 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask SingleAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return SingleOperator.InvokeAsync(source, cancellationToken, false); + } + + public static UniTask SingleAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask SingleAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask SingleAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.InvokeAsync(source, predicate, cancellationToken, false); + } + + public static UniTask SingleOrDefaultAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return SingleOperator.InvokeAsync(source, cancellationToken, true); + } + + public static UniTask SingleOrDefaultAsync(this IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.InvokeAsync(source, predicate, cancellationToken, true); + } + + public static UniTask SingleOrDefaultAwaitAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.InvokeAsync(source, predicate, cancellationToken, true); + } + + public static UniTask SingleOrDefaultAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return SingleOperator.InvokeAsync(source, predicate, cancellationToken, true); + } + } + + internal static class SingleOperator + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + if (await e.MoveNextAsync()) + { + var v = e.Current; + if (!await e.MoveNextAsync()) + { + return v; + } + + throw Error.MoreThanOneElement(); + } + else + { + if (defaultIfEmpty) + { + return default; + } + else + { + throw Error.NoElements(); + } + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (predicate(v)) + { + if (found) + { + throw Error.MoreThanOneElement(); + } + else + { + found = true; + value = v; + } + } + } + + if (found || defaultIfEmpty) + { + return value; + } + + throw Error.NoElements(); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v)) + { + if (found) + { + throw Error.MoreThanOneElement(); + } + else + { + found = true; + value = v; + } + } + } + + if (found || defaultIfEmpty) + { + return value; + } + + throw Error.NoElements(); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken, bool defaultIfEmpty) + { + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + TSource value = default; + bool found = false; + while (await e.MoveNextAsync()) + { + var v = e.Current; + if (await predicate(v, cancellationToken)) + { + if (found) + { + throw Error.MoreThanOneElement(); + } + else + { + found = true; + value = v; + } + } + } + + if (found || defaultIfEmpty) + { + return value; + } + + throw Error.NoElements(); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Single.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Single.cs.meta new file mode 100644 index 0000000..c053dfd --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Single.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1bcd3928b90472e43a3a92c3ba708967 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Skip.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Skip.cs new file mode 100644 index 0000000..8c46119 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Skip.cs @@ -0,0 +1,69 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Skip(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Skip(source, count); + } + } + + internal sealed class Skip : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public Skip(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, count, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorBase + { + readonly int count; + + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.count = count; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (count <= checked(index++)) + { + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + else + { + result = false; + return true; + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Skip.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Skip.cs.meta new file mode 100644 index 0000000..25ad847 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Skip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c46b6c7dce0cb049a73c81084c75154 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SkipLast.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipLast.cs new file mode 100644 index 0000000..345ec3e --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipLast.cs @@ -0,0 +1,157 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable SkipLast(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + // non skip. + if (count <= 0) + { + return source; + } + + return new SkipLast(source, count); + } + } + + internal sealed class SkipLast : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public SkipLast(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, count, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Queue queue; + + bool continueNext; + + public Enumerator(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + queue = new Queue(); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + try + { + + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.queue.Count == self.count) + { + self.continueNext = false; + + var deq = self.queue.Dequeue(); + self.Current = deq; + self.queue.Enqueue(self.enumerator.Current); + + self.completionSource.TrySetResult(true); + } + else + { + self.queue.Enqueue(self.enumerator.Current); + + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.completionSource.TrySetResult(false); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SkipLast.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipLast.cs.meta new file mode 100644 index 0000000..06b1ede --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipLast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: df1d7f44d4fe7754f972c9e0b6fa72d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SkipWhile.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipWhile.cs new file mode 100644 index 0000000..ec97e42 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipWhile.cs @@ -0,0 +1,379 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable SkipWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhile(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileIntAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileAwaitWithCancellation(source, predicate); + } + + public static IUniTaskAsyncEnumerable SkipWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new SkipWhileIntAwaitWithCancellation(source, predicate); + } + } + + internal sealed class SkipWhile : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public SkipWhile(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + Func predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate == null || !predicate(SourceCurrent)) + { + predicate = null; + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class SkipWhileInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public SkipWhileInt(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + Func predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate == null || !predicate(SourceCurrent, checked(index++))) + { + predicate = null; + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class SkipWhileAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + terminateIteration= false; + return true; + } + else + { + terminateIteration= false; + return false; + } + } + } + } + + internal sealed class SkipWhileIntAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileIntAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent, checked(index++)); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration= false; + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + internal sealed class SkipWhileAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration= false; + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + internal sealed class SkipWhileIntAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public SkipWhileIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + if (predicate == null) + { + return CompletedTasks.False; + } + + return predicate(sourceCurrent, checked(index++), cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration= false; + if (!awaitResult) + { + predicate = null; + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/SkipWhile.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipWhile.cs.meta new file mode 100644 index 0000000..f2b210a --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/SkipWhile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b74b9fe361bf7148b51a29c8b2561e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.cs new file mode 100644 index 0000000..c2a92ce --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.cs @@ -0,0 +1,1244 @@ +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask SumAsync(this IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + } + + internal static class Sum + { + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64 sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int32? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Int64? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Single? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Double? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current.GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func selector, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + Decimal? sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken)).GetValueOrDefault(); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + } +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.cs.meta new file mode 100644 index 0000000..5331e34 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4149754066a21a341be58c04357061f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.tt b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.tt new file mode 100644 index 0000000..afc23bc --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.tt @@ -0,0 +1,167 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ output extension=".cs" #> +<# + var types = new[] + { + typeof(int), + typeof(long), + typeof(float), + typeof(double), + typeof(decimal), + + typeof(int?), + typeof(long?), + typeof(float?), + typeof(double?), + typeof(decimal?), + }; + + Func IsNullable = x => x.IsGenericType; + Func TypeName = x => IsNullable(x) ? x.GetGenericArguments()[0].Name + "?" : x.Name; + Func WithSuffix = x => IsNullable(x) ? ".GetValueOrDefault()" : ""; +#> +using System; +using System.Threading; +using Cysharp.Threading.Tasks.Internal; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { +<# foreach(var t in types) { #> + public static UniTask<<#= TypeName(t) #>> SumAsync(this IUniTaskAsyncEnumerable<<#= TypeName(t) #>> source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Sum.InvokeAsync(source, cancellationToken); + } + + public static UniTask<<#= TypeName(t) #>> SumAsync(this IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask<<#= TypeName(t) #>> SumAwaitAsync(this IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + + public static UniTask<<#= TypeName(t) #>> SumAwaitCancellationAsync(this IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(source, nameof(selector)); + + return Sum.InvokeAsync(source, selector, cancellationToken); + } + +<# } #> + } + + internal static class Sum + { +<# foreach(var t in types) { #> + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable<<#= TypeName(t) #>> source, CancellationToken cancellationToken) + { + <#= TypeName(t) #> sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += e.Current<#= WithSuffix(t) #>; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func> selector, CancellationToken cancellationToken) + { + <#= TypeName(t) #> sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += selector(e.Current)<#= WithSuffix(t) #>; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken) + { + <#= TypeName(t) #> sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current))<#= WithSuffix(t) #>; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + + public static async UniTask<<#= TypeName(t) #>> InvokeAsync(IUniTaskAsyncEnumerable source, Func>> selector, CancellationToken cancellationToken) + { + <#= TypeName(t) #> sum = default; + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + sum += (await selector(e.Current, cancellationToken))<#= WithSuffix(t) #>; + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return sum; + } + +<# } #> + } +} diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.tt.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.tt.meta new file mode 100644 index 0000000..eaec35c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Sum.tt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b61271ca8e712494ab1ce2d10b180b6f +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Take.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Take.cs new file mode 100644 index 0000000..d632b1c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Take.cs @@ -0,0 +1,69 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Take(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new Take(source, count); + } + } + + internal sealed class Take : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public Take(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, count, cancellationToken); + } + + sealed class Enumerator : AsyncEnumeratorBase + { + readonly int count; + + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.count = count; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (checked(index++) < count) + { + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = false; + return true; + } + } + else + { + result = false; + return true; + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Take.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Take.cs.meta new file mode 100644 index 0000000..1cc91ab --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Take.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42f02cb84e5875b488304755d0e1383d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/TakeLast.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeLast.cs new file mode 100644 index 0000000..d770c3b --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeLast.cs @@ -0,0 +1,173 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable TakeLast(this IUniTaskAsyncEnumerable source, Int32 count) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + // non take. + if (count <= 0) + { + return Empty(); + } + + return new TakeLast(source, count); + } + } + + internal sealed class TakeLast : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly int count; + + public TakeLast(IUniTaskAsyncEnumerable source, int count) + { + this.source = source; + this.count = count; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, count, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action MoveNextCoreDelegate = MoveNextCore; + + readonly IUniTaskAsyncEnumerable source; + readonly int count; + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator enumerator; + UniTask.Awaiter awaiter; + Queue queue; + + bool iterateCompleted; + bool continueNext; + + public Enumerator(IUniTaskAsyncEnumerable source, int count, CancellationToken cancellationToken) + { + this.source = source; + this.count = count; + this.cancellationToken = cancellationToken; + } + + public TSource Current { get; private set; } + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetAsyncEnumerator(cancellationToken); + queue = new Queue(); + } + + completionSource.Reset(); + SourceMoveNext(); + return new UniTask(this, completionSource.Version); + } + + void SourceMoveNext() + { + if (iterateCompleted) + { + if (queue.Count > 0) + { + Current = queue.Dequeue(); + completionSource.TrySetResult(true); + } + else + { + completionSource.TrySetResult(false); + } + + return; + } + + try + { + LOOP: + awaiter = enumerator.MoveNextAsync().GetAwaiter(); + if (awaiter.IsCompleted) + { + continueNext = true; + MoveNextCore(this); + if (continueNext) + { + continueNext = false; + goto LOOP; // avoid recursive + } + } + else + { + awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); + } + } + catch (Exception ex) + { + completionSource.TrySetException(ex); + } + } + + + static void MoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.awaiter, out var result)) + { + if (result) + { + if (self.queue.Count < self.count) + { + self.queue.Enqueue(self.enumerator.Current); + + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + else + { + self.queue.Dequeue(); + self.queue.Enqueue(self.enumerator.Current); + + if (!self.continueNext) + { + self.SourceMoveNext(); + } + } + } + else + { + self.continueNext = false; + self.iterateCompleted = true; + self.SourceMoveNext(); + } + } + else + { + self.continueNext = false; + } + } + + public UniTask DisposeAsync() + { + if (enumerator != null) + { + return enumerator.DisposeAsync(); + } + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/TakeLast.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeLast.cs.meta new file mode 100644 index 0000000..d80037f --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeLast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 510aa9fd35b45fc40bcdb7e59f01fd1b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/TakeWhile.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeWhile.cs new file mode 100644 index 0000000..8e98292 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeWhile.cs @@ -0,0 +1,342 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable TakeWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhile(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhile(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileIntAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileAwaitWithCancellation(source, predicate); + } + + public static IUniTaskAsyncEnumerable TakeWhileAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new TakeWhileIntAwaitWithCancellation(source, predicate); + } + } + + internal sealed class TakeWhile : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public TakeWhile(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + Func predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate(SourceCurrent)) + { + Current = SourceCurrent; + result = true; + return true; + } + } + + result = false; + return true; + } + } + } + + internal sealed class TakeWhileInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public TakeWhileInt(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly Func predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate(SourceCurrent, checked(index++))) + { + Current = SourceCurrent; + result = true; + return true; + } + } + + result = false; + return true; + } + } + } + + internal sealed class TakeWhileAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } + + internal sealed class TakeWhileIntAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileIntAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, checked(index++)); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } + + internal sealed class TakeWhileAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + Func> predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } + + internal sealed class TakeWhileIntAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public TakeWhileIntAwaitWithCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, checked(index++), cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + if (awaitResult) + { + Current = SourceCurrent; + terminateIteration = false; + return true; + } + else + { + terminateIteration = true; + return false; + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/TakeWhile.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeWhile.cs.meta new file mode 100644 index 0000000..f2173d5 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/TakeWhile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bca55adabcc4b3141b50b8b09634f764 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Throw.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Throw.cs new file mode 100644 index 0000000..a939559 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Throw.cs @@ -0,0 +1,54 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Throw(Exception exception) + { + return new Throw(exception); + } + } + + internal class Throw : IUniTaskAsyncEnumerable + { + readonly Exception exception; + + public Throw(Exception exception) + { + this.exception = exception; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(exception, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly Exception exception; + CancellationToken cancellationToken; + + public Enumerator(Exception exception, CancellationToken cancellationToken) + { + this.exception = exception; + this.cancellationToken = cancellationToken; + } + + public TValue Current => default; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + return UniTask.FromException(exception); + } + + public UniTask DisposeAsync() + { + return default; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Throw.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Throw.cs.meta new file mode 100644 index 0000000..c768ef1 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Throw.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d05a7d4f4161e549b4789e1022baae8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToArray.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToArray.cs new file mode 100644 index 0000000..25c56ec --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToArray.cs @@ -0,0 +1,60 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask ToArrayAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Cysharp.Threading.Tasks.Linq.ToArray.InvokeAsync(source, cancellationToken); + } + } + + internal static class ToArray + { + internal static async UniTask InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + TSource[] result = default; + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + result = Array.Empty(); + } + else + { + result = new TSource[i]; + Array.Copy(array, result, i); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + + return result; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToArray.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToArray.cs.meta new file mode 100644 index 0000000..679d61c --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToArray.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: debb010bbb1622e43b94fe70ec0133dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToDictionary.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToDictionary.cs new file mode 100644 index 0000000..56d65e2 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToDictionary.cs @@ -0,0 +1,278 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToDictionary.InvokeAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.InvokeAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToDictionary.InvokeAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.InvokeAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToDictionary.InvokeAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.InvokeAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToDictionary.InvokeAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.InvokeAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToDictionary.InvokeAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.InvokeAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToDictionary.InvokeAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToDictionaryAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToDictionary.InvokeAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + } + + internal static class ToDictionary + { + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = keySelector(v); + dict.Add(key, v); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = keySelector(v); + var value = elementSelector(v); + dict.Add(key, value); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + // with await + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v); + dict.Add(key, v); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v); + var value = await elementSelector(v); + dict.Add(key, value); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + // with cancellation + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v, cancellationToken); + dict.Add(key, v); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + var v = e.Current; + var key = await keySelector(v, cancellationToken); + var value = await elementSelector(v, cancellationToken); + dict.Add(key, value); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return dict; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToDictionary.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToDictionary.cs.meta new file mode 100644 index 0000000..4deed19 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03b109b1fe1f2df46aa56ffb26747654 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToHashSet.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToHashSet.cs new file mode 100644 index 0000000..ec54841 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToHashSet.cs @@ -0,0 +1,50 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToHashSetAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Cysharp.Threading.Tasks.Linq.ToHashSet.InvokeAsync(source, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToHashSetAsync(this IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return Cysharp.Threading.Tasks.Linq.ToHashSet.InvokeAsync(source, comparer, cancellationToken); + } + } + + internal static class ToHashSet + { + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var set = new HashSet(comparer); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + set.Add(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return set; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToHashSet.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToHashSet.cs.meta new file mode 100644 index 0000000..8d3c4af --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToHashSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a3e552113af96e4986805ec3c4fc80a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToList.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToList.cs new file mode 100644 index 0000000..07182c9 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToList.cs @@ -0,0 +1,42 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToListAsync(this IUniTaskAsyncEnumerable source, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return Cysharp.Threading.Tasks.Linq.ToList.InvokeAsync(source, cancellationToken); + } + } + + internal static class ToList + { + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, CancellationToken cancellationToken) + { + var list = new List(); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + while (await e.MoveNextAsync()) + { + list.Add(e.Current); + } + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + + return list; + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToList.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToList.cs.meta new file mode 100644 index 0000000..4f09373 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3859c1b31e81d9b44b282e7d97e11635 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToLookup.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToLookup.cs new file mode 100644 index 0000000..9cccec0 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToLookup.cs @@ -0,0 +1,554 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToLookup.InvokeAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.InvokeAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToLookup.InvokeAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAsync(this IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.InvokeAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToLookup.InvokeAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.InvokeAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToLookup.InvokeAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.InvokeAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + + return ToLookup.InvokeAsync(source, keySelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.InvokeAsync(source, keySelector, comparer, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + + return ToLookup.InvokeAsync(source, keySelector, elementSelector, EqualityComparer.Default, cancellationToken); + } + + public static UniTask> ToLookupAwaitWithCancellationAsync(this IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken = default) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(keySelector, nameof(keySelector)); + Error.ThrowArgumentNullException(elementSelector, nameof(elementSelector)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + return ToLookup.InvokeAsync(source, keySelector, elementSelector, comparer, cancellationToken); + } + } + + internal static class ToLookup + { + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + var e = source.GetAsyncEnumerator(cancellationToken); + try + { + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return Lookup.Create(new ArraySegment(array, 0, i), keySelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func keySelector, Func elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return Lookup.Create(new ArraySegment(array, 0, i), keySelector, elementSelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + + // with await + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, elementSelector, comparer); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // with cancellation + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, comparer, cancellationToken); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal static async UniTask> InvokeAsync(IUniTaskAsyncEnumerable source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(16); + + IUniTaskAsyncEnumerator e = default; + try + { + e = source.GetAsyncEnumerator(cancellationToken); + var i = 0; + while (await e.MoveNextAsync()) + { + ArrayPoolUtil.EnsureCapacity(ref array, i, pool); + array[i++] = e.Current; + } + + if (i == 0) + { + return Lookup.CreateEmpty(); + } + else + { + return await Lookup.CreateAsync(new ArraySegment(array, 0, i), keySelector, elementSelector, comparer, cancellationToken); + } + } + finally + { + pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType()); + + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + // Lookup + + class Lookup : ILookup + { + static readonly Lookup empty = new Lookup(new Dictionary>()); + + // original lookup keeps order but this impl does not(dictionary not guarantee) + readonly Dictionary> dict; + + Lookup(Dictionary> dict) + { + this.dict = dict; + } + + public static Lookup CreateEmpty() + { + return empty; + } + + public static Lookup Create(ArraySegment source, Func keySelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = keySelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(arr[i]); + } + + return new Lookup(dict); + } + + public static Lookup Create(ArraySegment source, Func keySelector, Func elementSelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = keySelector(arr[i]); + var elem = elementSelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(elem); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(arr[i]); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i]); + var elem = await elementSelector(arr[i]); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(elem); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i], cancellationToken); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(arr[i]); + } + + return new Lookup(dict); + } + + public static async UniTask> CreateAsync(ArraySegment source, Func> keySelector, Func> elementSelector, IEqualityComparer comparer, CancellationToken cancellationToken) + { + var dict = new Dictionary>(comparer); + + var arr = source.Array; + var c = source.Count; + for (int i = source.Offset; i < c; i++) + { + var key = await keySelector(arr[i], cancellationToken); + var elem = await elementSelector(arr[i], cancellationToken); + + if (!dict.TryGetValue(key, out var list)) + { + list = new Grouping(key); + dict[key] = list; + } + + list.Add(elem); + } + + return new Lookup(dict); + } + + public IEnumerable this[TKey key] => dict.TryGetValue(key, out var g) ? g : Enumerable.Empty(); + + public int Count => dict.Count; + + public bool Contains(TKey key) + { + return dict.ContainsKey(key); + } + + public IEnumerator> GetEnumerator() + { + return dict.Values.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return dict.Values.GetEnumerator(); + } + } + + class Grouping : IGrouping // , IUniTaskAsyncGrouping + { + readonly List elements; + + public TKey Key { get; private set; } + + public Grouping(TKey key) + { + this.Key = key; + this.elements = new List(); + } + + public void Add(TElement value) + { + elements.Add(value); + } + public IEnumerator GetEnumerator() + { + return elements.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return elements.GetEnumerator(); + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return this.ToUniTaskAsyncEnumerable().GetAsyncEnumerator(cancellationToken); + } + + public override string ToString() + { + return "Key: " + Key + ", Count: " + elements.Count; + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToLookup.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToLookup.cs.meta new file mode 100644 index 0000000..7dd8ecd --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToLookup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57da22563bcd6ca4aaf256d941de5cb0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToObservable.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToObservable.cs new file mode 100644 index 0000000..4f48388 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToObservable.cs @@ -0,0 +1,97 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IObservable ToObservable(this IUniTaskAsyncEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToObservable(source); + } + } + + internal sealed class ToObservable : IObservable + { + readonly IUniTaskAsyncEnumerable source; + + public ToObservable(IUniTaskAsyncEnumerable source) + { + this.source = source; + } + + public IDisposable Subscribe(IObserver observer) + { + var ctd = new CancellationTokenDisposable(); + + RunAsync(source, observer, ctd.Token).Forget(); + + return ctd; + } + + static async UniTaskVoid RunAsync(IUniTaskAsyncEnumerable src, IObserver observer, CancellationToken cancellationToken) + { + // cancellationToken.IsCancellationRequested is called when Rx's Disposed. + // when disposed, finish silently. + + var e = src.GetAsyncEnumerator(cancellationToken); + try + { + bool hasNext; + + do + { + try + { + hasNext = await e.MoveNextAsync(); + } + catch (Exception ex) + { + if (cancellationToken.IsCancellationRequested) + { + return; + } + + observer.OnError(ex); + return; + } + + if (hasNext) + { + observer.OnNext(e.Current); + } + else + { + observer.OnCompleted(); + return; + } + } while (!cancellationToken.IsCancellationRequested); + } + finally + { + if (e != null) + { + await e.DisposeAsync(); + } + } + } + + internal sealed class CancellationTokenDisposable : IDisposable + { + readonly CancellationTokenSource cts = new CancellationTokenSource(); + + public CancellationToken Token => cts.Token; + + public void Dispose() + { + if (!cts.IsCancellationRequested) + { + cts.Cancel(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToObservable.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToObservable.cs.meta new file mode 100644 index 0000000..44d917e --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToObservable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4f6f48a532188e4c80b7ebe69aea3a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToUniTaskAsyncEnumerable.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/ToUniTaskAsyncEnumerable.cs new file mode 100644 index 0000000..500ce13 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToUniTaskAsyncEnumerable.cs @@ -0,0 +1,1112 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.ExceptionServices; +using System.Threading; +using System.Threading.Tasks; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this IEnumerable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToUniTaskAsyncEnumerable(source); + } + + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this Task source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToUniTaskAsyncEnumerableTask(source); + } + + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this UniTask source) + { + return new ToUniTaskAsyncEnumerableUniTask(source); + } + + public static IUniTaskAsyncEnumerable ToUniTaskAsyncEnumerable(this IObservable source) + { + Error.ThrowArgumentNullException(source, nameof(source)); + + return new ToUniTaskAsyncEnumerableObservable(source); + } + } + + internal class ToUniTaskAsyncEnumerable : IUniTaskAsyncEnumerable + { + readonly IEnumerable source; + + public ToUniTaskAsyncEnumerable(IEnumerable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly IEnumerable source; + CancellationToken cancellationToken; + + IEnumerator enumerator; + + public Enumerator(IEnumerable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + } + + public T Current => enumerator.Current; + + public UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (enumerator == null) + { + enumerator = source.GetEnumerator(); + } + + if (enumerator.MoveNext()) + { + return CompletedTasks.True; + } + + return CompletedTasks.False; + } + + public UniTask DisposeAsync() + { + enumerator.Dispose(); + return default; + } + } + } + + internal class ToUniTaskAsyncEnumerableTask : IUniTaskAsyncEnumerable + { + readonly Task source; + + public ToUniTaskAsyncEnumerableTask(Task source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly Task source; + CancellationToken cancellationToken; + + T current; + bool called; + + public Enumerator(Task source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + + this.called = false; + } + + public T Current => current; + + public async UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (called) + { + return false; + } + called = true; + + current = await source; + return true; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } + + internal class ToUniTaskAsyncEnumerableUniTask : IUniTaskAsyncEnumerable + { + readonly UniTask source; + + public ToUniTaskAsyncEnumerableUniTask(UniTask source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + class Enumerator : IUniTaskAsyncEnumerator + { + readonly UniTask source; + CancellationToken cancellationToken; + + T current; + bool called; + + public Enumerator(UniTask source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + + this.called = false; + } + + public T Current => current; + + public async UniTask MoveNextAsync() + { + cancellationToken.ThrowIfCancellationRequested(); + + if (called) + { + return false; + } + called = true; + + current = await source; + return true; + } + + public UniTask DisposeAsync() + { + return default; + } + } + } + + internal class ToUniTaskAsyncEnumerableObservable : IUniTaskAsyncEnumerable + { + readonly IObservable source; + + public ToUniTaskAsyncEnumerableObservable(IObservable source) + { + this.source = source; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, cancellationToken); + } + + class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator, IObserver + { + static readonly Action OnCanceledDelegate = OnCanceled; + + readonly IObservable source; + CancellationToken cancellationToken; + + + bool useCachedCurrent; + T current; + bool subscribeCompleted; + readonly Queue queuedResult; + Exception error; + IDisposable subscription; + CancellationTokenRegistration cancellationTokenRegistration; + + public Enumerator(IObservable source, CancellationToken cancellationToken) + { + this.source = source; + this.cancellationToken = cancellationToken; + this.queuedResult = new Queue(); + + if (cancellationToken.CanBeCanceled) + { + cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(OnCanceledDelegate, this); + } + } + + public T Current + { + get + { + if (useCachedCurrent) + { + return current; + } + + if (queuedResult.Count != 0) + { + current = queuedResult.Dequeue(); + useCachedCurrent = true; + return current; + } + else + { + return default; // undefined. + } + } + } + + public UniTask MoveNextAsync() + { + lock (queuedResult) + { + useCachedCurrent = false; + + if (cancellationToken.IsCancellationRequested) + { + return UniTask.FromCanceled(cancellationToken); + } + + if (subscription == null) + { + subscription = source.Subscribe(this); + } + + if (error != null) + { + return UniTask.FromException(error); + } + + if (queuedResult.Count != 0) + { + return CompletedTasks.True; + } + + if (subscribeCompleted) + { + return CompletedTasks.False; + } + + completionSource.Reset(); + return new UniTask(this, completionSource.Version); + } + } + + public UniTask DisposeAsync() + { + subscription.Dispose(); + cancellationTokenRegistration.Dispose(); + completionSource.Reset(); + return default; + } + + public void OnCompleted() + { + lock (queuedResult) + { + subscribeCompleted = true; + completionSource.TrySetResult(false); + } + } + + public void OnError(Exception error) + { + lock (queuedResult) + { + this.error = error; + completionSource.TrySetException(error); + } + } + + public void OnNext(T value) + { + lock (queuedResult) + { + queuedResult.Enqueue(value); + completionSource.TrySetResult(true); // include callback execution, too long lock? + } + } + + static void OnCanceled(object state) + { + var self = (Enumerator)state; + lock (self.queuedResult) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + } + } + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/ToUniTaskAsyncEnumerable.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/ToUniTaskAsyncEnumerable.cs.meta new file mode 100644 index 0000000..45fd3b0 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/ToUniTaskAsyncEnumerable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d7192de2a0581ec4db62962cc1404af5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Union.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Union.cs new file mode 100644 index 0000000..2ceefab --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Union.cs @@ -0,0 +1,26 @@ +using Cysharp.Threading.Tasks.Internal; +using System.Collections.Generic; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Union(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return Union(first, second, EqualityComparer.Default); + } + + public static IUniTaskAsyncEnumerable Union(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, IEqualityComparer comparer) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(comparer, nameof(comparer)); + + // improv without combinate? + return first.Concat(second).Distinct(comparer); + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Union.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Union.cs.meta new file mode 100644 index 0000000..1d9c7ad --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Union.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae57a55bdeba98b4f8ff234d98d7dd76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Where.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Where.cs new file mode 100644 index 0000000..6b1cdd6 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Where.cs @@ -0,0 +1,355 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + public static IUniTaskAsyncEnumerable Where(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new Where(source, predicate); + } + + public static IUniTaskAsyncEnumerable Where(this IUniTaskAsyncEnumerable source, Func predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereAwait(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwait(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereAwaitInt(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereAwaitCancellation(source, predicate); + } + + public static IUniTaskAsyncEnumerable WhereAwaitWithCancellation(this IUniTaskAsyncEnumerable source, Func> predicate) + { + Error.ThrowArgumentNullException(source, nameof(source)); + Error.ThrowArgumentNullException(predicate, nameof(predicate)); + + return new WhereAwaitIntCancellation(source, predicate); + } + } + + internal sealed class Where : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public Where(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly Func predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate(SourceCurrent)) + { + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class WhereInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func predicate; + + public WhereInt(IUniTaskAsyncEnumerable source, Func predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorBase + { + readonly Func predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override bool TryMoveNextCore(bool sourceHasCurrent, out bool result) + { + if (sourceHasCurrent) + { + if (predicate(SourceCurrent, checked(index++))) + { + Current = SourceCurrent; + result = true; + return true; + } + else + { + result = default; + return false; + } + } + + result = false; + return true; + } + } + } + + internal sealed class WhereAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereAwait(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration = false; + if (awaitResult) + { + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + internal sealed class WhereAwaitInt : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereAwaitInt(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, checked(index++)); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration = false; + if (awaitResult) + { + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + + + internal sealed class WhereAwaitCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereAwaitCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration = false; + if (awaitResult) + { + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + + internal sealed class WhereAwaitIntCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable source; + readonly Func> predicate; + + public WhereAwaitIntCancellation(IUniTaskAsyncEnumerable source, Func> predicate) + { + this.source = source; + this.predicate = predicate; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(source, predicate, cancellationToken); + } + + class Enumerator : AsyncEnumeratorAwaitSelectorBase + { + readonly Func> predicate; + int index; + + public Enumerator(IUniTaskAsyncEnumerable source, Func> predicate, CancellationToken cancellationToken) + + : base(source, cancellationToken) + { + this.predicate = predicate; + } + + protected override UniTask TransformAsync(TSource sourceCurrent) + { + return predicate(sourceCurrent, checked(index++), cancellationToken); + } + + protected override bool TrySetCurrentCore(bool awaitResult, out bool terminateIteration) + { + terminateIteration = false; + if (awaitResult) + { + Current = SourceCurrent; + return true; + } + else + { + return false; + } + } + } + } + +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Where.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Where.cs.meta new file mode 100644 index 0000000..7e50337 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Where.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d882a3238d9535e4e8ce1ad3291eb7fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Zip.cs b/src/UniTask/Assets/Plugins/UniTask/Linq/Zip.cs new file mode 100644 index 0000000..d646d78 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Zip.cs @@ -0,0 +1,535 @@ +using Cysharp.Threading.Tasks.Internal; +using System; +using System.Threading; + +namespace Cysharp.Threading.Tasks.Linq +{ + public static partial class UniTaskAsyncEnumerable + { + + public static IUniTaskAsyncEnumerable<(TFirst First, TSecond Second)> Zip(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + + return Zip(first, second, (x, y) => (x, y)); + } + + public static IUniTaskAsyncEnumerable Zip(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func resultSelector) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); + + return new Zip(first, second, resultSelector); + } + + public static IUniTaskAsyncEnumerable ZipAwait(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> selector) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new ZipAwait(first, second, selector); + } + + public static IUniTaskAsyncEnumerable ZipAwaitWithCancellation(this IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> selector) + { + Error.ThrowArgumentNullException(first, nameof(first)); + Error.ThrowArgumentNullException(second, nameof(second)); + Error.ThrowArgumentNullException(selector, nameof(selector)); + + return new ZipAwaitWithCancellation(first, second, selector); + } + } + + internal sealed class Zip : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func resultSelector; + + public Zip(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func resultSelector) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(first, second, resultSelector, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action firstMoveNextCoreDelegate = FirstMoveNextCore; + static readonly Action secondMoveNextCoreDelegate = SecondMoveNextCore; + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func resultSelector; + + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator firstEnumerator; + IUniTaskAsyncEnumerator secondEnumerator; + + UniTask.Awaiter firstAwaiter; + UniTask.Awaiter secondAwaiter; + + public Enumerator(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func resultSelector, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + if (firstEnumerator == null) + { + firstEnumerator = first.GetAsyncEnumerator(cancellationToken); + secondEnumerator = second.GetAsyncEnumerator(cancellationToken); + } + + firstAwaiter = firstEnumerator.MoveNextAsync().GetAwaiter(); + + if (firstAwaiter.IsCompleted) + { + FirstMoveNextCore(this); + } + else + { + firstAwaiter.SourceOnCompleted(firstMoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void FirstMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.firstAwaiter, out var result)) + { + if (result) + { + try + { + self.secondAwaiter = self.secondEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.secondAwaiter.IsCompleted) + { + SecondMoveNextCore(self); + } + else + { + self.secondAwaiter.SourceOnCompleted(secondMoveNextCoreDelegate, self); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SecondMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.secondAwaiter, out var result)) + { + if (result) + { + try + { + self.Current = self.resultSelector(self.firstEnumerator.Current, self.secondEnumerator.Current); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(true); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + public async UniTask DisposeAsync() + { + if (firstEnumerator != null) + { + await firstEnumerator.DisposeAsync(); + } + if (secondEnumerator != null) + { + await secondEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class ZipAwait : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + public ZipAwait(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(first, second, resultSelector, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action firstMoveNextCoreDelegate = FirstMoveNextCore; + static readonly Action secondMoveNextCoreDelegate = SecondMoveNextCore; + static readonly Action resultAwaitCoreDelegate = ResultAwaitCore; + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator firstEnumerator; + IUniTaskAsyncEnumerator secondEnumerator; + + UniTask.Awaiter firstAwaiter; + UniTask.Awaiter secondAwaiter; + UniTask.Awaiter resultAwaiter; + + public Enumerator(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + if (firstEnumerator == null) + { + firstEnumerator = first.GetAsyncEnumerator(cancellationToken); + secondEnumerator = second.GetAsyncEnumerator(cancellationToken); + } + + firstAwaiter = firstEnumerator.MoveNextAsync().GetAwaiter(); + + if (firstAwaiter.IsCompleted) + { + FirstMoveNextCore(this); + } + else + { + firstAwaiter.SourceOnCompleted(firstMoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void FirstMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.firstAwaiter, out var result)) + { + if (result) + { + try + { + self.secondAwaiter = self.secondEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.secondAwaiter.IsCompleted) + { + SecondMoveNextCore(self); + } + else + { + self.secondAwaiter.SourceOnCompleted(secondMoveNextCoreDelegate, self); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SecondMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.secondAwaiter, out var result)) + { + if (result) + { + try + { + self.resultAwaiter = self.resultSelector(self.firstEnumerator.Current, self.secondEnumerator.Current).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultAwaitCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(resultAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void ResultAwaitCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(true); + } + } + } + + public async UniTask DisposeAsync() + { + if (firstEnumerator != null) + { + await firstEnumerator.DisposeAsync(); + } + if (secondEnumerator != null) + { + await secondEnumerator.DisposeAsync(); + } + } + } + } + + internal sealed class ZipAwaitWithCancellation : IUniTaskAsyncEnumerable + { + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + public ZipAwaitWithCancellation(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + } + + public IUniTaskAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) + { + return new Enumerator(first, second, resultSelector, cancellationToken); + } + + sealed class Enumerator : MoveNextSource, IUniTaskAsyncEnumerator + { + static readonly Action firstMoveNextCoreDelegate = FirstMoveNextCore; + static readonly Action secondMoveNextCoreDelegate = SecondMoveNextCore; + static readonly Action resultAwaitCoreDelegate = ResultAwaitCore; + + readonly IUniTaskAsyncEnumerable first; + readonly IUniTaskAsyncEnumerable second; + readonly Func> resultSelector; + + CancellationToken cancellationToken; + + IUniTaskAsyncEnumerator firstEnumerator; + IUniTaskAsyncEnumerator secondEnumerator; + + UniTask.Awaiter firstAwaiter; + UniTask.Awaiter secondAwaiter; + UniTask.Awaiter resultAwaiter; + + public Enumerator(IUniTaskAsyncEnumerable first, IUniTaskAsyncEnumerable second, Func> resultSelector, CancellationToken cancellationToken) + { + this.first = first; + this.second = second; + this.resultSelector = resultSelector; + this.cancellationToken = cancellationToken; + } + + public TResult Current { get; private set; } + + public UniTask MoveNextAsync() + { + completionSource.Reset(); + + if (firstEnumerator == null) + { + firstEnumerator = first.GetAsyncEnumerator(cancellationToken); + secondEnumerator = second.GetAsyncEnumerator(cancellationToken); + } + + firstAwaiter = firstEnumerator.MoveNextAsync().GetAwaiter(); + + if (firstAwaiter.IsCompleted) + { + FirstMoveNextCore(this); + } + else + { + firstAwaiter.SourceOnCompleted(firstMoveNextCoreDelegate, this); + } + + return new UniTask(this, completionSource.Version); + } + + static void FirstMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.firstAwaiter, out var result)) + { + if (result) + { + try + { + self.secondAwaiter = self.secondEnumerator.MoveNextAsync().GetAwaiter(); + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + return; + } + + if (self.secondAwaiter.IsCompleted) + { + SecondMoveNextCore(self); + } + else + { + self.secondAwaiter.SourceOnCompleted(secondMoveNextCoreDelegate, self); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void SecondMoveNextCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.secondAwaiter, out var result)) + { + if (result) + { + try + { + self.resultAwaiter = self.resultSelector(self.firstEnumerator.Current, self.secondEnumerator.Current, self.cancellationToken).GetAwaiter(); + if (self.resultAwaiter.IsCompleted) + { + ResultAwaitCore(self); + } + else + { + self.resultAwaiter.SourceOnCompleted(resultAwaitCoreDelegate, self); + } + } + catch (Exception ex) + { + self.completionSource.TrySetException(ex); + } + } + else + { + self.completionSource.TrySetResult(false); + } + } + } + + static void ResultAwaitCore(object state) + { + var self = (Enumerator)state; + + if (self.TryGetResult(self.resultAwaiter, out var result)) + { + self.Current = result; + + if (self.cancellationToken.IsCancellationRequested) + { + self.completionSource.TrySetCanceled(self.cancellationToken); + } + else + { + self.completionSource.TrySetResult(true); + } + } + } + + public async UniTask DisposeAsync() + { + if (firstEnumerator != null) + { + await firstEnumerator.DisposeAsync(); + } + if (secondEnumerator != null) + { + await secondEnumerator.DisposeAsync(); + } + } + } + } +} \ No newline at end of file diff --git a/src/UniTask/Assets/Plugins/UniTask/Linq/Zip.cs.meta b/src/UniTask/Assets/Plugins/UniTask/Linq/Zip.cs.meta new file mode 100644 index 0000000..bf12163 --- /dev/null +++ b/src/UniTask/Assets/Plugins/UniTask/Linq/Zip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: acc1acff153e347418f0f30b1c535994 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/UniTask/Assets/Plugins/UniTask/UniTask.cs b/src/UniTask/Assets/Plugins/UniTask/UniTask.cs index 1958d3e..35bf8b6 100644 --- a/src/UniTask/Assets/Plugins/UniTask/UniTask.cs +++ b/src/UniTask/Assets/Plugins/UniTask/UniTask.cs @@ -15,6 +15,7 @@ namespace Cysharp.Threading.Tasks { internal static readonly Action InvokeActionDelegate = InvokeAction; + [DebuggerHidden] static void InvokeAction(object state) { ((Action)state).Invoke(); @@ -318,6 +319,8 @@ namespace Cysharp.Threading.Tasks /// /// If register manually continuation, you can use it instead of for compiler OnCompleted methods. /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SourceOnCompleted(Action continuation, object state) { if (task.source == null) @@ -640,6 +643,8 @@ namespace Cysharp.Threading.Tasks /// /// If register manually continuation, you can use it instead of for compiler OnCompleted methods. /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SourceOnCompleted(Action continuation, object state) { var s = task.source; diff --git a/src/UniTask/Assets/Plugins/UniTask/UniTaskScheduler.cs b/src/UniTask/Assets/Plugins/UniTask/UniTaskScheduler.cs index d725470..2f91f2a 100644 --- a/src/UniTask/Assets/Plugins/UniTask/UniTaskScheduler.cs +++ b/src/UniTask/Assets/Plugins/UniTask/UniTaskScheduler.cs @@ -70,7 +70,7 @@ namespace Cysharp.Threading.Tasks string msg = null; if (UnobservedExceptionWriteLogType != UnityEngine.LogType.Exception) { - msg = "UnobservedTaskException:" + ex.ToString(); + msg = "UnobservedTaskException: " + ex.ToString(); } switch (UnobservedExceptionWriteLogType) { @@ -93,7 +93,7 @@ namespace Cysharp.Threading.Tasks break; } #else - Console.WriteLine(ex.ToString()); + Console.WriteLine("UnobservedTaskException: " + ex.ToString()); #endif } } diff --git a/src/UniTask/Assets/Scenes/SandboxMain.cs b/src/UniTask/Assets/Scenes/SandboxMain.cs index 2b33874..ff9c1e6 100644 --- a/src/UniTask/Assets/Scenes/SandboxMain.cs +++ b/src/UniTask/Assets/Scenes/SandboxMain.cs @@ -12,6 +12,7 @@ using Unity.Jobs; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; +using Cysharp.Threading.Tasks.Linq; public struct MyJob : IJob { @@ -32,7 +33,7 @@ public struct MyJob : IJob public enum MyEnum { - A,B,C + A, B, C } public class SandboxMain : MonoBehaviour @@ -85,6 +86,25 @@ public class SandboxMain : MonoBehaviour job.inOut.Dispose(); } + + async UniTaskVoid Update2() + { + + UnityEngine.Debug.Log("async linq!"); + + await UniTaskAsyncEnumerable.Range(1, 10) + .Where(x => x % 2 == 0) + .Select(x => x * x) + .ForEachAsync(x => + { + UnityEngine.Debug.Log(x); + }); + + UnityEngine.Debug.Log("done"); + + + } + void Start() { Application.SetStackTraceLogType(LogType.Error, StackTraceLogType.Full); @@ -94,6 +114,8 @@ public class SandboxMain : MonoBehaviour ShowPlayerLoop.DumpPlayerLoop("Current", playerLoop); + Update2().Forget(); + //RunStandardDelayAsync().Forget(); //for (int i = 0; i < 14; i++) @@ -144,7 +166,7 @@ public class SandboxMain : MonoBehaviour UniTask foo = UniTask.FromResult(10); // foo.Status.IsCanceled - + Foo(foo); diff --git a/src/UniTask/Packages/manifest.json b/src/UniTask/Packages/manifest.json index c55fa3f..caf0872 100644 --- a/src/UniTask/Packages/manifest.json +++ b/src/UniTask/Packages/manifest.json @@ -1,7 +1,7 @@ { "dependencies": { "com.unity.addressables": "1.8.3", - "com.unity.ads": "2.0.8", + "com.unity.ads": "3.4.4", "com.unity.analytics": "3.3.5", "com.unity.collab-proxy": "1.2.16", "com.unity.ext.nunit": "1.0.0",