Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 719b4e85f5 | |||
| 3d34a3021d | |||
| 57e83fbafa |
23
README.md
23
README.md
@@ -69,9 +69,9 @@ Result<T> Bar()
|
|||||||
```csharp
|
```csharp
|
||||||
Result<int> result = GetResult();
|
Result<int> result = GetResult();
|
||||||
|
|
||||||
var value = result
|
string value = result
|
||||||
.Append("new")
|
.Append("new") // -> Result<(int, string)>
|
||||||
.Map((i, s) => $"{s} result {i}")
|
.Map((i, s) => $"{s} result {i}") // -> Result<string>
|
||||||
.Match(
|
.Match(
|
||||||
onSuccess: x => x,
|
onSuccess: x => x,
|
||||||
onFailure: err => err.ToString()
|
onFailure: err => err.ToString()
|
||||||
@@ -81,6 +81,17 @@ var value = result
|
|||||||
Result<int> GetResult() => Result.Success(1);
|
Result<int> GetResult() => Result.Success(1);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Recover from failure
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
Result<string> failed = new NotImplementedException();
|
||||||
|
|
||||||
|
Result<string> result = failed.TryRecover(err => err.Type == "System.NotImplementedException"
|
||||||
|
? "recovered"
|
||||||
|
: err);
|
||||||
|
// result with value: "recovered"
|
||||||
|
```
|
||||||
|
|
||||||
### Try
|
### Try
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
@@ -99,9 +110,9 @@ int SomeFunction() => 1;
|
|||||||
### Ensure
|
### Ensure
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
var value = GetValue();
|
int? value = GetValue();
|
||||||
Result<int> result = Ensure.That(value)
|
Result<int> result = Ensure.That(value) // -> Ensure<int?>
|
||||||
.NotNull()
|
.NotNull() // -> Ensure<int>
|
||||||
.Satisfies(i => i < 100)
|
.Satisfies(i => i < 100)
|
||||||
.Result();
|
.Result();
|
||||||
|
|
||||||
|
|||||||
@@ -41,22 +41,46 @@ public sealed class EnsureExtensionsExecutor : IGeneratorExecutor
|
|||||||
|
|
||||||
var sb = new StringBuilder();
|
var sb = new StringBuilder();
|
||||||
|
|
||||||
sb.AppendLine($"#region Satisfies");
|
sb.AppendLine("#region Satisfies");
|
||||||
errorGenerationDefinitions.ForEach(def => GenerateSatisfiesExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
errorGenerationDefinitions.ForEach(def => GenerateSatisfiesExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
||||||
sb.AppendLine("#endregion");
|
sb.AppendLine("#endregion");
|
||||||
|
|
||||||
sb.AppendLine($"#region NotNull");
|
sb.AppendLine("#region NotNull");
|
||||||
errorGenerationDefinitions.ForEach(def => GenerateNotNullExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
errorGenerationDefinitions.ForEach(def => GenerateNotNullExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
||||||
sb.AppendLine("#endregion");
|
sb.AppendLine("#endregion");
|
||||||
|
|
||||||
sb.AppendLine($"#region NotEmpty");
|
sb.AppendLine("#region NotEmpty");
|
||||||
errorGenerationDefinitions.ForEach(def => GenerateNotEmptyExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
errorGenerationDefinitions.ForEach(def => GenerateNotEmptyExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
||||||
sb.AppendLine("#endregion");
|
sb.AppendLine("#endregion");
|
||||||
|
|
||||||
|
sb.AppendLine("#region NotWhitespace");
|
||||||
|
errorGenerationDefinitions.ForEach(def => GenerateNotWhitespaceExtensions(sb, def.ErrorParameterDecl, def.ErrorValueExpr));
|
||||||
|
sb.AppendLine("#endregion");
|
||||||
|
|
||||||
return sb.ToString();
|
return sb.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void GenerateNotWhitespaceExtensions(StringBuilder sb, string errorParameterDecl, string errorValueExpr)
|
||||||
|
{
|
||||||
|
string defaultErrorExpr = "?? Error.New(DefaultErrorType, $\"Value {{{ensure.ValueExpression}}} is empty or consists exclusively of white-space characters.\")";
|
||||||
|
|
||||||
|
sb.AppendLine($$"""
|
||||||
|
[PureAttribute]
|
||||||
|
[GeneratedCodeAttribute("{{nameof(EnsureExtensionsExecutor)}}", "1.0.0.0")]
|
||||||
|
public static Ensure<string> NotWhitespace(this in Ensure<string> ensure, {{errorParameterDecl}})
|
||||||
|
{
|
||||||
|
return ensure.State switch
|
||||||
|
{
|
||||||
|
ResultState.Success => string.IsNullOrWhiteSpace(ensure.Value)
|
||||||
|
? new({{errorValueExpr}} {{defaultErrorExpr}}, ensure.ValueExpression)
|
||||||
|
: new(ensure.Value!, ensure.ValueExpression),
|
||||||
|
ResultState.Error => new(ensure.Error!, ensure.ValueExpression),
|
||||||
|
_ => throw new EnsureNotInitializedException(nameof(ensure))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
|
||||||
private void GenerateNotEmptyExtensions(StringBuilder sb, string errorParameterDecl, string errorValueExpr)
|
private void GenerateNotEmptyExtensions(StringBuilder sb, string errorParameterDecl, string errorValueExpr)
|
||||||
{
|
{
|
||||||
string defaultErrorExpr = "?? Error.New(DefaultErrorType, $\"Value {{{ensure.ValueExpression}}} is empty.\")";
|
string defaultErrorExpr = "?? Error.New(DefaultErrorType, $\"Value {{{ensure.ValueExpression}}} is empty.\")";
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ public class ExtensionsMethodGenerator : IIncrementalGenerator
|
|||||||
new ResultMapExecutor(),
|
new ResultMapExecutor(),
|
||||||
new ResultBindExecutor(),
|
new ResultBindExecutor(),
|
||||||
new ResultTapExecutor(),
|
new ResultTapExecutor(),
|
||||||
|
new ResultTryRecoverExecutor(),
|
||||||
new ResultAppendExecutor(),
|
new ResultAppendExecutor(),
|
||||||
new TryExtensionsExecutor(),
|
new TryExtensionsExecutor(),
|
||||||
new EnsureExtensionsExecutor(),
|
new EnsureExtensionsExecutor(),
|
||||||
|
|||||||
86
Railway.SourceGenerator/ResultTryRecoverExecutor.cs
Normal file
86
Railway.SourceGenerator/ResultTryRecoverExecutor.cs
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
using System.Collections.Immutable;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.CodeAnalysis;
|
||||||
|
|
||||||
|
namespace Just.Railway.SourceGen;
|
||||||
|
|
||||||
|
internal sealed class ResultTryRecoverExecutor : ResultExtensionsExecutor
|
||||||
|
{
|
||||||
|
protected override string ExtensionType => "TryRecover";
|
||||||
|
protected override void GenerateMethodsForArgCount(StringBuilder sb, int argCount)
|
||||||
|
{
|
||||||
|
if (argCount > 1) return;
|
||||||
|
|
||||||
|
var templateArgNames = Enumerable.Repeat("T", argCount)
|
||||||
|
.ToImmutableArray();
|
||||||
|
|
||||||
|
string methodTemplateDecl = GenerateTemplateDecl(templateArgNames);
|
||||||
|
string resultTypeDef = GenerateResultTypeDef(templateArgNames);
|
||||||
|
|
||||||
|
sb.AppendLine($"#region {resultTypeDef}");
|
||||||
|
|
||||||
|
sb.AppendLine($$"""
|
||||||
|
[PureAttribute]
|
||||||
|
[GeneratedCodeAttribute("{{nameof(ResultTryRecoverExecutor)}}", "1.0.0.0")]
|
||||||
|
public static {{resultTypeDef}} TryRecover{{methodTemplateDecl}}(this in {{resultTypeDef}} result, Func<Error, {{resultTypeDef}}> recover)
|
||||||
|
{
|
||||||
|
return result.State switch
|
||||||
|
{
|
||||||
|
ResultState.Success => ({{resultTypeDef}})result.Value,
|
||||||
|
ResultState.Error => recover(result.Error!),
|
||||||
|
_ => throw new ResultNotInitializedException(nameof(result))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
|
||||||
|
GenerateAsyncMethods("Task", sb, templateArgNames, resultTypeDef, methodTemplateDecl);
|
||||||
|
GenerateAsyncMethods("ValueTask", sb, templateArgNames, resultTypeDef, methodTemplateDecl);
|
||||||
|
|
||||||
|
sb.AppendLine("#endregion");
|
||||||
|
}
|
||||||
|
private static void GenerateAsyncMethods(string taskType, StringBuilder sb, ImmutableArray<string> templateArgNames, string resultTypeDef, string methodTemplateDecl)
|
||||||
|
{
|
||||||
|
sb.AppendLine($$"""
|
||||||
|
[PureAttribute]
|
||||||
|
[GeneratedCodeAttribute("{{nameof(ResultTryRecoverExecutor)}}", "1.0.0.0")]
|
||||||
|
public static async {{taskType}}<{{resultTypeDef}}> TryRecover{{methodTemplateDecl}}(this {{taskType}}<{{resultTypeDef}}> resultTask, Func<Error, {{resultTypeDef}}> recover)
|
||||||
|
{
|
||||||
|
var result = await resultTask.ConfigureAwait(false);
|
||||||
|
return result.State switch
|
||||||
|
{
|
||||||
|
ResultState.Success => ({{resultTypeDef}})result.Value,
|
||||||
|
ResultState.Error => recover(result.Error!),
|
||||||
|
_ => throw new ResultNotInitializedException(nameof(resultTask))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
sb.AppendLine($$"""
|
||||||
|
[PureAttribute]
|
||||||
|
[GeneratedCodeAttribute("{{nameof(ResultTryRecoverExecutor)}}", "1.0.0.0")]
|
||||||
|
public static async {{taskType}}<{{resultTypeDef}}> TryRecover{{methodTemplateDecl}}(this {{resultTypeDef}} result, Func<Error, {{taskType}}<{{resultTypeDef}}>> recover)
|
||||||
|
{
|
||||||
|
return result.State switch
|
||||||
|
{
|
||||||
|
ResultState.Success => ({{resultTypeDef}})result.Value,
|
||||||
|
ResultState.Error => await recover(result.Error!).ConfigureAwait(false),
|
||||||
|
_ => throw new ResultNotInitializedException(nameof(result))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
sb.AppendLine($$"""
|
||||||
|
[PureAttribute]
|
||||||
|
[GeneratedCodeAttribute("{{nameof(ResultTryRecoverExecutor)}}", "1.0.0.0")]
|
||||||
|
public static async {{taskType}}<{{resultTypeDef}}> TryRecover{{methodTemplateDecl}}(this {{taskType}}<{{resultTypeDef}}> resultTask, Func<Error, {{taskType}}<{{resultTypeDef}}>> recover)
|
||||||
|
{
|
||||||
|
var result = await resultTask.ConfigureAwait(false);
|
||||||
|
return result.State switch
|
||||||
|
{
|
||||||
|
ResultState.Success => ({{resultTypeDef}})result.Value,
|
||||||
|
ResultState.Error => await recover(result.Error!).ConfigureAwait(false),
|
||||||
|
_ => throw new ResultNotInitializedException(nameof(resultTask))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,18 +34,6 @@ public static partial class Ensure
|
|||||||
_ => throw new EnsureNotInitializedException(nameof(ensureTask))
|
_ => throw new EnsureNotInitializedException(nameof(ensureTask))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
[Pure] public static Ensure<string> NotWhitespace(this in Ensure<string> ensure, Error error = default!)
|
|
||||||
{
|
|
||||||
return ensure.State switch
|
|
||||||
{
|
|
||||||
ResultState.Success => string.IsNullOrWhiteSpace(ensure.Value)
|
|
||||||
? new(error ?? Error.New(DefaultErrorType, $"Value {{{ensure.ValueExpression}}} is empty or consists exclusively of white-space characters."), ensure.ValueExpression)
|
|
||||||
: new(ensure.Value, ensure.ValueExpression),
|
|
||||||
ResultState.Error => new(ensure.Error!, ensure.ValueExpression),
|
|
||||||
_ => throw new EnsureNotInitializedException(nameof(ensure))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public readonly struct Ensure<T>
|
public readonly struct Ensure<T>
|
||||||
@@ -60,6 +48,7 @@ public readonly struct Ensure<T>
|
|||||||
Value = value;
|
Value = value;
|
||||||
ValueExpression = valueExpression;
|
ValueExpression = valueExpression;
|
||||||
State = ResultState.Success;
|
State = ResultState.Success;
|
||||||
|
Error = default;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal Ensure(Error error, string valueExpression)
|
internal Ensure(Error error, string valueExpression)
|
||||||
@@ -72,7 +61,12 @@ public readonly struct Ensure<T>
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Serializable]
|
[Serializable]
|
||||||
public class EnsureNotInitializedException(string variableName = "this") : InvalidOperationException("Ensure was not properly initialized.")
|
public class EnsureNotInitializedException : InvalidOperationException
|
||||||
{
|
{
|
||||||
public string VariableName { get; } = variableName;
|
public EnsureNotInitializedException(string variableName = "this")
|
||||||
|
: base("Ensure was not properly initialized.")
|
||||||
|
{
|
||||||
|
VariableName = variableName;
|
||||||
|
}
|
||||||
|
public string VariableName { get; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ public abstract class Error : IEquatable<Error>, IComparable<Error>
|
|||||||
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
public static Error Many(Error error1, Error error2) => (error1, error2) switch
|
public static Error Many(Error error1, Error error2) => (error1, error2) switch
|
||||||
{
|
{
|
||||||
(null, null) => new ManyErrors([]),
|
(null, null) => new ManyErrors(new List<Error>()),
|
||||||
(Error err, null) => err,
|
(Error err, null) => err,
|
||||||
(Error err, { IsEmpty: true }) => err,
|
(Error err, { IsEmpty: true }) => err,
|
||||||
(null, Error err) => err,
|
(null, Error err) => err,
|
||||||
@@ -178,14 +178,17 @@ public sealed class ExceptionalError : Error
|
|||||||
{
|
{
|
||||||
internal readonly Exception? Exception;
|
internal readonly Exception? Exception;
|
||||||
|
|
||||||
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
internal static string ToErrorType(Type exceptionType) => exceptionType.FullName ?? exceptionType.Name;
|
||||||
|
|
||||||
internal ExceptionalError(Exception exception)
|
internal ExceptionalError(Exception exception)
|
||||||
: this(exception.GetType().FullName ?? exception.GetType().Name, exception.Message)
|
: this(ToErrorType(exception.GetType()), exception.Message)
|
||||||
{
|
{
|
||||||
Exception = exception;
|
Exception = exception;
|
||||||
ExtensionData = ExtractExtensionData(exception);
|
ExtensionData = ExtractExtensionData(exception);
|
||||||
}
|
}
|
||||||
internal ExceptionalError(string message, Exception exception)
|
internal ExceptionalError(string message, Exception exception)
|
||||||
: this(exception.GetType().FullName ?? exception.GetType().Name, message)
|
: this(ToErrorType(exception.GetType()), message)
|
||||||
{
|
{
|
||||||
Exception = exception;
|
Exception = exception;
|
||||||
ExtensionData = ExtractExtensionData(exception);
|
ExtensionData = ExtractExtensionData(exception);
|
||||||
@@ -231,7 +234,7 @@ public sealed class ExceptionalError : Error
|
|||||||
var valueString = value.ToString();
|
var valueString = value.ToString();
|
||||||
if (string.IsNullOrEmpty(keyString) || string.IsNullOrEmpty(valueString)) continue;
|
if (string.IsNullOrEmpty(keyString) || string.IsNullOrEmpty(valueString)) continue;
|
||||||
|
|
||||||
values ??= [];
|
values ??= new List<KeyValuePair<string, string>>(4);
|
||||||
values.Add(new(keyString, valueString));
|
values.Add(new(keyString, valueString));
|
||||||
}
|
}
|
||||||
return values?.ToImmutableDictionary() ?? ImmutableDictionary<string, string>.Empty;
|
return values?.ToImmutableDictionary() ?? ImmutableDictionary<string, string>.Empty;
|
||||||
@@ -377,7 +380,11 @@ public sealed class ManyErrors : Error, IEnumerable<Error>, IReadOnlyList<Error>
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Serializable]
|
[Serializable]
|
||||||
public sealed class ErrorException(string type, string message) : Exception(message)
|
public sealed class ErrorException : Exception
|
||||||
{
|
{
|
||||||
public string Type { get; } = type ?? nameof(ErrorException);
|
public ErrorException(string type, string message) : base(message)
|
||||||
|
{
|
||||||
|
Type = type ?? nameof(ErrorException);
|
||||||
|
}
|
||||||
|
public string Type { get; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ public sealed class ErrorJsonConverter : JsonConverter<Error>
|
|||||||
|
|
||||||
internal static ManyErrors ReadMany(ref Utf8JsonReader reader)
|
internal static ManyErrors ReadMany(ref Utf8JsonReader reader)
|
||||||
{
|
{
|
||||||
List<Error> errors = [];
|
List<Error> errors = new(4);
|
||||||
while (reader.Read())
|
while (reader.Read())
|
||||||
{
|
{
|
||||||
if (reader.TokenType == JsonTokenType.StartObject)
|
if (reader.TokenType == JsonTokenType.StartObject)
|
||||||
@@ -83,7 +83,7 @@ public sealed class ErrorJsonConverter : JsonConverter<Error>
|
|||||||
}
|
}
|
||||||
else if (!string.IsNullOrEmpty(propname))
|
else if (!string.IsNullOrEmpty(propname))
|
||||||
{
|
{
|
||||||
extensionData ??= [];
|
extensionData ??= new(4);
|
||||||
extensionData.Add(new(propname, propvalue));
|
extensionData.Add(new(propname, propvalue));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
|
||||||
|
<LangVersion>10.0</LangVersion>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<AssemblyName>Just.Railway</AssemblyName>
|
<AssemblyName>Just.Railway</AssemblyName>
|
||||||
@@ -13,7 +14,6 @@
|
|||||||
<Copyright>Copyright (c) 2023 JustFixMe</Copyright>
|
<Copyright>Copyright (c) 2023 JustFixMe</Copyright>
|
||||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||||
|
|
||||||
<RepositoryUrl>https://github.com/JustFixMe/Just.Railway/</RepositoryUrl>
|
<RepositoryUrl>https://github.com/JustFixMe/Just.Railway/</RepositoryUrl>
|
||||||
|
|
||||||
<EmitCompilerGeneratedFiles Condition="'$(Configuration)'=='Debug'">true</EmitCompilerGeneratedFiles>
|
<EmitCompilerGeneratedFiles Condition="'$(Configuration)'=='Debug'">true</EmitCompilerGeneratedFiles>
|
||||||
|
|||||||
@@ -10,58 +10,58 @@ internal static class ReflectionHelper
|
|||||||
|
|
||||||
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
public static int Compare<T>(T? left, T? right) => TypeReflectionCache<T>.CompareFunc(left, right);
|
public static int Compare<T>(T? left, T? right) => TypeReflectionCache<T>.CompareFunc(left, right);
|
||||||
}
|
|
||||||
|
|
||||||
file static class TypeReflectionCache<T>
|
private static class TypeReflectionCache<T>
|
||||||
{
|
|
||||||
public static readonly Func<T?, T?, bool> IsEqualFunc;
|
|
||||||
public static readonly Func<T?, T?, int> CompareFunc;
|
|
||||||
|
|
||||||
static TypeReflectionCache()
|
|
||||||
{
|
{
|
||||||
var type = typeof(T);
|
public static readonly Func<T?, T?, bool> IsEqualFunc;
|
||||||
var isNullableStruct = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
|
public static readonly Func<T?, T?, int> CompareFunc;
|
||||||
var underlyingType = isNullableStruct ? type.GenericTypeArguments.First() : type;
|
|
||||||
var thisType = typeof(TypeReflectionCache<T>);
|
|
||||||
|
|
||||||
var equatableType = typeof(IEquatable<>).MakeGenericType(underlyingType);
|
static TypeReflectionCache()
|
||||||
if (equatableType.IsAssignableFrom(underlyingType))
|
|
||||||
{
|
{
|
||||||
var isEqualFunc = thisType.GetMethod(isNullableStruct ? nameof(IsEqualNullable) : nameof(IsEqual), BindingFlags.Static | BindingFlags.Public)
|
var type = typeof(T);
|
||||||
!.MakeGenericMethod(underlyingType);
|
var isNullableStruct = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
|
||||||
|
var underlyingType = isNullableStruct ? type.GenericTypeArguments.First() : type;
|
||||||
|
var thisType = typeof(TypeReflectionCache<T>);
|
||||||
|
|
||||||
IsEqualFunc = (Func<T?, T?, bool>)Delegate.CreateDelegate(typeof(Func<T?, T?, bool>), isEqualFunc);
|
var equatableType = typeof(IEquatable<>).MakeGenericType(underlyingType);
|
||||||
}
|
if (equatableType.IsAssignableFrom(underlyingType))
|
||||||
else
|
{
|
||||||
{
|
var isEqualFunc = thisType.GetMethod(isNullableStruct ? nameof(IsEqualNullable) : nameof(IsEqual), BindingFlags.Static | BindingFlags.Public)
|
||||||
IsEqualFunc = static (left, right) => left is null ? right is null : left.Equals(right);
|
!.MakeGenericMethod(underlyingType);
|
||||||
|
|
||||||
|
IsEqualFunc = (Func<T?, T?, bool>)Delegate.CreateDelegate(typeof(Func<T?, T?, bool>), isEqualFunc);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
IsEqualFunc = static (left, right) => left is null ? right is null : left.Equals(right);
|
||||||
|
}
|
||||||
|
|
||||||
|
var comparableType = typeof(IComparable<>).MakeGenericType(underlyingType);
|
||||||
|
if (comparableType.IsAssignableFrom(underlyingType))
|
||||||
|
{
|
||||||
|
var compareFunc = thisType.GetMethod(isNullableStruct ? nameof(CompareNullable) : nameof(Compare), BindingFlags.Static | BindingFlags.Public)
|
||||||
|
!.MakeGenericMethod(underlyingType);
|
||||||
|
|
||||||
|
CompareFunc = (Func<T?, T?, int>)Delegate.CreateDelegate(typeof(Func<T?, T?, int>), compareFunc);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
CompareFunc = static (left, right) => left is null
|
||||||
|
? right is null ? 0 : -1
|
||||||
|
: right is null ? 1 : left.GetHashCode().CompareTo(right.GetHashCode());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var comparableType = typeof(IComparable<>).MakeGenericType(underlyingType);
|
#pragma warning disable CS8604 // Possible null reference argument.
|
||||||
if (comparableType.IsAssignableFrom(underlyingType))
|
[Pure] public static bool IsEqual<R>(R? left, R? right) where R : notnull, IEquatable<R>, T => left is null ? right is null : left.Equals(right);
|
||||||
{
|
[Pure] public static bool IsEqualNullable<R>(R? left, R? right) where R : struct, IEquatable<R> => left is null ? right is null : right is not null && left.Value.Equals(right.Value);
|
||||||
var compareFunc = thisType.GetMethod(isNullableStruct ? nameof(CompareNullable) : nameof(Compare), BindingFlags.Static | BindingFlags.Public)
|
|
||||||
!.MakeGenericMethod(underlyingType);
|
|
||||||
|
|
||||||
CompareFunc = (Func<T?, T?, int>)Delegate.CreateDelegate(typeof(Func<T?, T?, int>), compareFunc);
|
[Pure] public static int Compare<R>(R? left, R? right) where R : notnull, IComparable<R>, T => left is null
|
||||||
}
|
? right is null ? 0 : -1
|
||||||
else
|
: right is null ? 1 : left.CompareTo(right);
|
||||||
{
|
[Pure] public static int CompareNullable<R>(R? left, R? right) where R : struct, IComparable<R> => left is null
|
||||||
CompareFunc = static (left, right) => left is null
|
? right is null ? 0 : -1
|
||||||
? right is null ? 0 : -1
|
: right is null ? 1 : left.Value.CompareTo(right.Value);
|
||||||
: right is null ? 1 : left.GetHashCode().CompareTo(right.GetHashCode());
|
#pragma warning restore CS8604 // Possible null reference argument.
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma warning disable CS8604 // Possible null reference argument.
|
|
||||||
[Pure] public static bool IsEqual<R>(R? left, R? right) where R : notnull, IEquatable<R>, T => left is null ? right is null : left.Equals(right);
|
|
||||||
[Pure] public static bool IsEqualNullable<R>(R? left, R? right) where R : struct, IEquatable<R> => left is null ? right is null : right is not null && left.Value.Equals(right.Value);
|
|
||||||
|
|
||||||
[Pure] public static int Compare<R>(R? left, R? right) where R : notnull, IComparable<R>, T => left is null
|
|
||||||
? right is null ? 0 : -1
|
|
||||||
: right is null ? 1 : left.CompareTo(right);
|
|
||||||
[Pure] public static int CompareNullable<R>(R? left, R? right) where R : struct, IComparable<R> => left is null
|
|
||||||
? right is null ? 0 : -1
|
|
||||||
: right is null ? 1 : left.Value.CompareTo(right.Value);
|
|
||||||
#pragma warning restore CS8604 // Possible null reference argument.
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ internal enum ResultState : byte
|
|||||||
|
|
||||||
public readonly partial struct Result : IEquatable<Result>
|
public readonly partial struct Result : IEquatable<Result>
|
||||||
{
|
{
|
||||||
|
internal SuccessUnit Value => new();
|
||||||
internal readonly Error? Error;
|
internal readonly Error? Error;
|
||||||
internal readonly ResultState State;
|
internal readonly ResultState State;
|
||||||
|
|
||||||
@@ -51,13 +52,18 @@ public readonly partial struct Result : IEquatable<Result>
|
|||||||
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
public static implicit operator Result(Error error) => new(error ?? throw new ArgumentNullException(nameof(error)));
|
public static implicit operator Result(Error error) => new(error ?? throw new ArgumentNullException(nameof(error)));
|
||||||
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static implicit operator Result(Exception exception) => new(
|
||||||
|
new ExceptionalError(exception ?? throw new ArgumentNullException(nameof(exception))));
|
||||||
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
public static implicit operator Result<SuccessUnit>(Result result) => result.State switch
|
public static implicit operator Result<SuccessUnit>(Result result) => result.State switch
|
||||||
{
|
{
|
||||||
ResultState.Success => new(new SuccessUnit()),
|
ResultState.Success => new(new SuccessUnit()),
|
||||||
ResultState.Error => new(result.Error!),
|
ResultState.Error => new(result.Error!),
|
||||||
_ => throw new ResultNotInitializedException(nameof(result))
|
_ => throw new ResultNotInitializedException(nameof(result))
|
||||||
};
|
};
|
||||||
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static explicit operator Result(SuccessUnit _) => new(null);
|
||||||
|
|
||||||
[Pure] public bool IsSuccess => Error is null;
|
[Pure] public bool IsSuccess => Error is null;
|
||||||
[Pure] public bool IsFailure => Error is not null;
|
[Pure] public bool IsFailure => Error is not null;
|
||||||
|
|
||||||
@@ -136,16 +142,23 @@ public readonly struct Result<T> : IEquatable<Result<T>>
|
|||||||
{
|
{
|
||||||
Value = value;
|
Value = value;
|
||||||
State = ResultState.Success;
|
State = ResultState.Success;
|
||||||
|
Error = default;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Pure] public static explicit operator Result(Result<T> result) => result.State switch
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static explicit operator Result(Result<T> result) => result.State switch
|
||||||
{
|
{
|
||||||
ResultState.Success => new(null),
|
ResultState.Success => new(null),
|
||||||
ResultState.Error => new(result.Error!),
|
ResultState.Error => new(result.Error!),
|
||||||
_ => throw new ResultNotInitializedException(nameof(result))
|
_ => throw new ResultNotInitializedException(nameof(result))
|
||||||
};
|
};
|
||||||
[Pure] public static implicit operator Result<T>(Error error) => new(error);
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
[Pure] public static implicit operator Result<T>(T value) => new(value);
|
public static implicit operator Result<T>(Error error) => new(error);
|
||||||
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static implicit operator Result<T>(Exception exception) => new(
|
||||||
|
new ExceptionalError(exception ?? throw new ArgumentNullException(nameof(exception))));
|
||||||
|
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static implicit operator Result<T>(T value) => new(value);
|
||||||
[Pure] public bool IsSuccess => State == ResultState.Success;
|
[Pure] public bool IsSuccess => State == ResultState.Success;
|
||||||
[Pure] public bool IsFailure => State == ResultState.Error;
|
[Pure] public bool IsFailure => State == ResultState.Error;
|
||||||
|
|
||||||
@@ -263,7 +276,12 @@ public readonly struct SuccessUnit : IEquatable<SuccessUnit>
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Serializable]
|
[Serializable]
|
||||||
public class ResultNotInitializedException(string variableName = "this") : InvalidOperationException("Result was not properly initialized.")
|
public class ResultNotInitializedException : InvalidOperationException
|
||||||
{
|
{
|
||||||
public string VariableName { get; } = variableName;
|
public ResultNotInitializedException(string variableName = "this")
|
||||||
|
: base("Result was not properly initialized.")
|
||||||
|
{
|
||||||
|
VariableName = variableName;
|
||||||
|
}
|
||||||
|
public string VariableName { get; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ public static partial class ResultExtensions
|
|||||||
{
|
{
|
||||||
case ResultState.Error:
|
case ResultState.Error:
|
||||||
hasErrors = true;
|
hasErrors = true;
|
||||||
errors ??= [];
|
errors ??= new(4);
|
||||||
errors.Add(result.Error!);
|
errors.Add(result.Error!);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -123,13 +123,13 @@ public static partial class ResultExtensions
|
|||||||
{
|
{
|
||||||
case ResultState.Error:
|
case ResultState.Error:
|
||||||
hasErrors = true;
|
hasErrors = true;
|
||||||
errors ??= [];
|
errors ??= new(4);
|
||||||
errors.Add(result.Error!);
|
errors.Add(result.Error!);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case ResultState.Success:
|
case ResultState.Success:
|
||||||
if (hasErrors) goto afterLoop;
|
if (hasErrors) goto afterLoop;
|
||||||
values ??= [];
|
values ??= new(4);
|
||||||
values.Add(result.Value);
|
values.Add(result.Value);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|||||||
@@ -128,4 +128,45 @@ public class GeneralUsage
|
|||||||
// Then
|
// Then
|
||||||
Assert.Equal("satisfied", result);
|
Assert.Equal("satisfied", result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecoverResultFromFailureState()
|
||||||
|
{
|
||||||
|
// Given
|
||||||
|
Result<string> failed = new NotImplementedException();
|
||||||
|
// When
|
||||||
|
var result = failed.TryRecover(err =>
|
||||||
|
{
|
||||||
|
Assert.IsType<NotImplementedException>(err.ToException());
|
||||||
|
|
||||||
|
if (err.Type == "System.NotImplementedException")
|
||||||
|
return "recovered";
|
||||||
|
|
||||||
|
Assert.Fail();
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
// Then
|
||||||
|
Assert.True(result.IsSuccess);
|
||||||
|
Assert.Equal("recovered", result.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WhenCanNotRecoverResultFromFailureState()
|
||||||
|
{
|
||||||
|
// Given
|
||||||
|
var error = Error.New("test");
|
||||||
|
Result<string> failed = new NotImplementedException();
|
||||||
|
// When
|
||||||
|
var result = failed.TryRecover(err =>
|
||||||
|
{
|
||||||
|
if (err.Type == "System.NotImplementedException")
|
||||||
|
return error;
|
||||||
|
|
||||||
|
Assert.Fail();
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
// Then
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(error, result.Error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user