Files
aeqw89.tools.Publish/aeqw89.tools.Publish/Result.cs
T

63 lines
2.2 KiB
C#

using System.Diagnostics;
namespace aeqw89.tools.Publish;
record Success {
public static Ok<Success> AsResult() => new Ok<Success>(new Success());
}
record Ok<T>(T Value);
record ReadableError(string Reason, bool ShowHelp = true, bool RestoreContext = true);
union Result<T, E>(Ok<T>, E);
internal static class ResultExtensions {
public static T Unwrap<T>(this Result<T, ReadableError> result, Program.RunContext? rctx = null) {
switch (result) {
case Ok<T> r:
return r.Value;
case ReadableError error:
Program.ShowError(error.Reason);
if (error.ShowHelp) Program.ShowHelp();
if (error.RestoreContext) rctx?.Restore();
Environment.Exit(1);
throw new UnreachableException();
}
throw new UnreachableException();
}
public static async Task<T> Unwrap<T>(this Task<Result<T, ReadableError>> result, Program.RunContext? rctx = null) {
return (await result).Unwrap(rctx);
}
public static Result<TTo, ETo> Cast<TFrom, EFrom, TTo, ETo>(this Result<TFrom, EFrom> result) where TTo : notnull, TFrom where ETo: notnull, EFrom {
return result switch {
TFrom tfrom => ((TTo)tfrom).Ok(),
EFrom efrom => ((ETo)efrom),
_ => throw new UnreachableException()
};
}
public static Result<TTo, ETo> Upcast<TFrom, EFrom, TTo, ETo>(this Result<TFrom, EFrom> result)
where TFrom : TTo
where EFrom : ETo
{
return result switch {
TFrom tfrom => ((TTo)tfrom).Ok(), // Foo -> IFoo, implicit upcast, can't throw
EFrom efrom => ((ETo)efrom),
_ => throw new UnreachableException()
};
}
public static Result<TTo, E> CastSuccess<TFrom, TTo, E>(this Result<TFrom, E> result) where TTo : notnull, TFrom where E: notnull
=> Cast<TFrom, E, TTo, E>(result);
public static Result<TTo, E> UpcastSuccess<TFrom, TTo, E>(this Result<TFrom, E> result) where TFrom : notnull, TTo where E: notnull
=> Upcast<TFrom, E, TTo, E>(result);
}
internal static class ObjectExtensions {
public static Ok<T> Ok<T>(this T any) {
return new Ok<T>(any);
}
}