diff --git a/src/TypeCache.GraphQL/Attributes/GraphQLDeprecationReasonAttribute.cs b/src/TypeCache.GraphQL/Attributes/GraphQLDeprecationReasonAttribute.cs index 57e00cc9..adc83f4c 100644 --- a/src/TypeCache.GraphQL/Attributes/GraphQLDeprecationReasonAttribute.cs +++ b/src/TypeCache.GraphQL/Attributes/GraphQLDeprecationReasonAttribute.cs @@ -13,7 +13,7 @@ public sealed class GraphQLDeprecationReasonAttribute : Attribute { public GraphQLDeprecationReasonAttribute(string deprecationReason) { - deprecationReason.AssertNotBlank(); + deprecationReason.ThrowIfBlank(); this.DeprecationReason = deprecationReason; } diff --git a/src/TypeCache.GraphQL/Attributes/GraphQLDescriptionAttribute.cs b/src/TypeCache.GraphQL/Attributes/GraphQLDescriptionAttribute.cs index 1a16b76c..c510acda 100644 --- a/src/TypeCache.GraphQL/Attributes/GraphQLDescriptionAttribute.cs +++ b/src/TypeCache.GraphQL/Attributes/GraphQLDescriptionAttribute.cs @@ -13,7 +13,7 @@ public sealed class GraphQLDescriptionAttribute : Attribute { public GraphQLDescriptionAttribute(string description) { - description.AssertNotBlank(); + description.ThrowIfBlank(); this.Description = description; } diff --git a/src/TypeCache.GraphQL/Attributes/GraphQLInputNameAttribute.cs b/src/TypeCache.GraphQL/Attributes/GraphQLInputNameAttribute.cs index 900361e1..b15a7fa1 100644 --- a/src/TypeCache.GraphQL/Attributes/GraphQLInputNameAttribute.cs +++ b/src/TypeCache.GraphQL/Attributes/GraphQLInputNameAttribute.cs @@ -14,7 +14,7 @@ public sealed class GraphQLInputNameAttribute : Attribute /// public GraphQLInputNameAttribute(string name) { - name.AssertNotBlank(); + name.ThrowIfBlank(); this.Name = name; } diff --git a/src/TypeCache.GraphQL/Attributes/GraphQLNameAttribute.cs b/src/TypeCache.GraphQL/Attributes/GraphQLNameAttribute.cs index 85978628..37b06687 100644 --- a/src/TypeCache.GraphQL/Attributes/GraphQLNameAttribute.cs +++ b/src/TypeCache.GraphQL/Attributes/GraphQLNameAttribute.cs @@ -14,7 +14,7 @@ public sealed class GraphQLNameAttribute : Attribute /// public GraphQLNameAttribute(string name) { - name.AssertNotBlank(); + name.ThrowIfBlank(); this.Name = name; } diff --git a/src/TypeCache.GraphQL/Extensions/GraphQLExtensions.cs b/src/TypeCache.GraphQL/Extensions/GraphQLExtensions.cs index e208c7a2..cbaff4b3 100644 --- a/src/TypeCache.GraphQL/Extensions/GraphQLExtensions.cs +++ b/src/TypeCache.GraphQL/Extensions/GraphQLExtensions.cs @@ -183,8 +183,8 @@ public static Type ToGraphQLType(this Type @this, bool isInputType) return @this.ToGraphQLEnumType(); var objectType = @this.GetObjectType(); - (objectType is ObjectType.Delegate).AssertFalse(); - (objectType is ObjectType.Object).AssertFalse(); + (objectType is ObjectType.Delegate).ThrowIfTrue(); + (objectType is ObjectType.Object).ThrowIfTrue(); var scalarGraphType = @this.GetScalarType().ToGraphType(); if (scalarGraphType is not null) diff --git a/src/TypeCache.GraphQL/Extensions/ResolveFieldContextExtensions.cs b/src/TypeCache.GraphQL/Extensions/ResolveFieldContextExtensions.cs index 8f7a6054..aedba7b8 100644 --- a/src/TypeCache.GraphQL/Extensions/ResolveFieldContextExtensions.cs +++ b/src/TypeCache.GraphQL/Extensions/ResolveFieldContextExtensions.cs @@ -13,7 +13,7 @@ public static class ResolveFieldContextExtensions { public static DataTable GetArgumentAsDataTable(this IResolveFieldContext @this, string name, ObjectSchema objectSchema) { - name.AssertNotBlank(); + name.ThrowIfBlank(); var table = objectSchema.CreateDataTable(); var arguments = @this.GetArgument>>(name).ToArray(); diff --git a/src/TypeCache.GraphQL/Extensions/SchemaExtensions.cs b/src/TypeCache.GraphQL/Extensions/SchemaExtensions.cs index f5e56ea9..9917887a 100644 --- a/src/TypeCache.GraphQL/Extensions/SchemaExtensions.cs +++ b/src/TypeCache.GraphQL/Extensions/SchemaExtensions.cs @@ -7,7 +7,6 @@ using GraphQL.Types; using Microsoft.Extensions.DependencyInjection; using TypeCache.Attributes; -using TypeCache.Collections; using TypeCache.Data; using TypeCache.Data.Extensions; using TypeCache.Extensions; @@ -16,6 +15,7 @@ using TypeCache.GraphQL.Resolvers; using TypeCache.GraphQL.SqlApi; using TypeCache.GraphQL.Types; +using TypeCache.Utilities; namespace TypeCache.GraphQL.Extensions; @@ -59,7 +59,7 @@ public static FieldType[] AddDatabaseSchemaQueries(this ISchema @this, IDataSour /// public static FieldType AddDatabaseSchemaQuery(this ISchema @this, IDataSource dataSource, SchemaCollection collection) { - dataSource.AssertNotNull(); + dataSource.ThrowIfNull(); var table = dataSource.GetDatabaseSchema(collection); var graphDatabasesEnum = new EnumerationGraphType { @@ -136,7 +136,7 @@ public static void AddDatabaseEndpoints(this ISchema @this, IDataSource dataSour const string ColumnName = nameof(ColumnName); const string ColumnType = nameof(ColumnType); - dataSource.AssertNotNull(); + dataSource.ThrowIfNull(); database ??= dataSource.DefaultDatabase; var objectSchemas = dataSource.ObjectSchemas.Values.ToArray(); @@ -830,8 +830,8 @@ public static void AddSqlApiEndpoints(this ISchema @this, IDataSource dataSou public static FieldType AddSqlApiCallProcedureEndpoint(this ISchema @this, IDataSource dataSource, string procedure, bool mutation, string? graphQlName = null, IGraphType? graphQlType = null) where T : notnull, new() { - dataSource.AssertNotNull(); - procedure.AssertNotBlank(); + dataSource.ThrowIfNull(); + procedure.ThrowIfBlank(); var name = dataSource.Escape(procedure); var objectSchema = dataSource.ObjectSchemas[name]; @@ -875,8 +875,8 @@ public static FieldType AddSqlApiCallProcedureEndpoint(this ISchema @this, ID public static FieldType AddSqlApiDeleteDataEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; @@ -910,8 +910,8 @@ public static FieldType AddSqlApiDeleteDataEndpoint(this ISchema @this, IData public static FieldType AddSqlApiDeleteEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; @@ -946,8 +946,8 @@ public static FieldType AddSqlApiDeleteEndpoint(this ISchema @this, IDataSour public static FieldType AddSqlApiInsertDataEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; @@ -982,8 +982,8 @@ public static FieldType AddSqlApiInsertDataEndpoint(this ISchema @this, IData public static FieldType AddSqlApiInsertEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; @@ -1040,8 +1040,8 @@ public static FieldType AddSqlApiInsertEndpoint(this ISchema @this, IDataSour public static FieldType AddSqlApiSelectEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; @@ -1095,8 +1095,8 @@ public static FieldType AddSqlApiSelectEndpoint(this ISchema @this, IDataSour public static FieldType AddSqlApiUpdateDataEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; @@ -1130,8 +1130,8 @@ public static FieldType AddSqlApiUpdateDataEndpoint(this ISchema @this, IData public static FieldType AddSqlApiUpdateEndpoint(this ISchema @this, IDataSource dataSource, string table, string? graphQlName = null) where T : notnull, new() { - dataSource.AssertNotNull(); - table.AssertNotBlank(); + dataSource.ThrowIfNull(); + table.ThrowIfBlank(); var name = dataSource.Escape(table); var objectSchema = dataSource.ObjectSchemas[name]; diff --git a/src/TypeCache.GraphQL/Resolvers/BatchLoaderFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/BatchLoaderFieldResolver.cs index ffe38af0..0b0de93b 100644 --- a/src/TypeCache.GraphQL/Resolvers/BatchLoaderFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/BatchLoaderFieldResolver.cs @@ -4,9 +4,9 @@ using GraphQL; using GraphQL.DataLoader; using Microsoft.Extensions.DependencyInjection; -using TypeCache.Collections; using TypeCache.Extensions; using TypeCache.GraphQL.Extensions; +using TypeCache.Utilities; using IResolveFieldContext = global::GraphQL.IResolveFieldContext; namespace TypeCache.GraphQL.Resolvers; @@ -24,10 +24,10 @@ public sealed class BatchLoaderFieldResolver : FieldResolv /// public BatchLoaderFieldResolver(MethodInfo methodInfo, Func getParentKey, Func getChildKey, bool returnCollection) { - methodInfo.AssertNotNull(); - getParentKey.AssertNotNull(); - getChildKey.AssertNotNull(); - methodInfo.ReturnType.IsAny, Task, Task>, ValueTask, ValueTask>>().AssertTrue(); + methodInfo.ThrowIfNull(); + getParentKey.ThrowIfNull(); + getChildKey.ThrowIfNull(); + methodInfo.ReturnType.IsAny, Task, Task>, ValueTask, ValueTask>>().ThrowIfFalse(); this._DataLoaderKey = Invariant($"{typeof(PARENT).GraphQLName()}.{methodInfo.GraphQLName()}"); this._MethodInfo = methodInfo; @@ -39,11 +39,11 @@ public BatchLoaderFieldResolver(MethodInfo methodInfo, Func getPa /// protected override async ValueTask ResolveAsync(IResolveFieldContext context) { - context.RequestServices.AssertNotNull(); - context.Source.AssertNotNull(); + context.RequestServices.ThrowIfNull(); + context.Source.ThrowIfNull(); var dataLoaderAccessor = context.RequestServices.GetRequiredService(); - dataLoaderAccessor.Context.AssertNotNull(); + dataLoaderAccessor.Context.ThrowIfNull(); var key = this._GetParentKey((PARENT)context.Source); if (this._ReturnCollection) diff --git a/src/TypeCache.GraphQL/Resolvers/ItemLoaderFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/ItemLoaderFieldResolver.cs index 32cc9092..79d2c05d 100644 --- a/src/TypeCache.GraphQL/Resolvers/ItemLoaderFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/ItemLoaderFieldResolver.cs @@ -17,8 +17,8 @@ public sealed class ItemLoaderFieldResolver : FieldResolver /// public ItemLoaderFieldResolver(MethodInfo methodInfo) { - methodInfo.IsStatic.AssertTrue(); - methodInfo.ReturnType.IsAny, ValueTask>().AssertTrue(); + methodInfo.IsStatic.ThrowIfFalse(); + methodInfo.ReturnType.IsAny, ValueTask>().ThrowIfFalse(); this._MethodHandle = methodInfo.MethodHandle; this._Name = methodInfo.GraphQLName(); @@ -27,12 +27,12 @@ public ItemLoaderFieldResolver(MethodInfo methodInfo) /// protected override async ValueTask ResolveAsync(IResolveFieldContext context) { - context.RequestServices.AssertNotNull(); - context.Source.AssertNotNull(); + context.RequestServices.ThrowIfNull(); + context.Source.ThrowIfNull(); var dataLoaderAccessor = context.RequestServices.GetRequiredService(); var dataLoaderContext = dataLoaderAccessor.Context; - dataLoaderContext.AssertNotNull(); + dataLoaderContext.ThrowIfNull(); var loaderKey = Invariant($"{context.Source.GetType().GraphQLName()}.{this._Name}"); var dataLoader = dataLoaderContext.GetOrAddLoader(loaderKey, () => this.LoadData(context)); diff --git a/src/TypeCache.GraphQL/Resolvers/MethodFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/MethodFieldResolver.cs index e4188213..035290ce 100644 --- a/src/TypeCache.GraphQL/Resolvers/MethodFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/MethodFieldResolver.cs @@ -12,7 +12,7 @@ public sealed class MethodFieldResolver(MethodInfo methodInfo) : FieldResolver { protected override async ValueTask ResolveAsync(IResolveFieldContext context) { - context.RequestServices.AssertNotNull(); + context.RequestServices.ThrowIfNull(); var arguments = context.GetArguments(methodInfo).ToArray(); object? result; diff --git a/src/TypeCache.GraphQL/Resolvers/MethodSourceStreamResolver.cs b/src/TypeCache.GraphQL/Resolvers/MethodSourceStreamResolver.cs index 174f606a..a22e11e6 100644 --- a/src/TypeCache.GraphQL/Resolvers/MethodSourceStreamResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/MethodSourceStreamResolver.cs @@ -20,7 +20,7 @@ public MethodSourceStreamResolver(MethodInfo methodInfo) if (returnType is ObjectType.Task || returnType is ObjectType.ValueTask) returnsObservable = methodInfo.ReturnType.GenericTypeArguments.Single().GetObjectType() is ObjectType.Observable; - returnsObservable.AssertTrue(); + returnsObservable.ThrowIfFalse(); } this._MethodInfo = methodInfo; @@ -28,7 +28,7 @@ public MethodSourceStreamResolver(MethodInfo methodInfo) protected override ValueTask> ResolveAsync(global::GraphQL.IResolveFieldContext context) { - context.RequestServices.AssertNotNull(); + context.RequestServices.ThrowIfNull(); var arguments = context.GetArguments(this._MethodInfo).ToArray(); object? result; diff --git a/src/TypeCache.GraphQL/Resolvers/PropertyFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/PropertyFieldResolver.cs index 5b0493b3..a26e7cd6 100644 --- a/src/TypeCache.GraphQL/Resolvers/PropertyFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/PropertyFieldResolver.cs @@ -12,7 +12,7 @@ public sealed class PropertyFieldResolver(PropertyInfo propertyInfo) : FieldR { protected override async ValueTask ResolveAsync(IResolveFieldContext context) { - propertyInfo.AssertNotNull(); + propertyInfo.ThrowIfNull(); var source = context.Source switch { diff --git a/src/TypeCache.GraphQL/Resolvers/SqlApiDeleteFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/SqlApiDeleteFieldResolver.cs index fa41bec0..36785db0 100644 --- a/src/TypeCache.GraphQL/Resolvers/SqlApiDeleteFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/SqlApiDeleteFieldResolver.cs @@ -3,13 +3,13 @@ using System.Data; using GraphQL; using Microsoft.Extensions.DependencyInjection; -using TypeCache.Collections; using TypeCache.Data; using TypeCache.Data.Extensions; using TypeCache.Extensions; using TypeCache.GraphQL.Extensions; using TypeCache.GraphQL.SqlApi; using TypeCache.Mediation; +using TypeCache.Utilities; using static TypeCache.Data.DataSourceType; namespace TypeCache.GraphQL.Resolvers; diff --git a/src/TypeCache.GraphQL/Resolvers/SqlApiInsertFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/SqlApiInsertFieldResolver.cs index 7292306d..8bb0e425 100644 --- a/src/TypeCache.GraphQL/Resolvers/SqlApiInsertFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/SqlApiInsertFieldResolver.cs @@ -3,13 +3,13 @@ using System.Data; using GraphQL; using Microsoft.Extensions.DependencyInjection; -using TypeCache.Collections; using TypeCache.Data; using TypeCache.Data.Extensions; using TypeCache.Extensions; using TypeCache.GraphQL.Extensions; using TypeCache.GraphQL.SqlApi; using TypeCache.Mediation; +using TypeCache.Utilities; using static TypeCache.Data.DataSourceType; namespace TypeCache.GraphQL.Resolvers; diff --git a/src/TypeCache.GraphQL/Resolvers/SqlApiUpdateFieldResolver.cs b/src/TypeCache.GraphQL/Resolvers/SqlApiUpdateFieldResolver.cs index 677bc38c..4b35511b 100644 --- a/src/TypeCache.GraphQL/Resolvers/SqlApiUpdateFieldResolver.cs +++ b/src/TypeCache.GraphQL/Resolvers/SqlApiUpdateFieldResolver.cs @@ -3,13 +3,13 @@ using System.Data; using GraphQL; using Microsoft.Extensions.DependencyInjection; -using TypeCache.Collections; using TypeCache.Data; using TypeCache.Data.Extensions; using TypeCache.Extensions; using TypeCache.GraphQL.Extensions; using TypeCache.GraphQL.SqlApi; using TypeCache.Mediation; +using TypeCache.Utilities; using static TypeCache.Data.DataSourceType; namespace TypeCache.GraphQL.Resolvers; diff --git a/src/TypeCache.GraphQL/TypeCache.GraphQL.csproj b/src/TypeCache.GraphQL/TypeCache.GraphQL.csproj index 6033bfa1..bf57dddd 100644 --- a/src/TypeCache.GraphQL/TypeCache.GraphQL.csproj +++ b/src/TypeCache.GraphQL/TypeCache.GraphQL.csproj @@ -4,7 +4,7 @@ enable TypeCache.GraphQL TypeCache.GraphQL - 8.3.0 + 8.3.1 Samuel Abraham <sam987883@gmail.com> Samuel Abraham <sam987883@gmail.com> TypeCache GraphQL diff --git a/src/TypeCache.GraphQL/Types/GraphQLHashIdType.cs b/src/TypeCache.GraphQL/Types/GraphQLHashIdType.cs index dbda007f..d4736f80 100644 --- a/src/TypeCache.GraphQL/Types/GraphQLHashIdType.cs +++ b/src/TypeCache.GraphQL/Types/GraphQLHashIdType.cs @@ -22,7 +22,7 @@ public sealed class GraphQLHashIdType : ScalarGraphType /// public GraphQLHashIdType(IHashMaker hashMaker) { - hashMaker.AssertNotNull(); + hashMaker.ThrowIfNull(); this._HashMaker = hashMaker; this.Name = "HashID"; diff --git a/src/TypeCache.GraphQL/Types/GraphQLInterfaceType.cs b/src/TypeCache.GraphQL/Types/GraphQLInterfaceType.cs index 5ff94aa3..d78c2feb 100644 --- a/src/TypeCache.GraphQL/Types/GraphQLInterfaceType.cs +++ b/src/TypeCache.GraphQL/Types/GraphQLInterfaceType.cs @@ -12,7 +12,7 @@ public sealed class GraphQLInterfaceType : InterfaceGraphType { public GraphQLInterfaceType() { - typeof(T).IsInterface.AssertTrue(); + typeof(T).IsInterface.ThrowIfFalse(); this.Name = typeof(T).GraphQLName(); diff --git a/src/TypeCache.GraphQL/Types/GraphQLObjectType.cs b/src/TypeCache.GraphQL/Types/GraphQLObjectType.cs index 8b798e33..a3050d40 100644 --- a/src/TypeCache.GraphQL/Types/GraphQLObjectType.cs +++ b/src/TypeCache.GraphQL/Types/GraphQLObjectType.cs @@ -71,7 +71,7 @@ public FieldType AddQueryItem(MethodInfo methodInfo, Func, Task, Task>, ValueTask, ValueTask>>().AssertTrue(); + methodInfo.ReturnType.IsAny, Task, Task>, ValueTask, ValueTask>>().ThrowIfFalse(); var fieldType = new FieldType() { @@ -106,7 +106,7 @@ public FieldType AddQueryCollection(MethodInfo methodInfo, Func, Task, Task>, ValueTask, ValueTask>>().AssertTrue(); + methodInfo.ReturnType.IsAny, Task, Task>, ValueTask, ValueTask>>().ThrowIfFalse(); var fieldType = new FieldType() { diff --git a/src/TypeCache.Web/Attributes/RequireClaimAttribute.cs b/src/TypeCache.Web/Attributes/RequireClaimAttribute.cs index 1faec7ad..b09d9db2 100644 --- a/src/TypeCache.Web/Attributes/RequireClaimAttribute.cs +++ b/src/TypeCache.Web/Attributes/RequireClaimAttribute.cs @@ -1,8 +1,8 @@ // Copyright (c) 2021 Samuel Abraham using Microsoft.AspNetCore.Authorization; -using TypeCache.Collections; using TypeCache.Extensions; +using TypeCache.Utilities; using TypeCache.Web.Requirements; namespace TypeCache.Web.Attributes; @@ -19,12 +19,12 @@ public RequireClaimAttribute(string[] claims) : base(nameof(ClaimAuthorizationRe { const char separator = '='; - claims.AssertNotEmpty(); + claims.ThrowIfEmpty(); this.Claims = new Dictionary(claims.Length, StringComparer.OrdinalIgnoreCase); claims?.ForEach(claim => { - (claim.StartsWith(separator) || claim.EndsWith(separator) || claim.Count(c => c.Equals(separator)) > 1).AssertFalse(); + (claim.StartsWith(separator) || claim.EndsWith(separator) || claim.Count(c => c.Equals(separator)) > 1).ThrowIfTrue(); if (claim.Contains(separator)) { diff --git a/src/TypeCache.Web/Attributes/RequireHeaderAttribute.cs b/src/TypeCache.Web/Attributes/RequireHeaderAttribute.cs index c1703bff..1e2f016f 100644 --- a/src/TypeCache.Web/Attributes/RequireHeaderAttribute.cs +++ b/src/TypeCache.Web/Attributes/RequireHeaderAttribute.cs @@ -1,8 +1,8 @@ // Copyright (c) 2021 Samuel Abraham using Microsoft.AspNetCore.Authorization; -using TypeCache.Collections; using TypeCache.Extensions; +using TypeCache.Utilities; using TypeCache.Web.Requirements; namespace TypeCache.Web.Attributes; @@ -16,8 +16,8 @@ public class RequireHeaderAttribute : AuthorizeAttribute public RequireHeaderAttribute(string key, string[] allowedValues) : base(nameof(HeaderAuthorizationRequirement)) { - key.AssertNotBlank(); - allowedValues?.ForEach(allowedValue => allowedValue.AssertNotBlank()); + key.ThrowIfBlank(); + allowedValues?.ForEach(allowedValue => allowedValue.ThrowIfBlank()); this.Key = key; this.AllowedValues = allowedValues ?? Array.Empty; diff --git a/src/TypeCache.Web/Extensions/ClaimsPrincipalExtensions.cs b/src/TypeCache.Web/Extensions/ClaimsPrincipalExtensions.cs index 20163e0a..794219d8 100644 --- a/src/TypeCache.Web/Extensions/ClaimsPrincipalExtensions.cs +++ b/src/TypeCache.Web/Extensions/ClaimsPrincipalExtensions.cs @@ -9,7 +9,7 @@ public static class ClaimsPrincipalExtensions { public static bool Any(this ClaimsPrincipal @this, string claimType, string[] values) { - claimType.AssertNotBlank(); + claimType.ThrowIfBlank(); return values.Any() ? values.Any(value => @this.HasClaim(claimType, value)) diff --git a/src/TypeCache.Web/Extensions/HttpRequestExtensions.cs b/src/TypeCache.Web/Extensions/HttpRequestExtensions.cs index e46f8bd1..e5b95a64 100644 --- a/src/TypeCache.Web/Extensions/HttpRequestExtensions.cs +++ b/src/TypeCache.Web/Extensions/HttpRequestExtensions.cs @@ -1,7 +1,7 @@ // Copyright (c) 2021 Samuel Abraham using Microsoft.AspNetCore.Http; -using TypeCache.Collections; +using TypeCache.Utilities; namespace TypeCache.Web.Extensions; diff --git a/src/TypeCache.Web/Mediation/HttpClientValidationRule.cs b/src/TypeCache.Web/Mediation/HttpClientValidationRule.cs index ec2dbd42..d7cf6fd5 100644 --- a/src/TypeCache.Web/Mediation/HttpClientValidationRule.cs +++ b/src/TypeCache.Web/Mediation/HttpClientValidationRule.cs @@ -10,9 +10,9 @@ internal sealed class HttpClientValidationRule { public Task Validate(HttpClientRequest request, CancellationToken token) => Task.Run(() => { - request.AssertNotNull(); - request.Message.AssertNotNull(); - request.Message.RequestUri.AssertNotNull(); - request.Message.RequestUri.IsAbsoluteUri.AssertTrue(); + request.ThrowIfNull(); + request.Message.ThrowIfNull(); + request.Message.RequestUri.ThrowIfNull(); + request.Message.RequestUri.IsAbsoluteUri.ThrowIfFalse(); }, token); } diff --git a/src/TypeCache.Web/TypeCache.Web.csproj b/src/TypeCache.Web/TypeCache.Web.csproj index eb525553..f4b78af3 100644 --- a/src/TypeCache.Web/TypeCache.Web.csproj +++ b/src/TypeCache.Web/TypeCache.Web.csproj @@ -5,7 +5,7 @@ enable TypeCache.Web TypeCache.Web - 8.2.1 + 8.3.1 Samuel Abraham <sam987883@gmail.com> Samuel Abraham <sam987883@gmail.com> TypeCache Web Library diff --git a/src/TypeCache/Attributes/MapIgnoreAttribute.cs b/src/TypeCache/Attributes/MapIgnoreAttribute.cs index 9f951c9c..5297abdf 100644 --- a/src/TypeCache/Attributes/MapIgnoreAttribute.cs +++ b/src/TypeCache/Attributes/MapIgnoreAttribute.cs @@ -10,7 +10,7 @@ public class MapIgnoreAttribute() : Attribute protected MapIgnoreAttribute(Type type) : this() { - type.AssertNotNull(); + type.ThrowIfNull(); this.Type = type; } diff --git a/src/TypeCache/Collections/CustomComparer.cs b/src/TypeCache/Collections/CustomComparer.cs deleted file mode 100644 index 489c4caf..00000000 --- a/src/TypeCache/Collections/CustomComparer.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2021 Samuel Abraham - -using TypeCache.Extensions; - -namespace TypeCache.Collections; - -public readonly struct CustomComparer(Comparison compare, Func? equals, Func? getHashCode) - : IComparer, IEqualityComparer -{ - private readonly Comparison _Compare = compare ?? compare.ThrowArgumentNullException(); - private readonly Func _Equals = equals ?? ((x, y) => compare(x, y) == 0); - private readonly Func _GetHashCode = getHashCode ?? (_ => _?.GetHashCode() ?? 0); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public int Compare([AllowNull] T x, [AllowNull] T y) - => this._Compare(x, y); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public bool Equals([AllowNull] T x, [AllowNull] T y) - => this._Equals(x, y); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public int GetHashCode([DisallowNull] T value) - => this._GetHashCode(value); -} diff --git a/src/TypeCache/Collections/CustomEnumerable.cs b/src/TypeCache/Collections/CustomEnumerable.cs deleted file mode 100644 index dfcfe360..00000000 --- a/src/TypeCache/Collections/CustomEnumerable.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2021 Samuel Abraham - -using TypeCache.Extensions; - -namespace TypeCache.Collections; - -public readonly struct CustomEnumerable -{ - private readonly Func> _GetEnumerator; - - /// - public CustomEnumerable(Func> getEnumerator) - { - getEnumerator.AssertNotNull(); - - this._GetEnumerator = getEnumerator; - } - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public IEnumerator GetEnumerator() - => this._GetEnumerator(); -} diff --git a/src/TypeCache/Collections/CustomEqualityComparer.cs b/src/TypeCache/Collections/CustomEqualityComparer.cs deleted file mode 100644 index 4fd64574..00000000 --- a/src/TypeCache/Collections/CustomEqualityComparer.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2021 Samuel Abraham - -using TypeCache.Extensions; - -namespace TypeCache.Collections; - -public readonly struct CustomEqualityComparer(Func equals, Func? getHashCode) - : IEqualityComparer -{ - private readonly Func _Equals = equals ?? equals.ThrowArgumentNullException(); - private readonly Func _GetHashCode = getHashCode ?? (_ => _?.GetHashCode() ?? 0); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public bool Equals([AllowNull] T? x, [AllowNull] T? y) - => this._Equals(x, y); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public int GetHashCode([DisallowNull] T value) - => this._GetHashCode(value); -} diff --git a/src/TypeCache/Collections/CustomEquatable.cs b/src/TypeCache/Collections/CustomEquatable.cs deleted file mode 100644 index 362624ba..00000000 --- a/src/TypeCache/Collections/CustomEquatable.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2021 Samuel Abraham - -using TypeCache.Extensions; -using static System.Reflection.BindingFlags; - -namespace TypeCache.Collections; - -public abstract class CustomEquatable(Func equals) - : IEquatable - where T : class -{ - private readonly Func _Equals = equals ?? equals.ThrowArgumentNullException(); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public bool Equals(T? other) - => this._Equals(other); - - [MethodImpl(AggressiveInlining), DebuggerHidden] - public override bool Equals(object? other) - => this._Equals(other as T); - - public override int GetHashCode() - { - var fieldInfos = this.GetType().GetFields(DeclaredOnly | Instance | NonPublic | Public); - if (fieldInfos.Length == 0) - return base.GetHashCode(); - - var values = fieldInfos.Select(fieldInfo => fieldInfo.GetValueEx(this)).ToArray(); - var hashCode = new HashCode(); - values.ForEach(hashCode.Add); - return hashCode.ToHashCode(); - } -} diff --git a/src/TypeCache/Data/DataSource.cs b/src/TypeCache/Data/DataSource.cs index 5dacd6cc..5545ed00 100644 --- a/src/TypeCache/Data/DataSource.cs +++ b/src/TypeCache/Data/DataSource.cs @@ -3,9 +3,9 @@ using System.Collections.Frozen; using System.Data; using System.Data.Common; -using TypeCache.Collections; using TypeCache.Data.Extensions; using TypeCache.Extensions; +using TypeCache.Utilities; using static System.StringSplitOptions; using static TypeCache.Data.DataSourceType; @@ -106,7 +106,7 @@ public DbConnection CreateDbConnection() public string Escape(string databaseObject) { - databaseObject.AssertNotBlank(); + databaseObject.ThrowIfBlank(); var items = databaseObject.Split('.', RemoveEmptyEntries | TrimEntries); if (items.Length > 3 || (this.Type == MySql && items.Length > 2)) diff --git a/src/TypeCache/Data/ObjectSchema.cs b/src/TypeCache/Data/ObjectSchema.cs index 3b40bf0b..848cf513 100644 --- a/src/TypeCache/Data/ObjectSchema.cs +++ b/src/TypeCache/Data/ObjectSchema.cs @@ -72,7 +72,7 @@ public string CreateDeleteSQL(DataTable data, string[] output) { var primaryKeys = this.Columns.Where(column => column.PrimaryKey).ToArray(); - (primaryKeys.Length > 0).AssertTrue(); + (primaryKeys.Length > 0).ThrowIfFalse(); if (primaryKeys.Length == 1) { @@ -100,7 +100,7 @@ public string CreateDeleteSQL(JsonArray data, StringValues output) { var primaryKeys = this.Columns.Where(column => column.PrimaryKey).ToArray(); - (primaryKeys.Length > 0).AssertTrue(); + (primaryKeys.Length > 0).ThrowIfFalse(); if (primaryKeys.Length == 1) { @@ -128,7 +128,7 @@ public string CreateDeleteSQL(T[] data, StringValues output) { var primaryKeys = this.Columns.Where(column => column.PrimaryKey).ToArray(); - (primaryKeys.Length > 0).AssertTrue(); + (primaryKeys.Length > 0).ThrowIfFalse(); var type = typeof(T); diff --git a/src/TypeCache/Data/SqlCommand.cs b/src/TypeCache/Data/SqlCommand.cs index 84c8f14d..098959cc 100644 --- a/src/TypeCache/Data/SqlCommand.cs +++ b/src/TypeCache/Data/SqlCommand.cs @@ -11,8 +11,8 @@ public sealed class SqlCommand { internal SqlCommand(IDataSource dataSource, string sql) { - dataSource.AssertNotNull(); - sql.AssertNotBlank(); + dataSource.ThrowIfNull(); + sql.ThrowIfBlank(); this.DataSource = dataSource; this.SQL = sql; diff --git a/src/TypeCache/Extensions/ArrayExtensions.cs b/src/TypeCache/Extensions/ArrayExtensions.cs index 6bf66b8f..33eaf2cd 100644 --- a/src/TypeCache/Extensions/ArrayExtensions.cs +++ b/src/TypeCache/Extensions/ArrayExtensions.cs @@ -3,7 +3,7 @@ using System.Collections.Immutable; using System.Text.Json; using System.Text.Json.Nodes; -using TypeCache.Collections; +using TypeCache.Utilities; namespace TypeCache.Extensions; @@ -31,7 +31,7 @@ public static bool ContainsIgnoreCase(this string[] @this, string value) /// public static T[] Copy(this T[] @this) { - @this.AssertNotNull(); + @this.ThrowIfNull(); if (@this.Length is 0) return Array.Empty; @@ -52,7 +52,7 @@ public static void ForEach(this T[] @this, Action action) /// public static void ForEach(this T[] @this, Action action, Action between) { - between.AssertNotNull(); + between.ThrowIfNull(); var first = true; @this.ForEach(value => @@ -69,7 +69,7 @@ public static void ForEach(this T[] @this, Action action, Action between) /// public static void ForEach(this T[]? @this, ActionRef action) { - action.AssertNotNull(); + action.ThrowIfNull(); var count = @this?.Length ?? 0; for (var i = 0; i < count; ++i) @@ -85,7 +85,7 @@ public static void ForEach(this T[] @this, Action action) /// public static void ForEach(this T[]? @this, ActionIndexRef action) { - action.AssertNotNull(); + action.ThrowIfNull(); var count = @this?.Length ?? 0; for (var i = 0; i < count; ++i) @@ -95,7 +95,7 @@ public static void ForEach(this T[]? @this, ActionIndexRef action) /// public static void ForEach(this T[] @this, Action action, Action between) { - between.AssertNotNull(); + between.ThrowIfNull(); var i = -1; @this.ForEach(value => @@ -202,7 +202,7 @@ public static void Sort(this T[] @this, int start, int length = 0, IComparer< /// public static T[] Subarray(this T[] @this, int sourceIndex, int length = 0) { - @this.AssertNotNull(); + @this.ThrowIfNull(); if (sourceIndex + length > @this.Length) throw new IndexOutOfRangeException($"{nameof(Subarray)}: last index {sourceIndex + length} is more than array length {@this.Length}."); diff --git a/src/TypeCache/Extensions/CsvExtensions.cs b/src/TypeCache/Extensions/CsvExtensions.cs index fb5c49c6..058b423b 100644 --- a/src/TypeCache/Extensions/CsvExtensions.cs +++ b/src/TypeCache/Extensions/CsvExtensions.cs @@ -1,8 +1,8 @@ // Copyright (c) 2021 Samuel Abraham using System.Numerics; -using TypeCache.Collections; using TypeCache.Extensions; +using TypeCache.Utilities; using static System.Globalization.CultureInfo; namespace TypeCache.Extensions; diff --git a/src/TypeCache/Extensions/DateTimeExtensions.cs b/src/TypeCache/Extensions/DateTimeExtensions.cs index f00607c3..4a58d03f 100644 --- a/src/TypeCache/Extensions/DateTimeExtensions.cs +++ b/src/TypeCache/Extensions/DateTimeExtensions.cs @@ -1,5 +1,6 @@ // Copyright (c) 2021 Samuel Abraham +using System.Globalization; using static System.Globalization.CultureInfo; using static System.TimeZoneInfo; @@ -162,11 +163,11 @@ public static string ToISO8601(this TimeOnly @this, IFormatProvider? provider = => @this.ToString("HH:mm:ss", provider ?? InvariantCulture); /// - /// => @.ToString("D", ?? ); + /// => @.ToString("c", ?? ); /// [MethodImpl(AggressiveInlining), DebuggerHidden] - public static string ToText(this Guid @this, IFormatProvider? provider = null) - => @this.ToString("D", provider ?? InvariantCulture); + public static string ToText(this TimeSpan @this, IFormatProvider? provider = null) + => @this.ToString("c", provider ?? CultureInfo.InvariantCulture); /// /// diff --git a/src/TypeCache/Extensions/DictionaryExtensions.cs b/src/TypeCache/Extensions/DictionaryExtensions.cs index 820a4bbd..99af804d 100644 --- a/src/TypeCache/Extensions/DictionaryExtensions.cs +++ b/src/TypeCache/Extensions/DictionaryExtensions.cs @@ -10,7 +10,7 @@ public static class DictionaryExtensions public static bool If(this IDictionary @this, K key, Action action) where K : notnull { - @this.AssertNotNull(); + @this.ThrowIfNull(); var success = @this.ContainsKey(key); if (success) @@ -23,7 +23,7 @@ public static bool If(this IDictionary @this, K key, Action action) public static bool If(this IDictionary @this, K key, Action> action) where K : notnull { - @this.AssertNotNull(); + @this.ThrowIfNull(); var success = @this.TryGetValue(key, out var value); if (success) diff --git a/src/TypeCache/Extensions/EnumExtensions.cs b/src/TypeCache/Extensions/EnumExtensions.cs index e7e744e7..a41e08a0 100644 --- a/src/TypeCache/Extensions/EnumExtensions.cs +++ b/src/TypeCache/Extensions/EnumExtensions.cs @@ -1,6 +1,5 @@ // Copyright (c) 2021 Samuel Abraham -using TypeCache.Collections; using TypeCache.Extensions; using TypeCache.Utilities; using static System.Reflection.BindingFlags; diff --git a/src/TypeCache/Extensions/EnumerableExtensions.cs b/src/TypeCache/Extensions/EnumerableExtensions.cs index d2f73915..7c764556 100644 --- a/src/TypeCache/Extensions/EnumerableExtensions.cs +++ b/src/TypeCache/Extensions/EnumerableExtensions.cs @@ -1,7 +1,7 @@ // Copyright (c) 2021 Samuel Abraham using System.Collections; -using TypeCache.Collections; +using TypeCache.Utilities; namespace TypeCache.Extensions; diff --git a/src/TypeCache/Extensions/EnumeratorExtensions.cs b/src/TypeCache/Extensions/EnumeratorExtensions.cs index 836d4f32..f148d8a4 100644 --- a/src/TypeCache/Extensions/EnumeratorExtensions.cs +++ b/src/TypeCache/Extensions/EnumeratorExtensions.cs @@ -42,6 +42,7 @@ public static bool Move(this IEnumerator @this, int count) { while (count > 0 && @this.MoveNext()) --count; + return count == 0; } diff --git a/src/TypeCache/Extensions/ExpressionExtensions.cs b/src/TypeCache/Extensions/ExpressionExtensions.cs index 1b7d7276..4dac5e0f 100644 --- a/src/TypeCache/Extensions/ExpressionExtensions.cs +++ b/src/TypeCache/Extensions/ExpressionExtensions.cs @@ -217,8 +217,8 @@ public static Expression Convert(this Expression @this) /// public static Expression Convert(this Expression @this, Type targetType) { - @this.AssertNotNull(); - targetType.AssertNotNull(); + @this.ThrowIfNull(); + targetType.ThrowIfNull(); if (@this.Type == targetType) return @this; diff --git a/src/TypeCache/Extensions/GlobalExtensions.cs b/src/TypeCache/Extensions/GlobalExtensions.cs index 3d737eea..6650f014 100644 --- a/src/TypeCache/Extensions/GlobalExtensions.cs +++ b/src/TypeCache/Extensions/GlobalExtensions.cs @@ -52,22 +52,6 @@ public static StrongBox ToStrongBox(this T @this) where T : struct => new(@this); - /// - /// - /// => .Create(@); - /// - [MethodImpl(AggressiveInlining), DebuggerHidden] - public static Tuple ToTuple(this T @this) - => Tuple.Create(@this); - - /// - /// - /// => .Create(@); - /// - [MethodImpl(AggressiveInlining), DebuggerHidden] - public static ValueTuple ToValueTuple(this T @this) - => ValueTuple.Create(@this); - /// /// /// => (@); diff --git a/src/TypeCache/Extensions/IndexExtensions.cs b/src/TypeCache/Extensions/IndexExtensions.cs index 12c7393e..338cf87b 100644 --- a/src/TypeCache/Extensions/IndexExtensions.cs +++ b/src/TypeCache/Extensions/IndexExtensions.cs @@ -7,6 +7,26 @@ public static class IndexExtensions public static Index FromStart(this Index @this, int count) => @this.IsFromEnd ? (count > 0 ? new Index(count - @this.Value) : default) : @this; + /// + public static Index Max(this (Index, Index) @this) + { + (@this.Item1.IsFromEnd == @this.Item2.IsFromEnd).ThrowIfFalse(); + + return @this.Item1.IsFromEnd + ? Index.FromEnd((@this.Item1.Value, @this.Item2.Value).Min()) + : Index.FromStart((@this.Item1.Value, @this.Item2.Value).Max()); + } + + /// + public static Index Min(this (Index, Index) @this) + { + (@this.Item1.IsFromEnd == @this.Item2.IsFromEnd).ThrowIfFalse(); + + return @this.Item1.IsFromEnd + ? Index.FromEnd((@this.Item1.Value, @this.Item2.Value).Max()) + : Index.FromStart((@this.Item1.Value, @this.Item2.Value).Min()); + } + /// /// /// => (@.Value + ); diff --git a/src/TypeCache/Extensions/JsonExtensions.cs b/src/TypeCache/Extensions/JsonExtensions.cs index 6fb90678..e7a4b2be 100644 --- a/src/TypeCache/Extensions/JsonExtensions.cs +++ b/src/TypeCache/Extensions/JsonExtensions.cs @@ -9,21 +9,21 @@ public static class JsonExtensions { public static JsonElement[] GetArrayElements(this JsonElement @this) { - @this.ValueKind.AssertEquals(JsonValueKind.Array); + @this.ValueKind.ThrowIfNotEqual(JsonValueKind.Array); return @this.EnumerateArrayValues().ToArray(); } public static object?[] GetArrayValues(this JsonElement @this) { - @this.ValueKind.AssertEquals(JsonValueKind.Array); + @this.ValueKind.ThrowIfNotEqual(JsonValueKind.Array); return @this.EnumerateArrayValues().Select(jsonElement => jsonElement.GetValue()).ToArray(); } public static IDictionary GetObjectElements(this JsonElement @this) { - @this.ValueKind.AssertEquals(JsonValueKind.Object); + @this.ValueKind.ThrowIfNotEqual(JsonValueKind.Object); var properties = new Dictionary(StringComparer.Ordinal); using var enumerator = @this.EnumerateObject(); @@ -37,7 +37,7 @@ public static IDictionary GetObjectElements(this JsonElemen public static IDictionary GetObjectValues(this JsonElement @this) { - @this.ValueKind.AssertEquals(JsonValueKind.Object); + @this.ValueKind.ThrowIfNotEqual(JsonValueKind.Object); var properties = new Dictionary(StringComparer.Ordinal); using var enumerator = @this.EnumerateObject(); diff --git a/src/TypeCache/Extensions/LoggerExtensions.cs b/src/TypeCache/Extensions/LoggerExtensions.cs index 2a844860..318a6549 100644 --- a/src/TypeCache/Extensions/LoggerExtensions.cs +++ b/src/TypeCache/Extensions/LoggerExtensions.cs @@ -1,7 +1,7 @@ // Copyright (c) 2021 Samuel Abraham using Microsoft.Extensions.Logging; -using TypeCache.Collections; +using TypeCache.Utilities; namespace TypeCache.Extensions; @@ -12,8 +12,8 @@ public static class LoggerExtensions /// public static void LogAggregateException(this ILogger @this, EventId eventId, AggregateException error, string message, object?[]? args = null) { - @this.AssertNotNull(); - error.AssertNotNull(); + @this.ThrowIfNull(); + error.ThrowIfNull(); args ??= Array.Empty; @@ -30,8 +30,8 @@ public static void LogAggregateException(this ILogger @this, EventId event /// public static void LogAggregateException(this ILogger @this, AggregateException error, string message, object?[]? args = null) { - @this.AssertNotNull(); - error.AssertNotNull(); + @this.ThrowIfNull(); + error.ThrowIfNull(); args ??= Array.Empty; diff --git a/src/TypeCache/Extensions/MapExtensions.cs b/src/TypeCache/Extensions/MapExtensions.cs index b31e0619..f452751a 100644 --- a/src/TypeCache/Extensions/MapExtensions.cs +++ b/src/TypeCache/Extensions/MapExtensions.cs @@ -25,7 +25,7 @@ public static T Map(this bool @this, Func trueValue, Func falseValue) public static T? Map(this IDictionary @this, K key, Func map, T? keyNotFoundValue = default) where K : notnull { - @this.AssertNotNull(); + @this.ThrowIfNull(); return @this.TryGetValue(key, out var value) ? map(value) : keyNotFoundValue; } @@ -34,7 +34,7 @@ public static T Map(this bool @this, Func trueValue, Func falseValue) public static T? Map(this IDictionary @this, K key, Func map, T? keyNotFoundValue = default) where K : notnull { - @this.AssertNotNull(); + @this.ThrowIfNull(); return @this.TryGetValue(key, out var value) ? map(key, value) : keyNotFoundValue; } @@ -43,8 +43,8 @@ public static T Map(this bool @this, Func trueValue, Func falseValue) public static T MapTo(this IEnumerable> @this, T target, bool ignoreCase = true) where T : notnull { - @this.AssertNotNull(); - target.AssertNotNull(); + @this.ThrowIfNull(); + target.ThrowIfNull(); var targetType = target.GetType(); var bindings = ignoreCase switch @@ -77,9 +77,9 @@ public static T MapTo(this IEnumerable> @this, public static T MapTo(this T @this, T target) where T : notnull { - @this.AssertNotNull(); - target.AssertNotNull(); - (target, @this).AssertNotSame(); + @this.ThrowIfNull(); + target.ThrowIfNull(); + (target, @this).ThrowIfSame(); var properties = typeof(T).GetProperties(FlattenHierarchy | Instance | Public); foreach (var propertyInfo in properties) @@ -133,8 +133,8 @@ _ when typeof(S) == typeof(T) => (T)(object)@this.MapTo((S)(object)target), /// public static IDictionary MapToDictionary(this IEnumerable> @this, IDictionary target) { - @this.AssertNotNull(); - target.AssertNotNull(); + @this.ThrowIfNull(); + target.ThrowIfNull(); foreach (var pair in @this) target[pair.Key] = pair.Value; @@ -145,8 +145,8 @@ _ when typeof(S) == typeof(T) => (T)(object)@this.MapTo((S)(object)target), /// public static IDictionary MapToDictionary(this object @this, IDictionary target) { - @this.AssertNotNull(); - target.AssertNotNull(); + @this.ThrowIfNull(); + target.ThrowIfNull(); var sourceProperties = @this.GetType().GetProperties(FlattenHierarchy | Instance | Public) .Where(propertyInfo => propertyInfo.CanRead); @@ -175,8 +175,8 @@ private static T MapModel(S source, T target, BindingFlags bindings) where S : notnull where T : notnull { - source.AssertNotNull(); - target.AssertNotNull(); + source.ThrowIfNull(); + target.ThrowIfNull(); foreach (var sourcePropertyInfo in typeof(S).GetProperties(bindings) .Where(propertyInfo => propertyInfo.CanRead)) diff --git a/src/TypeCache/Extensions/NumberExtensions.cs b/src/TypeCache/Extensions/NumberExtensions.cs index 37148d1b..7675405a 100644 --- a/src/TypeCache/Extensions/NumberExtensions.cs +++ b/src/TypeCache/Extensions/NumberExtensions.cs @@ -1,8 +1,8 @@ // Copyright (c) 2021 Samuel Abraham -using System.Globalization; using System.Numerics; using TypeCache.Extensions; +using static System.Globalization.CultureInfo; namespace TypeCache.Extensions; @@ -47,7 +47,7 @@ public static T Ceiling(this T @this) /// public static ulong Factorial(this int @this) { - (@this >= 0).AssertTrue(); + (@this >= 0).ThrowIfFalse(); var result = 1UL; while (@this > 0) @@ -67,6 +67,159 @@ public static T Floor(this T @this) where T : IFloatingPoint => T.Floor(@this); + /// + /// + /// => .IsCanonical(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsCanonical(this T @this) + where T : INumberBase + => T.IsCanonical(@this); + + /// + /// + /// => .IsComplexNumber(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsComplexNumber(this T @this) + where T : INumberBase + => T.IsComplexNumber(@this); + + /// + /// + /// => .IsEvenInteger(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsEvenInteger(this T @this) + where T : INumberBase + => T.IsEvenInteger(@this); + + /// + /// + /// => .IsFinite(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsFinite(this T @this) + where T : INumberBase + => T.IsFinite(@this); + + /// + /// + /// => .IsImaginaryNumber(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsImaginaryNumber(this T @this) + where T : INumberBase + => T.IsImaginaryNumber(@this); + + /// + /// + /// => .IsInfinity(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsInfinity(this T @this) + where T : INumberBase + => T.IsInfinity(@this); + + /// + /// + /// => .IsInteger(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsInteger(this T @this) + where T : INumberBase + => T.IsInteger(@this); + + /// + /// + /// => .IsNaN(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsNaN(this T @this) + where T : INumberBase + => T.IsNaN(@this); + + /// + /// + /// => .IsNegative(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsNegative(this T @this) + where T : INumberBase + => T.IsNegative(@this); + + /// + /// + /// => .IsNegativeInfinity(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsNegativeInfinity(this T @this) + where T : INumberBase + => T.IsNegativeInfinity(@this); + + /// + /// + /// => .IsNormal(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsNormal(this T @this) + where T : INumberBase + => T.IsNormal(@this); + + /// + /// + /// => .IsOddInteger(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsOddInteger(this T @this) + where T : INumberBase + => T.IsOddInteger(@this); + + /// + /// + /// => .IsPositive(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsPositive(this T @this) + where T : INumberBase + => T.IsPositive(@this); + + /// + /// + /// => .IsPositiveInfinity(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsPositiveInfinity(this T @this) + where T : INumberBase + => T.IsPositiveInfinity(@this); + + /// + /// + /// => .IsRealNumber(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsRealNumber(this T @this) + where T : INumberBase + => T.IsRealNumber(@this); + + /// + /// + /// => .IsSubnormal(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsSubnormal(this T @this) + where T : INumberBase + => T.IsSubnormal(@this); + + /// + /// + /// => .IsZero(@); + /// + [MethodImpl(AggressiveInlining), DebuggerHidden] + public static bool IsZero(this T @this) + where T : INumberBase + => T.IsZero(@this); + /// /// /// => .Max(@.Item1, @.Item2); @@ -76,16 +229,6 @@ public static T Max(this (T, T) @this) where T : INumber => T.Max(@this.Item1, @this.Item2); - /// - public static Index Max(this (Index, Index) @this) - { - (@this.Item1.IsFromEnd == @this.Item2.IsFromEnd).AssertTrue(); - - return @this.Item1.IsFromEnd - ? Index.FromEnd((@this.Item1.Value, @this.Item2.Value).Min()) - : Index.FromStart((@this.Item1.Value, @this.Item2.Value).Max()); - } - /// /// /// => .Min(@.Item1, @.Item2); @@ -95,16 +238,6 @@ public static T Min(this (T, T) @this) where T : INumber => T.Min(@this.Item1, @this.Item2); - /// - public static Index Min(this (Index, Index) @this) - { - (@this.Item1.IsFromEnd == @this.Item2.IsFromEnd).AssertTrue(); - - return @this.Item1.IsFromEnd - ? Index.FromEnd((@this.Item1.Value, @this.Item2.Value).Max()) - : Index.FromStart((@this.Item1.Value, @this.Item2.Value).Min()); - } - public static IEnumerable Repeat(this T @this, int count) where T : unmanaged { @@ -166,11 +299,11 @@ public static byte[] ToBytes(this decimal @this) => decimal.GetBits(@this).SelectMany(_ => _.GetBytes()).ToArray(); /// - /// => @.ToString("c", ?? ); + /// => @.ToString("D", ?? ); /// [MethodImpl(AggressiveInlining), DebuggerHidden] - public static string ToText(this TimeSpan @this, IFormatProvider? provider = null) - => @this.ToString("c", provider ?? CultureInfo.InvariantCulture); + public static string ToText(this Guid @this, IFormatProvider? provider = null) + => @this.ToString("D", provider ?? InvariantCulture); /// /// diff --git a/src/TypeCache/Extensions/RangeExtensions.cs b/src/TypeCache/Extensions/RangeExtensions.cs index 0d1932b6..f2e0d1ef 100644 --- a/src/TypeCache/Extensions/RangeExtensions.cs +++ b/src/TypeCache/Extensions/RangeExtensions.cs @@ -7,7 +7,7 @@ public static class RangeExtensions /// public static bool Any(this Range @this) { - (@this.Start.IsFromEnd == @this.End.IsFromEnd).AssertTrue(); + (@this.Start.IsFromEnd == @this.End.IsFromEnd).ThrowIfFalse(); return !@this.Start.Equals(@this.End); } @@ -36,7 +36,7 @@ public static int Count(this Range @this) /// public static void ForEach(this Range @this, Action action) { - action.AssertNotNull(); + action.ThrowIfNull(); foreach (var i in @this) action(i); @@ -60,7 +60,7 @@ public static IEnumerator GetEnumerator(this Range @this) /// public static bool IsReverse(this Range @this) { - (@this.Start.IsFromEnd == @this.End.IsFromEnd).AssertTrue(); + (@this.Start.IsFromEnd == @this.End.IsFromEnd).ThrowIfFalse(); return @this.Start.IsFromEnd ? @this.Start.Value <= @this.End.Value : @this.Start.Value > @this.End.Value; } @@ -68,9 +68,9 @@ public static bool IsReverse(this Range @this) /// public static Index Maximum(this Range @this) { - @this.Start.IsFromEnd.AssertFalse(); - @this.End.IsFromEnd.AssertFalse(); - @this.Start.AssertNotEquals(@this.End); + @this.Start.IsFromEnd.ThrowIfTrue(); + @this.End.IsFromEnd.ThrowIfTrue(); + @this.Start.ThrowIfEqual(@this.End); return @this.IsReverse() ? @this.Start : @this.End.Previous(); } @@ -78,9 +78,9 @@ public static Index Maximum(this Range @this) /// public static Index Minimum(this Range @this) { - @this.Start.IsFromEnd.AssertFalse(); - @this.End.IsFromEnd.AssertFalse(); - @this.Start.AssertNotEquals(@this.End); + @this.Start.IsFromEnd.ThrowIfTrue(); + @this.End.IsFromEnd.ThrowIfTrue(); + @this.Start.ThrowIfEqual(@this.End); return @this.IsReverse() ? @this.End.Next() : @this.Start; } diff --git a/src/TypeCache/Extensions/ReadOnlySpanExtensions.cs b/src/TypeCache/Extensions/ReadOnlySpanExtensions.cs index 969a5f66..4f988681 100644 --- a/src/TypeCache/Extensions/ReadOnlySpanExtensions.cs +++ b/src/TypeCache/Extensions/ReadOnlySpanExtensions.cs @@ -4,7 +4,7 @@ using System.Globalization; using System.Numerics; using System.Runtime.InteropServices; -using TypeCache.Collections; +using TypeCache.Utilities; using static System.Globalization.CultureInfo; namespace TypeCache.Extensions; @@ -33,7 +33,7 @@ public static ReadOnlySpan Cast(this ReadOnlySpan @this) /// public static void ForEach(this scoped ReadOnlySpan @this, Action action) { - action.AssertNotNull(); + action.ThrowIfNull(); if (@this.IsEmpty) return; @@ -46,7 +46,7 @@ public static void ForEach(this scoped ReadOnlySpan @this, Action actio /// public static void ForEach(this scoped ReadOnlySpan @this, Action action) { - action.AssertNotNull(); + action.ThrowIfNull(); if (@this.IsEmpty) return; @@ -59,8 +59,8 @@ public static void ForEach(this scoped ReadOnlySpan @this, Action /// public static void ForEach(this scoped ReadOnlySpan @this, Action action, Action between) { - action.AssertNotNull(); - between.AssertNotNull(); + action.ThrowIfNull(); + between.ThrowIfNull(); if (@this.IsEmpty) return; @@ -78,8 +78,8 @@ public static void ForEach(this scoped ReadOnlySpan @this, Action actio /// public static void ForEach(this scoped ReadOnlySpan @this, Action action, Action between) { - action.AssertNotNull(); - between.AssertNotNull(); + action.ThrowIfNull(); + between.ThrowIfNull(); if (@this.IsEmpty) return; diff --git a/src/TypeCache/Extensions/ReflectionExtensions.ConstructorInfo.cs b/src/TypeCache/Extensions/ReflectionExtensions.ConstructorInfo.cs index 8c43ecf4..7aa43ff8 100644 --- a/src/TypeCache/Extensions/ReflectionExtensions.ConstructorInfo.cs +++ b/src/TypeCache/Extensions/ReflectionExtensions.ConstructorInfo.cs @@ -21,7 +21,7 @@ public static Delegate GetDelegate(this ConstructorInfo @this) public static object InvokeFunc(this ConstructorInfo @this, object?[]? arguments) { var func = TypeStore.ConstructorArrayFuncs[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - func.AssertNotNull(); + func.ThrowIfNull(); return func.Invoke(arguments); } @@ -29,7 +29,7 @@ public static object InvokeFunc(this ConstructorInfo @this, object?[]? arguments public static object InvokeFunc(this ConstructorInfo @this, ITuple? arguments) { var func = TypeStore.ConstructorTupleFuncs[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - func.AssertNotNull(); + func.ThrowIfNull(); return func.Invoke(arguments); } @@ -37,7 +37,7 @@ public static object InvokeFunc(this ConstructorInfo @this, ITuple? arguments) /// public static LambdaExpression ToDelegateExpression(this ConstructorInfo @this) { - @this.DeclaringType.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); var parameters = @this.GetParameters() .OrderBy(parameterInfo => parameterInfo.Position) @@ -101,7 +101,7 @@ public static NewExpression ToExpression(this ConstructorInfo @this, IEnumerable private static Expression CreateArrayCall(this ConstructorInfo @this, ParameterExpression arguments) { - @this.DeclaringType.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); var parameters = @this .GetParameters() @@ -117,7 +117,7 @@ private static Expression CreateTupleCall(this ConstructorInfo @this, ParameterE var valueTupleType = GetValueTupleType(parameterInfos); var valueTupleFields = GetValueTupleFields(arguments.Cast(valueTupleType), parameterInfos); var parameters = parameterInfos.Select(parameterInfo => - arguments.Property("Item", [parameterInfo.Position.ToConstantExpression()]).Convert(parameterInfo.ParameterType)); + arguments.Property(Item, [parameterInfo.Position.ToConstantExpression()]).Convert(parameterInfo.ParameterType)); return arguments.Is(valueTupleType).IIf(@this.ToExpression(valueTupleFields), @this.ToExpression(parameters)); } diff --git a/src/TypeCache/Extensions/ReflectionExtensions.FieldInfo.cs b/src/TypeCache/Extensions/ReflectionExtensions.FieldInfo.cs index 81b6790e..87684a30 100644 --- a/src/TypeCache/Extensions/ReflectionExtensions.FieldInfo.cs +++ b/src/TypeCache/Extensions/ReflectionExtensions.FieldInfo.cs @@ -74,9 +74,9 @@ public static MemberExpression ToExpression(this FieldInfo @this, Expression? in public static Expression> ToActionExpression(this FieldInfo @this) { - @this.IsInitOnly.AssertFalse(); - @this.IsLiteral.AssertFalse(); - @this.IsStatic.AssertFalse(); + @this.IsInitOnly.ThrowIfTrue(); + @this.IsLiteral.ThrowIfTrue(); + @this.IsStatic.ThrowIfTrue(); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression value = nameof(value).ToParameterExpression(); @@ -89,8 +89,8 @@ public static MemberExpression ToExpression(this FieldInfo @this, Expression? in public static Expression> ToFuncExpression(this FieldInfo @this) { - @this.IsLiteral.AssertFalse(); - @this.IsStatic.AssertFalse(); + @this.IsLiteral.ThrowIfTrue(); + @this.IsStatic.ThrowIfTrue(); ParameterExpression instance = nameof(instance).ToParameterExpression(); return instance @@ -102,9 +102,9 @@ public static MemberExpression ToExpression(this FieldInfo @this, Expression? in public static Expression> ToStaticActionExpression(this FieldInfo @this) { - @this.IsInitOnly.AssertFalse(); - @this.IsLiteral.AssertFalse(); - @this.IsStatic.AssertTrue(); + @this.IsInitOnly.ThrowIfTrue(); + @this.IsLiteral.ThrowIfTrue(); + @this.IsStatic.ThrowIfFalse(); ParameterExpression value = nameof(value).ToParameterExpression(); return @this.ToExpression(null).Assign(value.Convert(@this.FieldType)).Lambda>([value]); @@ -115,7 +115,7 @@ public static MemberExpression ToExpression(this FieldInfo @this, Expression? in if (@this.IsLiteral) return @this.GetRawConstantValue().ToConstantExpression().Cast().Lambda>(); - @this.IsStatic.AssertTrue(); + @this.IsStatic.ThrowIfFalse(); return @this.ToExpression(null).Cast().Lambda>(); } diff --git a/src/TypeCache/Extensions/ReflectionExtensions.MethodInfo.cs b/src/TypeCache/Extensions/ReflectionExtensions.MethodInfo.cs index 8d4c39ed..a16a793d 100644 --- a/src/TypeCache/Extensions/ReflectionExtensions.MethodInfo.cs +++ b/src/TypeCache/Extensions/ReflectionExtensions.MethodInfo.cs @@ -83,7 +83,7 @@ public static bool HasNoReturnValue(this MethodInfo @this) public static void InvokeAction(this MethodInfo @this, object instance, object?[]? arguments) { var action = TypeStore.MethodArrayActions[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - action.AssertNotNull(); + action.ThrowIfNull(); action.Invoke(instance, arguments); } @@ -94,7 +94,7 @@ public static void InvokeAction(this MethodInfo @this, object instance, object?[ public static void InvokeAction(this MethodInfo @this, object instance, ITuple? arguments) { var action = TypeStore.MethodTupleActions[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - action.AssertNotNull(); + action.ThrowIfNull(); action.Invoke(instance, arguments); } @@ -105,7 +105,7 @@ public static void InvokeAction(this MethodInfo @this, object instance, ITuple? public static object? InvokeFunc(this MethodInfo @this, object instance, object?[]? arguments) { var func = TypeStore.MethodArrayFuncs[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - func.AssertNotNull(); + func.ThrowIfNull(); return func.Invoke(instance, arguments); } @@ -116,7 +116,7 @@ public static void InvokeAction(this MethodInfo @this, object instance, ITuple? public static object? InvokeFunc(this MethodInfo @this, object instance, ITuple? arguments) { var func = TypeStore.MethodTupleFuncs[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - func.AssertNotNull(); + func.ThrowIfNull(); return func.Invoke(instance, arguments); } @@ -127,7 +127,7 @@ public static void InvokeAction(this MethodInfo @this, object instance, ITuple? public static void InvokeStaticAction(this MethodInfo @this, object?[]? arguments) { var action = TypeStore.StaticMethodArrayActions[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - action.AssertNotNull(); + action.ThrowIfNull(); action.Invoke(arguments); } @@ -138,7 +138,7 @@ public static void InvokeStaticAction(this MethodInfo @this, object?[]? argument public static void InvokeStaticAction(this MethodInfo @this, ITuple? arguments) { var action = TypeStore.StaticMethodTupleActions[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - action.AssertNotNull(); + action.ThrowIfNull(); action.Invoke(arguments); } @@ -149,7 +149,7 @@ public static void InvokeStaticAction(this MethodInfo @this, ITuple? arguments) public static object? InvokeStaticFunc(this MethodInfo @this, object?[]? arguments) { var func = TypeStore.StaticMethodArrayFuncs[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - func.AssertNotNull(); + func.ThrowIfNull(); return func.Invoke(arguments); } @@ -160,7 +160,7 @@ public static void InvokeStaticAction(this MethodInfo @this, ITuple? arguments) public static object? InvokeStaticFunc(this MethodInfo @this, ITuple? arguments) { var func = TypeStore.StaticMethodTupleFuncs[(@this.DeclaringType!.TypeHandle, @this.MethodHandle)]; - func.AssertNotNull(); + func.ThrowIfNull(); return func.Invoke(arguments); } @@ -253,8 +253,8 @@ public static MethodInfo MakeGenericMethod(this Meth /// public static Expression> ToArrayActionExpression(this MethodInfo @this) { - @this.IsStatic.AssertFalse(); - @this.ReturnType.AssertEquals(typeof(void)); + @this.IsStatic.ThrowIfTrue(); + @this.ReturnType.ThrowIfNotEqual(typeof(void)); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); @@ -268,8 +268,8 @@ public static MethodInfo MakeGenericMethod(this Meth /// public static Expression> ToArrayFuncExpression(this MethodInfo @this) { - @this.IsStatic.AssertFalse(); - @this.ReturnType.AssertNotEquals(typeof(void)); + @this.IsStatic.ThrowIfTrue(); + @this.ReturnType.ThrowIfEqual(typeof(void)); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); @@ -283,7 +283,7 @@ public static MethodInfo MakeGenericMethod(this Meth public static LambdaExpression ToDelegateExpression(this MethodInfo @this) { if (!@this.IsStatic) - @this.DeclaringType.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); ParameterExpression instance = nameof(instance).ToParameterExpression(@this.DeclaringType!); var parameters = @this.GetParameters() @@ -318,8 +318,8 @@ public static MethodCallExpression ToExpression(this MethodInfo @this, Expressio /// public static Expression> ToStaticArrayActionExpression(this MethodInfo @this) { - @this.IsStatic.AssertTrue(); - @this.ReturnType.AssertEquals(typeof(void)); + @this.IsStatic.ThrowIfFalse(); + @this.ReturnType.ThrowIfNotEqual(typeof(void)); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); var call = @this.CreateStaticArrayCall(arguments); @@ -332,8 +332,8 @@ public static MethodCallExpression ToExpression(this MethodInfo @this, Expressio /// public static Expression> ToStaticArrayFuncExpression(this MethodInfo @this) { - @this.IsStatic.AssertTrue(); - @this.ReturnType.AssertNotEquals(typeof(void)); + @this.IsStatic.ThrowIfFalse(); + @this.ReturnType.ThrowIfEqual(typeof(void)); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); var call = @this.CreateStaticArrayCall(arguments); @@ -346,8 +346,8 @@ public static MethodCallExpression ToExpression(this MethodInfo @this, Expressio /// public static Expression> ToStaticTupleActionExpression(this MethodInfo @this) { - @this.IsStatic.AssertTrue(); - @this.ReturnType.AssertEquals(typeof(void)); + @this.IsStatic.ThrowIfFalse(); + @this.ReturnType.ThrowIfNotEqual(typeof(void)); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); var call = @this.CreateStaticTupleCall(arguments); @@ -360,8 +360,8 @@ public static MethodCallExpression ToExpression(this MethodInfo @this, Expressio /// public static Expression> ToStaticTupleFuncExpression(this MethodInfo @this) { - @this.IsStatic.AssertTrue(); - @this.ReturnType.AssertNotEquals(typeof(void)); + @this.IsStatic.ThrowIfFalse(); + @this.ReturnType.ThrowIfEqual(typeof(void)); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); var call = @this.CreateStaticTupleCall(arguments); @@ -374,8 +374,8 @@ public static MethodCallExpression ToExpression(this MethodInfo @this, Expressio /// public static Expression> ToTupleActionExpression(this MethodInfo @this) { - @this.IsStatic.AssertFalse(); - @this.ReturnType.AssertEquals(typeof(void)); + @this.IsStatic.ThrowIfTrue(); + @this.ReturnType.ThrowIfNotEqual(typeof(void)); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); @@ -389,8 +389,8 @@ public static MethodCallExpression ToExpression(this MethodInfo @this, Expressio /// public static Expression> ToTupleFuncExpression(this MethodInfo @this) { - @this.IsStatic.AssertFalse(); - @this.ReturnType.AssertNotEquals(typeof(void)); + @this.IsStatic.ThrowIfTrue(); + @this.ReturnType.ThrowIfEqual(typeof(void)); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression arguments = nameof(arguments).ToParameterExpression(); @@ -411,7 +411,7 @@ private static Expression CreateStaticArrayCall(this MethodInfo @this, Parameter private static Expression CreateArrayCall(this MethodInfo @this, ParameterExpression instance, ParameterExpression arguments) { - @this.DeclaringType.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); var parameters = @this .GetParameters() @@ -423,25 +423,33 @@ private static Expression CreateArrayCall(this MethodInfo @this, ParameterExpres private static Expression CreateStaticTupleCall(this MethodInfo @this, ParameterExpression arguments) { - var parameterInfos = @this.GetParameters().OrderBy(parameterInfo => parameterInfo.Position).ToArray(); + var parameterInfos = @this.GetParameters(); + if (parameterInfos.Length == 0) + return @this.ToExpression(null); + + parameterInfos = @this.GetParameters().OrderBy(parameterInfo => parameterInfo.Position).ToArray(); var valueTupleType = GetValueTupleType(parameterInfos); var valueTupleFields = GetValueTupleFields(arguments.Cast(valueTupleType), parameterInfos); var parameters = parameterInfos.Select(parameterInfo => - arguments.Property("Item", [parameterInfo.Position.ToConstantExpression()]).Convert(parameterInfo.ParameterType)); + arguments.Property(Item, [parameterInfo.Position.ToConstantExpression()]).Convert(parameterInfo.ParameterType)); return arguments.Is(valueTupleType).IIf(@this.ToExpression(null, valueTupleFields), @this.ToExpression(null, parameters)); } private static Expression CreateTupleCall(this MethodInfo @this, ParameterExpression instance, ParameterExpression arguments) { - @this.DeclaringType.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); + + var typedInstance = instance.Cast(@this.DeclaringType); + var parameterInfos = @this.GetParameters(); + if (parameterInfos.Length == 0) + return typedInstance.Call(@this); - var parameterInfos = @this.GetParameters().OrderBy(parameterInfo => parameterInfo.Position).ToArray(); + parameterInfos = @this.GetParameters().OrderBy(parameterInfo => parameterInfo.Position).ToArray(); var valueTupleType = GetValueTupleType(parameterInfos); var valueTupleFields = GetValueTupleFields(arguments.Cast(valueTupleType), parameterInfos); var parameters = parameterInfos.Select(parameterInfo => - arguments.Property("Item", [parameterInfo.Position.ToConstantExpression()]).Convert(parameterInfo.ParameterType)); - var typedInstance = instance.Cast(@this.DeclaringType); + arguments.Property(Item, [parameterInfo.Position.ToConstantExpression()]).Convert(parameterInfo.ParameterType)); return arguments.Is(valueTupleType).IIf(typedInstance.Call(@this, valueTupleFields), typedInstance.Call(@this, parameters)); } @@ -453,11 +461,11 @@ private static IEnumerable GetValueTupleFields(Expression tupleExpre { if (++i == 8) { - tupleExpression = tupleExpression.Field("Rest"); + tupleExpression = tupleExpression.Field(Rest); i = 1; } - yield return tupleExpression.Field(Invariant($"Item{i}")); + yield return tupleExpression.Field(Item + i); } } diff --git a/src/TypeCache/Extensions/ReflectionExtensions.PropertyInfo.cs b/src/TypeCache/Extensions/ReflectionExtensions.PropertyInfo.cs index 1ea1aee8..42293fff 100644 --- a/src/TypeCache/Extensions/ReflectionExtensions.PropertyInfo.cs +++ b/src/TypeCache/Extensions/ReflectionExtensions.PropertyInfo.cs @@ -15,25 +15,25 @@ public partial class ReflectionExtensions /// /// [MethodImpl(AggressiveInlining), DebuggerHidden] - public static object? GetStaticValue(this PropertyInfo @this, ITuple? index = null) - => @this.GetStaticValueFunc()(index); + public static object? GetStaticValue(this PropertyInfo @this, ITuple? indexes = null) + => @this.GetStaticValueFunc()(indexes); /// /// public static Func GetStaticValueFunc(this PropertyInfo @this) { - @this.DeclaringType.AssertNotNull(); - @this.GetMethod.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); + @this.GetMethod.ThrowIfNull(); - return TypeStore.StaticPropertyFuncs[(@this.DeclaringType.TypeHandle, @this.Name)]; + return TypeStore.StaticMethodTupleFuncs[(@this.DeclaringType.TypeHandle, @this.GetMethod.MethodHandle)]; } /// /// public static Delegate GetValueDelegate(this PropertyInfo @this) { - @this.DeclaringType.AssertNotNull(); - @this.GetMethod.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); + @this.GetMethod.ThrowIfNull(); return TypeStore.Delegates[(@this.DeclaringType.TypeHandle, @this.GetMethod.MethodHandle)]; } @@ -44,17 +44,17 @@ public static Delegate GetValueDelegate(this PropertyInfo @this) /// /// [MethodImpl(AggressiveInlining), DebuggerHidden] - public static object? GetValueEx(this PropertyInfo @this, object instance, ITuple? index = null) - => @this.GetValueFunc()(instance, index); + public static object? GetValueEx(this PropertyInfo @this, object instance, ITuple? indexes = null) + => @this.GetValueFunc()(instance, indexes); /// /// public static Func GetValueFunc(this PropertyInfo @this) { - @this.DeclaringType.AssertNotNull(); - @this.GetMethod.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); + @this.GetMethod.ThrowIfNull(); - return TypeStore.PropertyFuncs[(@this.DeclaringType.TypeHandle, @this.Name)]; + return TypeStore.MethodTupleFuncs[(@this.DeclaringType.TypeHandle, @this.GetMethod.MethodHandle)]; } /// @@ -65,7 +65,7 @@ public static Delegate GetValueDelegate(this PropertyInfo @this) /// [MethodImpl(AggressiveInlining), DebuggerHidden] public static void SetStaticValue(this PropertyInfo @this, object? value) - => @this.SetStaticValueAction()(null, value); + => @this.SetStaticValueAction()(ValueTuple.Create(value)); /// /// Call this instead of for added performance improvement.
@@ -73,18 +73,19 @@ public static void SetStaticValue(this PropertyInfo @this, object? value) ///
/// /// + /// The last field of the tuple should be the value to set the property to./param> [MethodImpl(AggressiveInlining), DebuggerHidden] - public static void SetStaticValue(this PropertyInfo @this, ITuple index, object? value) - => @this.SetStaticValueAction()(index, value); + public static void SetStaticValue(this PropertyInfo @this, ITuple indexesAndValue) + => @this.SetStaticValueAction()(indexesAndValue); /// /// - public static Action SetStaticValueAction(this PropertyInfo @this) + public static Action SetStaticValueAction(this PropertyInfo @this) { - @this.DeclaringType.AssertNotNull(); - @this.SetMethod.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); + @this.SetMethod.ThrowIfNull(); - return TypeStore.StaticPropertyActions[(@this.DeclaringType.TypeHandle, @this.Name)]; + return TypeStore.StaticMethodTupleActions[(@this.DeclaringType.TypeHandle, @this.SetMethod.MethodHandle)]; } /// @@ -95,7 +96,7 @@ public static void SetStaticValue(this PropertyInfo @this, ITuple index, object? /// [MethodImpl(AggressiveInlining), DebuggerHidden] public static void SetValueEx(this PropertyInfo @this, object instance, object? value) - => @this.SetValueAction()(instance, null, value); + => @this.SetValueAction()(instance, ValueTuple.Create(value)); /// /// Call this instead of for added performance improvement.
@@ -103,24 +104,31 @@ public static void SetValueEx(this PropertyInfo @this, object instance, object? ///
/// /// - public static void SetValueWithIndex(this PropertyInfo @this, object instance, ITuple index, object? value) - => @this.SetValueAction()(instance, index, value); + /// The last field of the tuple should be the value to set the property to./param> + public static void SetValueEx(this PropertyInfo @this, object instance, ITuple indexesAndValue) + { + var indexParameters = @this.GetIndexParameters(); + indexParameters.ThrowIfNull(); + indexParameters.ThrowIfEmpty(); + + @this.SetValueAction()(instance, indexesAndValue); + } /// /// - public static Action SetValueAction(this PropertyInfo @this) + public static Action SetValueAction(this PropertyInfo @this) { - @this.DeclaringType.AssertNotNull(); - @this.SetMethod.AssertNotNull(); + @this.DeclaringType.ThrowIfNull(); + @this.SetMethod.ThrowIfNull(); - return TypeStore.PropertyActions[(@this.DeclaringType.TypeHandle, @this.Name)]; + return TypeStore.MethodTupleActions[(@this.DeclaringType.TypeHandle, @this.SetMethod.MethodHandle)]; } /// public static Delegate SetValueDelegate(this PropertyInfo @this) { - @this.SetMethod.AssertNotNull(); - @this.SetMethod.DeclaringType.AssertNotNull(); + @this.SetMethod.ThrowIfNull(); + @this.SetMethod.DeclaringType.ThrowIfNull(); return TypeStore.Delegates[(@this.SetMethod.DeclaringType.TypeHandle, @this.SetMethod.MethodHandle)]; } @@ -148,10 +156,10 @@ public static IndexExpression ToExpression(this PropertyInfo @this, Expression? /// public static Expression> ToPropertyActionExpression(this PropertyInfo @this) { - @this.AssertNotNull(); - @this.DeclaringType.AssertNotNull(); - @this.SetMethod.AssertNotNull(); - @this.SetMethod.IsStatic.AssertFalse(); + @this.ThrowIfNull(); + @this.DeclaringType.ThrowIfNull(); + @this.SetMethod.ThrowIfNull(); + @this.SetMethod.IsStatic.ThrowIfTrue(); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression value = nameof(instance).ToParameterExpression(); @@ -171,10 +179,10 @@ public static IndexExpression ToExpression(this PropertyInfo @this, Expression? /// public static Expression> ToPropertyFuncExpression(this PropertyInfo @this) { - @this.AssertNotNull(); - @this.DeclaringType.AssertNotNull(); - @this.GetMethod.AssertNotNull(); - @this.GetMethod.IsStatic.AssertFalse(); + @this.ThrowIfNull(); + @this.DeclaringType.ThrowIfNull(); + @this.GetMethod.ThrowIfNull(); + @this.GetMethod.IsStatic.ThrowIfTrue(); ParameterExpression instance = nameof(instance).ToParameterExpression(); ParameterExpression index = nameof(index).ToParameterExpression(); @@ -195,10 +203,10 @@ public static IndexExpression ToExpression(this PropertyInfo @this, Expression? /// public static Expression> ToStaticPropertyActionExpression(this PropertyInfo @this) { - @this.AssertNotNull(); - @this.DeclaringType.AssertNotNull(); - @this.SetMethod.AssertNotNull(); - @this.SetMethod.IsStatic.AssertTrue(); + @this.ThrowIfNull(); + @this.DeclaringType.ThrowIfNull(); + @this.SetMethod.ThrowIfNull(); + @this.SetMethod.IsStatic.ThrowIfFalse(); ParameterExpression value = nameof(value).ToParameterExpression(); ParameterExpression index = nameof(index).ToParameterExpression(); @@ -218,10 +226,10 @@ public static IndexExpression ToExpression(this PropertyInfo @this, Expression? /// public static Expression> ToStaticPropertyFuncExpression(this PropertyInfo @this) { - @this.AssertNotNull(); - @this.DeclaringType.AssertNotNull(); - @this.GetMethod.AssertNotNull(); - @this.GetMethod.IsStatic.AssertTrue(); + @this.ThrowIfNull(); + @this.DeclaringType.ThrowIfNull(); + @this.GetMethod.ThrowIfNull(); + @this.GetMethod.IsStatic.ThrowIfFalse(); ParameterExpression index = nameof(index).ToParameterExpression(); var itemProperty = typeof(ITuple).GetProperty("Item", INSTANCE_BINDING_FLAGS)!; diff --git a/src/TypeCache/Extensions/ReflectionExtensions.Type.cs b/src/TypeCache/Extensions/ReflectionExtensions.Type.cs index 345c3e7f..240e54ce 100644 --- a/src/TypeCache/Extensions/ReflectionExtensions.Type.cs +++ b/src/TypeCache/Extensions/ReflectionExtensions.Type.cs @@ -245,7 +245,7 @@ static bool isDescendantOf(Type? baseType, Type type) public static void InvokeMethodAction(this Type @this, string name, object instance, object?[]? arguments) { var methodInfo = @this.FindMethod(name, arguments); - methodInfo.AssertNotNull(); + methodInfo.ThrowIfNull(); methodInfo.InvokeAction(instance, arguments); } @@ -254,7 +254,7 @@ public static void InvokeMethodAction(this Type @this, string name, object insta public static void InvokeMethodAction(this Type @this, string name, object instance, ITuple? arguments) { var methodInfo = @this.FindMethod(name, arguments); - methodInfo.AssertNotNull(); + methodInfo.ThrowIfNull(); methodInfo.InvokeAction(instance, arguments); } @@ -263,15 +263,15 @@ public static void InvokeMethodAction(this Type @this, string name, object insta public static object? InvokeMethod(this Type @this, string name, object instance, object?[]? arguments) { var methodInfo = @this.FindMethod(name, arguments); - methodInfo.AssertNotNull(); - methodInfo.DeclaringType.AssertNotNull(); + methodInfo.ThrowIfNull(); + methodInfo.DeclaringType.ThrowIfNull(); var func = TypeStore.MethodArrayFuncs[(methodInfo.DeclaringType.TypeHandle, methodInfo.MethodHandle)]; if (func is not null) return func(instance, arguments); var action = TypeStore.MethodArrayActions[(methodInfo.DeclaringType.TypeHandle, methodInfo.MethodHandle)]; - action.AssertNotNull(); + action.ThrowIfNull(); action(instance, arguments); return null; @@ -450,8 +450,8 @@ public static bool IsConvertible(this Type @this) /// public static bool IsConvertibleTo(this Type @this, Type targetType) { - @this.AssertNotNull(); - targetType.AssertNotNull(); + @this.ThrowIfNull(); + targetType.ThrowIfNull(); return @this.GetScalarType().IsConvertibleTo(targetType.GetScalarType()); } diff --git a/src/TypeCache/Extensions/ReflectionExtensions.cs b/src/TypeCache/Extensions/ReflectionExtensions.cs index 9bbccd76..042e1ff7 100644 --- a/src/TypeCache/Extensions/ReflectionExtensions.cs +++ b/src/TypeCache/Extensions/ReflectionExtensions.cs @@ -8,7 +8,11 @@ namespace TypeCache.Extensions; public static partial class ReflectionExtensions { private const char GENERIC_TICKMARK = '`'; + private const BindingFlags BINDING_FLAGS = FlattenHierarchy | IgnoreCase | Instance | NonPublic | Public | Static; private const BindingFlags INSTANCE_BINDING_FLAGS = FlattenHierarchy | IgnoreCase | Instance | NonPublic | Public; private const BindingFlags STATIC_BINDING_FLAGS = FlattenHierarchy | IgnoreCase | NonPublic | Public | Static; + + private const string Item = nameof(Item); + private const string Rest = nameof(Rest); } diff --git a/src/TypeCache/Extensions/StringExtensions.cs b/src/TypeCache/Extensions/StringExtensions.cs index 031ca039..d8204dd4 100644 --- a/src/TypeCache/Extensions/StringExtensions.cs +++ b/src/TypeCache/Extensions/StringExtensions.cs @@ -6,7 +6,7 @@ using System.Text; using System.Text.RegularExpressions; using Microsoft.Extensions.Primitives; -using TypeCache.Collections; +using TypeCache.Utilities; using static System.Globalization.CultureInfo; namespace TypeCache.Extensions; @@ -316,7 +316,7 @@ public static ParameterExpression ToParameterExpression(this string @this, Type /// /// /// => RegexCache[(@, )]; - /// // _ => new Regex(@, , .FromMinutes(1)); + /// // _ => Regex(@, , .FromMinutes(1)); /// /// [MethodImpl(AggressiveInlining), DebuggerHidden] diff --git a/src/TypeCache/Extensions/AssertExtensions.cs b/src/TypeCache/Extensions/ThrowIfExtensions.cs similarity index 55% rename from src/TypeCache/Extensions/AssertExtensions.cs rename to src/TypeCache/Extensions/ThrowIfExtensions.cs index d37b5db6..e789d65d 100644 --- a/src/TypeCache/Extensions/AssertExtensions.cs +++ b/src/TypeCache/Extensions/ThrowIfExtensions.cs @@ -4,146 +4,128 @@ namespace TypeCache.Extensions; -public static class AssertExtensions +public static class ThrowIfExtensions { private const string NULL = "null"; /// - public static void AssertEquals(this string? @this, string? value, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase, - [CallerArgumentExpression("this")] string? argument = null, - [CallerMemberName] string? caller = null) - { - if (!string.Equals(@this, value, comparisonType)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this ?? NULL}.{nameof(AssertEquals)}({value ?? NULL}).")); - } - - /// - public static void AssertEquals(this T? @this, T? value, IEqualityComparer? comparer = null, + public static void ThrowIfNotEqual(this T? @this, T? value, IEqualityComparer? comparer = null, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { comparer ??= EqualityComparer.Default; if (!comparer.Equals(@this, value)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(AssertEquals)}<{typeof(T).Name}>({value?.ToString() ?? NULL}).")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(ThrowIfNotEqual)}<{typeof(T).Name}>({argument}).")); } /// - public static void AssertFalse(this bool @this, + public static void ThrowIfNotEqualIgnoreCase(this string? @this, string? value, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { - if (@this) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {nameof(AssertFalse)}({argument}).")); + if (!string.Equals(@this, value, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this ?? NULL}.{nameof(ThrowIfNotEqualIgnoreCase)}({argument}).")); } - /// /// - public static void AssertNotBlank([NotNull] this string? @this, + public static void ThrowIfBlank([NotNull] this string? @this, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { - @this.AssertNotNull(argument, caller); - if (@this.IsBlank()) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {argument}.{nameof(AssertNotBlank)}().")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {argument}.{nameof(ThrowIfBlank)}().")); } - /// /// - public static void AssertNotEmpty([NotNull] this IEnumerable? @this, + public static void ThrowIfEmpty([NotNull] this IEnumerable @this, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) where T : notnull { - @this.AssertNotNull(argument, caller); - if (!@this.Any()) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {argument}.{nameof(AssertNotEmpty)}>().")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {argument}.{nameof(ThrowIfEmpty)}>().")); } /// - public static void AssertNotEquals(this string? @this, string? value, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase, + public static void ThrowIfEmpty([NotNull] this T[] @this, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) + where T : notnull { - if (string.Equals(@this, value, comparisonType)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this ?? NULL}.{nameof(AssertEquals)}({value ?? NULL}).")); + if (@this.Length is 0) + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {argument}.{nameof(ThrowIfEmpty)}<{typeof(T).Name}[]>().")); } /// - public static void AssertNotEquals(this T? @this, T? value, IEqualityComparer? comparer = null, + public static void ThrowIfEqual(this T? @this, T? value, IEqualityComparer? comparer = null, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { comparer ??= EqualityComparer.Default; if (comparer.Equals(@this, value)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(AssertNotEquals)}<{typeof(T).Name}>({value?.ToString() ?? NULL}).")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(ThrowIfEqual)}<{typeof(T).Name}>({argument}).")); } - /// /// - public static void AssertNotEmpty([NotNull] this T[]? @this, + public static void ThrowIfEqualIgnoreCase(this string? @this, string? value, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) - where T : notnull { - @this.AssertNotNull(argument, caller); + if (string.Equals(@this, value, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this ?? NULL}.{nameof(ThrowIfEqualIgnoreCase)}({argument}).")); + } - if (!@this.Any()) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {argument}.{nameof(AssertNotEmpty)}<{typeof(T).Name}[]>().")); + /// + public static void ThrowIfFalse(this bool @this, + [CallerArgumentExpression("this")] string? argument = null, + [CallerMemberName] string? caller = null) + { + if (!@this) + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {nameof(ThrowIfFalse)}({argument}).")); } /// - public static void AssertNotNull([NotNull] this T? @this, + public static void ThrowIfNull([NotNull] this T? @this, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) - where T : notnull - => ArgumentNullException.ThrowIfNull(@this, Invariant($"{caller}: {argument}.{nameof(AssertNotNull)}<{typeof(T).Name}>().")); + => ArgumentNullException.ThrowIfNull(@this, Invariant($"{caller}: {argument}.{nameof(ThrowIfNull)}<{typeof(T).Name}>().")); /// - public static void AssertNotSame(this object? @this, object? value, StringComparison comparison = StringComparison.OrdinalIgnoreCase, + public static void ThrowIfSame(this T? @this, T? value, StringComparison comparison = StringComparison.OrdinalIgnoreCase, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { if (object.ReferenceEquals(@this, value)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(AssertNotSame)}({value?.ToString() ?? NULL}).")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(ThrowIfSame)}({value?.ToString() ?? NULL}).")); } /// - public static void AssertNotSame(this (T?, T?) @this, + public static void ThrowIfSame(this (T?, T?) @this, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) where T : notnull { if (object.ReferenceEquals(@this.Item1, @this.Item2)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this.Item1?.ToString() ?? NULL}.{nameof(AssertNotSame)}<{typeof(T).Name}>({@this.Item2?.ToString() ?? NULL}).")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this.Item1?.ToString() ?? NULL}.{nameof(ThrowIfSame)}<{typeof(T).Name}>({@this.Item2?.ToString() ?? NULL}).")); } /// - public static void AssertSame(this object? @this, object? value, + public static void ThrowIfNotSame(this object? @this, object? value, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { if (object.ReferenceEquals(@this, value)) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(AssertNotSame)}({value?.ToString() ?? NULL}).")); + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {@this?.ToString() ?? NULL}.{nameof(ThrowIfNotSame)}({value?.ToString() ?? NULL}).")); } /// - public static void AssertTrue(this bool @this, + public static void ThrowIfTrue(this bool @this, [CallerArgumentExpression("this")] string? argument = null, [CallerMemberName] string? caller = null) { - if (!@this) - throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {nameof(AssertTrue)}({argument}).")); + if (@this) + throw new ArgumentOutOfRangeException(argument, Invariant($"{caller}: {nameof(ThrowIfTrue)}({argument}).")); } - - /// - [DoesNotReturn] - public static T? ThrowArgumentNullException( - this T? @this, - [CallerArgumentExpression("this")] string? argument = null, - [CallerMemberName] string? caller = null) - => throw new ArgumentNullException(Invariant($"{caller}: {argument}.{nameof(AssertNotNull)}<{typeof(T).Name}>().")); } diff --git a/src/TypeCache/Mediation/RuleFactory.cs b/src/TypeCache/Mediation/RuleFactory.cs index 6be49c63..7b9be014 100644 --- a/src/TypeCache/Mediation/RuleFactory.cs +++ b/src/TypeCache/Mediation/RuleFactory.cs @@ -10,7 +10,7 @@ public static class RuleFactory public static IAfterRule CreateAfterRule(Func handleAsync) where REQUEST : IRequest { - handleAsync.AssertNotNull(); + handleAsync.ThrowIfNull(); return new CustomAfterRule(handleAsync); } @@ -19,7 +19,7 @@ public static IAfterRule CreateAfterRule(Func CreateAfterRule(Action handle) where REQUEST : IRequest { - handle.AssertNotNull(); + handle.ThrowIfNull(); return new CustomAfterRule((REQUEST request, CancellationToken token) => Task.Run(() => handle(request), token)); } @@ -28,7 +28,7 @@ public static IAfterRule CreateAfterRule(Action handl public static IAfterRule CreateAfterRule(Func handleAsync) where REQUEST : IRequest { - handleAsync.AssertNotNull(); + handleAsync.ThrowIfNull(); return new CustomAfterRule(handleAsync); } @@ -37,7 +37,7 @@ public static IAfterRule CreateAfterRule(F public static IAfterRule CreateAfterRule(Action handle) where REQUEST : IRequest { - handle.AssertNotNull(); + handle.ThrowIfNull(); return new CustomAfterRule((REQUEST request, RESPONSE response, CancellationToken token) => Task.Run(() => handle(request, response), token)); } @@ -46,7 +46,7 @@ public static IAfterRule CreateAfterRule(A public static IRule CreateRule(Func executeAsync) where REQUEST : IRequest { - executeAsync.AssertNotNull(); + executeAsync.ThrowIfNull(); return new CustomRule(executeAsync); } @@ -55,7 +55,7 @@ public static IRule CreateRule(Func CreateRule(Action execute) where REQUEST : IRequest { - execute.AssertNotNull(); + execute.ThrowIfNull(); return new CustomRule((REQUEST request, CancellationToken token) => Task.Run(() => execute(request), token)); } @@ -64,7 +64,7 @@ public static IRule CreateRule(Action execute) public static IRule CreateRule(Func> mapAsync) where REQUEST : IRequest { - mapAsync.AssertNotNull(); + mapAsync.ThrowIfNull(); return new CustomRule(mapAsync); } @@ -73,7 +73,7 @@ public static IRule CreateRule(Func CreateRule(Func map) where REQUEST : IRequest { - map.AssertNotNull(); + map.ThrowIfNull(); return new CustomRule((REQUEST request, CancellationToken token) => Task.Run(() => map(request), token)); } @@ -82,7 +82,7 @@ public static IRule CreateRule(Func CreateValidationRule(Func validateAsync) where REQUEST : IRequest { - validateAsync.AssertNotNull(); + validateAsync.ThrowIfNull(); return new CustomValidationRule(validateAsync); } @@ -91,7 +91,7 @@ public static IValidationRule CreateValidationRule(Func CreateValidationRule(Action validate) where REQUEST : IRequest { - validate.AssertNotNull(); + validate.ThrowIfNull(); return new CustomValidationRule((request, token) => Task.Run(() => validate(request), token)); } diff --git a/src/TypeCache/README.md b/src/TypeCache/README.md index b6017d2e..41df4411 100644 --- a/src/TypeCache/README.md +++ b/src/TypeCache/README.md @@ -47,7 +47,7 @@ - `IAfterRule` - `RuleFactory` --- -### `TypeCache.Extensions` - Simple Robust Database CRUD Access +### `TypeCache.Data` - Simple Robust Database CRUD Access - `System.Data.Common.DbCommand.ExecuteReaderAsync(...)` - `System.Data.Common.DbCommand.GetDataTableAsync(...)` - `System.Data.Common.DbCommand.GetJsonArrayAsync(...)` @@ -61,17 +61,16 @@ - `System.Data.Common.DbDataReader.ReadJsonAsync(...)`__ --- ### `TypeCache.Extensions` - Helpful Extensions -- `Array/Linq/Enumerator` extensions -- Assertion extensions +- Array, Linq, Enumerator extensions +- ThrowIf extensions - `System.Linq.Expressions` extensions - `System.BitConverter` extensions - `System.Char` extensions - `System.Enum` extensions - `System.ReadOnlySpan<>` extensions -- `System.Reflection` extensions - `System.Span<>` extensions - `System.Text.Rune` extensions - `System.Text.StringBuilder` extensions -- `Range/Index` extensions +- `Range` and `Index` extensions - Time Zone extensions - And many more! diff --git a/src/TypeCache/TypeCache.csproj b/src/TypeCache/TypeCache.csproj index a8801cc3..a22d16fa 100644 --- a/src/TypeCache/TypeCache.csproj +++ b/src/TypeCache/TypeCache.csproj @@ -6,7 +6,7 @@ TypeCache true TypeCache - 8.3.0 + 8.3.1 Samuel Abraham <sam987883@gmail.com> Samuel Abraham <sam987883@gmail.com> TypeCache Reflection diff --git a/src/TypeCache/Collections/Array.cs b/src/TypeCache/Utilities/Array.cs similarity index 85% rename from src/TypeCache/Collections/Array.cs rename to src/TypeCache/Utilities/Array.cs index 3e24d290..ae221e79 100644 --- a/src/TypeCache/Collections/Array.cs +++ b/src/TypeCache/Utilities/Array.cs @@ -1,6 +1,6 @@ // Copyright (c) 2021 Samuel Abraham -namespace TypeCache.Collections; +namespace TypeCache.Utilities; public static class Array { diff --git a/src/TypeCache/Collections/EnumComparer.cs b/src/TypeCache/Utilities/EnumComparer.cs similarity index 96% rename from src/TypeCache/Collections/EnumComparer.cs rename to src/TypeCache/Utilities/EnumComparer.cs index 976d1eb8..db71a854 100644 --- a/src/TypeCache/Collections/EnumComparer.cs +++ b/src/TypeCache/Utilities/EnumComparer.cs @@ -1,9 +1,8 @@ // Copyright (c) 2021 Samuel Abraham using TypeCache.Extensions; -using TypeCache.Utilities; -namespace TypeCache.Collections; +namespace TypeCache.Utilities; public readonly struct EnumComparer : IComparer, IEqualityComparer where T : struct, Enum diff --git a/src/TypeCache/Utilities/EventHandler.cs b/src/TypeCache/Utilities/EventHandler.cs index 458f1892..ac38966c 100644 --- a/src/TypeCache/Utilities/EventHandler.cs +++ b/src/TypeCache/Utilities/EventHandler.cs @@ -20,13 +20,13 @@ public static class EventHandler /// public static long Add(T instance, string eventMemberName, Delegate handler) { - instance.AssertNotNull(); - eventMemberName.AssertNotBlank(); - handler.AssertNotNull(); + instance.ThrowIfNull(); + eventMemberName.ThrowIfBlank(); + handler.ThrowIfNull(); var eventInfo = typeof(T).GetEvent(eventMemberName); - eventInfo.AssertNotNull(); - eventInfo.AddMethod.AssertNotNull(); + eventInfo.ThrowIfNull(); + eventInfo.AddMethod.ThrowIfNull(); var key = DateTime.UtcNow.Ticks; var reference = new EventHandlerReference(instance.ToWeakReference(), eventInfo.AddMethod.MethodHandle, eventInfo.RemoveMethod?.MethodHandle, handler); diff --git a/src/TypeCache/Utilities/HashMaker.cs b/src/TypeCache/Utilities/HashMaker.cs index 6a209617..f696b733 100644 --- a/src/TypeCache/Utilities/HashMaker.cs +++ b/src/TypeCache/Utilities/HashMaker.cs @@ -57,7 +57,7 @@ public byte[] Encrypt(ReadOnlySpan data, PaddingMode paddingMode = Padding /// public byte[] Encrypt(byte[] data, PaddingMode paddingMode = PaddingMode.PKCS7) { - data.AssertNotNull(); + data.ThrowIfNull(); return this._SymmetricAlgorithm .EncryptCbc(data, this._SymmetricAlgorithm.IV, paddingMode); diff --git a/src/TypeCache/Utilities/LambdaFactory.cs b/src/TypeCache/Utilities/LambdaFactory.cs index c6cbd83e..6997fb0d 100644 --- a/src/TypeCache/Utilities/LambdaFactory.cs +++ b/src/TypeCache/Utilities/LambdaFactory.cs @@ -156,4 +156,14 @@ public static Expression> CreatePredicate(Func(); return Expression.Lambda>(lambda(value), value); } + + public static LambdaExpression CreateEnumParseFunc(Type enumType) + { + ParameterExpression value = nameof(value).ToParameterExpression(); + + return typeof(Enum) + .GetMethod(nameof(Enum.Parse), 1, [typeof(string), typeof(bool)])! + .ToExpression(null, [value, true.ToConstantExpression()]) + .LambdaFunc(enumType, [value]); + } } diff --git a/src/TypeCache/Collections/LazyDictionary.cs b/src/TypeCache/Utilities/LazyDictionary.cs similarity index 95% rename from src/TypeCache/Collections/LazyDictionary.cs rename to src/TypeCache/Utilities/LazyDictionary.cs index 38589739..cc7b2c2f 100644 --- a/src/TypeCache/Collections/LazyDictionary.cs +++ b/src/TypeCache/Utilities/LazyDictionary.cs @@ -4,7 +4,7 @@ using System.Collections.Concurrent; using TypeCache.Extensions; -namespace TypeCache.Collections; +namespace TypeCache.Utilities; public sealed class LazyDictionary : IReadOnlyDictionary where K : notnull @@ -15,7 +15,7 @@ public sealed class LazyDictionary : IReadOnlyDictionary /// public LazyDictionary(Func createValue, LazyThreadSafetyMode mode = LazyThreadSafetyMode.PublicationOnly, IEqualityComparer? comparer = null) { - createValue.AssertNotNull(); + createValue.ThrowIfNull(); this._CreateValue = key => new Lazy(() => createValue(key), mode); this._Dictionary = new(comparer); } @@ -23,7 +23,7 @@ public LazyDictionary(Func createValue, LazyThreadSafetyMode mode = LazyTh /// public LazyDictionary(Func createValue, int concurrencyLevel, int capacity, LazyThreadSafetyMode mode = LazyThreadSafetyMode.PublicationOnly, IEqualityComparer? comparer = null) { - createValue.AssertNotNull(); + createValue.ThrowIfNull(); this._CreateValue = key => new Lazy(() => createValue(key), mode); this._Dictionary = new(concurrencyLevel, capacity, comparer); diff --git a/src/TypeCache/Utilities/TypeStore.cs b/src/TypeCache/Utilities/TypeStore.cs index b783b2b8..23c23a8f 100644 --- a/src/TypeCache/Utilities/TypeStore.cs +++ b/src/TypeCache/Utilities/TypeStore.cs @@ -12,14 +12,13 @@ using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; -using TypeCache.Collections; using TypeCache.Extensions; namespace TypeCache.Utilities; public static class TypeStore { - internal static IReadOnlySet<(RuntimeTypeHandle Handle, CollectionType CollectionType)> CollectionTypeMap => new[] + public static IReadOnlySet<(RuntimeTypeHandle Handle, CollectionType CollectionType)> CollectionTypeMap => new[] { (typeof(Array).TypeHandle, CollectionType.Array), (typeof(ArrayList).TypeHandle, CollectionType.ArrayList), @@ -73,7 +72,7 @@ public static class TypeStore (typeof(ICollection<>).TypeHandle, CollectionType.Collection) }.ToFrozenSet(); - internal static IReadOnlySet<(RuntimeTypeHandle Handle, ObjectType ObjectType)> ObjectTypeMap => new[] + public static IReadOnlySet<(RuntimeTypeHandle Handle, ObjectType ObjectType)> ObjectTypeMap => new[] { (typeof(Attribute).TypeHandle, ObjectType.Attribute), (typeof(DataColumn).TypeHandle, ObjectType.DataColumn), @@ -108,6 +107,7 @@ public static class TypeStore (typeof(Range).TypeHandle, ObjectType.Range), (typeof(Task).TypeHandle, ObjectType.Task), (typeof(Task<>).TypeHandle, ObjectType.Task), + (typeof(Tuple).TypeHandle, ObjectType.Tuple), (typeof(Tuple<>).TypeHandle, ObjectType.Tuple), (typeof(Tuple<,>).TypeHandle, ObjectType.Tuple), (typeof(Tuple<,,>).TypeHandle, ObjectType.Tuple), @@ -173,8 +173,6 @@ static TypeStore() { typeof(UIntPtr).TypeHandle, ScalarType.UIntPtr }, { typeof(Uri).TypeHandle, ScalarType.Uri } }.ToFrozenDictionary(); - DefaultValueFactory = new LazyDictionary>(handle => - handle.ToType().ToDefaultExpression().As().Lambda>().Compile()); DefaultValueTypeConstructorFuncs = new LazyDictionary>(handle => handle.ToType().ToNewExpression().As().Lambda>().Compile()); Delegates = new LazyDictionary<(RuntimeTypeHandle TypeHandle, RuntimeMethodHandle MethodHandle), Delegate>(_ => @@ -205,10 +203,6 @@ static TypeStore() Type type when type.GetScalarType() is not ScalarType.None => ObjectType.DataType, Type type => ObjectTypeMap.FirstOrDefault(_ => type.Implements(_.Handle.ToType())).ObjectType }); - PropertyActions = new LazyDictionary<(RuntimeTypeHandle TypeHandle, string Property), Action>(_ => - _.TypeHandle.ToType().GetProperty(_.Property)!.ToPropertyActionExpression().Compile()); - PropertyFuncs = new LazyDictionary<(RuntimeTypeHandle TypeHandle, string Property), Func>(_ => - _.TypeHandle.ToType().GetProperty(_.Property)!.ToPropertyFuncExpression().Compile()); StaticFieldGetFuncs = new LazyDictionary>(handle => handle.ToFieldInfo().ToStaticFuncExpression().Compile()); StaticFieldSetActions = new LazyDictionary>(handle => @@ -221,10 +215,6 @@ Type type when type.GetScalarType() is not ScalarType.None => ObjectType.DataTyp ((MethodInfo)_.MethodHandle.ToMethodBase(_.TypeHandle)).ToStaticArrayFuncExpression().Compile()); StaticMethodTupleFuncs = new LazyDictionary<(RuntimeTypeHandle TypeHandle, RuntimeMethodHandle MethodHandle), Func>(_ => ((MethodInfo)_.MethodHandle.ToMethodBase(_.TypeHandle)).ToStaticTupleFuncExpression().Compile()); - StaticPropertyActions = new LazyDictionary<(RuntimeTypeHandle TypeHandle, string Property), Action>(_ => - _.TypeHandle.ToType().GetProperty(_.Property)!.ToStaticPropertyActionExpression().Compile()); - StaticPropertyFuncs = new LazyDictionary<(RuntimeTypeHandle TypeHandle, string Property), Func>(_ => - _.TypeHandle.ToType().GetProperty(_.Property)!.ToStaticPropertyFuncExpression().Compile()); } public static IReadOnlyDictionary CollectionTypes { get; } @@ -235,8 +225,6 @@ Type type when type.GetScalarType() is not ScalarType.None => ObjectType.DataTyp public static IReadOnlyDictionary DataTypes { get; } - public static IReadOnlyDictionary> DefaultValueFactory { get; } - public static IReadOnlyDictionary> DefaultValueTypeConstructorFuncs { get; } public static IReadOnlyDictionary<(RuntimeTypeHandle, RuntimeMethodHandle), Delegate> Delegates { get; } @@ -253,10 +241,6 @@ Type type when type.GetScalarType() is not ScalarType.None => ObjectType.DataTyp public static IReadOnlyDictionary<(RuntimeTypeHandle, RuntimeMethodHandle), Func> MethodTupleFuncs { get; } - public static IReadOnlyDictionary<(RuntimeTypeHandle, string), Func> PropertyFuncs { get; } - - public static IReadOnlyDictionary<(RuntimeTypeHandle, string), Action> PropertyActions { get; } - public static IReadOnlyDictionary ObjectTypes { get; } public static IReadOnlyDictionary> StaticFieldGetFuncs { get; } @@ -270,8 +254,4 @@ Type type when type.GetScalarType() is not ScalarType.None => ObjectType.DataTyp public static IReadOnlyDictionary<(RuntimeTypeHandle, RuntimeMethodHandle), Func> StaticMethodArrayFuncs { get; } public static IReadOnlyDictionary<(RuntimeTypeHandle, RuntimeMethodHandle), Func> StaticMethodTupleFuncs { get; } - - public static IReadOnlyDictionary<(RuntimeTypeHandle, string), Func> StaticPropertyFuncs { get; } - - public static IReadOnlyDictionary<(RuntimeTypeHandle, string), Action> StaticPropertyActions { get; } } diff --git a/src/TypeCache/Utilities/ValueConverter.cs b/src/TypeCache/Utilities/ValueConverter.cs index 9abcb3bb..4cbd0fe4 100644 --- a/src/TypeCache/Utilities/ValueConverter.cs +++ b/src/TypeCache/Utilities/ValueConverter.cs @@ -11,15 +11,10 @@ public static class ValueConverter { private const string TRUE_CHARS = "1XxYyTt"; - [MethodImpl(AggressiveInlining)] - private static bool IsNotZero(in T value) - where T : INumberBase - => value != T.Zero; - public static Expression CreateConversionExpression(this Expression @this, Type targetType) { - @this.AssertNotNull(); - targetType.AssertNotNull(); + @this.ThrowIfNull(); + targetType.ThrowIfNull(); var isSourceNullable = @this.Type.IsNullable(); var value = isSourceNullable ? @this.Property(nameof(Nullable.Value)) : @this; @@ -28,138 +23,139 @@ public static Expression CreateConversionExpression(this Expression @this, Type var expression = (sourceScalarType, targetScalarType) switch { - (ScalarType.Boolean, ScalarType.Char) => LambdaFactory.CreateFunc((bool _) => _ ? '1' : '0'), - (ScalarType.Boolean, ScalarType.SByte) => LambdaFactory.CreateFunc((bool _) => _ ? (sbyte)1 : (sbyte)0), - (ScalarType.Boolean, ScalarType.Int16) => LambdaFactory.CreateFunc((bool _) => _ ? (short)1 : (short)0), - (ScalarType.Boolean, ScalarType.Int32) => LambdaFactory.CreateFunc((bool _) => _ ? 1 : 0), - (ScalarType.Boolean, ScalarType.Int64) => LambdaFactory.CreateFunc((bool _) => _ ? 1L : 0L), - (ScalarType.Boolean, ScalarType.Int128) => LambdaFactory.CreateFunc((bool _) => _ ? Int128.One : Int128.Zero), - (ScalarType.Boolean, ScalarType.BigInteger) => LambdaFactory.CreateFunc((bool _) => _ ? BigInteger.One : BigInteger.Zero), - (ScalarType.Boolean, ScalarType.Byte) => LambdaFactory.CreateFunc((bool _) => _ ? (byte)1 : (byte)0), - (ScalarType.Boolean, ScalarType.UInt16) => LambdaFactory.CreateFunc((bool _) => _ ? (ushort)1 : (ushort)0), - (ScalarType.Boolean, ScalarType.UInt32) => LambdaFactory.CreateFunc((bool _) => _ ? 1U : 0U), - (ScalarType.Boolean, ScalarType.UInt64) => LambdaFactory.CreateFunc((bool _) => _ ? 1UL : 0UL), - (ScalarType.Boolean, ScalarType.UInt128) => LambdaFactory.CreateFunc((bool _) => _ ? UInt128.One : UInt128.Zero), - - (ScalarType.Char, ScalarType.Boolean) => LambdaFactory.CreateFunc((char _) => TRUE_CHARS.Contains(_)), - (ScalarType.SByte, ScalarType.Boolean) => LambdaFactory.CreateFunc((sbyte _) => IsNotZero(_)), - (ScalarType.Int16, ScalarType.Boolean) => LambdaFactory.CreateFunc((short _) => _ != 0), - (ScalarType.Int32, ScalarType.Boolean) => LambdaFactory.CreateFunc((int _) => _ != 0), - (ScalarType.Int64, ScalarType.Boolean) => LambdaFactory.CreateFunc((long _) => _ != 0L), - (ScalarType.Int128, ScalarType.Boolean) => LambdaFactory.CreateFunc((Int128 _) => _ != Int128.Zero), - (ScalarType.BigInteger, ScalarType.Boolean) => LambdaFactory.CreateFunc((BigInteger _) => _ != BigInteger.Zero), - (ScalarType.Byte, ScalarType.Boolean) => LambdaFactory.CreateFunc((byte _) => _ != 0), - (ScalarType.UInt16, ScalarType.Boolean) => LambdaFactory.CreateFunc((ushort _) => _ != 0), - (ScalarType.UInt32, ScalarType.Boolean) => LambdaFactory.CreateFunc((uint _) => _ != 0U), - (ScalarType.UInt64, ScalarType.Boolean) => LambdaFactory.CreateFunc((ulong _) => _ != 0UL), - (ScalarType.UInt128, ScalarType.Boolean) => LambdaFactory.CreateFunc((UInt128 _) => _ != UInt128.Zero), - (ScalarType.IntPtr, ScalarType.Boolean) => LambdaFactory.CreateFunc((IntPtr _) => _ != nint.Zero), - (ScalarType.UIntPtr, ScalarType.Boolean) => LambdaFactory.CreateFunc((UIntPtr _) => _ != nuint.Zero), - (ScalarType.Half, ScalarType.Boolean) => LambdaFactory.CreateFunc((Half _) => _ != Half.Zero), - (ScalarType.Single, ScalarType.Boolean) => LambdaFactory.CreateFunc((float _) => _ != 0F), - (ScalarType.Double, ScalarType.Boolean) => LambdaFactory.CreateFunc((double _) => _ != 0D), - (ScalarType.Decimal, ScalarType.Boolean) => LambdaFactory.CreateFunc((decimal _) => _ != 0M), - (ScalarType.DateOnly, ScalarType.Boolean) => LambdaFactory.CreateFunc((DateOnly _) => _ != DateOnly.MinValue), - (ScalarType.DateTime, ScalarType.Boolean) => LambdaFactory.CreateFunc((DateTime _) => _ != DateTime.MinValue), - (ScalarType.DateTimeOffset, ScalarType.Boolean) => LambdaFactory.CreateFunc((DateTimeOffset _) => _ != DateTimeOffset.MinValue), - (ScalarType.TimeOnly, ScalarType.Boolean) => LambdaFactory.CreateFunc((TimeOnly _) => _ != TimeOnly.MinValue), - (ScalarType.TimeSpan, ScalarType.Boolean) => LambdaFactory.CreateFunc((TimeSpan _) => _ != TimeSpan.Zero), - - (ScalarType.Char, ScalarType.String) => LambdaFactory.CreateFunc((char _) => _.ToString()), - (ScalarType.SByte, ScalarType.String) => LambdaFactory.CreateFunc((sbyte _) => _.ToString()), - (ScalarType.Int16, ScalarType.String) => LambdaFactory.CreateFunc((short _) => _.ToString()), - (ScalarType.Int32, ScalarType.String) => LambdaFactory.CreateFunc((int _) => _.ToString()), - (ScalarType.Int64, ScalarType.String) => LambdaFactory.CreateFunc((long _) => _.ToString()), - (ScalarType.Int128, ScalarType.String) => LambdaFactory.CreateFunc((Int128 _) => _.ToString()), - (ScalarType.BigInteger, ScalarType.String) => LambdaFactory.CreateFunc((BigInteger _) => _.ToString()), - (ScalarType.Byte, ScalarType.String) => LambdaFactory.CreateFunc((sbyte _) => _.ToString()), - (ScalarType.UInt16, ScalarType.String) => LambdaFactory.CreateFunc((short _) => _.ToString()), - (ScalarType.UInt32, ScalarType.String) => LambdaFactory.CreateFunc((int _) => _.ToString()), - (ScalarType.UInt64, ScalarType.String) => LambdaFactory.CreateFunc((long _) => _.ToString()), - (ScalarType.UInt128, ScalarType.String) => LambdaFactory.CreateFunc((Int128 _) => _.ToString()), - (ScalarType.IntPtr, ScalarType.String) => LambdaFactory.CreateFunc((IntPtr _) => _.ToString()), - (ScalarType.UIntPtr, ScalarType.String) => LambdaFactory.CreateFunc((UIntPtr _) => _.ToString()), - (ScalarType.Half, ScalarType.String) => LambdaFactory.CreateFunc((Half _) => _.ToString()), - (ScalarType.Single, ScalarType.String) => LambdaFactory.CreateFunc((float _) => _.ToString()), - (ScalarType.Double, ScalarType.String) => LambdaFactory.CreateFunc((double _) => _.ToString()), - (ScalarType.Decimal, ScalarType.String) => LambdaFactory.CreateFunc((decimal _) => _.ToString()), - (ScalarType.DateOnly, ScalarType.String) => LambdaFactory.CreateFunc((DateOnly _) => _.ToISO8601(null)), - (ScalarType.DateTime, ScalarType.String) => LambdaFactory.CreateFunc((DateTime _) => _.ToISO8601(null)), - (ScalarType.DateTimeOffset, ScalarType.String) => LambdaFactory.CreateFunc((DateTimeOffset _) => _.ToISO8601(null)), - (ScalarType.Enum, ScalarType.String) => LambdaFactory.CreateFunc((Enum _) => _.Name()), - (ScalarType.TimeOnly, ScalarType.String) => LambdaFactory.CreateFunc((TimeOnly _) => _.ToISO8601(null)), - (ScalarType.TimeSpan, ScalarType.String) => LambdaFactory.CreateFunc((TimeSpan _) => _.ToText(null)), - (ScalarType.Guid, ScalarType.String) => LambdaFactory.CreateFunc((Guid _) => _.ToString("D")), - (ScalarType.Index, ScalarType.String) => LambdaFactory.CreateFunc((Index _) => _.Value.ToString()), - (ScalarType.Uri, ScalarType.String) => LambdaFactory.CreateFunc((Uri _) => _.ToString()), - - (ScalarType.Int32, ScalarType.Index) => LambdaFactory.CreateFunc((int _) => new Index(_, false)), - (ScalarType.UInt32, ScalarType.Index) => LambdaFactory.CreateFunc((uint _) => new Index((int)_, false)), - - (ScalarType.Int32, ScalarType.DateOnly) => LambdaFactory.CreateFunc((int _) => DateOnly.FromDayNumber(_)), - (ScalarType.UInt32, ScalarType.DateOnly) => LambdaFactory.CreateFunc((uint _) => DateOnly.FromDayNumber((int)_)), - (ScalarType.Int64, ScalarType.DateOnly) => LambdaFactory.CreateFunc((long _) => DateOnly.FromDayNumber((int)_)), - (ScalarType.UInt64, ScalarType.DateOnly) => LambdaFactory.CreateFunc((ulong _) => DateOnly.FromDayNumber((int)_)), - - (ScalarType.Int64, ScalarType.DateTime) => LambdaFactory.CreateFunc((long _) => new DateTime(_)), - (ScalarType.UInt64, ScalarType.DateTime) => LambdaFactory.CreateFunc((ulong _) => new DateTime((long)_)), - - (ScalarType.DateOnly, ScalarType.DateTime) => LambdaFactory.CreateFunc((DateOnly _) => _.ToDateTime(TimeOnly.MinValue)), - (ScalarType.DateOnly, ScalarType.DateTimeOffset) => LambdaFactory.CreateFunc((DateOnly _) => _.ToDateTime(TimeOnly.MinValue).ToDateTimeOffset()), - (ScalarType.DateOnly, ScalarType.TimeSpan) => LambdaFactory.CreateFunc((DateOnly _) => TimeSpan.FromDays(_.DayNumber)), - (ScalarType.DateOnly, ScalarType.Int32) => LambdaFactory.CreateFunc((DateOnly _) => _.DayNumber), - (ScalarType.DateOnly, ScalarType.UInt32) => LambdaFactory.CreateFunc((DateOnly _) => (uint)_.DayNumber), - (ScalarType.DateOnly, ScalarType.Int64) => LambdaFactory.CreateFunc((DateOnly _) => (long)_.DayNumber), - (ScalarType.DateOnly, ScalarType.UInt64) => LambdaFactory.CreateFunc((DateOnly _) => (ulong)_.DayNumber), - - (ScalarType.DateTime, ScalarType.DateOnly) => LambdaFactory.CreateFunc((DateTime _) => _.ToDateOnly()), - (ScalarType.DateTime, ScalarType.DateTimeOffset) => LambdaFactory.CreateFunc((DateTime _) => _.ToDateTimeOffset()), - (ScalarType.DateTime, ScalarType.TimeOnly) => LambdaFactory.CreateFunc((DateTime _) => _.ToTimeOnly()), - (ScalarType.DateTime, ScalarType.Int64) => LambdaFactory.CreateFunc((DateTime _) => _.Ticks), - (ScalarType.DateTime, ScalarType.UInt64) => LambdaFactory.CreateFunc((DateTime _) => (ulong)_.Ticks), - - (ScalarType.DateTimeOffset, ScalarType.DateOnly) => LambdaFactory.CreateFunc((DateTimeOffset _) => _.ToDateOnly()), - (ScalarType.DateTimeOffset, ScalarType.DateTime) => LambdaFactory.CreateFunc((DateTimeOffset _) => _.LocalDateTime), - (ScalarType.DateTimeOffset, ScalarType.TimeOnly) => LambdaFactory.CreateFunc((DateTimeOffset _) => _.ToTimeOnly()), - (ScalarType.DateTimeOffset, ScalarType.Int64) => LambdaFactory.CreateFunc((DateTimeOffset _) => _.Ticks), - (ScalarType.DateTimeOffset, ScalarType.UInt64) => LambdaFactory.CreateFunc((DateTimeOffset _) => (ulong)_.Ticks), - - (ScalarType.TimeOnly, ScalarType.TimeSpan) => LambdaFactory.CreateFunc((TimeOnly _) => _.ToTimeSpan()), - (ScalarType.TimeOnly, ScalarType.Int64) => LambdaFactory.CreateFunc((TimeOnly _) => _.Ticks), - (ScalarType.TimeOnly, ScalarType.UInt64) => LambdaFactory.CreateFunc((TimeOnly _) => (ulong)_.Ticks), - - (ScalarType.TimeSpan, ScalarType.TimeOnly) => LambdaFactory.CreateFunc((TimeSpan _) => TimeOnly.FromTimeSpan(_)), - (ScalarType.TimeSpan, ScalarType.Int64) => LambdaFactory.CreateFunc((TimeSpan _) => _.Ticks), - (ScalarType.TimeSpan, ScalarType.UInt64) => LambdaFactory.CreateFunc((TimeSpan _) => (ulong)_.Ticks), - - (ScalarType.String, ScalarType.Char) => LambdaFactory.CreateFunc((string _) => Convert.ToChar(_)), - (ScalarType.String, ScalarType.Enum) => LambdaFactory.CreateFunc((string _) => Enum.Parse(targetType, _, true)), - (ScalarType.String, ScalarType.Guid) => LambdaFactory.CreateFunc((string _) => Guid.Parse(_)), - (ScalarType.String, ScalarType.Index) => LambdaFactory.CreateFunc((string _) => Index.FromStart(int.Parse(_))), - (ScalarType.String, ScalarType.Uri) => LambdaFactory.CreateFunc((string _) => new Uri(_)), - (ScalarType.String, ScalarType.Boolean) => LambdaFactory.CreateFunc((string _) => bool.Parse(_)), - (ScalarType.String, ScalarType.SByte) => LambdaFactory.CreateFunc((string _) => sbyte.Parse(_)), - (ScalarType.String, ScalarType.Int16) => LambdaFactory.CreateFunc((string _) => short.Parse(_)), - (ScalarType.String, ScalarType.Int32) => LambdaFactory.CreateFunc((string _) => int.Parse(_)), - (ScalarType.String, ScalarType.Int64) => LambdaFactory.CreateFunc((string _) => long.Parse(_)), - (ScalarType.String, ScalarType.Int128) => LambdaFactory.CreateFunc((string _) => Int128.Parse(_)), - (ScalarType.String, ScalarType.BigInteger) => LambdaFactory.CreateFunc((string _) => BigInteger.Parse(_)), - (ScalarType.String, ScalarType.Byte) => LambdaFactory.CreateFunc((string _) => byte.Parse(_)), - (ScalarType.String, ScalarType.UInt16) => LambdaFactory.CreateFunc((string _) => ushort.Parse(_)), - (ScalarType.String, ScalarType.UInt32) => LambdaFactory.CreateFunc((string _) => uint.Parse(_)), - (ScalarType.String, ScalarType.UInt64) => LambdaFactory.CreateFunc((string _) => ulong.Parse(_)), - (ScalarType.String, ScalarType.UInt128) => LambdaFactory.CreateFunc((string _) => UInt128.Parse(_)), - (ScalarType.String, ScalarType.IntPtr) => LambdaFactory.CreateFunc((string _) => nint.Parse(_)), - (ScalarType.String, ScalarType.UIntPtr) => LambdaFactory.CreateFunc((string _) => nuint.Parse(_)), - (ScalarType.String, ScalarType.Half) => LambdaFactory.CreateFunc((string _) => Half.Parse(_)), - (ScalarType.String, ScalarType.Single) => LambdaFactory.CreateFunc((string _) => float.Parse(_)), - (ScalarType.String, ScalarType.Double) => LambdaFactory.CreateFunc((string _) => double.Parse(_)), - (ScalarType.String, ScalarType.Decimal) => LambdaFactory.CreateFunc((string _) => decimal.Parse(_)), - (ScalarType.String, ScalarType.DateOnly) => LambdaFactory.CreateFunc((string _) => DateOnly.Parse(_)), - (ScalarType.String, ScalarType.DateTime) => LambdaFactory.CreateFunc((string _) => DateTime.Parse(_)), - (ScalarType.String, ScalarType.DateTimeOffset) => LambdaFactory.CreateFunc((string _) => DateTimeOffset.Parse(_)), - (ScalarType.String, ScalarType.TimeOnly) => LambdaFactory.CreateFunc((string _) => TimeOnly.Parse(_)), - (ScalarType.String, ScalarType.TimeSpan) => LambdaFactory.CreateFunc((string _) => TimeSpan.Parse(_)), + (ScalarType.Boolean, ScalarType.Char) => LambdaFactory.CreateFunc(_ => _ ? '1' : '0'), + (ScalarType.Boolean, ScalarType.SByte) => LambdaFactory.CreateFunc(_ => _ ? (sbyte)1 : (sbyte)0), + (ScalarType.Boolean, ScalarType.Int16) => LambdaFactory.CreateFunc(_ => _ ? (short)1 : (short)0), + (ScalarType.Boolean, ScalarType.Int32) => LambdaFactory.CreateFunc(_ => _ ? 1 : 0), + (ScalarType.Boolean, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => _ ? 1L : 0L), + (ScalarType.Boolean, ScalarType.Int128) => LambdaFactory.CreateFunc(_ => _ ? Int128.One : Int128.Zero), + (ScalarType.Boolean, ScalarType.BigInteger) => LambdaFactory.CreateFunc(_ => _ ? BigInteger.One : BigInteger.Zero), + (ScalarType.Boolean, ScalarType.Byte) => LambdaFactory.CreateFunc(_ => _ ? (byte)1 : (byte)0), + (ScalarType.Boolean, ScalarType.UInt16) => LambdaFactory.CreateFunc(_ => _ ? (ushort)1 : (ushort)0), + (ScalarType.Boolean, ScalarType.UInt32) => LambdaFactory.CreateFunc(_ => _ ? 1U : 0U), + (ScalarType.Boolean, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => _ ? 1UL : 0UL), + (ScalarType.Boolean, ScalarType.UInt128) => LambdaFactory.CreateFunc(_ => _ ? UInt128.One : UInt128.Zero), + + (ScalarType.Char, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => TRUE_CHARS.Contains(_)), + (ScalarType.SByte, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Int16, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Int32, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Int64, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Int128, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.BigInteger, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Byte, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.UInt16, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.UInt32, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.UInt64, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.UInt128, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.IntPtr, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.UIntPtr, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Half, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Single, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Double, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.Decimal, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => !_.IsZero()), + (ScalarType.DateOnly, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => _ != DateOnly.MinValue), + (ScalarType.DateTime, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => _ != DateTime.MinValue), + (ScalarType.DateTimeOffset, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => _ != DateTimeOffset.MinValue), + (ScalarType.TimeOnly, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => _ != TimeOnly.MinValue), + (ScalarType.TimeSpan, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => _ != TimeSpan.Zero), + + (ScalarType.Char, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.SByte, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Int16, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Int32, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Int64, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Int128, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.BigInteger, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Byte, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.UInt16, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.UInt32, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.UInt64, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.UInt128, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.IntPtr, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.UIntPtr, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Half, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Single, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Double, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.Decimal, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + (ScalarType.DateOnly, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToISO8601(null)), + (ScalarType.DateTime, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToISO8601(null)), + (ScalarType.DateTimeOffset, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToISO8601(null)), + (ScalarType.Enum, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.Name()), + (ScalarType.TimeOnly, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToISO8601(null)), + (ScalarType.TimeSpan, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToText(null)), + (ScalarType.Guid, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString("D")), + (ScalarType.Index, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.Value.ToString()), + (ScalarType.Uri, ScalarType.String) => LambdaFactory.CreateFunc(_ => _.ToString()), + + (ScalarType.Int32, ScalarType.Index) => LambdaFactory.CreateFunc(_ => new Index(_, false)), + (ScalarType.Int32, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => DateOnly.FromDayNumber(_)), + + (ScalarType.UInt32, ScalarType.Index) => LambdaFactory.CreateFunc(_ => new Index((int)_, false)), + (ScalarType.UInt32, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => DateOnly.FromDayNumber((int)_)), + + (ScalarType.Int64, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => DateOnly.FromDayNumber((int)_)), + (ScalarType.Int64, ScalarType.DateTime) => LambdaFactory.CreateFunc(_ => new DateTime(_)), + + (ScalarType.UInt64, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => DateOnly.FromDayNumber((int)_)), + (ScalarType.UInt64, ScalarType.DateTime) => LambdaFactory.CreateFunc(_ => new DateTime((long)_)), + + (ScalarType.DateOnly, ScalarType.DateTime) => LambdaFactory.CreateFunc(_ => _.ToDateTime(TimeOnly.MinValue)), + (ScalarType.DateOnly, ScalarType.DateTimeOffset) => LambdaFactory.CreateFunc(_ => _.ToDateTime(TimeOnly.MinValue).ToDateTimeOffset()), + (ScalarType.DateOnly, ScalarType.TimeSpan) => LambdaFactory.CreateFunc(_ => TimeSpan.FromDays(_.DayNumber)), + (ScalarType.DateOnly, ScalarType.Int32) => LambdaFactory.CreateFunc(_ => _.DayNumber), + (ScalarType.DateOnly, ScalarType.UInt32) => LambdaFactory.CreateFunc(_ => (uint)_.DayNumber), + (ScalarType.DateOnly, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => (long)_.DayNumber), + (ScalarType.DateOnly, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => (ulong)_.DayNumber), + + (ScalarType.DateTime, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => _.ToDateOnly()), + (ScalarType.DateTime, ScalarType.DateTimeOffset) => LambdaFactory.CreateFunc(_ => _.ToDateTimeOffset()), + (ScalarType.DateTime, ScalarType.TimeOnly) => LambdaFactory.CreateFunc(_ => _.ToTimeOnly()), + (ScalarType.DateTime, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => _.Ticks), + (ScalarType.DateTime, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => (ulong)_.Ticks), + + (ScalarType.DateTimeOffset, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => _.ToDateOnly()), + (ScalarType.DateTimeOffset, ScalarType.DateTime) => LambdaFactory.CreateFunc(_ => _.LocalDateTime), + (ScalarType.DateTimeOffset, ScalarType.TimeOnly) => LambdaFactory.CreateFunc(_ => _.ToTimeOnly()), + (ScalarType.DateTimeOffset, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => _.Ticks), + (ScalarType.DateTimeOffset, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => (ulong)_.Ticks), + + (ScalarType.TimeOnly, ScalarType.TimeSpan) => LambdaFactory.CreateFunc(_ => _.ToTimeSpan()), + (ScalarType.TimeOnly, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => _.Ticks), + (ScalarType.TimeOnly, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => (ulong)_.Ticks), + + (ScalarType.TimeSpan, ScalarType.TimeOnly) => LambdaFactory.CreateFunc(_ => TimeOnly.FromTimeSpan(_)), + (ScalarType.TimeSpan, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => _.Ticks), + (ScalarType.TimeSpan, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => (ulong)_.Ticks), + + (ScalarType.String, ScalarType.Char) => LambdaFactory.CreateFunc(_ => Convert.ToChar(_)), + (ScalarType.String, ScalarType.Enum) => LambdaFactory.CreateEnumParseFunc(targetType), + (ScalarType.String, ScalarType.Guid) => LambdaFactory.CreateFunc(_ => Guid.Parse(_)), + (ScalarType.String, ScalarType.Index) => LambdaFactory.CreateFunc(_ => Index.FromStart(int.Parse(_))), + (ScalarType.String, ScalarType.Uri) => LambdaFactory.CreateFunc(_ => new Uri(_)), + (ScalarType.String, ScalarType.Boolean) => LambdaFactory.CreateFunc(_ => bool.Parse(_)), + (ScalarType.String, ScalarType.SByte) => LambdaFactory.CreateFunc(_ => sbyte.Parse(_)), + (ScalarType.String, ScalarType.Int16) => LambdaFactory.CreateFunc(_ => short.Parse(_)), + (ScalarType.String, ScalarType.Int32) => LambdaFactory.CreateFunc(_ => int.Parse(_)), + (ScalarType.String, ScalarType.Int64) => LambdaFactory.CreateFunc(_ => long.Parse(_)), + (ScalarType.String, ScalarType.Int128) => LambdaFactory.CreateFunc(_ => Int128.Parse(_)), + (ScalarType.String, ScalarType.BigInteger) => LambdaFactory.CreateFunc(_ => BigInteger.Parse(_)), + (ScalarType.String, ScalarType.Byte) => LambdaFactory.CreateFunc(_ => byte.Parse(_)), + (ScalarType.String, ScalarType.UInt16) => LambdaFactory.CreateFunc(_ => ushort.Parse(_)), + (ScalarType.String, ScalarType.UInt32) => LambdaFactory.CreateFunc(_ => uint.Parse(_)), + (ScalarType.String, ScalarType.UInt64) => LambdaFactory.CreateFunc(_ => ulong.Parse(_)), + (ScalarType.String, ScalarType.UInt128) => LambdaFactory.CreateFunc(_ => UInt128.Parse(_)), + (ScalarType.String, ScalarType.IntPtr) => LambdaFactory.CreateFunc(_ => nint.Parse(_)), + (ScalarType.String, ScalarType.UIntPtr) => LambdaFactory.CreateFunc(_ => nuint.Parse(_)), + (ScalarType.String, ScalarType.Half) => LambdaFactory.CreateFunc(_ => Half.Parse(_)), + (ScalarType.String, ScalarType.Single) => LambdaFactory.CreateFunc(_ => float.Parse(_)), + (ScalarType.String, ScalarType.Double) => LambdaFactory.CreateFunc(_ => double.Parse(_)), + (ScalarType.String, ScalarType.Decimal) => LambdaFactory.CreateFunc(_ => decimal.Parse(_)), + (ScalarType.String, ScalarType.DateOnly) => LambdaFactory.CreateFunc(_ => DateOnly.Parse(_)), + (ScalarType.String, ScalarType.DateTime) => LambdaFactory.CreateFunc(_ => DateTime.Parse(_)), + (ScalarType.String, ScalarType.DateTimeOffset) => LambdaFactory.CreateFunc(_ => DateTimeOffset.Parse(_)), + (ScalarType.String, ScalarType.TimeOnly) => LambdaFactory.CreateFunc(_ => TimeOnly.Parse(_)), + (ScalarType.String, ScalarType.TimeSpan) => LambdaFactory.CreateFunc(_ => TimeSpan.Parse(_)), _ => null }; @@ -182,12 +178,12 @@ public static Expression CreateConversionExpression(this Expression @this, Type char x when TRUE_CHARS.Contains(x) => true, string text when text.IsNotBlank() => text.Parse(), null or string => null, - Int128 x => x != Int128.Zero, - BigInteger x => x != BigInteger.Zero, - UInt128 x => x != UInt128.Zero, - IntPtr x => x != IntPtr.Zero, - UIntPtr x => x != UIntPtr.Zero, - Half x => x != Half.Zero, + Int128 x => !x.IsZero(), + BigInteger x => !x.IsZero(), + UInt128 x => !x.IsZero(), + IntPtr x => !x.IsZero(), + UIntPtr x => !x.IsZero(), + Half x => !x.IsZero(), DateOnly x => x != DateOnly.MinValue, DateTime x => x != DateTime.MinValue, DateTimeOffset x => x != DateTimeOffset.MinValue, @@ -262,14 +258,18 @@ string text when text.IsNotBlank() => Guid.Parse(text), Index x => x, string text when text.IsNotBlank() => new Index(text.Parse()), null or string => null, - sbyte x => new Index(x), - short x => new Index(x), - int x => new Index(x), - long x => new Index(checked((int)x)), - byte x => new Index(x), - ushort x => new Index(x), - uint x => new Index(checked((int)x)), - ulong x => new Index(checked((int)x)), + int number => new Index(number), + sbyte number => new Index(int.CreateChecked(number)), + short number => new Index(int.CreateChecked(number)), + long number => new Index(int.CreateChecked(number)), + Int128 number => new Index(int.CreateChecked(number)), + BigInteger number => new Index(int.CreateChecked(number)), + nint number => new Index(int.CreateChecked(number)), + ushort number => new Index(int.CreateChecked(number)), + uint number => new Index(int.CreateChecked(number)), + ulong number => new Index(int.CreateChecked(number)), + UInt128 number => new Index(int.CreateChecked(number)), + nuint number => new Index(int.CreateChecked(number)), _ => (Index)value }; @@ -286,7 +286,19 @@ string text when text.IsNotBlank() => IntPtr.Parse(text), where T : struct, INumberBase => @this switch { - T value => value, + T value => (T?)value, + sbyte number => T.CreateChecked(number), + short number => T.CreateChecked(number), + int number => T.CreateChecked(number), + long number => T.CreateChecked(number), + Int128 number => T.CreateChecked(number), + BigInteger number => T.CreateChecked(number), + nint number => T.CreateChecked(number), + ushort number => T.CreateChecked(number), + uint number => T.CreateChecked(number), + ulong number => T.CreateChecked(number), + UInt128 number => T.CreateChecked(number), + nuint number => T.CreateChecked(number), string text when text.IsNotBlank() => T.Parse(text, InvariantCulture), null or string => null, true => T.One, diff --git a/tests/TypeCache.GraphQL.TestApp/TypeCache.GraphQL.TestApp.csproj b/tests/TypeCache.GraphQL.TestApp/TypeCache.GraphQL.TestApp.csproj index a8088e42..bdb172eb 100644 --- a/tests/TypeCache.GraphQL.TestApp/TypeCache.GraphQL.TestApp.csproj +++ b/tests/TypeCache.GraphQL.TestApp/TypeCache.GraphQL.TestApp.csproj @@ -8,7 +8,7 @@ - + diff --git a/tests/TypeCache.Tests/Extensions/ArrayExtensions.cs b/tests/TypeCache.Tests/Extensions/ArrayExtensions.cs index feaddcd0..73fbc665 100644 --- a/tests/TypeCache.Tests/Extensions/ArrayExtensions.cs +++ b/tests/TypeCache.Tests/Extensions/ArrayExtensions.cs @@ -7,8 +7,8 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using TypeCache.Collections; using TypeCache.Extensions; +using TypeCache.Utilities; using Xunit; using static System.FormattableString; diff --git a/tests/TypeCache.Tests/Extensions/AssertExtensions.cs b/tests/TypeCache.Tests/Extensions/AssertExtensions.cs deleted file mode 100644 index 2491c298..00000000 --- a/tests/TypeCache.Tests/Extensions/AssertExtensions.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2021 Samuel Abraham - -using System; -using TypeCache.Collections; -using TypeCache.Extensions; -using Xunit; - -namespace TypeCache.Tests.Extensions; - -public class AssertExtensions -{ - [Fact] - public void AssertEquals() - { - 123456.AssertEquals(123456); - "AAA".AssertEquals("AAA"); - (null as string).AssertEquals(null); - "AAA".AssertEquals("AAA", StringComparer.Ordinal); - "AAA".AssertEquals("aaa", StringComparison.OrdinalIgnoreCase); - Xunit.Assert.Throws(() => 123.AssertEquals(456)); - Xunit.Assert.Throws(() => "AAA".AssertEquals("bbb")); - Xunit.Assert.Throws(() => (null as string).AssertEquals("bbb")); - Xunit.Assert.Throws(() => "AAA".AssertEquals("bbb", StringComparer.Ordinal)); - Xunit.Assert.Throws(() => "AAA".AssertEquals(null, null)); - } - - [Fact] - public void AssertFalse() - { - false.AssertFalse(); - Xunit.Assert.Throws(() => true.AssertFalse()); - } - - [Fact] - public void AssertNotBlank() - { - "AAA".AssertNotBlank(); - Xunit.Assert.Throws(() => (null as string).AssertNotBlank()); - Xunit.Assert.Throws(() => string.Empty.AssertNotBlank()); - Xunit.Assert.Throws(() => " ".AssertNotBlank()); - } - - [Fact] - public void AssertNotEmpty() - { - "AAA".AssertNotEmpty(); - Xunit.Assert.Throws(() => (null as string).AssertNotEmpty()); - Xunit.Assert.Throws(() => string.Empty.AssertNotEmpty()); - Xunit.Assert.Throws(() => Array.Empty.AssertNotEmpty()); - } - - [Fact] - public void AssertNotEquals() - { - 123456.AssertNotEquals(12345); - "AAA".AssertNotEquals("AA"); - (null as string).AssertNotEquals(string.Empty); - "AAA".AssertNotEquals("BBB", StringComparer.Ordinal); - "AAA".AssertNotEquals("bbb", StringComparison.OrdinalIgnoreCase); - Xunit.Assert.Throws(() => 123.AssertNotEquals(123)); - Xunit.Assert.Throws(() => "bbb".AssertNotEquals("bbb")); - Xunit.Assert.Throws(() => (null as string).AssertNotEquals(null as string)); - Xunit.Assert.Throws(() => "AAA".AssertNotEquals("AAA", StringComparer.Ordinal)); - Xunit.Assert.Throws(() => "AAA".AssertNotEquals("AAA", null)); - } - - [Fact] - public void AssertNotNull() - { - ((int?)123456).AssertNotNull(); - "AAA".AssertNotNull(); - Xunit.Assert.Throws(() => (null as string).AssertNotNull()); - Xunit.Assert.Throws(() => (null as int?).AssertNotNull()); - } - - [Fact] - public void AssertNotSame() - { - var a = new object(); - var b = new object(); - - (a, b).AssertNotSame(); - Xunit.Assert.Throws(() => (a, a).AssertNotSame()); - } - - [Fact] - public void AssertTrue() - { - true.AssertTrue(); - Xunit.Assert.Throws(() => false.AssertTrue()); - } -} diff --git a/tests/TypeCache.Tests/Extensions/ReflectionExtensions.cs b/tests/TypeCache.Tests/Extensions/ReflectionExtensions.cs index 0fa36f4a..cddfc078 100644 --- a/tests/TypeCache.Tests/Extensions/ReflectionExtensions.cs +++ b/tests/TypeCache.Tests/Extensions/ReflectionExtensions.cs @@ -38,6 +38,14 @@ public long WriteOutput(int i, string text1, string text2, string text3, TimeOnl } } + [Fact] + public void Create() + { + Assert.NotNull(typeof(Contact).Create()); + Assert.NotNull(typeof(object).Create()); + Assert.NotNull(typeof(IndexOutOfRangeException).Create()); + } + [Fact] public void FieldInfo_GetValueFunc() { @@ -383,14 +391,14 @@ public void PropertyInfo_SetValueAction() stopwatch.Restart(); while (++i < 100000) { - setID(null, Guid.NewGuid()); - setFirstName(contact, null, "FirstName"); - setMiddleName(contact, null, "MiddleName"); - setLastName(contact, null, "LastName"); - setAge(contact, null, 31); - setEmail(contact, null, "Email"); - setPhone(contact, null, "Phone"); - setDeleted(contact, null, !contact.Deleted); + setID(ValueTuple.Create(Guid.NewGuid())); + setFirstName(contact, ValueTuple.Create("FirstName")); + setMiddleName(contact, ValueTuple.Create("MiddleName")); + setLastName(contact, ValueTuple.Create("LastName")); + setAge(contact, ValueTuple.Create(31)); + setEmail(contact, ValueTuple.Create("Email")); + setPhone(contact, ValueTuple.Create("Phone")); + setDeleted(contact, ValueTuple.Create(!contact.Deleted)); } stopwatch.Stop(); var elapsedSetPropertyValue = stopwatch.Elapsed; diff --git a/tests/TypeCache.Tests/Extensions/ThrowIfExtensions.cs b/tests/TypeCache.Tests/Extensions/ThrowIfExtensions.cs new file mode 100644 index 00000000..f642460a --- /dev/null +++ b/tests/TypeCache.Tests/Extensions/ThrowIfExtensions.cs @@ -0,0 +1,107 @@ +// Copyright (c) 2021 Samuel Abraham + +using System; +using TypeCache.Extensions; +using TypeCache.Utilities; +using Xunit; + +namespace TypeCache.Tests.Extensions; + +public class ThrowIfExtensions +{ + [Fact] + public void ThrowIfNotEqual() + { + 123456.ThrowIfNotEqual(123456); + "AAA".ThrowIfNotEqual("AAA"); + (null as string).ThrowIfNotEqual(null); + "AAA".ThrowIfNotEqual("AAA", StringComparer.Ordinal); + Assert.Throws(() => 123.ThrowIfNotEqual(456)); + Assert.Throws(() => "AAA".ThrowIfNotEqual("bbb")); + Assert.Throws(() => (null as string).ThrowIfNotEqual("bbb")); + Assert.Throws(() => "AAA".ThrowIfNotEqual("bbb", StringComparer.Ordinal)); + Assert.Throws(() => "AAA".ThrowIfNotEqual(null, null)); + } + + [Fact] + public void ThrowIfNotEqualIgnoreCase() + { + "AAA".ThrowIfNotEqualIgnoreCase("aaa"); + "AAA".ThrowIfNotEqualIgnoreCase("AAA"); + Assert.Throws(() => "AAA".ThrowIfNotEqualIgnoreCase("bbb")); + } + + [Fact] + public void ThrowIfTrue() + { + false.ThrowIfTrue(); + Assert.Throws(() => true.ThrowIfTrue()); + } + + [Fact] + public void ThrowIfBlank() + { + "AAA".ThrowIfBlank(); + Assert.Throws(() => (null as string).ThrowIfBlank()); + Assert.Throws(() => string.Empty.ThrowIfBlank()); + Assert.Throws(() => " ".ThrowIfBlank()); + } + + [Fact] + public void ThrowIfEmpty() + { + "AAA".ThrowIfEmpty(); + Assert.Throws(() => (null as string).ThrowIfEmpty()); + Assert.Throws(() => string.Empty.ThrowIfEmpty()); + Assert.Throws(() => Array.Empty.ThrowIfEmpty()); + } + + [Fact] + public void ThrowIfEqual() + { + 123456.ThrowIfEqual(12345); + "AAA".ThrowIfEqual("AA"); + (null as string).ThrowIfEqual(string.Empty); + "AAA".ThrowIfEqual("BBB", StringComparer.Ordinal); + Assert.Throws(() => 123.ThrowIfEqual(123)); + Assert.Throws(() => "bbb".ThrowIfEqual("bbb")); + Assert.Throws(() => (null as string).ThrowIfEqual(null as string)); + Assert.Throws(() => "AAA".ThrowIfEqual("AAA", StringComparer.Ordinal)); + Assert.Throws(() => "AAA".ThrowIfEqual("AAA", null)); + } + + [Fact] + public void ThrowIfEqualIgnoreCase() + { + "AAA".ThrowIfEqualIgnoreCase("bbb"); + "AAA".ThrowIfEqualIgnoreCase("aba"); + Assert.Throws(() => "AAA".ThrowIfEqualIgnoreCase("aaa")); + Assert.Throws(() => "ABA".ThrowIfEqualIgnoreCase("aba")); + } + + [Fact] + public void ThrowIfNull() + { + ((int?)123456).ThrowIfNull(); + "AAA".ThrowIfNull(); + Assert.Throws(() => (null as string).ThrowIfNull()); + Assert.Throws(() => (null as int?).ThrowIfNull()); + } + + [Fact] + public void ThrowIfSame() + { + var a = new object(); + var b = new object(); + + (a, b).ThrowIfSame(); + Assert.Throws(() => (a, a).ThrowIfSame()); + } + + [Fact] + public void ThrowIfFalse() + { + true.ThrowIfFalse(); + Assert.Throws(() => false.ThrowIfFalse()); + } +} diff --git a/tests/TypeCache.Tests/Extensions/ValueExtensions.cs b/tests/TypeCache.Tests/Extensions/ValueExtensions.cs index 656565f6..25b307de 100644 --- a/tests/TypeCache.Tests/Extensions/ValueExtensions.cs +++ b/tests/TypeCache.Tests/Extensions/ValueExtensions.cs @@ -2,8 +2,8 @@ using System; using System.Linq; -using TypeCache.Collections; using TypeCache.Extensions; +using TypeCache.Utilities; using Xunit; namespace TypeCache.Tests.Extensions; diff --git a/tests/TypeCache.Tests/TypeCache.Tests.csproj b/tests/TypeCache.Tests/TypeCache.Tests.csproj index 79b0b547..9a130abe 100644 --- a/tests/TypeCache.Tests/TypeCache.Tests.csproj +++ b/tests/TypeCache.Tests/TypeCache.Tests.csproj @@ -9,10 +9,10 @@ - + - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all