public RequestHandler <TRep> MakeRequestHandler(Uri baseUri, Router <TRep> router) { return(async(request, modelBinder) => { var requestUri = new Uri(request.Uri.PathAndQuery.ToString(), UriKind.Relative); var path = new BaseUrlRelativePath(requestUri.ToString().Substring(baseUri.ToString().Length)); var target = router(path); OneOf <Resource <TRep>, None> oneOf = (await target); return await oneOf.Match( resource => resource.GetMethodHandler(request.Method) .Match( async handler => { var bindResult = await modelBinder(handler.Parameters); var response = await bindResult.Match( failed => Task.FromResult <Response <TRep> >(new Response <TRep> .ModelBindingFailedResponse()), async boundModel => (await handler.Invoke(boundModel)).Match( representation => (Response <TRep>) new Response <TRep> .RepresentationResponse(representation.Representation) )); return response; }, none => Task.FromResult((Response <TRep>) new Response <TRep> .MethodNotAllowed())), none => Task.FromResult((Response <TRep>) new Response <TRep> .NotFoundResponse())); }); }
private OneOf <string, int> Convert(OneOf <string, int> source) { return(source.Match <OneOf <string, int> >( (str) => int.Parse(str), (num) => num.ToString() )); }
public static OneOf <TSuccessNew, TError> ContinueOnSuccessWith <TSuccessOriginal, TError, TSuccessNew>( this OneOf <TSuccessOriginal, TError> original, Func <TSuccessOriginal, OneOf <TSuccessNew, TError> > continuation) { return(original.Match( originalSuccess => continuation(originalSuccess).Match <OneOf <TSuccessNew, TError> >(newSuccess => newSuccess, newError => newError), originalError => originalError)); }
public void ReturnsDefaultWhenNoMatch() { var oo = new OneOf <int, string>(123); var ret = oo.Match((string x) => FailIfCalled <string>()) .Else((object x) => "ELSE:" + x.ToString()); Assert.AreEqual("ELSE:123", ret); }
static async Task <Block> GetBlockAsync(RpcClient rpcClient, OneOf <uint, UInt256> id) { var task = id.Match( index => rpcClient.GetBlockHexAsync($"{index}"), hash => rpcClient.GetBlockHexAsync($"{hash}")); var hex = await task.ConfigureAwait(false); return(Convert.FromBase64String(hex).AsSerializable <Block>()); }
public void ReturnsValueWhenMatch() { var oo = new OneOf <int, string>(123); var ret = oo.Match((string x) => FailIfCalled <string>()) .Match((int x) => "OK:" + x.ToString()); Assert.AreEqual("OK:123", ret); }
public void MatchActionSelectsFirstCorrectly(string testStr) { OneOf <string, int, float> strEither = new OneOf <string, int, float>(testStr); strEither.Match( (str) => Assert.Equal(testStr, str), (i) => Assert.True(false, "second is matched, but first was expected"), (f) => Assert.True(false, "third is matched, but first was expected") ); }
public void MatchActionSelectsSecondCorrectly() { int testInt = 5; OneOf <string, int, float> intEither = new OneOf <string, int, float>(testInt); intEither.Match( (str) => Assert.True(false, "first is matched, but second was expected"), (i) => Assert.Equal(testInt, i), (f) => Assert.True(false, "third is matched, but second was expected") ); }
public void MatchActionSelectsThirdCorrectly() { float testFloat = 5; OneOf <string, int, float> intEither = new OneOf <string, int, float>(testFloat); intEither.Match( (str) => Assert.True(false, "first is matched, but third was expected"), (i) => Assert.True(false, "second is matched, but third was expected"), (f) => Assert.Equal(testFloat, f) ); }
public static OneOf <TResult, TError> SelectMany <TSuccess1, TSuccess2, TError, TResult>( this OneOf <TSuccess1, TError> source, Func <TSuccess1, OneOf <TSuccess2, TError> > selector, Func <TSuccess1, TSuccess2, TResult> resultSelector) { return(source.Match( sourceSuccess => selector(sourceSuccess).Match <OneOf <TResult, TError> >( secondSuccess => resultSelector(sourceSuccess, secondSuccess), error => error), error => error)); }
public void ThrowsExceptionWhenNoMatch() { var oo = new OneOf <int, string>(123); TestDelegate test = () => { var ret = oo .Match((string x) => FailIfCalled <string>()) .ElseThrow((object x) => new InvalidOperationException()); }; NUnit.Framework.Assert.Throws <InvalidOperationException>(test); }
public async Task ExecuteResultAsync(ActionContext context) { context.HttpContext.Response.StatusCode = StatusCodes.Status200OK; context.HttpContext.Response.Headers.Add(HeaderNames.ContentType, "text/csv"); context.HttpContext.Response.Headers.Add( HeaderNames.ContentDisposition, new ContentDispositionHeaderValue("attachment") { FileName = _fileName }.ToString()); await using (var stream = context.HttpContext.Response.Body) await using (var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true))) await using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csvWriter.WriteHeader <T>(); await csvWriter.NextRecordAsync(); await writer.FlushAsync(); await _records.Match( async records => { foreach (var record in records) { await WriteRecord(record); } }, async records => { await foreach (var record in records) { await WriteRecord(record); } }); async Task WriteRecord(T record) { csvWriter.WriteRecord(record); await csvWriter.NextRecordAsync(); await writer.FlushAsync(); } } }
public async ValueTask <bool> MoveNextAsync() { if (!_pageInfo.HasNextPage) { return(false); } Current = await NyaaSiService.SearchAsync(_request); if (Current.Match((IAniListError error) => true) .Match(data => data.PageInfo?.HasNextPage != true)) { return(false); } _request.PageNumber += 1; Current.Switch(result => _pageInfo.HasNextPage = result.PageInfo.HasNextPage = result.Data.Count >= 75); return(true); }
static void AtomicUpdate(ref TrackingMap trackingMap, byte[]?key, OneOf <byte[]?, None> value) { key = key == null?Array.Empty <byte>() : key.AsSpan().ToArray(); var _value = value.Match <OneOf <ReadOnlyMemory <byte>, None> >( v => v == null ? default(ReadOnlyMemory <byte>) : v.AsSpan().ToArray(), n => n); var priorCollection = Volatile.Read(ref trackingMap); do { var updatedCollection = priorCollection.SetItem(key, _value); var interlockedResult = Interlocked.CompareExchange(ref trackingMap, updatedCollection, priorCollection); if (object.ReferenceEquals(priorCollection, interlockedResult)) { break; } priorCollection = interlockedResult; }while (true); }
public IActionResult Get(int id) { OneOf <Product, NotFound, SystemError> result = GetProject(id); return(result.Match <IActionResult>( product => { _logger.LogInformation("查询成功"); return new JsonResult(product); }, notfound => { _logger.LogInformation("没有查到"); return new NotFoundResult(); }, systemerror => { _logger.LogError("查询成败"); return new StatusCodeResult(500); })); }
public async ValueTask <bool> MoveNextAsync() { if (_info.Remaining == false) { return(false); } var pageResult = await _source._getPage(_info, default); Current = pageResult; if (Current.Match((IAniListError error) => true) .Match(data => (data.PageInfo?.CurrentPage ?? 0) == 0)) { return(false); } _info.Page++; _info.Remaining = _source._nextPage(_info, Current); return(true); }
public static OneOf <TSuccessNew, TError> Select <TSuccessOriginal, TSuccessNew, TError>( this OneOf <TSuccessOriginal, TError> source, Func <TSuccessOriginal, TSuccessNew> projection) { return(source.Match <OneOf <TSuccessNew, TError> >(success => projection(success), error => error)); }
public static OneOf <TSuccess, TErrorNew> SelectError <TSuccess, TErrorOriginal, TErrorNew>( this OneOf <TSuccess, TErrorOriginal> source, Func <TErrorOriginal, TErrorNew> projection) { return(source.Match <OneOf <TSuccess, TErrorNew> >(success => success, error => projection(error))); }
public static ExecutableAction From(OneOf <ActionDefinition, ContextActionDefinition, ContextDataActionDefinition> actionDefinition) => actionDefinition.Match(From, From, From);
public static SubmissionResult Map( OneOf <int, IReadOnlyList <ChallengeResult>, IReadOnlyList <CompileErrorMessage> > o) => o.Match( score => new SubmissionResult(score, null, null), runErrors => new SubmissionResult(null, null, runErrors), compileErrors => new SubmissionResult(null, compileErrors, null));
private static bool HasNextPage <T>(PagingInfo info, OneOf <IPagedData <T>, IAniListError> data) => data.Match((IAniListError error) => false) .Match(pagedData => pagedData?.PageInfo?.HasNextPage == true);
public T Match <T>(Func <TimeSpan, T> matchFunc, Func <string, T> matchFunc2, Func <T> defaultFunc) => _input3.Match(matchFunc, matchFunc2);
public T Match <T>(Func <int, T> matchFunc, Func <string, T> matchFunc2) => _input1.Match(matchFunc, matchFunc2);
public void DefaultConstructorSetsValueToDefaultValueOfT0() { var x = new OneOf <int, bool>(); var result = x.Match(n => n == default(int), n => false); }
public static OneOf <TSuccess, TError> Flatten <TSuccess, TError>(this OneOf <OneOf <TSuccess, TError>, TError> source) { return(source.Match(inner => inner.Match <OneOf <TSuccess, TError> >(success => success, error => error), error => error)); }
public static T Bifold <T>(this OneOf <T, T> source) { return(source.Match(success => success, error => error)); }
private static string ToString(OneOf <Result <MetaData>, Error> r) { return(r.Match(a => a.results.Single().provider.display_name, e => e.error)); }