RSCG – EnumsEnhanced

RSCG – EnumsEnhanced
 
 

name EnumsEnhanced
nuget https://www.nuget.org/packages/EnumsEnhanced/
link https://github.com/snowberry-software/EnumsEnhanced
author VNCC

generating enums fast retrieval

 

This is how you can use EnumsEnhanced .

The code that you start with is


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>

  <ItemGroup>
    <PackageReference Include="EnumsEnhanced" Version="2.0.0">
    </PackageReference>
  </ItemGroup>
	<PropertyGroup>
		<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
	</PropertyGroup>
</Project>


The code that you will use is


// See https://aka.ms/new-console-template for more information
using EnumDemo;

Console.WriteLine("Hello, World!");
Console.WriteLine("Car types:" + CarTypesEnhanced.GetNamesFast().Length);
var cars= CarTypesEnhanced.GetValuesFast();
foreach (var car in cars)
{
    Console.WriteLine( car.ToStringFast());
}



namespace EnumDemo;
public enum CarTypes 
{
    None,
    Dacia ,
    Tesla ,
    BMW ,
    Mercedes ,
}


 

The code that is generated is

#nullable enable

using System.Text;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System;
using System;
using System.Globalization;

namespace EnumDemo
{
///

/// Reflection free extension methods for the type.
///

public static partial class CarTypesEnhanced
{

///

/// Determines whether one or more bit fields are set in the current instance.
///

/// The value of the enum. /// The flag to check. /// if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, false.
#if NETCOREAPP3_0_OR_GREATER
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
#else
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif

public static bool HasFlagFast(this CarTypes e, CarTypes flag)
{
return (e & flag) == flag;
}

///
#if NETCOREAPP3_0_OR_GREATER
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
#else
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif

public static unsafe bool HasFlagFastUnsafe(this CarTypes e, CarTypes flag)
{
return HasFlagFastUnsafe(&e, &flag);
}

///

/// Determines whether one or more bit fields are set in the current instance using unsafe pointer type casting.
///

/// The value of the enum. /// The flag to check. /// if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, false.
#if NETCOREAPP3_0_OR_GREATER
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
#else
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif

public static unsafe bool HasFlagFastUnsafe(CarTypes* e, CarTypes* flag)
{
return (*(int*)e & *(int*)flag) == *(int*)flag;
}

///

/// Retrieves an array of the names of the constants.
///

/// A string array of the names of the constants.
public static string[] GetNamesFast()
{
return new string[] {
“None”, “Dacia”, “Tesla”, “BMW”, “Mercedes”
};
}

///

/// Retrieves an array of the values of the constants.
///

/// An array that contains the values of the constants.
public static CarTypes[] GetValuesFast()
{
return new CarTypes[] {
CarTypes.None, CarTypes.Dacia, CarTypes.Tesla, CarTypes.BMW, CarTypes.Mercedes
};
}

///
public static bool IsDefinedFast(string value)
{
_ = value ?? throw new ArgumentNullException(nameof(value));

switch(value)
{
case “BMW”:
return true;
case “None”:
return true;
case “Dacia”:
return true;
case “Tesla”:
return true;
case “Mercedes”:
return true;

}

return false;
}

///
#if NETCOREAPP3_0_OR_GREATER
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
#else
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif

public static bool IsDefinedFast(Int32 value)
{
return IsDefinedFast((CarTypes)value);
}

///

/// Returns a telling whether its given value exists in the enumeration.
///

/// The value of the enumeration constant. /// if a constant is defined with the given value from the .
public static bool IsDefinedFast(CarTypes value)
{
switch(value)
{
case CarTypes.BMW:
return true;
case CarTypes.None:
return true;
case CarTypes.Dacia:
return true;
case CarTypes.Tesla:
return true;
case CarTypes.Mercedes:
return true;

}

return false;
}

///

/// Resolves the name of the given enum value.
///

/// The value of a particular enumerated constant in terms of its underlying type. /// Determines whether the value has flags, so it will return `EnumValue, EnumValue2`. /// A string containing the name of the enumerated constant or if the enum has multiple flags set but is not enabled.
public static string? GetNameFast(this CarTypes e, bool includeFlagNames = false)
{
switch(e)
{
case CarTypes.None:
return nameof(CarTypes.None);

case CarTypes.Dacia:
return nameof(CarTypes.Dacia);

case CarTypes.Tesla:
return nameof(CarTypes.Tesla);

case CarTypes.BMW:
return nameof(CarTypes.BMW);

case CarTypes.Mercedes:
return nameof(CarTypes.Mercedes);

}

// Returning null is the default behavior.
if(!includeFlagNames)
return null;
//throw new Exception(“Enum name could not be found!”);

var flagBuilder = new StringBuilder();
if(e.HasFlagFast(CarTypes.None))
flagBuilder.Append(CarTypes.None.GetNameFast(false) + “, “);

if(e.HasFlagFast(CarTypes.Dacia))
flagBuilder.Append(CarTypes.Dacia.GetNameFast(false) + “, “);

if(e.HasFlagFast(CarTypes.Tesla))
flagBuilder.Append(CarTypes.Tesla.GetNameFast(false) + “, “);

if(e.HasFlagFast(CarTypes.BMW))
flagBuilder.Append(CarTypes.BMW.GetNameFast(false) + “, “);

if(e.HasFlagFast(CarTypes.Mercedes))
flagBuilder.Append(CarTypes.Mercedes.GetNameFast(false) + “, “);

return flagBuilder.ToString().Trim(new char[] { ‘,’, ‘ ‘ });
}

///

/// Converts the value of this instance to its equivalent string representation.
///

/// The value of a particular enumerated constant in terms of its underlying type. /// The string representation of the value of this instance.
#if NETCOREAPP3_0_OR_GREATER
[MethodImplAttribute(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
#else
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
#endif

public static string? ToStringFast(this CarTypes e)
{
return GetNameFast(e, true);
}

///

/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
///

/// A string containing the name or value to convert. /// to ignore case; false to regard case. /// The result of the enumeration constant. /// if the conversion succeeded; otherwise.
public static bool TryParseFast(string value, bool ignoreCase, out CarTypes result)
{
result = ParseFast(out var successful, value: value, ignoreCase: ignoreCase, throwOnFailure: false);
return successful;
}

///

/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
///

/// A string containing the name or value to convert. /// to ignore case; false to regard case. /// The enumeration value whose value is represented by the given value.
public static CarTypes ParseFast(string value, bool ignoreCase = false)
{
return ParseFast(out _, value: value, ignoreCase: ignoreCase, throwOnFailure: true);
}

///

/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
///

/// if the conversion succeeded; otherwise. /// A string containing the name or value to convert. /// to ignore case; false to regard case. /// Determines whether to throw an on errors or not. /// The enumeration value whose value is represented by the given value.
public static CarTypes ParseFast(out bool successful, string value, bool ignoreCase = false, bool throwOnFailure = true)
{
successful = false;

if (throwOnFailure && (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)))
{
throw new ArgumentException(“Value can’t be null or whitespace!”, nameof(value));
}

Int32 localResult = 0;
bool parsed = false;
string subValue;
string originalValue = value;
char firstChar = value[0];

if (char.IsDigit(firstChar) || firstChar == ‘-‘ || firstChar == ‘+’)
{
if(Int32.TryParse(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, null, out var valueNumber))
switch(valueNumber)
{
case (Int32)CarTypes.BMW:
successful = true;
return CarTypes.BMW;

case (Int32)CarTypes.None:
successful = true;
return CarTypes.None;

case (Int32)CarTypes.Dacia:
successful = true;
return CarTypes.Dacia;

case (Int32)CarTypes.Tesla:
successful = true;
return CarTypes.Tesla;

case (Int32)CarTypes.Mercedes:
successful = true;
return CarTypes.Mercedes;

}
}
else
while(value != null && value.Length > 0)
{
parsed = false;

int endIndex = value.IndexOf(‘,’);

if(endIndex < 0) { // No next separator; use the remainder as the next value. subValue = value.Trim(); value = null!; } else if(endIndex != value!.Length - 1) { // Found a separator before the last char. subValue = value.Substring(0, endIndex).Trim(); value = value.Substring(endIndex + 1); } else { // Last char was a separator, which is invalid. break; } if(!ignoreCase) { switch(subValue) { case nameof(CarTypes.BMW): parsed = true; localResult |= (Int32)CarTypes.BMW; break; case nameof(CarTypes.None): parsed = true; localResult |= (Int32)CarTypes.None; break; case nameof(CarTypes.Dacia): parsed = true; localResult |= (Int32)CarTypes.Dacia; break; case nameof(CarTypes.Tesla): parsed = true; localResult |= (Int32)CarTypes.Tesla; break; case nameof(CarTypes.Mercedes): parsed = true; localResult |= (Int32)CarTypes.Mercedes; break; } } else { if(subValue.Equals("BMW", StringComparison.OrdinalIgnoreCase)) { parsed = true; localResult |= (Int32)CarTypes.BMW; } if(subValue.Equals("None", StringComparison.OrdinalIgnoreCase)) { parsed = true; localResult |= (Int32)CarTypes.None; } if(subValue.Equals("Dacia", StringComparison.OrdinalIgnoreCase)) { parsed = true; localResult |= (Int32)CarTypes.Dacia; } if(subValue.Equals("Tesla", StringComparison.OrdinalIgnoreCase)) { parsed = true; localResult |= (Int32)CarTypes.Tesla; } if(subValue.Equals("Mercedes", StringComparison.OrdinalIgnoreCase)) { parsed = true; localResult |= (Int32)CarTypes.Mercedes; } } if(!parsed) break; } successful = true; if (!parsed) { successful = false; if (throwOnFailure) throw new ArgumentException($"Could not convert the given value `{originalValue}`.", nameof(value)); } return (CarTypes)localResult; } } } #nullable restore [/code] Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/EnumsEnhanced


Posted

in

, ,

by

Tags: