├── Functional.All ├── _._ └── Functional.All.csproj ├── Functional.All.NetStandard2 ├── _._ └── Functional.All.NetStandard2.csproj ├── Functional.Unions ├── UnionSerializationException.cs ├── UnionInvalidMatchException.cs ├── UnionNotInitializedException.cs ├── UnionHelpers.cs ├── Functional.Unions.csproj ├── UnionTask.cs ├── UnionTaskAwaiter.cs ├── UnionDefinitionBase.cs └── UnionDefinition.cs ├── Functional.Primitives ├── ResultNotInitializedException.cs ├── PartialOption.cs ├── Unit.cs ├── Functional.Primitives.csproj ├── OptionMatchExtensions.cs ├── Helpers.cs ├── ResultMatchExtensions.cs └── PartialResult.cs ├── Functional.AsyncEnumerables.NetStandard2 ├── IAsyncEnumerable.cs ├── Iterators │ ├── BasicIteratorContinuationType.cs │ ├── AppendIterator.cs │ ├── AppendTaskIterator.cs │ ├── DefaultIfEmptyIterator.cs │ ├── ConcatIterator.cs │ ├── ZipIterator.cs │ ├── ZipIteratorAsync.cs │ ├── BasicIterator.cs │ ├── BasicIteratorAsync.cs │ ├── BatchIterator.cs │ ├── SelectManyIterator.cs │ ├── SelectManyIteratorAsync.cs │ └── ConcurrentSelectIterator.cs ├── IAsyncEnumerator.cs ├── AsyncTaskAsyncEnumerable.cs ├── AsyncTaskEnumerable.cs ├── AsyncIteratorEnumerable.cs ├── AsyncPartition.cs ├── Functional.AsyncEnumerables.NetStandard2.csproj ├── AsyncEnumerator.cs ├── AsyncTaskEnumerator.cs ├── AsyncTaskAsyncEnumerator.cs ├── AsyncEnumerable.cs └── ReplayableAsyncEnumerable.cs ├── Functional.AsyncEnumerables ├── Iterators │ ├── BasicIteratorContinuationType.cs │ ├── AppendIterator.cs │ ├── AppendTaskIterator.cs │ ├── DefaultIfEmptyIterator.cs │ ├── ConcatIterator.cs │ ├── ZipIterator.cs │ ├── BasicIterator.cs │ ├── ZipIteratorAsync.cs │ ├── BasicIteratorAsync.cs │ ├── BatchIterator.cs │ ├── SelectManyIteratorAsync.cs │ └── SelectManyIterator.cs ├── Functional.AsyncEnumerables.csproj ├── AsyncTaskAsyncEnumerable.cs ├── AsyncPartition.cs ├── AsyncTaskEnumerable.cs ├── AsyncIteratorEnumerable.cs ├── AsyncEnumerator.cs ├── AsyncTaskEnumerator.cs ├── AsyncTaskAsyncEnumerator.cs ├── AsyncEnumerable.cs └── ReplayableAsyncEnumerable.cs ├── Functional.Tests ├── TestException.cs ├── Utilities │ ├── Helpers.cs │ ├── OptionTestExtensions.cs │ ├── SerializationUtility.cs │ ├── ResultTestExtensions.cs │ └── Assertions │ │ └── FunctionalPrimitiveAssertions.cs ├── IL │ ├── Instruction.cs │ └── ParsedMethodBody.cs ├── Options │ ├── OptionImplicitCastTests.cs │ ├── OptionSerializationTests.cs │ ├── OptionLinqSyntaxTests.cs │ ├── OptionLinqSyntaxWhereTests.cs │ └── OptionOfStringExtensionsTests.cs ├── AsyncEnumerables │ ├── ToCollectionTests.cs │ ├── BatchTests.cs │ ├── CastTests.cs │ ├── WhereTests.cs │ ├── AllTests.cs │ ├── ElementAtTests.cs │ ├── ElementAtOrDefaultTests.cs │ ├── AppendTests.cs │ ├── OfTypeTests.cs │ ├── MiscellaneousTests.cs │ ├── PickIntoTests.cs │ ├── SelectTests.cs │ ├── AnyTests.cs │ ├── FirstTests.cs │ ├── FirstOrDefaultTests.cs │ ├── ConcatTests.cs │ ├── SelectManyTests.cs │ ├── SkipTests.cs │ ├── TakeTests.cs │ ├── LinqSyntaxTests.cs │ ├── DefaultIfEmptyTests.cs │ ├── SingleTests.cs │ ├── SingleOrDefaultTests.cs │ └── ZipTests.cs ├── Results │ ├── ResultSerializationTests.cs │ ├── ResultImplicitCastTests.cs │ └── ResultLinqSyntaxTests.cs ├── Enumerables │ ├── PickIntoTests.cs │ ├── LinqSyntaxTests.cs │ ├── BatchTests.cs │ └── TakeUntilNoneTests.cs └── Functional.Tests.csproj ├── .github ├── actions │ └── publishPackages │ │ └── action.yml └── workflows │ ├── pullrequestbuild.yml │ └── build.yml ├── Directory.Build.props ├── Functional.Unions.AsyncEnumerables ├── UnionTask.cs ├── UnionTaskAwaiter.cs ├── Functional.Unions.AsyncEnumerables.csproj └── ReplayableEnumerable.cs ├── Functional.Unions.AsyncEnumerables.NetStandard2 ├── UnionTask.cs ├── UnionTaskAwaiter.cs ├── Functional.Unions.AsyncEnumerables.NetStandard2.csproj ├── ReplayableAsyncEnumerable.cs └── ReplayableEnumerable.cs ├── Functional.Enumerables.Extensions ├── Functional.Enumerables.Extensions.csproj ├── Partition.cs ├── IteratorEnumerable.cs ├── PartitionExtensions.cs ├── AsyncEnumerableExtensions.cs ├── Iterators │ └── BatchIterator.cs └── ReplayableEnumerable.cs ├── Functional.Common.Extensions ├── Functional.Common.Extensions.csproj ├── ResultPartition.cs ├── StackExtensions.cs ├── QueueExtensions.cs ├── DictionaryExtensions.cs └── ReplayableEnumerable.cs ├── Functional.Primitives.Extensions ├── Functional.Primitives.Extensions.csproj ├── OptionOfStringExtensions.cs └── OptionLinqSyntaxWhereExtensions.cs ├── Functional.Unions.Extensions └── Functional.Unions.Extensions.csproj ├── README.md ├── Functional.Primitives.AsyncEnumerables.NetStandard2 ├── AsyncResultPartition.cs ├── OptionEnumerable.cs ├── Functional.Primitives.AsyncEnumerables.NetStandard2.csproj ├── ResultEnumerable.cs ├── AsyncOptionEnumerable.cs └── ReplayableAsyncEnumerable.cs ├── Functional.Primitives.AsyncEnumerables ├── AsyncResultPartition.cs ├── Functional.Primitives.AsyncEnumerables.csproj ├── OptionEnumerable.cs ├── ResultEnumerable.cs ├── AsyncOptionEnumerable.cs └── ReplayableAsyncEnumerable.cs ├── doc └── collections.md └── LICENSE /Functional.All/_._: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Functional.All.NetStandard2/_._: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Functional.Unions/UnionSerializationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public class UnionSerializationException : Exception 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Functional.Unions/UnionInvalidMatchException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public class UnionInvalidMatchException : Exception 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Functional.Unions/UnionNotInitializedException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public class UnionNotInitializedException : Exception 8 | { 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Functional.Primitives/ResultNotInitializedException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | [AllowAllocations] 8 | public class ResultNotInitializedException : Exception 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/IAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public interface IAsyncEnumerable 8 | { 9 | IAsyncEnumerator GetEnumerator(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/BasicIteratorContinuationType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | internal enum BasicIteratorContinuationType 8 | { 9 | Take, 10 | Skip, 11 | Stop 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/BasicIteratorContinuationType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | internal enum BasicIteratorContinuationType 8 | { 9 | Take, 10 | Skip, 11 | Stop 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Functional.Tests/TestException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional.Tests 6 | { 7 | public class TestException : Exception 8 | { 9 | public TestException() { } 10 | 11 | public TestException(string message) : base(message) { } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/IAsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public interface IAsyncEnumerator 9 | { 10 | Task MoveNext(); 11 | 12 | T Current { get; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Functional.Unions/UnionHelpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | internal static class UnionHelpers 8 | { 9 | public static T CheckForNull(T value, string argumentName) 10 | { 11 | if (value == null) 12 | throw new ArgumentNullException(argumentName); 13 | 14 | return value; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /.github/actions/publishPackages/action.yml: -------------------------------------------------------------------------------- 1 | name: Publish NuGet 2 | 3 | inputs: 4 | PROJECTS: 5 | description: Projects to upload to NuGet 6 | required: true 7 | GITHUB_TOKEN: 8 | description: Github token 9 | required: true 10 | NUGET_KEY: 11 | description: API key for the NuGet feed 12 | required: true 13 | 14 | runs: 15 | using: node12 16 | main: index.js -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | latest 5 | https://github.com/JohannesMoersch/Functional 6 | Johannes Moersch + contributors 7 | MIT 8 | Copyright © 2020 Johannes Moersch 9 | 2.15.0 10 | 11 | 12 | -------------------------------------------------------------------------------- /Functional.Tests/Utilities/Helpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public static class Helpers 9 | { 10 | public static Task DelayedTask() 11 | => Task.Delay(10); 12 | 13 | public static async Task DelayedTask(TValue value) 14 | { 15 | await Task.Delay(10); 16 | 17 | return value; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Functional.Primitives/PartialOption.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public static class PartialOption 8 | { 9 | public struct None : IEquatable 10 | { 11 | public bool Equals(None other) 12 | => true; 13 | 14 | public override bool Equals(object obj) 15 | => obj is None; 16 | 17 | public override int GetHashCode() 18 | => -1937169414; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Functional.Tests/IL/Instruction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Reflection.Emit; 5 | using System.Text; 6 | 7 | namespace Functional.Tests.IL 8 | { 9 | public class Instruction 10 | { 11 | public OpCode OpCode { get; } 12 | 13 | public Option Operand { get; } 14 | 15 | public Instruction(OpCode opCode, Option operand) 16 | { 17 | OpCode = opCode; 18 | Operand = operand; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Functional.Unions/Functional.Unions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Unions 7 | This package contains discriminated union types for arbitrary unions of 2 to 8 types and associated factory methods. 8 | functional 9 | enable 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Functional.Primitives/Unit.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | [Serializable] 8 | public struct Unit : IEquatable 9 | { 10 | public static Unit Value { get; } = new Unit(); 11 | 12 | public bool Equals(Unit other) 13 | => true; 14 | 15 | public override int GetHashCode() 16 | => 0; 17 | 18 | public override bool Equals(object obj) 19 | => obj is Unit; 20 | 21 | public override string ToString() 22 | => "Unit"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.github/workflows/pullrequestbuild.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core Pull Request Build 2 | 3 | on: 4 | pull_request_target: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Setup .NET Core 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 6.0.100 19 | - name: Build with dotnet 20 | run: dotnet build --configuration Release 21 | - name: Run unit tests 22 | run: dotnet test 23 | -------------------------------------------------------------------------------- /Functional.Primitives/Functional.Primitives.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Primitives 7 | This package contains allocation free Option and Result discriminated union types and associated factory methods. 8 | functional 9 | enable 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables/UnionTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class UnionPartitionTask : IUnionTask 9 | { 10 | private readonly Task _task; 11 | 12 | public UnionPartitionTask(Task task) 13 | => _task = task ?? throw new ArgumentNullException(nameof(task)); 14 | 15 | public IUnionTaskAwaiter GetAwaiter() 16 | => new UnionPartitionTaskAwaiter(_task.GetAwaiter()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables.NetStandard2/UnionTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class UnionPartitionTask : IUnionTask 9 | { 10 | private readonly Task _task; 11 | 12 | public UnionPartitionTask(Task task) 13 | => _task = task ?? throw new ArgumentNullException(nameof(task)); 14 | 15 | public IUnionTaskAwaiter GetAwaiter() 16 | => new UnionPartitionTaskAwaiter(_task.GetAwaiter()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Functional.Unions/UnionTask.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public interface IUnionTask 9 | { 10 | IUnionTaskAwaiter GetAwaiter(); 11 | } 12 | 13 | internal class UnionTask : IUnionTask 14 | { 15 | private readonly Task _task; 16 | 17 | public UnionTask(Task task) 18 | => _task = task ?? throw new ArgumentNullException(nameof(task)); 19 | 20 | public IUnionTaskAwaiter GetAwaiter() 21 | => new UnionTaskAwaiter(_task.GetAwaiter()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/Functional.Enumerables.Extensions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Enumerables.Extensions 7 | This package contains extension methods for IEnumerable<T> and extension methods that add support for Task<IEnumerable<T>> to LINQ. 8 | functional 9 | enable 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Functional.Common.Extensions/Functional.Common.Extensions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Common.Extensions 7 | This package contains extension methods for .NET types. 8 | functional 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Functional.Tests/Options/OptionImplicitCastTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using FluentAssertions; 7 | using Xunit; 8 | 9 | namespace Functional.Tests.Options 10 | { 11 | public class OptionImplicitCastTests 12 | { 13 | [Fact] 14 | public void ImplicitSuccessCastFromValue() 15 | => OptionTestExtensions 16 | .AssertSome(1) 17 | .Should() 18 | .Be(1); 19 | 20 | [Fact] 21 | public void ImplicitFailureCastFromOptionFailure() 22 | => OptionTestExtensions 23 | .AssertNone(Option.None()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables/UnionTaskAwaiter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.CompilerServices; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | internal class UnionPartitionTaskAwaiter : IUnionTaskAwaiter 9 | { 10 | private readonly TaskAwaiter _task; 11 | 12 | public bool IsCompleted => _task.IsCompleted; 13 | 14 | public UnionPartitionTaskAwaiter(TaskAwaiter task) 15 | => _task = task; 16 | 17 | public T GetResult() 18 | => _task.GetResult(); 19 | 20 | public void OnCompleted(Action continuation) 21 | => _task.OnCompleted(continuation); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables.NetStandard2/UnionTaskAwaiter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.CompilerServices; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | internal class UnionPartitionTaskAwaiter : IUnionTaskAwaiter 9 | { 10 | private readonly TaskAwaiter _task; 11 | 12 | public bool IsCompleted => _task.IsCompleted; 13 | 14 | public UnionPartitionTaskAwaiter(TaskAwaiter task) 15 | => _task = task; 16 | 17 | public T GetResult() 18 | => _task.GetResult(); 19 | 20 | public void OnCompleted(Action continuation) 21 | => _task.OnCompleted(continuation); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Functional.Primitives.Extensions/Functional.Primitives.Extensions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Primitives.Extensions 7 | This package contains a suite of extension methods for working with Option and Result types. 8 | functional 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Functional.AsyncEnumerables.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | true 6 | Functional.AsyncEnumerables 7 | This package contains a framework and extension methods for asynchronous enumerables. 8 | functional 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncTaskAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncTaskAsyncEnumerable : IAsyncEnumerable 9 | { 10 | private readonly Task> _source; 11 | 12 | public AsyncTaskAsyncEnumerable(Task> source) 13 | => _source = source; 14 | 15 | public IAsyncEnumerator GetEnumerator() 16 | => new AsyncTaskAsyncEnumerator(GetTaskEnumerator()); 17 | 18 | private async Task> GetTaskEnumerator() 19 | => (await _source).GetEnumerator(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/ToCollectionTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.AsyncEnumerables 8 | { 9 | public class ToCollectionTests 10 | { 11 | [Fact] 12 | public Task ToArray() 13 | => Task 14 | .FromResult(new[] { 1, 2, 3 }) 15 | .AsAsyncEnumerable() 16 | .ToArray() 17 | .Should() 18 | .BeEquivalentTo(new[] { 1, 2, 3 }); 19 | 20 | [Fact] 21 | public Task ToList() 22 | => Task 23 | .FromResult(new[] { 1, 2, 3 }) 24 | .AsAsyncEnumerable() 25 | .ToList() 26 | .Should() 27 | .BeEquivalentTo(new[] { 1, 2, 3 }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/Partition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public struct Partition 8 | { 9 | public IEnumerable Matches { get; } 10 | 11 | public IEnumerable NonMatches { get; } 12 | 13 | internal Partition(IEnumerable matches, IEnumerable nonMatches) 14 | { 15 | Matches = matches ?? throw new ArgumentNullException(nameof(matches)); 16 | NonMatches = nonMatches ?? throw new ArgumentNullException(nameof(nonMatches)); 17 | } 18 | 19 | public void Deconstruct(out IEnumerable matches, out IEnumerable nonMatches) 20 | { 21 | matches = Matches; 22 | nonMatches = NonMatches; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Functional.Unions.Extensions/Functional.Unions.Extensions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Unions.Extensions 7 | This package contains extension methods for working with Union types. 8 | functional 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncTaskEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class AsyncTaskEnumerable : IAsyncEnumerable 10 | { 11 | private readonly Lazy>> _source; 12 | 13 | public AsyncTaskEnumerable(Func>> source) 14 | => _source = new Lazy>>(source, LazyThreadSafetyMode.ExecutionAndPublication); 15 | 16 | public IAsyncEnumerator GetEnumerator() 17 | => new AsyncTaskEnumerator(new Lazy>>(() => _source.Value.GetEnumerator(), LazyThreadSafetyMode.PublicationOnly)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncTaskAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class AsyncTaskAsyncEnumerable : IAsyncEnumerable 10 | { 11 | private readonly Task> _source; 12 | 13 | public AsyncTaskAsyncEnumerable(Task> source) 14 | => _source = source; 15 | 16 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) 17 | => new AsyncTaskAsyncEnumerator(GetTaskEnumerator()); 18 | 19 | private async Task> GetTaskEnumerator() 20 | => (await _source).GetAsyncEnumerator(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Functional.Unions/UnionTaskAwaiter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.CompilerServices; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | public interface IUnionTaskAwaiter : INotifyCompletion 9 | { 10 | bool IsCompleted { get; } 11 | 12 | T GetResult(); 13 | } 14 | 15 | internal class UnionTaskAwaiter : IUnionTaskAwaiter 16 | { 17 | private readonly TaskAwaiter _task; 18 | 19 | public bool IsCompleted => _task.IsCompleted; 20 | 21 | public UnionTaskAwaiter(TaskAwaiter task) 22 | => _task = task; 23 | 24 | public T GetResult() 25 | => _task.GetResult(); 26 | 27 | public void OnCompleted(Action continuation) 28 | => _task.OnCompleted(continuation); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Functional 2 | 3 | [![Actions Status](https://github.com/JohannesMoersch/Functional/workflows/.NET%20Core%20Build/badge.svg)](https://github.com/JohannesMoersch/Functional/actions) 4 | [![nuget](https://img.shields.io/nuget/v/Functional.All.svg)](https://www.nuget.org/packages/Functional.All/) 5 | 6 | ## Introduction 7 | 8 | `Functional` is a set of libraries that support functional programming patterns in C#. 9 | 10 | ## Sections 11 | 12 | - [`Option` Types](doc/option.md) 13 | - [`Result` Types](doc/result.md) 14 | - [`Result` Collections](doc/result-collections.md) 15 | - [Query Expressions](doc/query-expressions.md) 16 | - [Collections](doc/collections.md) 17 | - [Advanced Scenarios](doc/advanced-scenarios.md) 18 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncPartition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public struct AsyncPartition 8 | { 9 | public IAsyncEnumerable Matches { get; } 10 | 11 | public IAsyncEnumerable NonMatches { get; } 12 | 13 | internal AsyncPartition(IAsyncEnumerable matches, IAsyncEnumerable nonMatches) 14 | { 15 | Matches = matches ?? throw new ArgumentNullException(nameof(matches)); 16 | NonMatches = nonMatches ?? throw new ArgumentNullException(nameof(nonMatches)); 17 | } 18 | 19 | public void Deconstruct(out IAsyncEnumerable matches, out IAsyncEnumerable nonMatches) 20 | { 21 | matches = Matches; 22 | nonMatches = NonMatches; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncIteratorEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | internal class AsyncIteratorEnumerable : IAsyncEnumerable 8 | { 9 | private readonly Func> _iteratorFactory; 10 | 11 | public AsyncIteratorEnumerable(Func> iteratorFactory) 12 | => _iteratorFactory = iteratorFactory; 13 | 14 | public IAsyncEnumerator GetEnumerator() 15 | => _iteratorFactory.Invoke(); 16 | } 17 | 18 | internal static class AsyncIteratorEnumerable 19 | { 20 | public static IAsyncEnumerable Create(Func> enumeratorFactory) 21 | => new AsyncIteratorEnumerable(enumeratorFactory); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncPartition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public struct AsyncPartition 8 | { 9 | public IAsyncEnumerable Matches { get; } 10 | 11 | public IAsyncEnumerable NonMatches { get; } 12 | 13 | internal AsyncPartition(IAsyncEnumerable matches, IAsyncEnumerable nonMatches) 14 | { 15 | Matches = matches ?? throw new ArgumentNullException(nameof(matches)); 16 | NonMatches = nonMatches ?? throw new ArgumentNullException(nameof(nonMatches)); 17 | } 18 | 19 | public void Deconstruct(out IAsyncEnumerable matches, out IAsyncEnumerable nonMatches) 20 | { 21 | matches = Matches; 22 | nonMatches = NonMatches; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncTaskEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class AsyncTaskEnumerable : IAsyncEnumerable 10 | { 11 | private readonly Lazy>> _source; 12 | 13 | public AsyncTaskEnumerable(Func>> source) 14 | => _source = new Lazy>>(source, LazyThreadSafetyMode.ExecutionAndPublication); 15 | 16 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) 17 | => new AsyncTaskEnumerator(new Lazy>>(() => _source.Value.GetEnumerator(), LazyThreadSafetyMode.PublicationOnly)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/BatchTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.AsyncEnumerables 8 | { 9 | public class BatchTests 10 | { 11 | [Fact] 12 | public Task FullBatchesCorrectly() 13 | => Task 14 | .FromResult(new[] { 1, 2, 3, 4, 5, 6 }) 15 | .AsAsyncEnumerable() 16 | .Batch(2) 17 | .Should() 18 | .BeEquivalentTo(new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5, 6 } }); 19 | 20 | [Fact] 21 | public Task PartialBatchesCorrectly() 22 | => Task 23 | .FromResult(new[] { 1, 2, 3, 4, 5 }) 24 | .AsAsyncEnumerable() 25 | .Batch(2) 26 | .Should() 27 | .BeEquivalentTo(new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5 } }); 28 | } 29 | } -------------------------------------------------------------------------------- /Functional.Common.Extensions/ResultPartition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Functional 5 | { 6 | public readonly struct ResultPartition 7 | where TSuccess : notnull 8 | where TFailure : notnull 9 | { 10 | internal ResultPartition(IEnumerable successes, IEnumerable failures) 11 | { 12 | Successes = successes ?? throw new ArgumentNullException(nameof(successes)); 13 | Failures = failures ?? throw new ArgumentNullException(nameof(failures)); 14 | } 15 | 16 | public IEnumerable Successes { get; } 17 | public IEnumerable Failures { get; } 18 | 19 | public void Deconstruct(out IEnumerable successes, out IEnumerable failures) 20 | { 21 | successes = Successes; 22 | failures = Failures; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Functional.Tests/Results/ResultSerializationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using FluentAssertions; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.Results 8 | { 9 | public class ResultSerializationTests 10 | { 11 | [Fact] 12 | public void SuccessCanSerializeAndDeserialize() 13 | { 14 | var value = Result.Success("Some Test Value"); 15 | 16 | SerializationUtility 17 | .CloneViaSerialization(value) 18 | .Should() 19 | .BeEquivalentTo(value); 20 | } 21 | 22 | [Fact] 23 | public void FailureCanSerializeAndDeserialize() 24 | { 25 | var value = Result.Failure("Some Test Value"); 26 | 27 | SerializationUtility 28 | .CloneViaSerialization(value) 29 | .Should() 30 | .BeEquivalentTo(value); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Functional.AsyncEnumerables.NetStandard2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.AsyncEnumerables.NetStandard2 7 | This package contains a framework and extension methods for asynchronous enumerables. 8 | functional 9 | Functional.AsyncEnumerables 10 | Functional.AsyncEnumerables.NetStandard2 11 | enable 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/IteratorEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class IteratorEnumerable : IEnumerable 10 | { 11 | private readonly Func> _iteratorFactory; 12 | 13 | public IteratorEnumerable(Func> iteratorFactory) 14 | => _iteratorFactory = iteratorFactory; 15 | 16 | public IEnumerator GetEnumerator() 17 | => _iteratorFactory.Invoke(); 18 | 19 | IEnumerator IEnumerable.GetEnumerator() 20 | => _iteratorFactory.Invoke(); 21 | } 22 | 23 | internal static class IteratorEnumerable 24 | { 25 | public static IEnumerable Create(Func> enumeratorFactory) 26 | => new IteratorEnumerable(enumeratorFactory); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables.NetStandard2/AsyncResultPartition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Functional 4 | { 5 | public readonly struct AsyncResultPartition 6 | where TSuccess : notnull 7 | where TFailure : notnull 8 | { 9 | internal AsyncResultPartition(IAsyncEnumerable successes, IAsyncEnumerable failures) 10 | { 11 | Successes = successes ?? throw new ArgumentNullException(nameof(successes)); 12 | Failures = failures ?? throw new ArgumentNullException(nameof(failures)); 13 | } 14 | 15 | public IAsyncEnumerable Successes { get; } 16 | public IAsyncEnumerable Failures { get; } 17 | 18 | public void Deconstruct(out IAsyncEnumerable successes, out IAsyncEnumerable failures) 19 | { 20 | successes = Successes; 21 | failures = Failures; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncIteratorEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class AsyncIteratorEnumerable : IAsyncEnumerable 10 | { 11 | private readonly Func> _iteratorFactory; 12 | 13 | public AsyncIteratorEnumerable(Func> iteratorFactory) 14 | => _iteratorFactory = iteratorFactory; 15 | 16 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) 17 | => _iteratorFactory.Invoke(); 18 | } 19 | 20 | internal static class AsyncIteratorEnumerable 21 | { 22 | public static IAsyncEnumerable Create(Func> enumeratorFactory) 23 | => new AsyncIteratorEnumerable(enumeratorFactory); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables/AsyncResultPartition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Functional 5 | { 6 | public readonly struct AsyncResultPartition 7 | where TSuccess : notnull 8 | where TFailure : notnull 9 | { 10 | internal AsyncResultPartition(IAsyncEnumerable successes, IAsyncEnumerable failures) 11 | { 12 | Successes = successes ?? throw new ArgumentNullException(nameof(successes)); 13 | Failures = failures ?? throw new ArgumentNullException(nameof(failures)); 14 | } 15 | 16 | public IAsyncEnumerable Successes { get; } 17 | public IAsyncEnumerable Failures { get; } 18 | 19 | public void Deconstruct(out IAsyncEnumerable successes, out IAsyncEnumerable failures) 20 | { 21 | successes = Successes; 22 | failures = Failures; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables/Functional.Primitives.AsyncEnumerables.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | true 6 | Functional.Primitives.AsyncEnumerables 7 | This package contains a extension methods for primitives and async enumerables. 8 | functional 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/CastTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class CastTests 11 | { 12 | [Fact] 13 | public async Task CastWrongType() 14 | => await Assert 15 | .ThrowsAsync(() => 16 | AsyncEnumerable 17 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable().Cast()) 18 | .Cast() 19 | .AsEnumerable() 20 | ); 21 | 22 | [Fact] 23 | public async Task CastRightType() 24 | => ( 25 | await 26 | AsyncEnumerable 27 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable().Cast()) 28 | .Cast() 29 | .AsEnumerable() 30 | ) 31 | .Should() 32 | .BeEquivalentTo(new[] { 1, 2, 3 }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/WhereTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class WhereTests 11 | { 12 | [Fact] 13 | public async Task WhereOdd() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 18 | .Where(i => i % 2 == 1) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(new[] { 1, 3 }); 23 | 24 | [Fact] 25 | public async Task WhereIndexEven() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 30 | .Where((_, index) => index % 2 == 0) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 1, 3 }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Functional.Tests/Utilities/OptionTestExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public static class OptionTestExtensions 9 | { 10 | public static TSome AssertSome(this Option option) 11 | => option.Match(s => s, () => throw new Exception("Option should be some.")); 12 | 13 | public static async Task AssertSome(this Task> option) 14 | => (await option).Match(s => s, () => throw new Exception("Option should be some.")); 15 | 16 | public static void AssertNone(this Option option) 17 | => option.Match(s => throw new Exception("Option should be none."), () => 0); 18 | 19 | public static async Task AssertNone(this Task> option) 20 | => (await option).Match(s => throw new Exception("Option should be none."), () => 0); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables/Functional.Unions.AsyncEnumerables.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | true 6 | Functional.Unions.AsyncEnumerables 7 | This package contains a extension methods for unions and async enumerables. 8 | functional 9 | enable 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncEnumerator : IAsyncEnumerator 9 | { 10 | private readonly Lazy>> _enumerator; 11 | 12 | #pragma warning disable CS8603 // Possible null reference return. 13 | public T Current => _enumerator.IsValueCreated && _enumerator.Value.IsCompleted ? _enumerator.Value.Result.Current : default; 14 | #pragma warning restore CS8603 // Possible null reference return. 15 | 16 | internal AsyncEnumerator(Lazy>> enumerator) 17 | => _enumerator = enumerator; 18 | 19 | public async ValueTask DisposeAsync() 20 | { 21 | if (_enumerator.IsValueCreated) 22 | (await _enumerator.Value).Dispose(); 23 | } 24 | 25 | public async ValueTask MoveNextAsync() 26 | => (await _enumerator.Value).MoveNext(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Functional.Tests/IL/ParsedMethodBody.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | 6 | namespace Functional.Tests.IL 7 | { 8 | public class ParsedMethodBody 9 | { 10 | public Union Parent { get; } 11 | 12 | public IReadOnlyList Instructions { get; } 13 | 14 | private ParsedMethodBody(Union parent, Instruction[] instructions) 15 | { 16 | Parent = parent; 17 | Instructions = instructions; 18 | } 19 | 20 | public static ParsedMethodBody Create(ConstructorInfo constructor, Instruction[] instructions) 21 | => new ParsedMethodBody(Union.FromTypes().Create(constructor), instructions); 22 | 23 | public static ParsedMethodBody Create(MethodInfo method, Instruction[] instructions) 24 | => new ParsedMethodBody(Union.FromTypes().Create(method), instructions); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Functional.Primitives/OptionMatchExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | [EditorBrowsable(EditorBrowsableState.Never)] 10 | public static class OptionMatchExtensions 11 | { 12 | public static async Task Match(this Task> option, Func some, Func none) 13 | where TValue : notnull 14 | => (await option).Match(some, none); 15 | 16 | public static Task MatchAsync(this Option option, Func> some, Func> none) 17 | where TValue : notnull 18 | => option.Match(some, none); 19 | 20 | public static async Task MatchAsync(this Task> option, Func> some, Func> none) 21 | where TValue : notnull 22 | => await (await option).Match(some, none); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Functional.Tests/Utilities/SerializationUtility.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Runtime.Serialization.Formatters.Binary; 5 | using System.Text; 6 | 7 | namespace Functional 8 | { 9 | #pragma warning disable SYSLIB0011 // Type or member is obsolete 10 | public static class SerializationUtility 11 | { 12 | public static Stream Serialize(T obj) 13 | { 14 | var formatter = new BinaryFormatter(); 15 | var stream = new MemoryStream(); 16 | 17 | formatter.Serialize(stream, obj); 18 | 19 | stream.Position = 0; 20 | 21 | return stream; 22 | } 23 | 24 | public static T Deserialize(Stream stream) 25 | { 26 | var formatter = new BinaryFormatter(); 27 | 28 | return (T)formatter.Deserialize(stream); 29 | } 30 | 31 | public static T CloneViaSerialization(T obj) 32 | { 33 | using (var stream = Serialize(obj)) 34 | return Deserialize(stream); 35 | } 36 | } 37 | #pragma warning restore SYSLIB0011 // Type or member is obsolete 38 | } 39 | -------------------------------------------------------------------------------- /Functional.Common.Extensions/StackExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Text; 6 | 7 | namespace Functional 8 | { 9 | [EditorBrowsable(EditorBrowsableState.Never)] 10 | public static class StackExtensions 11 | { 12 | public static Option TryPeek(this Stack source) 13 | where T : notnull 14 | => source.Count > 0 ? Option.Some(source.Peek()) : Option.None(); 15 | 16 | public static Option TryPeek(this ConcurrentStack source) 17 | where T : notnull 18 | => source.TryPeek(out var value) ? Option.Some(value) : Option.None(); 19 | 20 | public static Option TryPop(this Stack source) 21 | where T : notnull 22 | => source.Count > 0 ? Option.Some(source.Pop()) : Option.None(); 23 | 24 | public static Option TryPop(this ConcurrentStack source) 25 | where T : notnull 26 | => source.TryPop(out var value) ? Option.Some(value) : Option.None(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Functional.Common.Extensions/QueueExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Text; 6 | 7 | namespace Functional 8 | { 9 | [EditorBrowsable(EditorBrowsableState.Never)] 10 | public static class QueueExtensions 11 | { 12 | public static Option TryPeek(this Queue source) 13 | where T : notnull 14 | => source.Count > 0 ? Option.Some(source.Peek()) : Option.None(); 15 | 16 | public static Option TryPeek(this ConcurrentQueue source) 17 | where T : notnull 18 | => source.TryPeek(out var value) ? Option.Some(value) : Option.None(); 19 | 20 | public static Option TryDequeue(this Queue source) 21 | where T : notnull 22 | => source.Count > 0 ? Option.Some(source.Dequeue()) : Option.None(); 23 | 24 | public static Option TryDequeue(this ConcurrentQueue source) 25 | where T : notnull 26 | => source.TryDequeue(out var value) ? Option.Some(value) : Option.None(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/AllTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class AllTests 11 | { 12 | [Fact] 13 | public async Task AllWhenEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .All(i => i == 0) 19 | ) 20 | .Should() 21 | .BeTrue(); 22 | 23 | [Fact] 24 | public async Task AllIsTrue() 25 | => ( 26 | await 27 | AsyncEnumerable 28 | .Create(Task.FromResult(new[] { 2, 4, 6 }).AsEnumerable()) 29 | .All(i => i % 2 == 0) 30 | ) 31 | .Should() 32 | .BeTrue(); 33 | 34 | [Fact] 35 | public async Task AllIsFalse() 36 | => ( 37 | await 38 | AsyncEnumerable 39 | .Create(Task.FromResult(new[] { 2, 3, 4 }).AsEnumerable()) 40 | .All(i => i % 2 == 0) 41 | ) 42 | .Should() 43 | .BeFalse(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Functional.Tests/Utilities/ResultTestExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public static class ResultTestExtensions 9 | { 10 | public static TSuccess AssertSuccess(this Result result) 11 | => result.Match(s => s, f => throw new Exception("Result should be success.")); 12 | 13 | public static async Task AssertSuccess(this Task> result) 14 | => (await result).Match(s => s, f => throw new Exception("Result should be success.")); 15 | 16 | public static TFailure AssertFailure(this Result result) 17 | => result.Match(s => throw new Exception("Result should be failure."), f => f); 18 | 19 | public static async Task AssertFailure(this Task> result) 20 | => (await result).Match(s => throw new Exception("Result should be failure."), f => f); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Functional.Tests/Results/ResultImplicitCastTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using FluentAssertions; 7 | using Xunit; 8 | 9 | namespace Functional.Tests.Results 10 | { 11 | public class ResultImplicitCastTests 12 | { 13 | [Fact] 14 | public void ImplicitSuccessCastFromValue() 15 | => ResultTestExtensions 16 | .AssertSuccess(1) 17 | .Should() 18 | .Be(1); 19 | 20 | [Fact] 21 | public void ImplicitSuccessCastFromResultSuccess() 22 | => ResultTestExtensions 23 | .AssertSuccess(Result.Success(1)) 24 | .Should() 25 | .Be(1); 26 | 27 | [Fact] 28 | public void ImplicitFailureCastFromValue() 29 | => ResultTestExtensions 30 | .AssertFailure("One") 31 | .Should() 32 | .Be("One"); 33 | 34 | [Fact] 35 | public void ImplicitFailureCastFromResultFailure() 36 | => ResultTestExtensions 37 | .AssertFailure(Result.Failure("One")) 38 | .Should() 39 | .Be("One"); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables/OptionEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | public interface IOptionEnumerable : IEnumerable> 9 | where TValue : notnull 10 | { 11 | } 12 | 13 | internal class OptionEnumerable : IOptionEnumerable 14 | where TValue : notnull 15 | { 16 | private readonly IEnumerable> _source; 17 | 18 | public OptionEnumerable(IEnumerable> source) 19 | => _source = source ?? throw new ArgumentNullException(nameof(source)); 20 | 21 | public IEnumerator> GetEnumerator() 22 | => _source.GetEnumerator(); 23 | 24 | IEnumerator IEnumerable.GetEnumerator() 25 | => _source.GetEnumerator(); 26 | } 27 | 28 | internal static class OptionEnumerable 29 | { 30 | public static IOptionEnumerable AsOptionEnumerable(this IEnumerable> source) 31 | where TValue : notnull 32 | => new OptionEnumerable(source); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables.NetStandard2/OptionEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | public interface IOptionEnumerable : IEnumerable> 9 | where TValue : notnull 10 | { 11 | } 12 | 13 | internal class OptionEnumerable : IOptionEnumerable 14 | where TValue : notnull 15 | { 16 | private readonly IEnumerable> _source; 17 | 18 | public OptionEnumerable(IEnumerable> source) 19 | => _source = source ?? throw new ArgumentNullException(nameof(source)); 20 | 21 | public IEnumerator> GetEnumerator() 22 | => _source.GetEnumerator(); 23 | 24 | IEnumerator IEnumerable.GetEnumerator() 25 | => _source.GetEnumerator(); 26 | } 27 | 28 | internal static class OptionEnumerable 29 | { 30 | public static IOptionEnumerable AsOptionEnumerable(this IEnumerable> source) 31 | where TValue : notnull 32 | => new OptionEnumerable(source); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Functional.Primitives/Helpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Functional 4 | { 5 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false)] 6 | internal class AllowAllocationsAttribute : Attribute { } 7 | 8 | internal static class DelegateCache 9 | { 10 | public static readonly Func Passthrough = x => x; 11 | } 12 | 13 | internal static class ResultFactoryHelpers 14 | { 15 | [AllowAllocations] 16 | public static TSuccess SuccessUnsafe(this Result source) 17 | where TSuccess : notnull 18 | where TFailure : notnull 19 | => source.Match(DelegateCache.Passthrough, _ => throw new InvalidOperationException("Not a successful result!")); 20 | 21 | [AllowAllocations] 22 | public static TFailure FailureUnsafe(this Result source) 23 | where TSuccess : notnull 24 | where TFailure : notnull 25 | => source.Match(_ => throw new InvalidOperationException("Not a faulted result!"), DelegateCache.Passthrough); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/ElementAtTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class ElementAtTests 11 | { 12 | [Fact] 13 | public async Task ElementAtEmpty() 14 | => await Assert 15 | .ThrowsAsync(() => 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .ElementAt(0) 19 | ); 20 | 21 | [Fact] 22 | public async Task ElementAtOutOfRange() 23 | => await Assert 24 | .ThrowsAsync(() => 25 | AsyncEnumerable 26 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 27 | .ElementAt(5) 28 | ); 29 | 30 | [Fact] 31 | public async Task ElementAtInRange() 32 | => ( 33 | await 34 | AsyncEnumerable 35 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 36 | .ElementAt(1) 37 | ) 38 | .Should() 39 | .Be(2); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/ElementAtOrDefaultTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class ElementAtOrDefaultTests 11 | { 12 | [Fact] 13 | public async Task ElementAtEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .ElementAtOrDefault(0) 19 | ) 20 | .Should() 21 | .Be(0); 22 | 23 | [Fact] 24 | public async Task ElementAtOutOfRange() 25 | => ( 26 | await 27 | AsyncEnumerable 28 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 29 | .ElementAtOrDefault(5) 30 | ) 31 | .Should() 32 | .Be(0); 33 | 34 | [Fact] 35 | public async Task ElementAtInRange() 36 | => ( 37 | await 38 | AsyncEnumerable 39 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 40 | .ElementAtOrDefault(1) 41 | ) 42 | .Should() 43 | .Be(2); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /doc/collections.md: -------------------------------------------------------------------------------- 1 | # Collections 2 | 3 | ## Perform Side Effects Using `Apply` and `Do` 4 | 5 | Instead of using a `foreach` loop, you can use `Apply` or `Do` to execute some `Action` or `Action` for each item in the collection. 6 | 7 | The `Apply` extension method returns no value. 8 | 9 | ``` csharp 10 | new { 1, 2, 3 }.Apply(i => Console.WriteLine(i)); 11 | 12 | // 1 13 | // 2 14 | // 3 15 | 16 | new { "ITEM1", "ITEM2", "ITEM3" }.Apply((item, index) => Console.WriteLine($"[{index}] = {item}")); 17 | 18 | // [0] = ITEM1 19 | // [1] = ITEM2 20 | // [2] = ITEM3 21 | ``` 22 | 23 | The `Do` extension method returns the original collection. This method is useful when you want to perform additional processing on the collection after applying side effects. 24 | 25 | ``` csharp 26 | // returns { 1, 2, 3 } 27 | new { 1, 2, 3 }.Do(i => Console.WriteLine(i)); 28 | 29 | // 1 30 | // 2 31 | // 3 32 | 33 | // returns { "ITEM1", "ITEM2", "ITEM3" } 34 | new { "ITEM1", "ITEM2", "ITEM3" }.Do((item, index) => Console.WriteLine($"[{index}] = {item}")); 35 | 36 | // [0] = ITEM1 37 | // [1] = ITEM2 38 | // [2] = ITEM3 39 | ``` 40 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables.NetStandard2/Functional.Primitives.AsyncEnumerables.NetStandard2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Primitives.AsyncEnumerables.NetStandard2 7 | This package contains a extension methods for primitives and async enumerables. 8 | functional 9 | Functional.Primitives.AsyncEnumerables 10 | Functional.Primitives.AsyncEnumerables.NetStandard2 11 | enable 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/AppendTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.AsyncEnumerables 8 | { 9 | public class AppendTests 10 | { 11 | [Fact] 12 | public Task AppendToEmpty() 13 | => new string[0] 14 | .AsAsyncEnumerable() 15 | .Append("Hello") 16 | .Should() 17 | .BeEquivalentTo(new[] { "Hello" }); 18 | 19 | [Fact] 20 | public Task AppendToNonEmpty() 21 | => new[] { "A", "B", "C" } 22 | .AsAsyncEnumerable() 23 | .Append("Hello") 24 | .Should() 25 | .BeEquivalentTo(new[] { "A", "B", "C", "Hello" }); 26 | 27 | [Fact] 28 | public Task AppendNull() 29 | => new[] { "A", "B", "C" } 30 | .AsAsyncEnumerable() 31 | .Append(null) 32 | .Should() 33 | .BeEquivalentTo(new[] { "A", "B", "C", null }); 34 | 35 | [Fact] 36 | public Task AppendTask() 37 | => new[] { "A", "B", "C" } 38 | .AsAsyncEnumerable() 39 | .AppendAsync(Task.FromResult("D")) 40 | .Should() 41 | .BeEquivalentTo(new[] { "A", "B", "C", "D" }); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 JohannesMoersch 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables.NetStandard2/Functional.Unions.AsyncEnumerables.NetStandard2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.Unions.AsyncEnumerables.NetStandard2 7 | This package contains a extension methods for unions and async enumerables. 8 | functional 9 | Functional.Unions.AsyncEnumerables 10 | Functional.Unions.AsyncEnumerables.NetStandard2 11 | enable 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncTaskEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncTaskEnumerator : IAsyncEnumerator 9 | { 10 | private readonly Lazy>> _enumerator; 11 | 12 | public T Current { get; private set; } 13 | 14 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 15 | internal AsyncTaskEnumerator(Lazy>> enumerator) 16 | => _enumerator = enumerator; 17 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | 19 | public ValueTask DisposeAsync() 20 | { 21 | if (_enumerator.IsValueCreated) 22 | _enumerator.Value.Dispose(); 23 | 24 | return default; 25 | } 26 | 27 | public async ValueTask MoveNextAsync() 28 | { 29 | var enumerator = _enumerator.Value; 30 | 31 | if (!enumerator.MoveNext()) 32 | return false; 33 | 34 | Current = await enumerator.Current; 35 | 36 | return true; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Functional.Primitives.Extensions/OptionOfStringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using System.Threading.Tasks; 4 | 5 | namespace Functional 6 | { 7 | public static class OptionOfStringExtensions 8 | { 9 | private static readonly Func _whereNonEmptyFunc = s => !string.IsNullOrEmpty(s); 10 | private static readonly Func _whereNonWhiteSpaceFunc = s => !string.IsNullOrWhiteSpace(s); 11 | 12 | 13 | [EditorBrowsable(EditorBrowsableState.Never)] 14 | public static Option WhereNonEmpty(this Option option) 15 | => option.Where(_whereNonEmptyFunc); 16 | 17 | [EditorBrowsable(EditorBrowsableState.Never)] 18 | public static Option WhereNonWhiteSpace(this Option option) 19 | => option.Where(_whereNonWhiteSpaceFunc); 20 | 21 | [EditorBrowsable(EditorBrowsableState.Never)] 22 | public static async Task> WhereNonEmpty(this Task> option) 23 | => (await option).WhereNonEmpty(); 24 | 25 | [EditorBrowsable(EditorBrowsableState.Never)] 26 | public static async Task> WhereNonWhiteSpace(this Task> option) 27 | => (await option).WhereNonWhiteSpace(); 28 | } 29 | } -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/OfTypeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class OfTypeTests 11 | { 12 | [Fact] 13 | public async Task OfTypeWrongType() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable().Cast()) 18 | .OfType() 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(new int[0]); 23 | 24 | [Fact] 25 | public async Task OfTypeRightType() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable().Cast()) 30 | .OfType() 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 1, 2, 3 }); 35 | 36 | [Fact] 37 | public async Task OfTypeMixedType() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new object[] { 1, 2.0, 3 }).AsEnumerable()) 42 | .OfType() 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(new[] { 1, 3 }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Functional.Tests/Enumerables/PickIntoTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.Enumerables 9 | { 10 | public class PickIntoTests 11 | { 12 | [Fact] 13 | public void EnumerablePickInto() 14 | { 15 | new[] { 1, 2, 3, 4, 5 } 16 | .PickInto(out var evens, i => i % 2 == 0) 17 | .Should() 18 | .BeEquivalentTo(new[] { 1, 3, 5 }); 19 | 20 | evens.Should().BeEquivalentTo(new[] { 2, 4 }); 21 | } 22 | 23 | [Fact] 24 | public async Task TaskEnumerablePickInto() 25 | { 26 | await Task.FromResult(new[] { 1, 2, 3, 4, 5 }) 27 | .AsEnumerable() 28 | .PickInto(out var evens, i => i % 2 == 0) 29 | .Should() 30 | .BeEquivalentTo(new[] { 1, 3, 5 }); 31 | 32 | await evens.Should().BeEquivalentTo(new[] { 2, 4 }); 33 | } 34 | 35 | [Fact] 36 | public async Task AsyncEnumerablePickInto() 37 | { 38 | await Task.FromResult(new[] { 1, 2, 3, 4, 5 }) 39 | .AsAsyncEnumerable() 40 | .PickInto(out var evens, i => i % 2 == 0) 41 | .Should() 42 | .BeEquivalentTo(new[] { 1, 3, 5 }); 43 | 44 | await evens.Should().BeEquivalentTo(new[] { 2, 4 }); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncEnumerator : IAsyncEnumerator 9 | { 10 | private static readonly Task _trueResult = Task.FromResult(true); 11 | 12 | private static readonly Task _falseResult = Task.FromResult(false); 13 | 14 | private readonly Lazy>> _enumerator; 15 | 16 | #pragma warning disable CS8603 // Possible null reference return. 17 | public T Current => _enumerator.IsValueCreated && _enumerator.Value.IsCompleted ? _enumerator.Value.Result.Current : default; 18 | #pragma warning restore CS8603 // Possible null reference return. 19 | 20 | internal AsyncEnumerator(Lazy>> enumerator) 21 | => _enumerator = enumerator; 22 | 23 | public Task MoveNext() 24 | { 25 | var enumerator = _enumerator.Value; 26 | 27 | if (enumerator.IsCompleted) 28 | return enumerator.Result.MoveNext() ? _trueResult : _falseResult; 29 | 30 | return enumerator.ContinueWith(t => t.Result.MoveNext(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables/ResultEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | public interface IResultEnumerable : IEnumerable> 9 | where TSuccess : notnull 10 | where TFailure : notnull 11 | { 12 | } 13 | 14 | internal class ResultEnumerable : IResultEnumerable 15 | where TSuccess : notnull 16 | where TFailure : notnull 17 | { 18 | private readonly IEnumerable> _source; 19 | 20 | public ResultEnumerable(IEnumerable> source) 21 | => _source = source ?? throw new ArgumentNullException(nameof(source)); 22 | 23 | public IEnumerator> GetEnumerator() 24 | => _source.GetEnumerator(); 25 | 26 | IEnumerator IEnumerable.GetEnumerator() 27 | => _source.GetEnumerator(); 28 | } 29 | 30 | internal static class ResultEnumerable 31 | { 32 | public static IResultEnumerable AsResultEnumerable(this IEnumerable> source) 33 | where TSuccess : notnull 34 | where TFailure : notnull 35 | => new ResultEnumerable(source); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncTaskEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncTaskEnumerator : IAsyncEnumerator 9 | { 10 | private static readonly Task _trueResult = Task.FromResult(true); 11 | 12 | private static readonly Task _falseResult = Task.FromResult(false); 13 | 14 | private readonly Lazy>> _enumerator; 15 | 16 | public T Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | internal AsyncTaskEnumerator(Lazy>> enumerator) 20 | => _enumerator = enumerator; 21 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 22 | 23 | public Task MoveNext() 24 | { 25 | var enumerator = _enumerator.Value; 26 | 27 | if (!enumerator.MoveNext()) 28 | return _falseResult; 29 | 30 | return enumerator.Current.ContinueWith(t => { Current = t.Result; return true; }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables.NetStandard2/ResultEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | public interface IResultEnumerable : IEnumerable> 9 | where TSuccess : notnull 10 | where TFailure : notnull 11 | { 12 | } 13 | 14 | internal class ResultEnumerable : IResultEnumerable 15 | where TSuccess : notnull 16 | where TFailure : notnull 17 | { 18 | private readonly IEnumerable> _source; 19 | 20 | public ResultEnumerable(IEnumerable> source) 21 | => _source = source ?? throw new ArgumentNullException(nameof(source)); 22 | 23 | public IEnumerator> GetEnumerator() 24 | => _source.GetEnumerator(); 25 | 26 | IEnumerator IEnumerable.GetEnumerator() 27 | => _source.GetEnumerator(); 28 | } 29 | 30 | internal static class ResultEnumerable 31 | { 32 | public static IResultEnumerable AsResultEnumerable(this IEnumerable> source) 33 | where TSuccess : notnull 34 | where TFailure : notnull 35 | => new ResultEnumerable(source); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/MiscellaneousTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class MiscellaneousTests 11 | { 12 | [Fact] 13 | public async Task SelectExecutedOnlyElementsEvaluatedByTake() 14 | { 15 | int selectCallCount = 0; 16 | 17 | await AsyncEnumerable 18 | .Create(Task.FromResult(new int[] { 1, 2, 3 }).AsEnumerable()) 19 | .Select(i => ++selectCallCount) 20 | .TakeWhile(i => i != 2) 21 | .AsEnumerable(); 22 | 23 | selectCallCount.Should().Be(2); 24 | } 25 | 26 | [Fact] 27 | public async Task MultipleEnumerationShouldBeEquivalent() 28 | { 29 | int invokeCount = 0; 30 | 31 | var sut = AsyncEnumerable.Create(() => Task.FromResult(new[] { ++invokeCount }).AsEnumerable()); 32 | 33 | (await sut.AsEnumerable()).Should().BeEquivalentTo(await sut.AsEnumerable()); 34 | } 35 | 36 | [Fact] 37 | public async Task EnumerationOfArrayOfTasksIsSuccessful() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(new[] { Task.FromResult(1), Task.FromResult(2), Task.FromResult(3) }) 42 | .AsEnumerable() 43 | ) 44 | .Should() 45 | .BeEquivalentTo(new[] { 1, 2, 3 }); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Functional.Primitives/ResultMatchExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | [EditorBrowsable(EditorBrowsableState.Never)] 10 | public static class ResultMatchExtensions 11 | { 12 | public static async Task Match(this Task> result, Func success, Func failure) 13 | where TSuccess : notnull 14 | where TFailure : notnull 15 | where TResult : notnull 16 | => (await result).Match(success, failure); 17 | 18 | public static Task MatchAsync(this Result result, Func> success, Func> failure) 19 | where TSuccess : notnull 20 | where TFailure : notnull 21 | where TResult : notnull 22 | => result.Match(success, failure); 23 | 24 | public static async Task MatchAsync(this Task> result, Func> success, Func> failure) 25 | where TSuccess : notnull 26 | where TFailure : notnull 27 | where TResult : notnull 28 | => await (await result).Match(success, failure); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Functional.Tests/Options/OptionSerializationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using FluentAssertions; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.Options 8 | { 9 | public class OptionSerializationTests 10 | { 11 | [Fact] 12 | public void SomeCanSerializeAndDeserialize() 13 | { 14 | var value = Option.Some("Some Test Value"); 15 | 16 | SerializationUtility 17 | .CloneViaSerialization(value) 18 | .Should() 19 | .BeEquivalentTo(value); 20 | } 21 | 22 | [Fact] 23 | public void NoneCanSerializeAndDeserialize() 24 | { 25 | var value = Option.None(); 26 | 27 | SerializationUtility 28 | .CloneViaSerialization(value) 29 | .Should() 30 | .BeEquivalentTo(value); 31 | } 32 | 33 | [Fact] 34 | public void SomeInterfaceCanSerializeAndDeserialize() 35 | { 36 | var value = Option.Some(new TestImplementation()); 37 | 38 | SerializationUtility 39 | .CloneViaSerialization(value) 40 | .Should() 41 | .BeEquivalentTo(value); 42 | } 43 | 44 | public interface ITestInterface { } 45 | 46 | [Serializable] 47 | public class TestImplementation : ITestInterface 48 | { 49 | public override int GetHashCode() => 0; 50 | 51 | public override bool Equals(object obj) => obj is TestImplementation; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/PickIntoTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class PickIntoTests 11 | { 12 | [Fact] 13 | public async Task EnumerablePickIntoAsync() 14 | { 15 | await new[] { 1, 2, 3, 4, 5 } 16 | .PickIntoAsync(out var evens, i => Task.FromResult(i % 2 == 0)) 17 | .Should() 18 | .BeEquivalentTo(new[] { 1, 3, 5 }); 19 | 20 | await evens.Should().BeEquivalentTo(new[] { 2, 4 }); 21 | } 22 | 23 | [Fact] 24 | public async Task TaskEnumerablePickIntoAsync() 25 | { 26 | await Task.FromResult(new[] { 1, 2, 3, 4, 5 }) 27 | .AsEnumerable() 28 | .PickIntoAsync(out var evens, i => Task.FromResult(i % 2 == 0)) 29 | .Should() 30 | .BeEquivalentTo(new[] { 1, 3, 5 }); 31 | 32 | await evens.Should().BeEquivalentTo(new[] { 2, 4 }); 33 | } 34 | 35 | [Fact] 36 | public async Task AsyncEnumerablePickIntoAsync() 37 | { 38 | await Task.FromResult(new[] { 1, 2, 3, 4, 5 }) 39 | .AsAsyncEnumerable() 40 | .PickIntoAsync(out var evens, i => Task.FromResult(i % 2 == 0)) 41 | .Should() 42 | .BeEquivalentTo(new[] { 1, 3, 5 }); 43 | 44 | await evens.Should().BeEquivalentTo(new[] { 2, 4 }); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/SelectTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class SelectTests 11 | { 12 | [Fact] 13 | public async Task SelectIndex() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 18 | .Select((_, index) => index) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(new[] { 0, 1, 2 }); 23 | 24 | [Fact] 25 | public async Task SelectCompletedTask() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 30 | .Select(value => value * 10) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 10, 20, 30 }); 35 | 36 | [Fact] 37 | public async Task SelectNonCompletedTask() 38 | { 39 | var task = new TaskCompletionSource>(); 40 | 41 | var result = AsyncEnumerable 42 | .Create(task.Task) 43 | .Select(value => value * 10) 44 | .AsEnumerable(); 45 | 46 | task.SetResult(new int[] { 1, 2, 3 }); 47 | 48 | (await result) 49 | .Should() 50 | .BeEquivalentTo(new[] { 10, 20, 30 }); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Setup .NET Core 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 6.0.100 19 | - name: Build with dotnet 20 | run: dotnet build --configuration Release 21 | - name: Run unit tests 22 | run: dotnet test 23 | - name: Publish on version change 24 | uses: ./.github/actions/publishPackages 25 | with: 26 | PROJECTS: 27 | Functional.All 28 | Functional.All.NetStandard2 29 | Functional.AsyncEnumerables 30 | Functional.AsyncEnumerables.NetStandard2 31 | Functional.Common.Extensions 32 | Functional.Enumerables.Extensions 33 | Functional.Primitives 34 | Functional.Primitives.AsyncEnumerables 35 | Functional.Primitives.AsyncEnumerables.NetStandard2 36 | Functional.Primitives.Extensions 37 | Functional.Unions 38 | Functional.Unions.AsyncEnumerables 39 | Functional.Unions.AsyncEnumerables.NetStandard2 40 | Functional.Unions.Extensions 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | NUGET_KEY: ${{ secrets.NUGET_KEY }} 43 | -------------------------------------------------------------------------------- /Functional.Primitives/PartialResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public static class PartialResult 8 | { 9 | public struct Success : IEquatable> 10 | where TSuccess : notnull 11 | { 12 | public TSuccess Value { get; } 13 | 14 | internal Success(TSuccess value) 15 | => Value = value; 16 | 17 | public override bool Equals(object? obj) 18 | => obj is Success result && Equals(result); 19 | 20 | public bool Equals(Success other) 21 | => EqualityComparer.Default.Equals(Value, other.Value); 22 | 23 | public override int GetHashCode() 24 | => -1937169414 + EqualityComparer.Default.GetHashCode(Value); 25 | } 26 | 27 | public struct Failure : IEquatable> 28 | where TFailure : notnull 29 | { 30 | public TFailure Value { get; } 31 | 32 | internal Failure(TFailure value) 33 | => Value = value; 34 | 35 | public override bool Equals(object? obj) 36 | => obj is Failure result && Equals(result); 37 | 38 | public bool Equals(Failure other) 39 | => EqualityComparer.Default.Equals(Value, other.Value); 40 | 41 | public override int GetHashCode() 42 | => -1937169414 + EqualityComparer.Default.GetHashCode(Value); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Functional.Tests/Utilities/Assertions/FunctionalPrimitiveAssertions.cs: -------------------------------------------------------------------------------- 1 | namespace Functional.Tests.Utilities.Assertions 2 | { 3 | /// 4 | /// Defines additional fluent assertion gateways for types defined in Functional.Primitives namespace. 5 | /// 6 | public static class FunctionalPrimitiveAssertions 7 | { 8 | /// 9 | /// Returns a object that can be used to assert the current . 10 | /// 11 | /// The success object type. 12 | /// The failure object type. 13 | /// The result. 14 | /// 15 | public static ResultTypeAssertions Should(this Result result) 16 | { 17 | return new ResultTypeAssertions(result); 18 | } 19 | 20 | /// 21 | /// Returns a object that is used to assert the current . 22 | /// 23 | /// The option type. 24 | /// The option. 25 | /// 26 | public static OptionTypeAssertions Should(this Option option) 27 | { 28 | return new OptionTypeAssertions(option); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/AppendIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AppendIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly TSource _element; 12 | 13 | private int _state = 0; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public AppendIterator(IAsyncEnumerable source, TSource element) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 21 | _element = element; 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async Task MoveNext() 26 | { 27 | if (_state == 0) 28 | { 29 | if (await _enumerator.MoveNext()) 30 | { 31 | Current = _enumerator.Current; 32 | return true; 33 | } 34 | else 35 | _state = 1; 36 | } 37 | 38 | if (_state == 1) 39 | { 40 | _state = 2; 41 | 42 | Current = _element; 43 | return true; 44 | } 45 | 46 | return false; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Functional.Tests/Enumerables/LinqSyntaxTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.Enumerables 8 | { 9 | public class LinqSyntaxTests 10 | { 11 | [Fact] 12 | public Task EnumerableAsyncSelect() 13 | => 14 | ( 15 | from num in new[] { 1, 2, 3 } 16 | select Task.FromResult(num) 17 | ) 18 | .ToArray() 19 | .Should() 20 | .BeEquivalentTo(new[] { 1, 2, 3 }); 21 | 22 | [Fact] 23 | public Task EnumerableEnumerableAsyncSelect() 24 | => 25 | ( 26 | from num in new[] { 1, 2, 3 } 27 | from other in new[] { 1, 2 } 28 | select Task.FromResult(num * other) 29 | ) 30 | .ToArray() 31 | .Should() 32 | .BeEquivalentTo(new[] { 1, 2, 2, 4, 3, 6 }); 33 | 34 | [Fact] 35 | public Task AsyncEnumerableAsyncSelect() 36 | => 37 | ( 38 | from num in new[] { 1, 2, 3 }.AsAsyncEnumerable() 39 | select Task.FromResult(num) 40 | ) 41 | .ToArray() 42 | .Should() 43 | .BeEquivalentTo(new[] { 1, 2, 3 }); 44 | 45 | [Fact] 46 | public Task AsyncEnumerableEnumerableAsyncSelect() 47 | => 48 | ( 49 | from num in new[] { 1, 2, 3 }.AsAsyncEnumerable() 50 | from other in new[] { 1, 2 } 51 | select Task.FromResult(num * other) 52 | ) 53 | .ToArray() 54 | .Should() 55 | .BeEquivalentTo(new[] { 1, 2, 2, 4, 3, 6 }); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncTaskAsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncTaskAsyncEnumerator : IAsyncEnumerator 9 | { 10 | private readonly Task> _asyncEnumeratorTask; 11 | 12 | private IAsyncEnumerator _asyncEnumerator; 13 | 14 | public T Current { get; private set; } 15 | 16 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 17 | public AsyncTaskAsyncEnumerator(Task> asyncEnumeratorTask) 18 | => _asyncEnumeratorTask = asyncEnumeratorTask ?? throw new ArgumentNullException(nameof(asyncEnumeratorTask)); 19 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 20 | 21 | public async Task MoveNext() 22 | { 23 | var enumerator = _asyncEnumerator ?? (_asyncEnumerator = (await _asyncEnumeratorTask)); 24 | 25 | if (await enumerator.MoveNext()) 26 | { 27 | Current = enumerator.Current; 28 | return true; 29 | } 30 | 31 | #pragma warning disable CS8601 // Possible null reference assignment. 32 | Current = default; 33 | #pragma warning restore CS8601 // Possible null reference assignment. 34 | return false; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/AppendTaskIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AppendTaskIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Task _element; 12 | 13 | private int _state = 0; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public AppendTaskIterator(IAsyncEnumerable source, Task element) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 21 | _element = element; 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async Task MoveNext() 26 | { 27 | if (_state == 0) 28 | { 29 | if (await _enumerator.MoveNext()) 30 | { 31 | Current = _enumerator.Current; 32 | return true; 33 | } 34 | else 35 | _state = 1; 36 | } 37 | 38 | if (_state == 1) 39 | { 40 | _state = 2; 41 | 42 | Current = await _element; 43 | return true; 44 | } 45 | 46 | return false; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/PartitionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Functional 10 | { 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public static class PartitionExtensions 13 | { 14 | public static Partition Partition(this IEnumerable source, Func predicate) 15 | { 16 | if (predicate == null) 17 | throw new ArgumentNullException(nameof(predicate)); 18 | 19 | var values = new ReplayableEnumerable<(bool matches, T value)>(source.Select(value => (predicate.Invoke(value), value))); 20 | 21 | return new Partition 22 | ( 23 | values.Where(set => set.matches).Select(set => set.value), 24 | values.Where(set => !set.matches).Select(set => set.value) 25 | ); 26 | } 27 | 28 | public static async Task> Partition(this Task> source, Func predicate) 29 | { 30 | if (predicate == null) 31 | throw new ArgumentNullException(nameof(predicate)); 32 | 33 | var values = new ReplayableEnumerable<(bool matches, T value)>((await source).Select(value => (predicate.Invoke(value), value))); 34 | 35 | return new Partition 36 | ( 37 | values.Where(set => set.matches).Select(set => set.value), 38 | values.Where(set => !set.matches).Select(set => set.value) 39 | ); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/AppendIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AppendIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly TSource _element; 12 | 13 | private int _state = 0; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public AppendIterator(IAsyncEnumerable source, TSource element) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 21 | _element = element; 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public ValueTask DisposeAsync() 26 | => _enumerator.DisposeAsync(); 27 | 28 | public async ValueTask MoveNextAsync() 29 | { 30 | if (_state == 0) 31 | { 32 | if (await _enumerator.MoveNextAsync()) 33 | { 34 | Current = _enumerator.Current; 35 | return true; 36 | } 37 | else 38 | _state = 1; 39 | } 40 | 41 | if (_state == 1) 42 | { 43 | _state = 2; 44 | 45 | Current = _element; 46 | return true; 47 | } 48 | 49 | return false; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncTaskAsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AsyncTaskAsyncEnumerator : IAsyncEnumerator 9 | { 10 | private readonly Task> _asyncEnumeratorTask; 11 | 12 | private IAsyncEnumerator? _asyncEnumerator; 13 | 14 | public T Current { get; private set; } 15 | 16 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 17 | public AsyncTaskAsyncEnumerator(Task> asyncEnumeratorTask) 18 | => _asyncEnumeratorTask = asyncEnumeratorTask ?? throw new ArgumentNullException(nameof(asyncEnumeratorTask)); 19 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 20 | 21 | public async ValueTask DisposeAsync() 22 | => await (_asyncEnumerator ??= await _asyncEnumeratorTask).DisposeAsync(); 23 | 24 | public async ValueTask MoveNextAsync() 25 | { 26 | var enumerator = _asyncEnumerator ??= await _asyncEnumeratorTask; 27 | 28 | if (await enumerator.MoveNextAsync()) 29 | { 30 | Current = enumerator.Current; 31 | return true; 32 | } 33 | 34 | #pragma warning disable CS8601 // Possible null reference assignment. 35 | Current = default; 36 | #pragma warning restore CS8601 // Possible null reference assignment. 37 | return false; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/AnyTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class AnyTests 11 | { 12 | [Fact] 13 | public async Task AnyWhenEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .Any() 19 | ) 20 | .Should() 21 | .BeFalse(); 22 | 23 | [Fact] 24 | public async Task AnyWhenNotEmpty() 25 | => ( 26 | await 27 | AsyncEnumerable 28 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 29 | .Any() 30 | ) 31 | .Should() 32 | .BeTrue(); 33 | 34 | [Fact] 35 | public async Task AnyWhenEmptyWithPredicate() 36 | => ( 37 | await 38 | AsyncEnumerable 39 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 40 | .Any(i => i == 0) 41 | ) 42 | .Should() 43 | .BeFalse(); 44 | 45 | [Fact] 46 | public async Task AnyIsTrue() 47 | => ( 48 | await 49 | AsyncEnumerable 50 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 51 | .Any(i => i % 2 == 0) 52 | ) 53 | .Should() 54 | .BeTrue(); 55 | 56 | [Fact] 57 | public async Task AnyIsFalse() 58 | => ( 59 | await 60 | AsyncEnumerable 61 | .Create(Task.FromResult(new[] { 1, 3, 5 }).AsEnumerable()) 62 | .Any(i => i % 2 == 0) 63 | ) 64 | .Should() 65 | .BeFalse(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/AppendTaskIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class AppendTaskIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Task _element; 12 | 13 | private int _state = 0; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public AppendTaskIterator(IAsyncEnumerable source, Task element) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 21 | _element = element; 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async ValueTask DisposeAsync() 26 | { 27 | await _element; 28 | 29 | await _enumerator.DisposeAsync(); 30 | } 31 | 32 | public async ValueTask MoveNextAsync() 33 | { 34 | if (_state == 0) 35 | { 36 | if (await _enumerator.MoveNextAsync()) 37 | { 38 | Current = _enumerator.Current; 39 | return true; 40 | } 41 | else 42 | _state = 1; 43 | } 44 | 45 | if (_state == 1) 46 | { 47 | _state = 2; 48 | 49 | Current = await _element; 50 | return true; 51 | } 52 | 53 | return false; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/DefaultIfEmptyIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class DefaultIfEmptyIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly TSource _defaultValue; 12 | 13 | private int _state; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public DefaultIfEmptyIterator(IAsyncEnumerable source, TSource defaultValue) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 21 | _defaultValue = defaultValue; 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async Task MoveNext() 26 | { 27 | switch (_state) 28 | { 29 | case 0: 30 | if (await _enumerator.MoveNext()) 31 | { 32 | _state = 1; 33 | Current = _enumerator.Current; 34 | } 35 | else 36 | { 37 | _state = 2; 38 | Current = _defaultValue; 39 | } 40 | return true; 41 | case 1: 42 | if (await _enumerator.MoveNext()) 43 | { 44 | Current = _enumerator.Current; 45 | return true; 46 | } 47 | _state = 2; 48 | break; 49 | } 50 | return false; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/AsyncEnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | [EditorBrowsable(EditorBrowsableState.Never)] 10 | public static class AsyncEnumerableExtensions 11 | { 12 | public static async Task ApplyAsync(this IEnumerable source, Func action) 13 | { 14 | if (action == null) 15 | throw new ArgumentNullException(nameof(action)); 16 | 17 | foreach (var item in source) 18 | await action.Invoke(item); 19 | } 20 | 21 | public static async Task ApplyAsync(this IEnumerable source, Func action) 22 | { 23 | if (action == null) 24 | throw new ArgumentNullException(nameof(action)); 25 | 26 | var index = 0; 27 | foreach (var item in source) 28 | await action.Invoke(item, index++); 29 | } 30 | 31 | public static async Task ApplyAsync(this Task> source, Func action) 32 | { 33 | if (action == null) 34 | throw new ArgumentNullException(nameof(action)); 35 | 36 | foreach (var item in await source) 37 | await action.Invoke(item); 38 | } 39 | 40 | public static async Task ApplyAsync(this Task> source, Func action) 41 | { 42 | if (action == null) 43 | throw new ArgumentNullException(nameof(action)); 44 | 45 | var index = 0; 46 | foreach (var item in await source) 47 | await action.Invoke(item, index++); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/FirstTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class FirstTests 11 | { 12 | [Fact] 13 | public async Task FirstEmpty() 14 | => await Assert 15 | .ThrowsAsync(() => 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .First() 19 | ); 20 | 21 | [Fact] 22 | public async Task FirstEmptyWithPredicate() 23 | => await Assert 24 | .ThrowsAsync(() => 25 | AsyncEnumerable 26 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 27 | .First(i => i == 0) 28 | ); 29 | 30 | [Fact] 31 | public async Task FirstWhereNoneMatchesPredicate() 32 | => await Assert 33 | .ThrowsAsync(() => 34 | AsyncEnumerable 35 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 36 | .First(i => i == 0) 37 | ); 38 | 39 | [Fact] 40 | public async Task FirstWithValue() 41 | => ( 42 | await 43 | AsyncEnumerable 44 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 45 | .First() 46 | ) 47 | .Should() 48 | .Be(1); 49 | 50 | [Fact] 51 | public async Task FirstEven() 52 | => ( 53 | await 54 | AsyncEnumerable 55 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 56 | .First(i => i % 2 == 0) 57 | ) 58 | .Should() 59 | .Be(2); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/ConcatIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ConcatIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumeratorOne; 11 | private readonly IAsyncEnumerator _enumeratorTwo; 12 | 13 | private int _state = 0; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public ConcatIterator(IAsyncEnumerable first, IAsyncEnumerable second) 19 | { 20 | _enumeratorOne = (first ?? throw new ArgumentNullException(nameof(first))).GetEnumerator(); 21 | _enumeratorTwo = (second ?? throw new ArgumentNullException(nameof(second))).GetEnumerator(); 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async Task MoveNext() 26 | { 27 | if (_state == 0) 28 | { 29 | if (await _enumeratorOne.MoveNext()) 30 | { 31 | Current = _enumeratorOne.Current; 32 | return true; 33 | } 34 | else 35 | _state = 1; 36 | } 37 | 38 | if (_state == 1) 39 | { 40 | if (await _enumeratorTwo.MoveNext()) 41 | { 42 | Current = _enumeratorTwo.Current; 43 | return true; 44 | } 45 | else 46 | _state = 2; 47 | } 48 | 49 | return false; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/FirstOrDefaultTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class FirstOrDefaultTests 11 | { 12 | [Fact] 13 | public async Task FirstEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .FirstOrDefault() 19 | ) 20 | .Should() 21 | .Be(0); 22 | 23 | [Fact] 24 | public async Task FirstEmptyWithPredicate() 25 | => ( 26 | await 27 | AsyncEnumerable 28 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 29 | .FirstOrDefault(i => i == 0) 30 | ) 31 | .Should() 32 | .Be(0); 33 | 34 | [Fact] 35 | public async Task FirstWhereNoneMatchesPredicate() 36 | => ( 37 | await 38 | AsyncEnumerable 39 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 40 | .FirstOrDefault(i => i == 0) 41 | ) 42 | .Should() 43 | .Be(0); 44 | 45 | [Fact] 46 | public async Task FirstWithValue() 47 | => ( 48 | await 49 | AsyncEnumerable 50 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 51 | .FirstOrDefault() 52 | ) 53 | .Should() 54 | .Be(1); 55 | 56 | [Fact] 57 | public async Task FirstEven() 58 | => ( 59 | await 60 | AsyncEnumerable 61 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 62 | .FirstOrDefault(i => i % 2 == 0) 63 | ) 64 | .Should() 65 | .Be(2); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Functional.Tests/Options/OptionLinqSyntaxTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.Options 9 | { 10 | public class OptionLinqSyntaxTests 11 | { 12 | [Fact] 13 | public Task OptionEnumerableAsyncSelect() 14 | => 15 | ( 16 | from num in new[] { 1, 2, 3 } 17 | from value in Option.Some(num) 18 | select Task.FromResult(value) 19 | ) 20 | .WhereSome() 21 | .Should() 22 | .BeEquivalentTo(new[] { 1, 2, 3 }); 23 | 24 | [Fact] 25 | public Task OptionEnumerableEnumerableAsyncSelect() 26 | => 27 | ( 28 | from num in new[] { 1, 2, 3 } 29 | from other in new[] { 1, 2 } 30 | from value in Option.Some(num * other) 31 | select Task.FromResult(value) 32 | ) 33 | .WhereSome() 34 | .Should() 35 | .BeEquivalentTo(new[] { 1, 2, 2, 4, 3, 6 }); 36 | 37 | [Fact] 38 | public Task OptionAsyncEnumerableAsyncSelect() 39 | => 40 | ( 41 | from num in new[] { 1, 2, 3 }.AsAsyncEnumerable() 42 | from value in Option.Some(num) 43 | select Task.FromResult(num) 44 | ) 45 | .WhereSome() 46 | .Should() 47 | .BeEquivalentTo(new[] { 1, 2, 3 }); 48 | 49 | [Fact] 50 | public Task OptionAsyncEnumerableEnumerableAsyncSelect() 51 | => 52 | ( 53 | from num in new[] { 1, 2, 3 }.AsAsyncEnumerable() 54 | from other in new[] { 1, 2 } 55 | from value in Option.Some(num * other) 56 | select Task.FromResult(value) 57 | ) 58 | .WhereSome() 59 | .Should() 60 | .BeEquivalentTo(new[] { 1, 2, 2, 4, 3, 6 }); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Functional.All/Functional.All.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | true 6 | Functional.All 7 | This package depends on all other packages in the Functional suite. 8 | functional 9 | false 10 | enable 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/DefaultIfEmptyIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class DefaultIfEmptyIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly TSource _defaultValue; 12 | 13 | private int _state; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public DefaultIfEmptyIterator(IAsyncEnumerable source, TSource defaultValue) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 21 | _defaultValue = defaultValue; 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public ValueTask DisposeAsync() 26 | => _enumerator.DisposeAsync(); 27 | 28 | public async ValueTask MoveNextAsync() 29 | { 30 | switch (_state) 31 | { 32 | case 0: 33 | if (await _enumerator.MoveNextAsync()) 34 | { 35 | _state = 1; 36 | Current = _enumerator.Current; 37 | } 38 | else 39 | { 40 | _state = 2; 41 | Current = _defaultValue; 42 | } 43 | return true; 44 | case 1: 45 | if (await _enumerator.MoveNextAsync()) 46 | { 47 | Current = _enumerator.Current; 48 | return true; 49 | } 50 | _state = 2; 51 | break; 52 | } 53 | return false; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/ConcatTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class ConcatTests 11 | { 12 | [Fact] 13 | public async Task ConcatEmptyToEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .Concat(Task.FromResult(Array.Empty()).AsEnumerable()) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(Array.Empty()); 23 | 24 | [Fact] 25 | public async Task ConcatItemsToEmpty() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 30 | .Concat(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 1, 2, 3 }); 35 | 36 | [Fact] 37 | public async Task ConcatEmptyToItems() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 42 | .Concat(Task.FromResult(Array.Empty()).AsEnumerable()) 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(new[] { 1, 2, 3 }); 47 | 48 | [Fact] 49 | public async Task ConcatItemsToItems() 50 | => ( 51 | await 52 | AsyncEnumerable 53 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 54 | .Concat(Task.FromResult(new[] { 4, 5, 6 }).AsEnumerable()) 55 | .AsEnumerable() 56 | ) 57 | .Should() 58 | .BeEquivalentTo(new[] { 1, 2, 3, 4, 5, 6 }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Functional.Tests/Functional.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/ZipIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ZipIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumeratorOne; 11 | private readonly IAsyncEnumerator _enumeratorTwo; 12 | private readonly Func _resultSelector; 13 | 14 | private bool _complete; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public ZipIterator(IAsyncEnumerable first, IAsyncEnumerable second, Func resultSelector) 20 | { 21 | _enumeratorOne = (first ?? throw new ArgumentNullException(nameof(first))).GetEnumerator(); 22 | _enumeratorTwo = (second ?? throw new ArgumentNullException(nameof(second))).GetEnumerator(); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async Task MoveNext() 28 | { 29 | if (_complete) 30 | return false; 31 | 32 | if (await _enumeratorOne.MoveNext() && await _enumeratorTwo.MoveNext()) 33 | { 34 | Current = _resultSelector.Invoke(_enumeratorOne.Current, _enumeratorTwo.Current); 35 | return true; 36 | } 37 | else 38 | _complete = true; 39 | 40 | return false; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/ZipIteratorAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ZipIteratorAsync : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumeratorOne; 11 | private readonly IAsyncEnumerator _enumeratorTwo; 12 | private readonly Func> _resultSelector; 13 | 14 | private bool _complete; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public ZipIteratorAsync(IAsyncEnumerable first, IAsyncEnumerable second, Func> resultSelector) 20 | { 21 | _enumeratorOne = (first ?? throw new ArgumentNullException(nameof(first))).GetEnumerator(); 22 | _enumeratorTwo = (second ?? throw new ArgumentNullException(nameof(second))).GetEnumerator(); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async Task MoveNext() 28 | { 29 | if (_complete) 30 | return false; 31 | 32 | if (await _enumeratorOne.MoveNext() && await _enumeratorTwo.MoveNext()) 33 | { 34 | Current = await _resultSelector.Invoke(_enumeratorOne.Current, _enumeratorTwo.Current); 35 | return true; 36 | } 37 | else 38 | _complete = true; 39 | 40 | return false; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/ConcatIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ConcatIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumeratorOne; 11 | private readonly IAsyncEnumerator _enumeratorTwo; 12 | 13 | private int _state = 0; 14 | 15 | public TSource Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public ConcatIterator(IAsyncEnumerable first, IAsyncEnumerable second) 19 | { 20 | _enumeratorOne = (first ?? throw new ArgumentNullException(nameof(first))).GetAsyncEnumerator(); 21 | _enumeratorTwo = (second ?? throw new ArgumentNullException(nameof(second))).GetAsyncEnumerator(); 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async ValueTask DisposeAsync() 26 | { 27 | await _enumeratorOne.DisposeAsync(); 28 | await _enumeratorTwo.DisposeAsync(); 29 | } 30 | 31 | public async ValueTask MoveNextAsync() 32 | { 33 | if (_state == 0) 34 | { 35 | if (await _enumeratorOne.MoveNextAsync()) 36 | { 37 | Current = _enumeratorOne.Current; 38 | return true; 39 | } 40 | else 41 | _state = 1; 42 | } 43 | 44 | if (_state == 1) 45 | { 46 | if (await _enumeratorTwo.MoveNextAsync()) 47 | { 48 | Current = _enumeratorTwo.Current; 49 | return true; 50 | } 51 | else 52 | _state = 2; 53 | } 54 | 55 | return false; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/SelectManyTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class SelectManyTests 11 | { 12 | [Fact] 13 | public async Task SelectManyEmptyOuter() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .SelectMany(a => a) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(new int[0]); 23 | 24 | [Fact] 25 | public async Task SelectManyInnerEmpty() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(new[] { Array.Empty(), Array.Empty() }).AsEnumerable()) 30 | .SelectMany(a => a) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new int[0]); 35 | 36 | [Fact] 37 | public async Task SelectManyInnerMixed() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new[] { new[] { 1, 2, 3 }, Array.Empty(), new[] { 4, 5, 6 } }).AsEnumerable()) 42 | .SelectMany(a => a) 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(new[] { 1, 2, 3, 4, 5, 6 }); 47 | 48 | [Fact] 49 | public async Task SelectManyInnerAsync() 50 | => ( 51 | await 52 | AsyncEnumerable 53 | .Create(Task.FromResult(new[] { Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable().AsAsyncEnumerable(), Array.Empty().AsAsyncEnumerable(), Task.FromResult(new[] { 4, 5, 6 }).AsEnumerable().AsAsyncEnumerable() }).AsEnumerable()) 54 | .SelectMany(a => a) 55 | .AsEnumerable() 56 | ) 57 | .Should() 58 | .BeEquivalentTo(new[] { 1, 2, 3, 4, 5, 6 }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/SkipTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class SkipTests 11 | { 12 | [Fact] 13 | public async Task SkipNone() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 18 | .Skip(0) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(new[] { 1, 2, 3 }); 23 | 24 | [Fact] 25 | public async Task SkipSome() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 30 | .Skip(2) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 3 }); 35 | 36 | [Fact] 37 | public async Task SkipAll() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 42 | .Skip(1000) 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(Array.Empty()); 47 | 48 | [Fact] 49 | public async Task SkipWhileOdd() 50 | => ( 51 | await 52 | AsyncEnumerable 53 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 54 | .SkipWhile(i => i % 2 == 1) 55 | .AsEnumerable() 56 | ) 57 | .Should() 58 | .BeEquivalentTo(new[] { 2, 3 }); 59 | 60 | [Fact] 61 | public async Task SkipWhileIndexLessThanOne() 62 | => ( 63 | await 64 | AsyncEnumerable 65 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 66 | .SkipWhile((_, index) => index < 1) 67 | .AsEnumerable() 68 | ) 69 | .Should() 70 | .BeEquivalentTo(new[] { 2, 3 }); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/TakeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class TakeTests 11 | { 12 | [Fact] 13 | public async Task TakeNone() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 18 | .Take(0) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(Array.Empty()); 23 | 24 | [Fact] 25 | public async Task TakeSome() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 30 | .Take(2) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 1, 2 }); 35 | 36 | [Fact] 37 | public async Task TakeAll() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 42 | .Take(1000) 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(new[] { 1, 2, 3 }); 47 | 48 | [Fact] 49 | public async Task TakeWhileOdd() 50 | => ( 51 | await 52 | AsyncEnumerable 53 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 54 | .TakeWhile(i => i % 2 == 1) 55 | .AsEnumerable() 56 | ) 57 | .Should() 58 | .BeEquivalentTo(new[] { 1 }); 59 | 60 | [Fact] 61 | public async Task TakeWhileIndexLessThanOne() 62 | => ( 63 | await 64 | AsyncEnumerable 65 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 66 | .TakeWhile((_, index) => index < 1) 67 | .AsEnumerable() 68 | ) 69 | .Should() 70 | .BeEquivalentTo(new[] { 1 }); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/BasicIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class BasicIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func<(TSource current, int index), (BasicIteratorContinuationType type, TResult? current)> _moveNext; 12 | 13 | private int _count; 14 | 15 | public TResult Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public BasicIterator(IAsyncEnumerable source, Func<(TSource current, int index), (BasicIteratorContinuationType type, TResult? current)> onNext) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 21 | _moveNext = onNext ?? throw new ArgumentNullException(nameof(onNext)); 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async Task MoveNext() 26 | { 27 | while (await _enumerator.MoveNext()) 28 | { 29 | var (type, current) = _moveNext.Invoke((_enumerator.Current, _count++)); 30 | 31 | #pragma warning disable CS8601 // Possible null reference assignment. 32 | switch (type) 33 | { 34 | case BasicIteratorContinuationType.Take: 35 | Current = current; 36 | return true; 37 | case BasicIteratorContinuationType.Skip: 38 | continue; 39 | } 40 | #pragma warning restore CS8601 // Possible null reference assignment. 41 | break; 42 | } 43 | 44 | return false; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Functional.Tests/Results/ResultLinqSyntaxTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.Results 9 | { 10 | public class OptionLinqSyntaxTests 11 | { 12 | [Fact] 13 | public Task ResultEnumerableAsyncSelect() 14 | => 15 | ( 16 | from num in new[] { 1, 2, 3 } 17 | from value in Result.Success(num) 18 | select Task.FromResult(value) 19 | ) 20 | .TakeUntilFailure() 21 | .AssertSuccess() 22 | .Should() 23 | .BeEquivalentTo(new[] { 1, 2, 3 }); 24 | 25 | [Fact] 26 | public Task ResultEnumerableEnumerableAsyncSelect() 27 | => 28 | ( 29 | from num in new[] { 1, 2, 3 } 30 | from other in new[] { 1, 2 } 31 | from value in Result.Success(num * other) 32 | select Task.FromResult(value) 33 | ) 34 | .TakeUntilFailure() 35 | .AssertSuccess() 36 | .Should() 37 | .BeEquivalentTo(new[] { 1, 2, 2, 4, 3, 6 }); 38 | 39 | [Fact] 40 | public Task ResultAsyncEnumerableAsyncSelect() 41 | => 42 | ( 43 | from num in new[] { 1, 2, 3 }.AsAsyncEnumerable() 44 | from value in Result.Success(num) 45 | select Task.FromResult(num) 46 | ) 47 | .TakeUntilFailure() 48 | .AssertSuccess() 49 | .Should() 50 | .BeEquivalentTo(new[] { 1, 2, 3 }); 51 | 52 | [Fact] 53 | public Task ResultAsyncEnumerableEnumerableAsyncSelect() 54 | => 55 | ( 56 | from num in new[] { 1, 2, 3 }.AsAsyncEnumerable() 57 | from other in new[] { 1, 2 } 58 | from value in Result.Success(num * other) 59 | select Task.FromResult(value) 60 | ) 61 | .TakeUntilFailure() 62 | .AssertSuccess() 63 | .Should() 64 | .BeEquivalentTo(new[] { 1, 2, 2, 4, 3, 6 }); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/BasicIteratorAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class BasicIteratorAsync : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func<(TSource current, int index), Task<(BasicIteratorContinuationType type, TResult? current)>> _moveNext; 12 | 13 | private int _count; 14 | 15 | public TResult Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public BasicIteratorAsync(IAsyncEnumerable source, Func<(TSource current, int index), Task<(BasicIteratorContinuationType type, TResult? current)>> onNext) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 21 | _moveNext = onNext ?? throw new ArgumentNullException(nameof(onNext)); 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public async Task MoveNext() 26 | { 27 | while (await _enumerator.MoveNext()) 28 | { 29 | var (type, current) = await _moveNext.Invoke((_enumerator.Current, _count++)); 30 | 31 | #pragma warning disable CS8601 // Possible null reference assignment. 32 | switch (type) 33 | { 34 | case BasicIteratorContinuationType.Take: 35 | Current = current; 36 | return true; 37 | case BasicIteratorContinuationType.Skip: 38 | continue; 39 | } 40 | #pragma warning restore CS8601 // Possible null reference assignment. 41 | break; 42 | } 43 | 44 | return false; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Functional.All.NetStandard2/Functional.All.NetStandard2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Functional.All.NetStandard2 7 | This package depends on all other packages in the Functional suite. 8 | functional 9 | false 10 | Functional.All 11 | Functional.All.NetStandard2 12 | enable 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/ZipIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ZipIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumeratorOne; 11 | private readonly IAsyncEnumerator _enumeratorTwo; 12 | private readonly Func _resultSelector; 13 | 14 | private bool _complete; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public ZipIterator(IAsyncEnumerable first, IAsyncEnumerable second, Func resultSelector) 20 | { 21 | _enumeratorOne = (first ?? throw new ArgumentNullException(nameof(first))).GetAsyncEnumerator(); 22 | _enumeratorTwo = (second ?? throw new ArgumentNullException(nameof(second))).GetAsyncEnumerator(); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async ValueTask DisposeAsync() 28 | { 29 | await _enumeratorOne.DisposeAsync(); 30 | await _enumeratorTwo.DisposeAsync(); 31 | } 32 | 33 | public async ValueTask MoveNextAsync() 34 | { 35 | if (_complete) 36 | return false; 37 | 38 | if (await _enumeratorOne.MoveNextAsync() && await _enumeratorTwo.MoveNextAsync()) 39 | { 40 | Current = _resultSelector.Invoke(_enumeratorOne.Current, _enumeratorTwo.Current); 41 | return true; 42 | } 43 | else 44 | _complete = true; 45 | 46 | return false; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/BasicIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class BasicIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func<(TSource current, int index), (BasicIteratorContinuationType type, TResult? current)> _moveNext; 12 | 13 | private int _count; 14 | 15 | public TResult Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public BasicIterator(IAsyncEnumerable source, Func<(TSource current, int index), (BasicIteratorContinuationType type, TResult? current)> onNext) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 21 | _moveNext = onNext ?? throw new ArgumentNullException(nameof(onNext)); 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public ValueTask DisposeAsync() 26 | => _enumerator.DisposeAsync(); 27 | 28 | public async ValueTask MoveNextAsync() 29 | { 30 | while (await _enumerator.MoveNextAsync()) 31 | { 32 | var (type, current) = _moveNext.Invoke((_enumerator.Current, _count++)); 33 | 34 | #pragma warning disable CS8601 // Possible null reference assignment. 35 | switch (type) 36 | { 37 | case BasicIteratorContinuationType.Take: 38 | Current = current; 39 | return true; 40 | case BasicIteratorContinuationType.Skip: 41 | continue; 42 | } 43 | #pragma warning restore CS8601 // Possible null reference assignment. 44 | break; 45 | } 46 | 47 | return false; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/BatchIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class BatchIterator : IAsyncEnumerator> 9 | { 10 | public IReadOnlyList Current { get; private set; } 11 | 12 | private readonly IAsyncEnumerator _enumerator; 13 | private readonly int _batchSize; 14 | 15 | private bool _ended; 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public BatchIterator(IAsyncEnumerator enumerator, int batchSize) 19 | { 20 | _enumerator = enumerator ?? throw new ArgumentNullException(nameof(enumerator)); 21 | _batchSize = batchSize; 22 | 23 | if (_batchSize <= 0) 24 | throw new ArgumentOutOfRangeException(nameof(batchSize), "Value must be greater than zero."); 25 | } 26 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 27 | 28 | public async Task MoveNext() 29 | { 30 | if (_ended) 31 | return false; 32 | 33 | var batch = new T[_batchSize]; 34 | int count = 0; 35 | while (count < _batchSize && await _enumerator.MoveNext()) 36 | batch[count++] = _enumerator.Current; 37 | 38 | if (count > 0) 39 | { 40 | if (count < _batchSize) 41 | { 42 | var temp = new T[count]; 43 | Array.Copy(batch, temp, count); 44 | batch = temp; 45 | } 46 | 47 | Current = batch; 48 | return true; 49 | } 50 | 51 | _ended = true; 52 | #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. 53 | Current = default; 54 | #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. 55 | return false; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/ZipIteratorAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ZipIteratorAsync : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumeratorOne; 11 | private readonly IAsyncEnumerator _enumeratorTwo; 12 | private readonly Func> _resultSelector; 13 | 14 | private bool _complete; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public ZipIteratorAsync(IAsyncEnumerable first, IAsyncEnumerable second, Func> resultSelector) 20 | { 21 | _enumeratorOne = (first ?? throw new ArgumentNullException(nameof(first))).GetAsyncEnumerator(); 22 | _enumeratorTwo = (second ?? throw new ArgumentNullException(nameof(second))).GetAsyncEnumerator(); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async ValueTask DisposeAsync() 28 | { 29 | await _enumeratorOne.DisposeAsync(); 30 | await _enumeratorTwo.DisposeAsync(); 31 | } 32 | 33 | public async ValueTask MoveNextAsync() 34 | { 35 | if (_complete) 36 | return false; 37 | 38 | if (await _enumeratorOne.MoveNextAsync() && await _enumeratorTwo.MoveNextAsync()) 39 | { 40 | Current = await _resultSelector.Invoke(_enumeratorOne.Current, _enumeratorTwo.Current); 41 | return true; 42 | } 43 | else 44 | _complete = true; 45 | 46 | return false; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/SelectManyIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class SelectManyIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func> _collectionSelector; 12 | private readonly Func _resultSelector; 13 | private int _count; 14 | private IAsyncEnumerator _subEnumerator; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public SelectManyIterator(IAsyncEnumerable source, Func> collectionSelector, Func resultSelector) 20 | { 21 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 22 | _collectionSelector = collectionSelector ?? throw new ArgumentNullException(nameof(collectionSelector)); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async Task MoveNext() 28 | { 29 | while (_subEnumerator == null || !await _subEnumerator.MoveNext()) 30 | { 31 | if (!await _enumerator.MoveNext()) 32 | return false; 33 | 34 | _subEnumerator = _collectionSelector.Invoke(_enumerator.Current, _count++).GetEnumerator(); 35 | } 36 | 37 | Current = _resultSelector.Invoke(_enumerator.Current, _subEnumerator.Current); 38 | 39 | return true; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/BasicIteratorAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class BasicIteratorAsync : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func<(TSource current, int index), Task<(BasicIteratorContinuationType type, TResult? current)>> _moveNext; 12 | 13 | private int _count; 14 | 15 | public TResult Current { get; private set; } 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public BasicIteratorAsync(IAsyncEnumerable source, Func<(TSource current, int index), Task<(BasicIteratorContinuationType type, TResult? current)>> onNext) 19 | { 20 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 21 | _moveNext = onNext ?? throw new ArgumentNullException(nameof(onNext)); 22 | } 23 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 24 | 25 | public ValueTask DisposeAsync() 26 | => _enumerator.DisposeAsync(); 27 | 28 | public async ValueTask MoveNextAsync() 29 | { 30 | while (await _enumerator.MoveNextAsync()) 31 | { 32 | var (type, current) = await _moveNext.Invoke((_enumerator.Current, _count++)); 33 | 34 | #pragma warning disable CS8601 // Possible null reference assignment. 35 | switch (type) 36 | { 37 | case BasicIteratorContinuationType.Take: 38 | Current = current; 39 | return true; 40 | case BasicIteratorContinuationType.Skip: 41 | continue; 42 | } 43 | #pragma warning restore CS8601 // Possible null reference assignment. 44 | break; 45 | } 46 | 47 | return false; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/SelectManyIteratorAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class SelectManyIteratorAsync : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func> _collectionSelector; 12 | private readonly Func> _resultSelector; 13 | private int _count; 14 | private IAsyncEnumerator _subEnumerator; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public SelectManyIteratorAsync(IAsyncEnumerable source, Func> collectionSelector, Func> resultSelector) 20 | { 21 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 22 | _collectionSelector = collectionSelector ?? throw new ArgumentNullException(nameof(collectionSelector)); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async Task MoveNext() 28 | { 29 | while (_subEnumerator == null || !await _subEnumerator.MoveNext()) 30 | { 31 | if (!await _enumerator.MoveNext()) 32 | return false; 33 | 34 | _subEnumerator = _collectionSelector.Invoke(_enumerator.Current, _count++).GetEnumerator(); 35 | } 36 | 37 | Current = await _resultSelector.Invoke(_enumerator.Current, _subEnumerator.Current); 38 | 39 | return true; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/BatchIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class BatchIterator : IAsyncEnumerator> 9 | { 10 | public IReadOnlyList Current { get; private set; } 11 | 12 | private readonly IAsyncEnumerator _enumerator; 13 | private readonly int _batchSize; 14 | 15 | private bool _ended; 16 | 17 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 18 | public BatchIterator(IAsyncEnumerator enumerator, int batchSize) 19 | { 20 | _enumerator = enumerator ?? throw new ArgumentNullException(nameof(enumerator)); 21 | _batchSize = batchSize; 22 | 23 | if (_batchSize <= 0) 24 | throw new ArgumentOutOfRangeException(nameof(batchSize), "Value must be greater than zero."); 25 | } 26 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 27 | 28 | public ValueTask DisposeAsync() 29 | => _enumerator.DisposeAsync(); 30 | 31 | public async ValueTask MoveNextAsync() 32 | { 33 | if (_ended) 34 | return false; 35 | 36 | var batch = new T[_batchSize]; 37 | int count = 0; 38 | while (count < _batchSize && await _enumerator.MoveNextAsync()) 39 | batch[count++] = _enumerator.Current; 40 | 41 | if (count > 0) 42 | { 43 | if (count < _batchSize) 44 | { 45 | var temp = new T[count]; 46 | Array.Copy(batch, temp, count); 47 | batch = temp; 48 | } 49 | 50 | Current = batch; 51 | return true; 52 | } 53 | 54 | _ended = true; 55 | #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. 56 | Current = default; 57 | #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. 58 | return false; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Functional.Primitives.Extensions/OptionLinqSyntaxWhereExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Functional 9 | { 10 | [EditorBrowsable(EditorBrowsableState.Never)] 11 | public static class OptionLinqSyntaxWhereExtensions 12 | { 13 | [EditorBrowsable(EditorBrowsableState.Never)] 14 | public static Option Where(this Option option, Func> predicate) 15 | where TValue : notnull 16 | { 17 | if (option.TryGetValue(out var some) && predicate.Invoke(some).TryGetValue(out var _)) 18 | return Option.Some(some); 19 | 20 | return Option.None(); 21 | } 22 | 23 | [EditorBrowsable(EditorBrowsableState.Never)] 24 | public static async Task> Where(this Task> option, Func> predicate) 25 | where TValue : notnull 26 | { 27 | if ((await option).TryGetValue(out var some) && predicate.Invoke(some).TryGetValue(out var _)) 28 | return Option.Some(some); 29 | 30 | return Option.None(); 31 | } 32 | 33 | [EditorBrowsable(EditorBrowsableState.Never)] 34 | public static async Task> Where(this Option option, Func>> predicate) 35 | where TValue : notnull 36 | { 37 | if (option.TryGetValue(out var some) && (await predicate.Invoke(some)).TryGetValue(out var _)) 38 | return Option.Some(some); 39 | 40 | return Option.None(); 41 | } 42 | 43 | [EditorBrowsable(EditorBrowsableState.Never)] 44 | public static async Task> Where(this Task> option, Func>> predicate) 45 | where TValue : notnull 46 | { 47 | if ((await option).TryGetValue(out var some) && (await predicate.Invoke(some)).TryGetValue(out var _)) 48 | return Option.Some(some); 49 | 50 | return Option.None(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Functional.Tests/Enumerables/BatchTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.Enumerables 9 | { 10 | public class BatchTests 11 | { 12 | [Fact] 13 | public void FullBatchesCorrectly() 14 | => new[] { 1, 2, 3, 4, 5, 6 } 15 | .Batch(2) 16 | .Should() 17 | .BeEquivalentTo(new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5, 6 } }); 18 | 19 | [Fact] 20 | public void PartialBatchesCorrectly() 21 | => new[] { 1, 2, 3, 4, 5 } 22 | .Batch(2) 23 | .Should() 24 | .BeEquivalentTo(new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5 } }); 25 | 26 | [Fact] 27 | public void MultipleEvaluationsSuccessful() 28 | { 29 | var batch = new[] { 1, 2, 3, 4 }.Batch(2).GetEnumerator(); 30 | 31 | batch.MoveNext().Should().BeTrue(); 32 | batch.Current.Should().BeEquivalentTo(new[] { 1, 2 }); 33 | batch.MoveNext().Should().BeTrue(); 34 | batch.Current.Should().BeEquivalentTo(new[] { 3, 4 }); 35 | batch.MoveNext().Should().BeFalse(); 36 | batch.Current.Should().BeNull(); 37 | 38 | batch.Reset(); 39 | 40 | batch.MoveNext().Should().BeTrue(); 41 | batch.Current.Should().BeEquivalentTo(new[] { 1, 2 }); 42 | batch.MoveNext().Should().BeTrue(); 43 | batch.Current.Should().BeEquivalentTo(new[] { 3, 4 }); 44 | batch.MoveNext().Should().BeFalse(); 45 | batch.Current.Should().BeNull(); 46 | } 47 | 48 | [Fact] 49 | public Task TaskFullBatchesCorrectly() 50 | => Task 51 | .FromResult(new[] { 1, 2, 3, 4, 5, 6 }) 52 | .AsEnumerable() 53 | .Batch(2) 54 | .Should() 55 | .BeEquivalentTo(new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5, 6 } }); 56 | 57 | [Fact] 58 | public Task TaskPartialBatchesCorrectly() 59 | => Task 60 | .FromResult(new[] { 1, 2, 3, 4, 5 }) 61 | .AsEnumerable() 62 | .Batch(2) 63 | .Should() 64 | .BeEquivalentTo(new[] { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 5 } }); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/Iterators/BatchIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | internal class BatchIterator : IEnumerator> 9 | { 10 | public IReadOnlyList Current { get; private set; } 11 | 12 | object IEnumerator.Current => Current; 13 | 14 | private readonly IEnumerator _enumerator; 15 | private readonly int _batchSize; 16 | 17 | private bool _ended; 18 | 19 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 20 | public BatchIterator(IEnumerator enumerator, int batchSize) 21 | { 22 | _enumerator = enumerator ?? throw new ArgumentNullException(nameof(enumerator)); 23 | _batchSize = batchSize; 24 | 25 | if (_batchSize <= 0) 26 | throw new ArgumentOutOfRangeException(nameof(batchSize), "Value must be greater than zero."); 27 | } 28 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 29 | 30 | public void Dispose() 31 | => _enumerator.Dispose(); 32 | 33 | public bool MoveNext() 34 | { 35 | if (_ended) 36 | return false; 37 | 38 | var batch = new T[_batchSize]; 39 | int count = 0; 40 | while (count < _batchSize && _enumerator.MoveNext()) 41 | batch[count++] = _enumerator.Current; 42 | 43 | if (count > 0) 44 | { 45 | if (count < _batchSize) 46 | { 47 | var temp = new T[count]; 48 | Array.Copy(batch, temp, count); 49 | batch = temp; 50 | } 51 | 52 | Current = batch; 53 | return true; 54 | } 55 | 56 | _ended = true; 57 | #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. 58 | Current = default; 59 | #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. 60 | return false; 61 | } 62 | 63 | public void Reset() 64 | { 65 | _enumerator.Reset(); 66 | _ended = false; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/AsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Functional 9 | { 10 | internal class AsyncEnumerable : IAsyncEnumerable 11 | { 12 | private readonly Lazy>> _source; 13 | 14 | public AsyncEnumerable(Func>> source) 15 | => _source = new Lazy>>(source, LazyThreadSafetyMode.ExecutionAndPublication); 16 | 17 | public IAsyncEnumerator GetEnumerator() 18 | => new AsyncEnumerator(new Lazy>>(() => _source.Value.ContinueWith(t => t.Result.GetEnumerator(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously), LazyThreadSafetyMode.PublicationOnly)); 19 | } 20 | 21 | public static class AsyncEnumerable 22 | { 23 | public static IAsyncEnumerable Create(IEnumerable source) 24 | => new AsyncEnumerable(() => Task.FromResult(source)); 25 | 26 | public static IAsyncEnumerable Create(Task> source) 27 | => new AsyncEnumerable(() => source); 28 | 29 | public static IAsyncEnumerable Create(Task source) 30 | => new AsyncEnumerable(async () => (await source).AsEnumerable()); 31 | 32 | public static IAsyncEnumerable Create(IEnumerable> source) 33 | => new AsyncTaskEnumerable(() => source); 34 | 35 | public static IAsyncEnumerable Create(Task> source) 36 | => new AsyncTaskAsyncEnumerable(source); 37 | 38 | public static IAsyncEnumerable Create(Func>> source) 39 | => new AsyncTaskEnumerable(source); 40 | 41 | public static IAsyncEnumerable Create(Func>> source) 42 | => new AsyncEnumerable(source); 43 | 44 | public static IAsyncEnumerable Repeat(T element, int count) 45 | => Create(Enumerable.Repeat(element, count)); 46 | 47 | public static IAsyncEnumerable Repeat(Task element, int count) 48 | => Create(Enumerable.Repeat(element, count)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/LinqSyntaxTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class LinqSyntaxTests 11 | { 12 | [Fact] 13 | public async Task FromAsyncAndAsync() 14 | => 15 | ( 16 | await 17 | ( 18 | from a in new[] { 1, 2, 3 }.AsAsyncEnumerable() 19 | from b in new[] { 4, 5, 6 }.AsAsyncEnumerable() 20 | select a + b 21 | ) 22 | .AsEnumerable() 23 | ) 24 | .Should() 25 | .BeEquivalentTo(new[] { 5, 6, 7, 6, 7, 8, 7, 8, 9 }); 26 | 27 | [Fact] 28 | public async Task FromEnumerableAndAsync() 29 | => 30 | ( 31 | await 32 | ( 33 | from a in new[] { 1, 2, 3 } 34 | from b in new[] { 4, 5, 6 }.AsAsyncEnumerable() 35 | select a + b 36 | ) 37 | .AsEnumerable() 38 | ) 39 | .Should() 40 | .BeEquivalentTo(new[] { 5, 6, 7, 6, 7, 8, 7, 8, 9 }); 41 | 42 | [Fact] 43 | public async Task FromTaskEnumerableAndAsync() 44 | => 45 | ( 46 | await 47 | ( 48 | from a in Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable() 49 | from b in new[] { 4, 5, 6 }.AsAsyncEnumerable() 50 | select a + b 51 | ) 52 | .AsEnumerable() 53 | ) 54 | .Should() 55 | .BeEquivalentTo(new[] { 5, 6, 7, 6, 7, 8, 7, 8, 9 }); 56 | 57 | [Fact] 58 | public async Task FromAsyncAndEnumerable() 59 | => 60 | ( 61 | await 62 | ( 63 | from a in new[] { 1, 2, 3 }.AsAsyncEnumerable() 64 | from b in new[] { 4, 5, 6 } 65 | select a + b 66 | ) 67 | .AsEnumerable() 68 | ) 69 | .Should() 70 | .BeEquivalentTo(new[] { 5, 6, 7, 6, 7, 8, 7, 8, 9 }); 71 | 72 | [Fact] 73 | public async Task FromAsyncAndTaskEnumerable() 74 | => 75 | ( 76 | await 77 | ( 78 | from a in new[] { 1, 2, 3 }.AsAsyncEnumerable() 79 | from b in Task.FromResult(new[] { 4, 5, 6 }).AsEnumerable() 80 | select a + b 81 | ) 82 | .AsEnumerable() 83 | ) 84 | .Should() 85 | .BeEquivalentTo(new[] { 5, 6, 7, 6, 7, 8, 7, 8, 9 }); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/SelectManyIteratorAsync.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class SelectManyIteratorAsync : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func> _collectionSelector; 12 | private readonly Func> _resultSelector; 13 | private int _count; 14 | private IAsyncEnumerator? _subEnumerator; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public SelectManyIteratorAsync(IAsyncEnumerable source, Func> collectionSelector, Func> resultSelector) 20 | { 21 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 22 | _collectionSelector = collectionSelector ?? throw new ArgumentNullException(nameof(collectionSelector)); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async ValueTask DisposeAsync() 28 | { 29 | if (_subEnumerator != null) 30 | await _subEnumerator.DisposeAsync(); 31 | 32 | await _enumerator.DisposeAsync(); 33 | } 34 | 35 | public async ValueTask MoveNextAsync() 36 | { 37 | while (_subEnumerator == null || !await _subEnumerator.MoveNextAsync()) 38 | { 39 | if (!await _enumerator.MoveNextAsync()) 40 | return false; 41 | 42 | _subEnumerator = _collectionSelector.Invoke(_enumerator.Current, _count++).GetAsyncEnumerator(); 43 | } 44 | 45 | Current = await _resultSelector.Invoke(_enumerator.Current, _subEnumerator.Current); 46 | 47 | return true; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.Common.Extensions/DictionaryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | 6 | namespace Functional 7 | { 8 | [EditorBrowsable(EditorBrowsableState.Never)] 9 | public static class DictionaryExtensions 10 | { 11 | public static Option TryGetValue(this Dictionary source, TKey key) 12 | where TValue : notnull 13 | { 14 | if (source.TryGetValue(key, out var value) && value != null) 15 | return Option.Some(value); 16 | 17 | return Option.None(); 18 | } 19 | 20 | public static Option TryGetValue(this ConcurrentDictionary source, TKey key) 21 | where TValue : notnull 22 | { 23 | if (source.TryGetValue(key, out var value) && value != null) 24 | return Option.Some(value); 25 | 26 | return Option.None(); 27 | } 28 | 29 | public static Option TryGetValue(this IDictionary source, TKey key) 30 | where TValue : notnull 31 | { 32 | if (source.TryGetValue(key, out var value) && value != null) 33 | return Option.Some(value); 34 | 35 | return Option.None(); 36 | } 37 | 38 | public static Option TryGetValue(this IReadOnlyDictionary source, TKey key) 39 | where TValue : notnull 40 | { 41 | if (source.TryGetValue(key, out var value) && value != null) 42 | return Option.Some(value); 43 | 44 | return Option.None(); 45 | } 46 | 47 | public static Option TryRemove(this ConcurrentDictionary source, TKey key) 48 | where TValue : notnull 49 | { 50 | if (source.TryRemove(key, out var value) && value != null) 51 | return Option.Some(value); 52 | 53 | return Option.None(); 54 | } 55 | 56 | public static Option TryRemove(this ConcurrentDictionary source, TKey key) 57 | where TValue : struct 58 | { 59 | if (source.TryRemove(key, out var value) && value is TValue v) 60 | return Option.Some(v); 61 | 62 | return Option.None(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/AsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Functional 9 | { 10 | internal class AsyncEnumerable : IAsyncEnumerable 11 | { 12 | private readonly Lazy>> _source; 13 | 14 | public AsyncEnumerable(Func>> source) 15 | => _source = new Lazy>>(source, LazyThreadSafetyMode.ExecutionAndPublication); 16 | 17 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) 18 | => new AsyncEnumerator(new Lazy>>(() => _source.Value.ContinueWith(t => t.Result.GetEnumerator(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously), LazyThreadSafetyMode.PublicationOnly)); 19 | } 20 | 21 | public static class AsyncEnumerable 22 | { 23 | public static IAsyncEnumerable Create(IEnumerable source) 24 | => new AsyncEnumerable(() => Task.FromResult(source)); 25 | 26 | public static IAsyncEnumerable Create(Task> source) 27 | => new AsyncEnumerable(() => source); 28 | 29 | public static IAsyncEnumerable Create(Task source) 30 | => new AsyncEnumerable(async () => (await source).AsEnumerable()); 31 | 32 | public static IAsyncEnumerable Create(IEnumerable> source) 33 | => new AsyncTaskEnumerable(() => source); 34 | 35 | public static IAsyncEnumerable Create(Task> source) 36 | => new AsyncTaskAsyncEnumerable(source); 37 | 38 | public static IAsyncEnumerable Create(Func>> source) 39 | => new AsyncTaskEnumerable(source); 40 | 41 | public static IAsyncEnumerable Create(Func>> source) 42 | => new AsyncEnumerable(source); 43 | 44 | public static IAsyncEnumerable Repeat(T element, int count) 45 | => Create(Enumerable.Repeat(element, count)); 46 | 47 | public static IAsyncEnumerable Repeat(Task element, int count) 48 | => Create(Enumerable.Repeat(element, count)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/DefaultIfEmptyTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class DefaultIfEmptyTests 11 | { 12 | [Fact] 13 | public async Task DefaultWhenEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .DefaultIfEmpty() 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(new[] { 0 }); 23 | 24 | [Fact] 25 | public async Task DefaultWithSpecifiedValueWhenEmpty() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 30 | .DefaultIfEmpty(10) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(new[] { 10 }); 35 | 36 | [Fact] 37 | public async Task DefaultWithSingleValue() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 42 | .DefaultIfEmpty() 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(new[] { 1, 2, 3 }); 47 | 48 | [Fact] 49 | public async Task DefaultWithSpecifiedValueWithSingleValue() 50 | => ( 51 | await 52 | AsyncEnumerable 53 | .Create(Task.FromResult(new[] { 1 }).AsEnumerable()) 54 | .DefaultIfEmpty(10) 55 | .AsEnumerable() 56 | ) 57 | .Should() 58 | .BeEquivalentTo(new[] { 1 }); 59 | 60 | [Fact] 61 | public async Task DefaultWithTwoValues() 62 | => ( 63 | await 64 | AsyncEnumerable 65 | .Create(Task.FromResult(new[] { 1, 2 }).AsEnumerable()) 66 | .DefaultIfEmpty() 67 | .AsEnumerable() 68 | ) 69 | .Should() 70 | .BeEquivalentTo(new[] { 1, 2 }); 71 | 72 | [Fact] 73 | public async Task DefaultWithSpecifiedValueWithTwoValues() 74 | => ( 75 | await 76 | AsyncEnumerable 77 | .Create(Task.FromResult(new[] { 1, 2 }).AsEnumerable()) 78 | .DefaultIfEmpty(10) 79 | .AsEnumerable() 80 | ) 81 | .Should() 82 | .BeEquivalentTo(new[] { 1, 2 }); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/SingleTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class SingleTests 11 | { 12 | [Fact] 13 | public async Task SingleEmpty() 14 | => await Assert 15 | .ThrowsAsync(() => 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .Single() 19 | ); 20 | 21 | [Fact] 22 | public async Task SingleEmptyWithPredicate() 23 | => await Assert 24 | .ThrowsAsync(() => 25 | AsyncEnumerable 26 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 27 | .Single(i => i == 0) 28 | ); 29 | 30 | [Fact] 31 | public async Task SingleWhereNoneMatchesPredicate() 32 | => await Assert 33 | .ThrowsAsync(() => 34 | AsyncEnumerable 35 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 36 | .Single(i => i == 0) 37 | ); 38 | 39 | [Fact] 40 | public async Task SingleWithOneValue() 41 | => ( 42 | await 43 | AsyncEnumerable 44 | .Create(Task.FromResult(new[] { 1 }).AsEnumerable()) 45 | .Single() 46 | ) 47 | .Should() 48 | .Be(1); 49 | 50 | [Fact] 51 | public async Task SingleWithOneValueMatchingPredicate() 52 | => ( 53 | await 54 | AsyncEnumerable 55 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 56 | .Single(i => i % 2 == 0) 57 | ) 58 | .Should() 59 | .Be(2); 60 | 61 | [Fact] 62 | public async Task SingleWithTwoValues() 63 | => await Assert 64 | .ThrowsAsync(() => 65 | AsyncEnumerable 66 | .Create(Task.FromResult(new[] { 1, 2 }).AsEnumerable()) 67 | .Single() 68 | ); 69 | 70 | [Fact] 71 | public async Task SingleWithTwoValuesMatchingPredicate() 72 | => await Assert 73 | .ThrowsAsync(() => 74 | AsyncEnumerable 75 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 76 | .Single(i => i % 2 == 1) 77 | ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/Iterators/SelectManyIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class SelectManyIterator : IAsyncEnumerator 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | private readonly Func> _collectionSelector; 12 | private readonly Func _resultSelector; 13 | private int _count; 14 | private IAsyncEnumerator? _subEnumerator; 15 | 16 | public TResult Current { get; private set; } 17 | 18 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 19 | public SelectManyIterator(IAsyncEnumerable source, Func> collectionSelector, Func resultSelector) 20 | { 21 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetAsyncEnumerator(); 22 | _collectionSelector = collectionSelector ?? throw new ArgumentNullException(nameof(collectionSelector)); 23 | _resultSelector = resultSelector ?? throw new ArgumentNullException(nameof(resultSelector)); 24 | } 25 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 26 | 27 | public async ValueTask DisposeAsync() 28 | { 29 | if (_subEnumerator != null) 30 | await _subEnumerator.DisposeAsync(); 31 | 32 | await _enumerator.DisposeAsync(); 33 | } 34 | 35 | public async ValueTask MoveNextAsync() 36 | { 37 | while (_subEnumerator == null || !await _subEnumerator.MoveNextAsync()) 38 | { 39 | if (!await _enumerator.MoveNextAsync()) 40 | return false; 41 | 42 | if (_subEnumerator != null) 43 | await _subEnumerator.DisposeAsync(); 44 | 45 | _subEnumerator = _collectionSelector.Invoke(_enumerator.Current, _count++).GetAsyncEnumerator(); 46 | } 47 | 48 | Current = _resultSelector.Invoke(_enumerator.Current, _subEnumerator.Current); 49 | 50 | return true; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Functional.Unions/UnionDefinitionBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Functional 6 | { 7 | public interface IUnionDefinition 8 | { 9 | } 10 | 11 | public abstract class UnionDefinitionBase : IUnionDefinition 12 | where TUnionDefinition : UnionDefinitionBase 13 | { 14 | } 15 | 16 | public abstract class UnionDefinitionBase : IUnionDefinition 17 | where TUnionDefinition : UnionDefinitionBase 18 | { 19 | } 20 | 21 | public abstract class UnionDefinitionBase : IUnionDefinition 22 | where TUnionDefinition : UnionDefinitionBase 23 | { 24 | } 25 | 26 | public abstract class UnionDefinitionBase : IUnionDefinition 27 | where TUnionDefinition : UnionDefinitionBase 28 | { 29 | } 30 | 31 | public abstract class UnionDefinitionBase : IUnionDefinition 32 | where TUnionDefinition : UnionDefinitionBase 33 | { 34 | } 35 | 36 | public abstract class UnionDefinitionBase : IUnionDefinition 37 | where TUnionDefinition : UnionDefinitionBase 38 | { 39 | } 40 | 41 | public abstract class UnionDefinitionBase : IUnionDefinition 42 | where TUnionDefinition : UnionDefinitionBase 43 | { 44 | } 45 | 46 | public abstract class UnionDefinitionBase : IUnionDefinition 47 | where TUnionDefinition : UnionDefinitionBase 48 | { 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/SingleOrDefaultTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class SingleOrDefaultTests 11 | { 12 | [Fact] 13 | public async Task SingleEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .SingleOrDefault() 19 | ) 20 | .Should() 21 | .Be(0); 22 | 23 | [Fact] 24 | public async Task SingleEmptyWithPredicate() 25 | => ( 26 | await 27 | AsyncEnumerable 28 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 29 | .SingleOrDefault(i => i == 0) 30 | ) 31 | .Should() 32 | .Be(0); 33 | 34 | [Fact] 35 | public async Task SingleWhereNoneMatchesPredicate() 36 | => ( 37 | await 38 | AsyncEnumerable 39 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 40 | .SingleOrDefault(i => i == 0) 41 | ) 42 | .Should() 43 | .Be(0); 44 | 45 | [Fact] 46 | public async Task SingleWithOneValue() 47 | => ( 48 | await 49 | AsyncEnumerable 50 | .Create(Task.FromResult(new[] { 1 }).AsEnumerable()) 51 | .SingleOrDefault() 52 | ) 53 | .Should() 54 | .Be(1); 55 | 56 | [Fact] 57 | public async Task SingleWithOneValueMatchingPredicate() 58 | => ( 59 | await 60 | AsyncEnumerable 61 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 62 | .SingleOrDefault(i => i % 2 == 0) 63 | ) 64 | .Should() 65 | .Be(2); 66 | 67 | [Fact] 68 | public async Task SingleWithTwoValues() 69 | => await Assert 70 | .ThrowsAsync(() => 71 | AsyncEnumerable 72 | .Create(Task.FromResult(new[] { 1, 2 }).AsEnumerable()) 73 | .SingleOrDefault() 74 | ); 75 | 76 | [Fact] 77 | public async Task SingleWithTwoValuesMatchingPredicate() 78 | => await Assert 79 | .ThrowsAsync(() => 80 | AsyncEnumerable 81 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 82 | .SingleOrDefault(i => i % 2 == 1) 83 | ); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Functional.Tests/Options/OptionLinqSyntaxWhereTests.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Functional.Tests.Options 10 | { 11 | public class OptionLinqSyntaxWhereTests 12 | { 13 | [Fact] 14 | public void WhereSuccessful() 15 | => 16 | ( 17 | from unit in Option.Unit() 18 | where Option.Where(true) 19 | select unit 20 | ) 21 | .AssertSome(); 22 | 23 | [Fact] 24 | public void WhereFailure() 25 | => 26 | ( 27 | from unit in Option.Unit() 28 | where Option.Where(false) 29 | select unit 30 | ) 31 | .AssertNone(); 32 | 33 | [Fact] 34 | public Task WhereTaskSuccessful() 35 | => 36 | ( 37 | from unit in Option.Unit() 38 | where Task.FromResult(Option.Where(true)) 39 | select unit 40 | ) 41 | .AssertSome(); 42 | 43 | [Fact] 44 | public Task WhereTaskFailure() 45 | => 46 | ( 47 | from unit in Option.Unit() 48 | where Task.FromResult(Option.Where(false)) 49 | select unit 50 | ) 51 | .AssertNone(); 52 | 53 | [Fact] 54 | public void EnumerableWhereSuccessful() 55 | => 56 | ( 57 | from num in new int[] { 1, 2, 3, 4, 5 } 58 | where Option.Where(true) 59 | select num 60 | ) 61 | .WhereSome() 62 | .Should() 63 | .BeEquivalentTo(new[] { 1, 2, 3, 4, 5 }); 64 | 65 | [Fact] 66 | public void EnumerableWhereFailure() 67 | => 68 | ( 69 | from num in new int[] { 1, 2, 3, 4, 5 } 70 | where Option.Where(num % 2 == 0) 71 | select num 72 | ) 73 | .Count(o => !o.HasValue()) 74 | .Should() 75 | .Be(3); 76 | 77 | [Fact] 78 | public Task EnumerableWhereAsyncSuccessful() 79 | => 80 | ( 81 | from num in new int[] { 1, 2, 3, 4, 5 } 82 | where Task.FromResult(Option.Where(true)) 83 | select num 84 | ) 85 | .WhereSome() 86 | .AsEnumerable() 87 | .Should() 88 | .BeEquivalentTo(new[] { 1, 2, 3, 4, 5 }); 89 | 90 | [Fact] 91 | public Task EnumerableWhereAsyncFailure() 92 | => 93 | ( 94 | from num in new int[] { 1, 2, 3, 4, 5 } 95 | where Task.FromResult(Option.Where(num % 2 == 0)) 96 | select num 97 | ) 98 | .AsEnumerable() 99 | .Count(o => !o.HasValue()) 100 | .Should() 101 | .Be(3); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Functional.Tests/AsyncEnumerables/ZipTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using FluentAssertions; 6 | using Xunit; 7 | 8 | namespace Functional.Tests.AsyncEnumerables 9 | { 10 | public class ZipTests 11 | { 12 | [Fact] 13 | public async Task ZipEmptyToEmpty() 14 | => ( 15 | await 16 | AsyncEnumerable 17 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 18 | .Zip(Task.FromResult(Array.Empty()).AsEnumerable(), (i1, i2) => i1 + i2) 19 | .AsEnumerable() 20 | ) 21 | .Should() 22 | .BeEquivalentTo(Array.Empty()); 23 | 24 | [Fact] 25 | public async Task ZipItemsToEmpty() 26 | => ( 27 | await 28 | AsyncEnumerable 29 | .Create(Task.FromResult(Array.Empty()).AsEnumerable()) 30 | .Zip(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable(), (i1, i2) => i1 + i2) 31 | .AsEnumerable() 32 | ) 33 | .Should() 34 | .BeEquivalentTo(Array.Empty()); 35 | 36 | [Fact] 37 | public async Task ZipEmptyToItems() 38 | => ( 39 | await 40 | AsyncEnumerable 41 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 42 | .Zip(Task.FromResult(Array.Empty()).AsEnumerable(), (i1, i2) => i1 + i2) 43 | .AsEnumerable() 44 | ) 45 | .Should() 46 | .BeEquivalentTo(Array.Empty()); 47 | 48 | [Fact] 49 | public async Task ZipItemsToItems() 50 | => ( 51 | await 52 | AsyncEnumerable 53 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 54 | .Zip(Task.FromResult(new[] { 4, 5, 6 }).AsEnumerable(), (i1, i2) => i1 + i2) 55 | .AsEnumerable() 56 | ) 57 | .Should() 58 | .BeEquivalentTo(new[] { 5, 7, 9 }); 59 | 60 | [Fact] 61 | public async Task ZipLongerToShorter() 62 | => ( 63 | await 64 | AsyncEnumerable 65 | .Create(Task.FromResult(new[] { 1, 2 }).AsEnumerable()) 66 | .Zip(Task.FromResult(new[] { 4, 5, 6 }).AsEnumerable(), (i1, i2) => i1 + i2) 67 | .AsEnumerable() 68 | ) 69 | .Should() 70 | .BeEquivalentTo(new[] { 5, 7 }); 71 | 72 | [Fact] 73 | public async Task ZipShorterToLonger() 74 | => ( 75 | await 76 | AsyncEnumerable 77 | .Create(Task.FromResult(new[] { 1, 2, 3 }).AsEnumerable()) 78 | .Zip(Task.FromResult(new[] { 4, 5 }).AsEnumerable(), (i1, i2) => i1 + i2) 79 | .AsEnumerable() 80 | ) 81 | .Should() 82 | .BeEquivalentTo(new[] { 5, 7 }); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Functional.Tests/Options/OptionOfStringExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using AutoFixture.Xunit2; 4 | using FluentAssertions; 5 | using Xunit; 6 | 7 | namespace Functional.Tests.Options 8 | { 9 | public class OptionOfStringExtensionsTests 10 | { 11 | public class Sync 12 | { 13 | [Theory] 14 | [InlineData(null)] 15 | [InlineData("")] 16 | public void ReturnsNoneForEmptyString(string value) 17 | => Option.FromNullable(value) 18 | .WhereNonEmpty() 19 | .AssertNone(); 20 | 21 | [Theory, AutoData] 22 | public void ReturnsSomeForNonEmptyString(string value) 23 | => Option.FromNullable(value) 24 | .WhereNonEmpty() 25 | .AssertSome() 26 | .Should() 27 | .Be(value); 28 | 29 | [Theory] 30 | [InlineData(null)] 31 | [InlineData("")] 32 | [InlineData(" ")] 33 | [InlineData(" ")] 34 | [InlineData("\t")] 35 | [InlineData("\n")] 36 | public void ReturnsNoneForWhiteSpaceString(string value) 37 | => Option.FromNullable(value) 38 | .WhereNonWhiteSpace() 39 | .AssertNone(); 40 | 41 | [Theory, AutoData] 42 | public void ReturnsSomeForNonWhiteSpaceString(string value) 43 | => Option.FromNullable(value) 44 | .WhereNonEmpty() 45 | .AssertSome() 46 | .Should() 47 | .Be(value); 48 | } 49 | 50 | public class Async 51 | { 52 | [Theory] 53 | [InlineData(null)] 54 | [InlineData("")] 55 | public async Task ReturnsNoneForEmptyString(string value) 56 | => await Task.FromResult(Option.FromNullable(value)) 57 | .WhereNonEmpty() 58 | .AssertNone(); 59 | 60 | [Theory, AutoData] 61 | public async Task ReturnsSomeForNonEmptyString(string value) 62 | => await Task.FromResult(Option.FromNullable(value)) 63 | .WhereNonEmpty() 64 | .AssertSome() 65 | .Should() 66 | .Be(value); 67 | 68 | [Theory] 69 | [InlineData(null)] 70 | [InlineData("")] 71 | [InlineData(" ")] 72 | [InlineData(" ")] 73 | [InlineData("\t")] 74 | [InlineData("\n")] 75 | public async Task ReturnsNoneForWhiteSpaceString(string value) 76 | => await Task.FromResult(Option.FromNullable(value)) 77 | .WhereNonWhiteSpace() 78 | .AssertNone(); 79 | 80 | [Theory, AutoData] 81 | public async Task ReturnsSomeForNonWhiteSpaceString(string value) 82 | => await Task.FromResult(Option.FromNullable(value)) 83 | .WhereNonEmpty() 84 | .AssertSome() 85 | .Should() 86 | .Be(value); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables.NetStandard2/AsyncOptionEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public interface IAsyncOptionEnumerable : IAsyncEnumerable> 9 | where TValue : notnull 10 | { 11 | } 12 | 13 | internal class AsyncOptionEnumerable : IAsyncOptionEnumerable 14 | where TValue : notnull 15 | { 16 | private readonly IAsyncEnumerable> _source; 17 | 18 | public AsyncOptionEnumerable(IAsyncEnumerable> source) 19 | => _source = source ?? throw new ArgumentNullException(nameof(source)); 20 | 21 | public IAsyncEnumerator> GetEnumerator() 22 | => _source.GetEnumerator(); 23 | } 24 | 25 | internal static class AsyncOptionEnumerable 26 | { 27 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this IAsyncEnumerable> source) 28 | where TValue : notnull 29 | => new AsyncOptionEnumerable(source); 30 | 31 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task>> source) 32 | where TValue : notnull 33 | => source 34 | .AsAsyncEnumerable() 35 | .AsAsyncOptionEnumerable(); 36 | 37 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task> source) 38 | where TValue : notnull 39 | => ConvertEnumerable(source) 40 | .AsAsyncEnumerable() 41 | .AsAsyncOptionEnumerable(); 42 | 43 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task>> source) 44 | where TValue : notnull 45 | => source 46 | .AsAsyncEnumerable() 47 | .AsAsyncOptionEnumerable(); 48 | 49 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task> source) 50 | where TValue : notnull 51 | => ConvertAsyncEnumerable(source) 52 | .AsAsyncEnumerable() 53 | .AsAsyncOptionEnumerable(); 54 | 55 | private static async Task>> ConvertEnumerable(Task> source) 56 | where TValue : notnull 57 | => await source; 58 | 59 | private static async Task>> ConvertAsyncEnumerable(Task> source) 60 | where TValue : notnull 61 | => await source; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/ReplayableAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ReplayableAsyncEnumerableData 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | 12 | private readonly List _values = new List(); 13 | 14 | private bool _complete; 15 | 16 | public ReplayableAsyncEnumerableData(IAsyncEnumerator enumerator) 17 | => _enumerator = enumerator; 18 | 19 | public async Task<(bool hasValue, T? value)> TryGetValue(int index) 20 | { 21 | if (index < _values.Count) 22 | return (true, _values[index]); 23 | 24 | if (!_complete) 25 | { 26 | if (await _enumerator.MoveNext()) 27 | { 28 | _values.Add(_enumerator.Current); 29 | return (true, _enumerator.Current); 30 | } 31 | else 32 | _complete = true; 33 | } 34 | 35 | return (false, default); 36 | } 37 | } 38 | 39 | internal class ReplayableAsyncEnumerator : IAsyncEnumerator 40 | { 41 | public T Current { get; private set; } 42 | 43 | private readonly ReplayableAsyncEnumerableData _data; 44 | 45 | private int _index = 0; 46 | 47 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 48 | public ReplayableAsyncEnumerator(ReplayableAsyncEnumerableData data) 49 | => _data = data; 50 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 51 | 52 | public void Dispose() { } 53 | 54 | #pragma warning disable CS8601 // Possible null reference assignment. 55 | public async Task MoveNext() 56 | { 57 | var value = await _data.TryGetValue(_index++); 58 | if (_index >= 0 && value.hasValue) 59 | { 60 | Current = value.value; 61 | return true; 62 | } 63 | 64 | Current = default; 65 | return false; 66 | } 67 | #pragma warning restore CS8601 // Possible null reference assignment. 68 | 69 | public void Reset() 70 | => _index = 0; 71 | } 72 | 73 | internal class ReplayableAsyncEnumerable : IAsyncEnumerable 74 | { 75 | private readonly ReplayableAsyncEnumerableData _data; 76 | 77 | public ReplayableAsyncEnumerable(IAsyncEnumerable data) 78 | => _data = new ReplayableAsyncEnumerableData(data.GetEnumerator()); 79 | 80 | public IAsyncEnumerator GetEnumerator() 81 | => new ReplayableAsyncEnumerator(_data); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Functional.Unions/UnionDefinition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne> 9 | where TUnionDefinition : UnionDefinition 10 | { 11 | } 12 | 13 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo> 14 | where TUnionDefinition : UnionDefinition 15 | { 16 | } 17 | 18 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo, TThree> 19 | where TUnionDefinition : UnionDefinition 20 | { 21 | } 22 | 23 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo, TThree, TFour> 24 | where TUnionDefinition : UnionDefinition 25 | { 26 | } 27 | 28 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo, TThree, TFour, TFive> 29 | where TUnionDefinition : UnionDefinition 30 | { 31 | } 32 | 33 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo, TThree, TFour, TFive, TSix> 34 | where TUnionDefinition : UnionDefinition 35 | { 36 | } 37 | 38 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo, TThree, TFour, TFive, TSix, TSeven> 39 | where TUnionDefinition : UnionDefinition 40 | { 41 | } 42 | 43 | public abstract class UnionDefinition : UnionDefinitionBase, TUnionDefinition, TOne, TTwo, TThree, TFour, TFive, TSix, TSeven, TEight> 44 | where TUnionDefinition : UnionDefinition 45 | { 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables.NetStandard2/ReplayableAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ReplayableAsyncEnumerableData 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | 12 | private readonly List _values = new List(); 13 | 14 | private bool _complete; 15 | 16 | public ReplayableAsyncEnumerableData(IAsyncEnumerator enumerator) 17 | => _enumerator = enumerator; 18 | 19 | public async Task<(bool hasValue, T? value)> TryGetValue(int index) 20 | { 21 | if (index < _values.Count) 22 | return (true, _values[index]); 23 | 24 | if (!_complete) 25 | { 26 | if (await _enumerator.MoveNext()) 27 | { 28 | _values.Add(_enumerator.Current); 29 | return (true, _enumerator.Current); 30 | } 31 | else 32 | _complete = true; 33 | } 34 | 35 | return (false, default); 36 | } 37 | } 38 | 39 | internal class ReplayableAsyncEnumerator : IAsyncEnumerator 40 | { 41 | public T Current { get; private set; } 42 | 43 | private readonly ReplayableAsyncEnumerableData _data; 44 | 45 | private int _index = 0; 46 | 47 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 48 | public ReplayableAsyncEnumerator(ReplayableAsyncEnumerableData data) 49 | => _data = data; 50 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 51 | 52 | public void Dispose() { } 53 | 54 | #pragma warning disable CS8601 // Possible null reference assignment. 55 | public async Task MoveNext() 56 | { 57 | var value = await _data.TryGetValue(_index++); 58 | if (_index >= 0 && value.hasValue) 59 | { 60 | Current = value.value; 61 | return true; 62 | } 63 | 64 | Current = default; 65 | return false; 66 | } 67 | #pragma warning restore CS8601 // Possible null reference assignment. 68 | 69 | public void Reset() 70 | => _index = 0; 71 | } 72 | 73 | internal class ReplayableAsyncEnumerable : IAsyncEnumerable 74 | { 75 | private readonly ReplayableAsyncEnumerableData _data; 76 | 77 | public ReplayableAsyncEnumerable(IAsyncEnumerable data) 78 | => _data = new ReplayableAsyncEnumerableData(data.GetEnumerator()); 79 | 80 | public IAsyncEnumerator GetEnumerator() 81 | => new ReplayableAsyncEnumerator(_data); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables.NetStandard2/ReplayableAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Functional 7 | { 8 | internal class ReplayableAsyncEnumerableData 9 | { 10 | private readonly IAsyncEnumerator _enumerator; 11 | 12 | private readonly List _values = new List(); 13 | 14 | private bool _complete; 15 | 16 | public ReplayableAsyncEnumerableData(IAsyncEnumerator enumerator) 17 | => _enumerator = enumerator; 18 | 19 | public async Task<(bool hasValue, T? value)> TryGetValue(int index) 20 | { 21 | if (index < _values.Count) 22 | return (true, _values[index]); 23 | 24 | if (!_complete) 25 | { 26 | if (await _enumerator.MoveNext()) 27 | { 28 | _values.Add(_enumerator.Current); 29 | return (true, _enumerator.Current); 30 | } 31 | else 32 | _complete = true; 33 | } 34 | 35 | return (false, default); 36 | } 37 | } 38 | 39 | internal class ReplayableAsyncEnumerator : IAsyncEnumerator 40 | { 41 | public T Current { get; private set; } 42 | 43 | private readonly ReplayableAsyncEnumerableData _data; 44 | 45 | private int _index = 0; 46 | 47 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 48 | public ReplayableAsyncEnumerator(ReplayableAsyncEnumerableData data) 49 | => _data = data; 50 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 51 | 52 | public void Dispose() { } 53 | 54 | #pragma warning disable CS8601 // Possible null reference assignment. 55 | public async Task MoveNext() 56 | { 57 | var value = await _data.TryGetValue(_index++); 58 | if (_index >= 0 && value.hasValue) 59 | { 60 | Current = value.value; 61 | return true; 62 | } 63 | 64 | Current = default; 65 | return false; 66 | } 67 | #pragma warning restore CS8601 // Possible null reference assignment. 68 | 69 | public void Reset() 70 | => _index = 0; 71 | } 72 | 73 | internal class ReplayableAsyncEnumerable : IAsyncEnumerable 74 | { 75 | private readonly ReplayableAsyncEnumerableData _data; 76 | 77 | public ReplayableAsyncEnumerable(IAsyncEnumerable data) 78 | => _data = new ReplayableAsyncEnumerableData(data.GetEnumerator()); 79 | 80 | public IAsyncEnumerator GetEnumerator() 81 | => new ReplayableAsyncEnumerator(_data); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables/AsyncOptionEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | public interface IAsyncOptionEnumerable : IAsyncEnumerable> 10 | where TValue : notnull 11 | { 12 | } 13 | 14 | internal class AsyncOptionEnumerable : IAsyncOptionEnumerable 15 | where TValue : notnull 16 | { 17 | private readonly IAsyncEnumerable> _source; 18 | 19 | public AsyncOptionEnumerable(IAsyncEnumerable> source) 20 | => _source = source ?? throw new ArgumentNullException(nameof(source)); 21 | 22 | public IAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) 23 | => _source.GetAsyncEnumerator(cancellationToken); 24 | } 25 | 26 | internal static class AsyncOptionEnumerable 27 | { 28 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this IAsyncEnumerable> source) 29 | where TValue : notnull 30 | => new AsyncOptionEnumerable(source); 31 | 32 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task>> source) 33 | where TValue : notnull 34 | => source 35 | .AsAsyncEnumerable() 36 | .AsAsyncOptionEnumerable(); 37 | 38 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task> source) 39 | where TValue : notnull 40 | => ConvertEnumerable(source) 41 | .AsAsyncEnumerable() 42 | .AsAsyncOptionEnumerable(); 43 | 44 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task>> source) 45 | where TValue : notnull 46 | => source 47 | .AsAsyncEnumerable() 48 | .AsAsyncOptionEnumerable(); 49 | 50 | public static IAsyncOptionEnumerable AsAsyncOptionEnumerable(this Task> source) 51 | where TValue : notnull 52 | => ConvertAsyncEnumerable(source) 53 | .AsAsyncEnumerable() 54 | .AsAsyncOptionEnumerable(); 55 | 56 | private static async Task>> ConvertEnumerable(Task> source) 57 | where TValue : notnull 58 | => await source; 59 | 60 | private static async Task>> ConvertAsyncEnumerable(Task> source) 61 | where TValue : notnull 62 | => await source; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables/ReplayableEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | internal class ReplayableEnumerableData 9 | { 10 | private readonly IEnumerator _enumerator; 11 | 12 | private readonly List _values = new List(); 13 | 14 | private bool _complete; 15 | 16 | public ReplayableEnumerableData(IEnumerator enumerator) 17 | => _enumerator = enumerator; 18 | 19 | public bool TryGetValue(int index, out T value) 20 | { 21 | if (index < _values.Count) 22 | { 23 | value = _values[index]; 24 | return true; 25 | } 26 | 27 | if (!_complete) 28 | { 29 | if (_enumerator.MoveNext()) 30 | { 31 | value = _enumerator.Current; 32 | _values.Add(value); 33 | return true; 34 | } 35 | else 36 | _complete = true; 37 | } 38 | 39 | #pragma warning disable CS8601 // Possible null reference assignment. 40 | value = default; 41 | #pragma warning restore CS8601 // Possible null reference assignment. 42 | return false; 43 | } 44 | } 45 | 46 | internal class ReplayableEnumerator : IEnumerator 47 | { 48 | public T Current { get; private set; } 49 | 50 | object? IEnumerator.Current => Current; 51 | 52 | private readonly ReplayableEnumerableData _data; 53 | 54 | private int _index = 0; 55 | 56 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 57 | public ReplayableEnumerator(ReplayableEnumerableData data) 58 | => _data = data; 59 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 60 | 61 | public void Dispose() { } 62 | 63 | public bool MoveNext() 64 | { 65 | if (_index >= 0 && _data.TryGetValue(_index++, out var value)) 66 | { 67 | Current = value; 68 | return true; 69 | } 70 | 71 | #pragma warning disable CS8601 // Possible null reference assignment. 72 | Current = default; 73 | #pragma warning restore CS8601 // Possible null reference assignment. 74 | return false; 75 | } 76 | 77 | public void Reset() 78 | => _index = 0; 79 | } 80 | 81 | internal class ReplayableEnumerable : IEnumerable 82 | { 83 | private readonly ReplayableEnumerableData _data; 84 | 85 | public ReplayableEnumerable(IEnumerable data) 86 | => _data = new ReplayableEnumerableData(data.GetEnumerator()); 87 | 88 | public IEnumerator GetEnumerator() 89 | => new ReplayableEnumerator(_data); 90 | 91 | IEnumerator IEnumerable.GetEnumerator() 92 | => new ReplayableEnumerator(_data); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables/ReplayableAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class ReplayableAsyncEnumerableData : IAsyncDisposable 10 | { 11 | private readonly IAsyncEnumerator _enumerator; 12 | 13 | private readonly List _values = new List(); 14 | 15 | private bool _complete; 16 | 17 | public ReplayableAsyncEnumerableData(IAsyncEnumerator enumerator) 18 | => _enumerator = enumerator; 19 | 20 | public ValueTask DisposeAsync() 21 | => _enumerator.DisposeAsync(); 22 | 23 | public async Task<(bool hasValue, T? value)> TryGetValue(int index) 24 | { 25 | if (index < _values.Count) 26 | return (true, _values[index]); 27 | 28 | if (!_complete) 29 | { 30 | if (await _enumerator.MoveNextAsync()) 31 | { 32 | _values.Add(_enumerator.Current); 33 | return (true, _enumerator.Current); 34 | } 35 | else 36 | _complete = true; 37 | } 38 | 39 | return (false, default); 40 | } 41 | } 42 | 43 | internal class ReplayableAsyncEnumerator : IAsyncEnumerator 44 | { 45 | public T Current { get; private set; } 46 | 47 | private readonly ReplayableAsyncEnumerableData _data; 48 | 49 | private int _index = 0; 50 | 51 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 52 | public ReplayableAsyncEnumerator(ReplayableAsyncEnumerableData data) 53 | => _data = data; 54 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 55 | 56 | public ValueTask DisposeAsync() 57 | => _data.DisposeAsync(); 58 | 59 | #pragma warning disable CS8601 // Possible null reference assignment. 60 | public async ValueTask MoveNextAsync() 61 | { 62 | var value = await _data.TryGetValue(_index++); 63 | if (_index >= 0 && value.hasValue) 64 | { 65 | Current = value.value; 66 | return true; 67 | } 68 | 69 | Current = default; 70 | return false; 71 | } 72 | #pragma warning restore CS8601 // Possible null reference assignment. 73 | 74 | public void Reset() 75 | => _index = 0; 76 | } 77 | 78 | internal class ReplayableAsyncEnumerable : IAsyncEnumerable 79 | { 80 | private readonly ReplayableAsyncEnumerableData _data; 81 | 82 | public ReplayableAsyncEnumerable(IAsyncEnumerable data) 83 | => _data = new ReplayableAsyncEnumerableData(data.GetAsyncEnumerator()); 84 | 85 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) 86 | => new ReplayableAsyncEnumerator(_data); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Functional.Primitives.AsyncEnumerables/ReplayableAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class ReplayableAsyncEnumerableData : IAsyncDisposable 10 | { 11 | private readonly IAsyncEnumerator _enumerator; 12 | 13 | private readonly List _values = new List(); 14 | 15 | private bool _complete; 16 | 17 | public ReplayableAsyncEnumerableData(IAsyncEnumerator enumerator) 18 | => _enumerator = enumerator; 19 | 20 | public ValueTask DisposeAsync() 21 | => _enumerator.DisposeAsync(); 22 | 23 | public async Task<(bool hasValue, T? value)> TryGetValue(int index) 24 | { 25 | if (index < _values.Count) 26 | return (true, _values[index]); 27 | 28 | if (!_complete) 29 | { 30 | if (await _enumerator.MoveNextAsync()) 31 | { 32 | _values.Add(_enumerator.Current); 33 | return (true, _enumerator.Current); 34 | } 35 | else 36 | _complete = true; 37 | } 38 | 39 | return (false, default); 40 | } 41 | } 42 | 43 | internal class ReplayableAsyncEnumerator : IAsyncEnumerator 44 | { 45 | public T Current { get; private set; } 46 | 47 | private readonly ReplayableAsyncEnumerableData _data; 48 | 49 | private int _index = 0; 50 | 51 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 52 | public ReplayableAsyncEnumerator(ReplayableAsyncEnumerableData data) 53 | => _data = data; 54 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 55 | 56 | public ValueTask DisposeAsync() 57 | => _data.DisposeAsync(); 58 | 59 | #pragma warning disable CS8601 // Possible null reference assignment. 60 | public async ValueTask MoveNextAsync() 61 | { 62 | var value = await _data.TryGetValue(_index++); 63 | if (_index >= 0 && value.hasValue) 64 | { 65 | Current = value.value; 66 | return true; 67 | } 68 | 69 | Current = default; 70 | return false; 71 | } 72 | #pragma warning restore CS8601 // Possible null reference assignment. 73 | 74 | public void Reset() 75 | => _index = 0; 76 | } 77 | 78 | internal class ReplayableAsyncEnumerable : IAsyncEnumerable 79 | { 80 | private readonly ReplayableAsyncEnumerableData _data; 81 | 82 | public ReplayableAsyncEnumerable(IAsyncEnumerable data) 83 | => _data = new ReplayableAsyncEnumerableData(data.GetAsyncEnumerator()); 84 | 85 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) 86 | => new ReplayableAsyncEnumerator(_data); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Functional.Common.Extensions/ReplayableEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | 4 | namespace Functional 5 | { 6 | internal class ReplayableEnumerableData 7 | { 8 | private readonly IEnumerator _enumerator; 9 | 10 | private readonly List _values = new List(); 11 | 12 | private bool _complete; 13 | 14 | public ReplayableEnumerableData(IEnumerator enumerator) 15 | => _enumerator = enumerator; 16 | 17 | public bool TryGetValue(int index, out T value) 18 | { 19 | if (index < _values.Count) 20 | { 21 | value = _values[index]; 22 | return true; 23 | } 24 | 25 | if (!_complete) 26 | { 27 | if (_enumerator.MoveNext()) 28 | { 29 | value = _enumerator.Current; 30 | _values.Add(value); 31 | return true; 32 | } 33 | else 34 | _complete = true; 35 | } 36 | 37 | #pragma warning disable CS8601 // Possible null reference assignment. 38 | value = default; 39 | #pragma warning restore CS8601 // Possible null reference assignment. 40 | return false; 41 | } 42 | } 43 | 44 | internal class ReplayableEnumerator : IEnumerator 45 | { 46 | public T Current { get; private set; } 47 | 48 | #pragma warning disable CS8603 // Possible null reference return. 49 | object IEnumerator.Current => Current; 50 | #pragma warning restore CS8603 // Possible null reference return. 51 | 52 | private readonly ReplayableEnumerableData _data; 53 | 54 | private int _index = 0; 55 | 56 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 57 | public ReplayableEnumerator(ReplayableEnumerableData data) 58 | => _data = data; 59 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 60 | 61 | public void Dispose() { } 62 | 63 | public bool MoveNext() 64 | { 65 | if (_index >= 0 && _data.TryGetValue(_index++, out var value)) 66 | { 67 | Current = value; 68 | return true; 69 | } 70 | 71 | #pragma warning disable CS8601 // Possible null reference assignment. 72 | Current = default; 73 | #pragma warning restore CS8601 // Possible null reference assignment. 74 | return false; 75 | } 76 | 77 | public void Reset() 78 | => _index = 0; 79 | } 80 | 81 | internal class ReplayableEnumerable : IEnumerable 82 | { 83 | private readonly ReplayableEnumerableData _data; 84 | 85 | public ReplayableEnumerable(IEnumerable data) 86 | => _data = new ReplayableEnumerableData(data.GetEnumerator()); 87 | 88 | public IEnumerator GetEnumerator() 89 | => new ReplayableEnumerator(_data); 90 | 91 | IEnumerator IEnumerable.GetEnumerator() 92 | => new ReplayableEnumerator(_data); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Functional.Enumerables.Extensions/ReplayableEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | 4 | namespace Functional 5 | { 6 | internal class ReplayableEnumerableData 7 | { 8 | private readonly IEnumerator _enumerator; 9 | 10 | private readonly List _values = new List(); 11 | 12 | private bool _complete; 13 | 14 | public ReplayableEnumerableData(IEnumerator enumerator) 15 | => _enumerator = enumerator; 16 | 17 | public bool TryGetValue(int index, out T value) 18 | { 19 | if (index < _values.Count) 20 | { 21 | value = _values[index]; 22 | return true; 23 | } 24 | 25 | if (!_complete) 26 | { 27 | if (_enumerator.MoveNext()) 28 | { 29 | value = _enumerator.Current; 30 | _values.Add(value); 31 | return true; 32 | } 33 | else 34 | _complete = true; 35 | } 36 | 37 | #pragma warning disable CS8601 // Possible null reference assignment. 38 | value = default; 39 | #pragma warning restore CS8601 // Possible null reference assignment. 40 | return false; 41 | } 42 | } 43 | 44 | internal class ReplayableEnumerator : IEnumerator 45 | { 46 | public T Current { get; private set; } 47 | 48 | #pragma warning disable CS8603 // Possible null reference return. 49 | object IEnumerator.Current => Current; 50 | #pragma warning restore CS8603 // Possible null reference return. 51 | 52 | private readonly ReplayableEnumerableData _data; 53 | 54 | private int _index = 0; 55 | 56 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 57 | public ReplayableEnumerator(ReplayableEnumerableData data) 58 | => _data = data; 59 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 60 | 61 | public void Dispose() { } 62 | 63 | public bool MoveNext() 64 | { 65 | if (_index >= 0 && _data.TryGetValue(_index++, out var value)) 66 | { 67 | Current = value; 68 | return true; 69 | } 70 | 71 | #pragma warning disable CS8601 // Possible null reference assignment. 72 | Current = default; 73 | #pragma warning restore CS8601 // Possible null reference assignment. 74 | return false; 75 | } 76 | 77 | public void Reset() 78 | => _index = 0; 79 | } 80 | 81 | internal class ReplayableEnumerable : IEnumerable 82 | { 83 | private readonly ReplayableEnumerableData _data; 84 | 85 | public ReplayableEnumerable(IEnumerable data) 86 | => _data = new ReplayableEnumerableData(data.GetEnumerator()); 87 | 88 | public IEnumerator GetEnumerator() 89 | => new ReplayableEnumerator(_data); 90 | 91 | IEnumerator IEnumerable.GetEnumerator() 92 | => new ReplayableEnumerator(_data); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Functional.AsyncEnumerables.NetStandard2/Iterators/ConcurrentSelectIterator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Functional 8 | { 9 | internal class ConcurrentSelectIterator : IAsyncEnumerator 10 | { 11 | private readonly IAsyncEnumerator _enumerator; 12 | private readonly Func> _selector; 13 | private int _maxConcurrency; 14 | 15 | private readonly Queue> _taskQueue = new Queue>(); 16 | 17 | private int _count; 18 | 19 | public TResult Current { get; private set; } 20 | 21 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 22 | public ConcurrentSelectIterator(IAsyncEnumerable source, Func> selector, int maxConcurrency) 23 | { 24 | _enumerator = (source ?? throw new ArgumentNullException(nameof(source))).GetEnumerator(); 25 | _selector = selector ?? throw new ArgumentNullException(nameof(selector)); 26 | _maxConcurrency = maxConcurrency; 27 | 28 | if (_maxConcurrency <= 0) 29 | throw new ArgumentOutOfRangeException(nameof(maxConcurrency), "Value must be greater than zero."); 30 | } 31 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 32 | 33 | public async Task MoveNext() 34 | { 35 | try 36 | { 37 | while (_taskQueue.Count < _maxConcurrency && await _enumerator.MoveNext()) 38 | _taskQueue.Enqueue(_selector.Invoke(_enumerator.Current, _count++)); 39 | } 40 | catch (Exception ex) 41 | { 42 | throw new AggregateException(Enumerable.Repeat(ex, 1).Concat(await DrainTaskQueue(_taskQueue))); 43 | } 44 | 45 | if (_taskQueue.Count == 0) 46 | { 47 | _maxConcurrency = 0; 48 | #pragma warning disable CS8601 // Possible null reference assignment. 49 | Current = default; 50 | #pragma warning restore CS8601 // Possible null reference assignment. 51 | return false; 52 | } 53 | 54 | try 55 | { 56 | Current = await _taskQueue.Dequeue(); 57 | return true; 58 | } 59 | catch (Exception ex) 60 | { 61 | throw new AggregateException(Enumerable.Repeat(ex, 1).Concat(await DrainTaskQueue(_taskQueue))); 62 | } 63 | } 64 | 65 | private async Task> DrainTaskQueue(Queue> taskQueue) 66 | { 67 | var exceptions = new List(); 68 | 69 | while (taskQueue.Count > 0) 70 | { 71 | try 72 | { 73 | await taskQueue.Dequeue(); 74 | } 75 | catch (Exception ex) 76 | { 77 | exceptions.Add(ex); 78 | } 79 | } 80 | 81 | return exceptions; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Functional.Tests/Enumerables/TakeUntilNoneTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Threading.Tasks; 3 | using FluentAssertions; 4 | using Xunit; 5 | 6 | namespace Functional.Tests.Enumerables 7 | { 8 | public class TakeUntilNoneTests 9 | { 10 | [Fact] 11 | public void EnumerableTakeUntilNoneSomes() 12 | => new[] 13 | { 14 | Option.Some(1), 15 | Option.Some(2), 16 | Option.Some(3) 17 | } 18 | .TakeUntilNone() 19 | .AssertSome() 20 | .Should() 21 | .BeEquivalentTo(new[] { 1, 2, 3 }); 22 | 23 | [Fact] 24 | public void EnumerableTakeUntilNoneNones() 25 | => new[] 26 | { 27 | Option.None(), 28 | Option.Some(2), 29 | Option.None() 30 | } 31 | .TakeUntilNone() 32 | .AssertNone(); 33 | 34 | [Fact] 35 | public Task TaskOfEnumerableTakeUntilNoneSomes() 36 | => Task 37 | .FromResult 38 | ( 39 | new[] 40 | { 41 | Option.Some(1), 42 | Option.Some(2), 43 | Option.Some(3) 44 | } 45 | .AsEnumerable() 46 | ) 47 | .TakeUntilNone() 48 | .AssertSome() 49 | .Should() 50 | .BeEquivalentTo(new[] { 1, 2, 3 }); 51 | 52 | [Fact] 53 | public Task TaskOfEnumerableTakeUntilNoneNones() 54 | => Task 55 | .FromResult 56 | ( 57 | new[] 58 | { 59 | Option.None(), 60 | Option.Some(2), 61 | Option.None() 62 | } 63 | .AsEnumerable() 64 | ) 65 | .TakeUntilNone() 66 | .AssertNone(); 67 | 68 | [Fact] 69 | public Task EnumerableOfTasksTakeUntilNoneSomes() 70 | => new[] 71 | { 72 | Task.FromResult(Option.Some(1)), 73 | Task.FromResult(Option.Some(2)), 74 | Task.FromResult(Option.Some(3)) 75 | } 76 | .TakeUntilNone() 77 | .AssertSome() 78 | .Should() 79 | .BeEquivalentTo(new[] { 1, 2, 3 }); 80 | 81 | [Fact] 82 | public Task EnumerableOfTasksTakeUntilNoneNones() 83 | => new[] 84 | { 85 | Task.FromResult(Option.None()), 86 | Task.FromResult(Option.Some(2)), 87 | Task.FromResult(Option.None()) 88 | } 89 | .TakeUntilNone() 90 | .AssertNone(); 91 | 92 | [Fact] 93 | public Task AsyncEnumerableTakeUntilNoneSomes() 94 | => new[] 95 | { 96 | Task.FromResult(Option.Some(1)), 97 | Task.FromResult(Option.Some(2)), 98 | Task.FromResult(Option.Some(3)) 99 | } 100 | .AsAsyncEnumerable() 101 | .TakeUntilNone() 102 | .AssertSome() 103 | .Should() 104 | .BeEquivalentTo(new[] { 1, 2, 3 }); 105 | 106 | [Fact] 107 | public Task AsyncEnumerableTakeUntilNoneNones() 108 | => new[] 109 | { 110 | Task.FromResult(Option.None()), 111 | Task.FromResult(Option.Some(2)), 112 | Task.FromResult(Option.None()) 113 | } 114 | .AsAsyncEnumerable() 115 | .TakeUntilNone() 116 | .AssertNone(); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Functional.Unions.AsyncEnumerables.NetStandard2/ReplayableEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Functional 7 | { 8 | internal class ReplayableEnumerableData 9 | { 10 | private readonly IEnumerator _enumerator; 11 | 12 | private readonly List _values = new List(); 13 | 14 | private bool _complete; 15 | 16 | public ReplayableEnumerableData(IEnumerator enumerator) 17 | => _enumerator = enumerator; 18 | 19 | public bool TryGetValue(int index, out T value) 20 | { 21 | if (index < _values.Count) 22 | { 23 | value = _values[index]; 24 | return true; 25 | } 26 | 27 | if (!_complete) 28 | { 29 | if (_enumerator.MoveNext()) 30 | { 31 | value = _enumerator.Current; 32 | _values.Add(value); 33 | return true; 34 | } 35 | else 36 | _complete = true; 37 | } 38 | 39 | #pragma warning disable CS8601 // Possible null reference assignment. 40 | value = default; 41 | #pragma warning restore CS8601 // Possible null reference assignment. 42 | return false; 43 | } 44 | } 45 | 46 | internal class ReplayableEnumerator : IEnumerator 47 | { 48 | public T Current { get; private set; } 49 | 50 | #pragma warning disable CS8603 // Possible null reference return. 51 | object IEnumerator.Current => Current; 52 | #pragma warning restore CS8603 // Possible null reference return. 53 | 54 | private readonly ReplayableEnumerableData _data; 55 | 56 | private int _index = 0; 57 | 58 | #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 59 | public ReplayableEnumerator(ReplayableEnumerableData data) 60 | => _data = data; 61 | #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. 62 | 63 | public void Dispose() { } 64 | 65 | public bool MoveNext() 66 | { 67 | if (_index >= 0 && _data.TryGetValue(_index++, out var value)) 68 | { 69 | Current = value; 70 | return true; 71 | } 72 | 73 | #pragma warning disable CS8601 // Possible null reference assignment. 74 | Current = default; 75 | #pragma warning restore CS8601 // Possible null reference assignment. 76 | return false; 77 | } 78 | 79 | public void Reset() 80 | => _index = 0; 81 | } 82 | 83 | internal class ReplayableEnumerable : IEnumerable 84 | { 85 | private readonly ReplayableEnumerableData _data; 86 | 87 | public ReplayableEnumerable(IEnumerable data) 88 | => _data = new ReplayableEnumerableData(data.GetEnumerator()); 89 | 90 | public IEnumerator GetEnumerator() 91 | => new ReplayableEnumerator(_data); 92 | 93 | IEnumerator IEnumerable.GetEnumerator() 94 | => new ReplayableEnumerator(_data); 95 | } 96 | } 97 | --------------------------------------------------------------------------------