SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
31 changed files with 768360 additions and 0 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,54 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Brutal.Core.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class OperatingSystemAnalyzer : DiagnosticAnalyzer
{
// Keep in mind: you have to list your rules here.
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Resources.BrutalCore0003);
public override void Initialize(AnalysisContext context)
{
// You must call this method to avoid analyzing generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
// You must call this method to enable the Concurrent Execution.
context.EnableConcurrentExecution();
// Subscribe to the Syntax Node with the appropriate 'SyntaxKind' (ClassDeclaration) action.
// To figure out which Syntax Nodes you should choose, consider installing the Roslyn syntax tree viewer plugin Rossynt: https://plugins.jetbrains.com/plugin/16902-rossynt/
context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.InvocationExpression);
}
private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
if (context.Node is not InvocationExpressionSyntax invocation)
return;
var memberAccess = invocation.Expression as MemberAccessExpressionSyntax;
if (memberAccess == null)
return;
var symbolInfo = context.SemanticModel.GetSymbolInfo(memberAccess.Expression);
if (symbolInfo.Symbol == null)
return;
var systemOperatingSystem = context.SemanticModel.Compilation.GetTypeByMetadataName("System.OperatingSystem");
if (!SymbolEqualityComparer.Default.Equals(symbolInfo.Symbol, systemOperatingSystem))
return;
// check if member name is "IsWindows", "IsLinux", "IsMacOS"
if (memberAccess.Name.Identifier.Text is not ("IsWindows" or "IsLinux" or "IsMacOS"))
return;
var diagnostic = Diagnostic.Create(Resources.BrutalCore0003, invocation.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}

View file

@ -0,0 +1,66 @@
using Microsoft.CodeAnalysis;
namespace Brutal.Core.Analyzers;
public static class Resources
{
public static readonly DiagnosticDescriptor BrutalCore0003 = new(
"BRUTALCORE0003",
"Prefer Brutal.Platform instead of System.OperatingSystem",
"Brutal.Platform provides a simpler API to check the current platform",
"Obsolete",
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "Use Brutal.Platform instead of System.OperatingSystem."
);
public const string BrutalCore0003Suggestion = "Use Brutal.Platform";
// From framework analyser BRUTAL4003 var fixes
public static readonly DiagnosticDescriptor VarBrutalCore0007 = new(
"BRUTALCORE0007",
"Prefer var over explicit type",
"Use var for terseness and ease of refactoring",
"Usage",
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "Use var instead of explicit types."
);
// From framework analyser BRUTAL4003 var fixes for default initialisation
public static readonly DiagnosticDescriptor VarDefaultBrutalCore0008 = new(
"BRUTALCORE0008",
"Prefer var default literal over explicit with default",
"Use var with default(type) for terseness and consistency",
"Usage",
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: "Use var instead of explicit types."
);
public static readonly DiagnosticDescriptor ExpectsFixedBrutalCore0009 = new(
"BRUTALCORE0009",
"This should be a fixed value",
"Potential unsafe call to {0}. Ensure the argument for '{1}' comes from a fixed source.",
"Usage",
DiagnosticSeverity.Error,
isEnabledByDefault: true
);
public static readonly DiagnosticDescriptor ExpectsFixedBrutalCore0010 = new(
"BRUTALCORE0010",
"This should be a fixed value",
"Potential unsafe implicit conversion from {0} to {1}. Ensure cast comes from a fixed source.",
"Usage",
DiagnosticSeverity.Error,
isEnabledByDefault: true
);
public static readonly DiagnosticDescriptor LosesFixedBrutalCore0012 = new(
"BRUTALCORE0012",
"Delegate conversion loses [Fixed]",
"Converting {0} to '{1}' erases the [Fixed] requirement on parameter '{2}'. Calls through the delegate are not checked; use a delegate type that marks the parameter [Fixed].",
"Usage",
DiagnosticSeverity.Warning,
isEnabledByDefault: true
);
}

View file

@ -0,0 +1,180 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Brutal.Core.Analyzers;
/// <summary>
/// Analyzer that flags explicit type declarations that can be replaced with 'var'.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class VarAnalyzer : DiagnosticAnalyzer
{
// Keep in mind: you have to list your rules here.
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Resources.VarBrutalCore0007, Resources.VarDefaultBrutalCore0008);
public override void Initialize(AnalysisContext context)
{
// You must call this method to avoid analyzing generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
// You must call this method to enable the Concurrent Execution.
context.EnableConcurrentExecution();
// Analyze variable declarations like `float x = 1f` or `MyType obj = new()`
context.RegisterSyntaxNodeAction(AnalyzeVariableDeclaration, SyntaxKind.VariableDeclaration);
// Check other 'context.Register...' methods that might be helpful for your purposes.
}
/// <summary>
/// Analyzes explicit variable declarations to suggest 'var' where applicable.
/// </summary>
/// <param name="context">Operation context.</param>
private void AnalyzeVariableDeclaration(SyntaxNodeAnalysisContext context)
{
var variableDeclaration = (VariableDeclarationSyntax)context.Node;
if (
variableDeclaration.Type.IsVar
|| variableDeclaration.Parent is not LocalDeclarationStatementSyntax localDecl
|| IsConst(localDecl)
)
return;
foreach (var variable in variableDeclaration.Variables)
{
if (variable.Initializer == null)
continue;
var declaredType = context.SemanticModel.GetTypeInfo(variableDeclaration.Type).Type;
var initializerType = context.SemanticModel.GetTypeInfo(variable.Initializer.Value).Type;
if (declaredType == null || initializerType == null)
continue;
// SomeType me = default -> var me default(SomeType);
if (variable.Initializer.Value.IsKind(SyntaxKind.DefaultLiteralExpression))
{
ReportVarDefaultDiagnostic(context, variableDeclaration);
continue;
}
if (!WouldVarDeclarationProduceSameType(variable, context.SemanticModel))
continue;
// Report diagnostic on the explicit type
context.ReportDiagnostic(
Diagnostic.Create(
Resources.VarBrutalCore0007,
variableDeclaration.Type.GetLocation(),
declaredType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
)
);
}
}
private static void ReportVarDefaultDiagnostic(
SyntaxNodeAnalysisContext context,
VariableDeclarationSyntax variableDeclaration
)
{
context.ReportDiagnostic(
Diagnostic.Create(
Resources.VarDefaultBrutalCore0008,
variableDeclaration.Type.GetLocation(),
variableDeclaration.Type.ToString()
)
);
}
/// <summary>
/// This function returns whether, if the variable declaration was made into a 'var' declaration,
/// that the same final type would be the same as what it originally was. e.g.
///
/// Given:
/// Span &lt;byte&gt; data = stackalloc byte[1024];
/// If we test
/// var data = stackalloc byte[1024];
///
/// Is the resulting type of the symbol 'data' the same in both cases.
/// </summary>
/// <param name="declarator"></param>
/// <param name="semanticModel"></param>
/// <param name="ct"></param>
/// <returns></returns>
public static bool WouldVarDeclarationProduceSameType(
VariableDeclaratorSyntax declarator,
SemanticModel semanticModel,
CancellationToken ct = default
)
{
// Must have an initializer to use 'var'
if (declarator.Initializer is null)
return false;
var declaration = (VariableDeclarationSyntax)declarator.Parent!;
var originalLocal = (ILocalSymbol?)semanticModel.GetDeclaredSymbol(declarator, ct);
if (originalLocal is null)
return false;
if (declaration.Parent is not LocalDeclarationStatementSyntax localStmt)
return false;
var synthesisedVarDeclaration = SynthesisedVarDeclaration(declarator, declaration);
if (!TryGetSynthesisedSymbol(semanticModel, localStmt, synthesisedVarDeclaration, out var specLocal, ct))
return false;
return specLocal?.Type is not null
&& specLocal.Type.Kind != SymbolKind.ErrorType
&& SymbolEqualityComparer.Default.Equals(originalLocal.Type, specLocal.Type);
}
private static bool TryGetSynthesisedSymbol(
SemanticModel semanticModel,
LocalDeclarationStatementSyntax localStmt,
VariableDeclarationSyntax synthesisedVarDeclaration,
out ILocalSymbol? specLocal,
CancellationToken ct
)
{
var newLocalStmt = localStmt.WithDeclaration(synthesisedVarDeclaration);
if (!semanticModel.TryGetSpeculativeSemanticModel(localStmt.SpanStart, newLocalStmt, out var specModel))
{
specLocal = null;
return false;
}
var specRoot = specModel.SyntaxTree.GetRoot(ct);
var specDeclarator = specRoot.FindNode(synthesisedVarDeclaration.Variables[0].Span); // <VariableDeclaratorSyntax>(node => node == varDeclaration.Variables[0]);
specLocal = (ILocalSymbol?)specModel.GetDeclaredSymbol(specDeclarator, ct);
return true;
}
private static VariableDeclarationSyntax SynthesisedVarDeclaration(
VariableDeclaratorSyntax declarator,
VariableDeclarationSyntax declaration
)
{
var varType = SyntaxFactory.IdentifierName("var").WithTriviaFrom(declaration.Type);
var varDecl = declaration.WithType(varType);
return varDecl;
}
private static bool IsConst(LocalDeclarationStatementSyntax localDecl)
{
for (var i = 0; i < localDecl.Modifiers.Count; i++)
{
if (localDecl.Modifiers[i].IsKind(SyntaxKind.ConstKeyword))
return true;
}
return false;
}
}

View file

@ -0,0 +1,76 @@
using System.Collections.Immutable;
using System.Composition;
using Brutal.Core.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Brutal.Core.Analyzers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(OperatingSystemFixProvider)), Shared]
public class OperatingSystemFixProvider : CodeFixProvider
{
// Specify the diagnostic IDs of analyzers that are expected to be linked.
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = [Resources.BrutalCore0003.Id];
// If you don't need the 'fix all' behaviour, return null.
public override FixAllProvider? GetFixAllProvider() => null;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
// We link only one diagnostic and assume there is only one diagnostic in the context.
var diagnostic = context.Diagnostics.Single();
// 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename.
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Get the root of Syntax Tree that contains the highlighted diagnostic.
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// Find SyntaxNode corresponding to the diagnostic.
var diagnosticNode = root?.FindNode(diagnosticSpan);
// To get the required metadata, we should match the Node to the specific type: 'ClassDeclarationSyntax'.
if (diagnosticNode is not InvocationExpressionSyntax declaration)
return;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Resources.BrutalCore0003Suggestion,
createChangedSolution: c => FixToBrutalPlatformAsync(context.Document, declaration, c),
equivalenceKey: nameof(Resources.BrutalCore0003.Id)
),
diagnostic
);
}
private static async Task<Solution> FixToBrutalPlatformAsync(
Document document,
InvocationExpressionSyntax invocationExpression,
CancellationToken cancellationToken
)
{
// Change from OperatingSystem.XYZ() to Platform.XYZ
// Platform.XYZ is a property, not a method, so we just change the expression part.
var memberAccess = invocationExpression.Expression as MemberAccessExpressionSyntax;
if (memberAccess == null)
return document.Project.Solution;
var root = await document.GetSyntaxRootAsync(cancellationToken);
if (root == null)
return document.Project.Solution;
var newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName("Platform"),
memberAccess.Name
);
var newRoot = root.ReplaceNode(invocationExpression, newMemberAccess);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument.Project.Solution;
}
}

View file

@ -0,0 +1,192 @@
using System.Collections.Immutable;
using System.Composition;
using Brutal.Core.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Brutal.Core.Analyzers;
/// <summary>
/// A code fix provider that replaces explicit types with 'var' and expands 'new()' to 'new TypeName()'.
/// All code fixes must be linked to specific analyzers.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(VarFixProvider)), Shared]
public class VarFixProvider : CodeFixProvider
{
// Specify the diagnostic IDs of analyzers that are expected to be linked.
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
[Resources.VarBrutalCore0007.Id, Resources.VarDefaultBrutalCore0008.Id];
// If you don't need the 'fix all' behavior, return null.
public override FixAllProvider? GetFixAllProvider() => null; //WellKnownFixAllProviders.BatchFixer;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
// We link only one diagnostic and assume there is only one diagnostic in the context.
if (context.Diagnostics.Length != 1)
{
return;
}
var diagnostic = context.Diagnostics[0];
// 'SourceSpan' of 'Location' is the highlighted area.
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Get the root of Syntax Tree that contains the highlighted diagnostic.
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// Find the TypeSyntax node to replace (eg., 'float' in 'float x = 1f')
if (root?.FindNode(diagnosticSpan) is not TypeSyntax typeSyntax)
return;
var declaration = typeSyntax.FirstAncestorOrSelf<VariableDeclarationSyntax>();
if (declaration is not null && TryRegisterDefault(declaration, context, diagnostic, root))
return;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: string.Format(Resources.VarBrutalCore0007.Id),
createChangedDocument: c => ReplaceWithVarAsync(context.Document, typeSyntax, c),
equivalenceKey: nameof(Resources.VarBrutalCore0007.Id)
),
diagnostic
);
}
private bool TryRegisterDefault(
VariableDeclarationSyntax declaration,
CodeFixContext context,
Diagnostic diagnostic,
SyntaxNode root
)
{
var variable = declaration.Variables.FirstOrDefault();
if (variable?.Initializer is null)
{
return false;
}
// e.g. int bob = default. Here, default is a DefaultLiteralExpression
// int bob = default(3). Here, default is a DefaultExpression
if (!variable.Initializer.Value.IsKind(SyntaxKind.DefaultLiteralExpression))
return false;
context.RegisterCodeFix(
CodeAction.Create(
Resources.VarDefaultBrutalCore0008.Title.ToString(),
c => UseVarAndExplicitDefaultAsync(context.Document, declaration, variable, c, root),
nameof(VarFixProvider)
),
diagnostic
);
return true;
}
private Task<Document> UseVarAndExplicitDefaultAsync(
Document document,
VariableDeclarationSyntax declaration,
VariableDeclaratorSyntax variable,
CancellationToken cancellationToken,
SyntaxNode root
)
{
var varType = SyntaxFactory
.IdentifierName("var")
.WithLeadingTrivia(declaration.Type.GetLeadingTrivia())
.WithTrailingTrivia(declaration.Type.GetTrailingTrivia());
var explicitDefault = SyntaxFactory.DefaultExpression(declaration.Type.WithoutTrivia());
var newVariable = variable.WithInitializer(
SyntaxFactory.EqualsValueClause(explicitDefault).WithEqualsToken(variable.Initializer!.EqualsToken)
);
var newDeclaration = declaration
.WithType(varType)
.WithVariables(SyntaxFactory.SingletonSeparatedList(newVariable));
// var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNode(declaration, newDeclaration);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
/// <summary>
/// Executed on the quick fix action raised by the user.
/// </summary>
/// <param name="document">Affected source file.</param>
/// <param name="explicitType">The explicit type syntax node to replace.</param>
/// <param name="cancellationToken">Any fix is cancellable by the user, so we should support the cancellation token.</param>
/// <returns>A new document with the explicit type replaced by 'var'.</returns>
private async Task<Document> ReplaceWithVarAsync(
Document document,
TypeSyntax explicitType,
CancellationToken cancellationToken
)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root == null)
return document;
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (semanticModel == null)
return document;
// Get the VariableDeclarationSyntax node (e.g., 'myObject obj = new();')
if (explicitType.Parent is not VariableDeclarationSyntax declaration || declaration.Variables.Count == 0)
return document;
var variable = declaration.Variables[0];
// Create 'var' keyword with preserved trivia
var varType = SyntaxFactory
.IdentifierName("var")
.WithLeadingTrivia(explicitType.GetLeadingTrivia())
.WithTrailingTrivia(explicitType.GetTrailingTrivia());
ExpressionSyntax? newInitializerExpr = variable.Initializer?.Value;
// Replace 'new()' with 'new myObject()' if necessary
if (variable.Initializer?.Value is ImplicitObjectCreationExpressionSyntax implicitNew)
{
newInitializerExpr = SyntaxFactory
.ObjectCreationExpression(explicitType.WithoutTrivia())
.WithArgumentList(implicitNew.ArgumentList ?? SyntaxFactory.ArgumentList())
.WithTrailingTrivia(implicitNew.GetTrailingTrivia())
.WithLeadingTrivia(implicitNew.GetLeadingTrivia());
}
if (variable.Initializer?.Value is DefaultExpressionSyntax defaultExpression)
{
newInitializerExpr = SyntaxFactory
.DefaultExpression(explicitType.WithoutTrivia())
.WithType(explicitType.NormalizeWhitespace());
}
// Reconstruct initializer
var newInitializer = variable.Initializer?.WithValue(newInitializerExpr!);
// Reconstruct the variable
var newVariable = variable
.WithInitializer(newInitializer)
.WithLeadingTrivia(variable.GetLeadingTrivia())
.WithTrailingTrivia(variable.GetTrailingTrivia());
// Replace the declaration node
var newDeclaration = declaration
.WithType(varType)
.WithVariables(SyntaxFactory.SingletonSeparatedList(newVariable))
.WithLeadingTrivia(declaration.GetLeadingTrivia())
.WithTrailingTrivia(declaration.GetTrailingTrivia());
// Replace the old node with the new one in the tree
var newRoot = root.ReplaceNode(declaration, newDeclaration);
return document.WithSyntaxRoot(newRoot);
}
}

View file

@ -0,0 +1,6 @@
namespace Brutal.Attributes;
[AttributeUsage(
AttributeTargets.ReturnValue | AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property
)]
public sealed class FixedAttribute : Attribute { }

View file

@ -0,0 +1,247 @@
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using CommunityToolkit.HighPerformance.Buffers;
namespace Brutal.Enums;
/// Represents a bit mask, ie a collection of bits that can be set/unset.
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public struct BitMask<T> : IEquatable<BitMask<T>>, IBitwiseOperators<BitMask<T>, BitMask<T>, BitMask<T>>
where T : unmanaged, IBinaryInteger<T>, IUnsignedNumber<T>
{
public static readonly int BitCount = Unsafe.SizeOf<T>() * 8;
/// A mask with no bits set.
public static readonly BitMask<T> Empty = default;
/// A mask with all the bits set.
public static readonly BitMask<T> Full = new(T.AllBitsSet);
T _value;
public T Value => _value;
/// Create a mask from a bit mask, ie no shifting.
public static BitMask<T> FromMask(T mask) => new(mask);
/// Create a mask from a bit index, ie shifting it.
public static BitMask<T> FromBit(byte bitIndex) => new(bitIndex);
/// Create a mask from a value, ie no shifting.
private BitMask(T mask)
{
_value = mask;
}
/// Create a mask from a bit index, ie shifting it.
public BitMask(byte bitIndex)
{
_value = T.One << bitIndex;
}
/// Create a mask with the given range of bit indices set.
public BitMask(Range bitRange)
{
this[bitRange] = true;
}
/// Create a mask with the given bit indices set.
public BitMask(params ReadOnlySpan<byte> bitIndices)
{
foreach (var bitIndex in bitIndices)
_value |= T.One << bitIndex;
}
#region this[index/range] accessors
/// Get/set the value of a bit by its index.
public bool this[byte bitIndex]
{
get => Contains(bitIndex);
set => Set(bitIndex, value);
}
/// Get/set the value of a bit by its index.
public bool this[Index bitIndex]
{
get => Contains((byte)bitIndex.GetOffset(BitCount));
set => Set((byte)bitIndex.GetOffset(BitCount), value);
}
/// Get/set the value of a range of bits.
public bool this[Range bitRange]
{
get => ContainsAll(new BitMask<T>(bitRange));
set
{
var (offset, length) = bitRange.GetOffsetAndLength(BitCount);
var start = (byte)offset;
var end = offset + (byte)length;
for (var i = start; i < end; i++)
this[i] = value;
}
}
#endregion
#region operators
public static BitMask<T> operator |(BitMask<T> a, BitMask<T> b) => FromMask(a._value | b._value);
public static BitMask<T> operator &(BitMask<T> a, BitMask<T> b) => FromMask(a._value & b._value);
public static BitMask<T> operator ^(BitMask<T> a, BitMask<T> b) => FromMask(a._value ^ b._value);
public static BitMask<T> operator ~(BitMask<T> a) => FromMask(~a._value);
#endregion
#region Contains/Add/Remove/Set(bitIndex)
/// <inheritdoc cref="ContainsAny"/>
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool Contains(byte bitIndex) => ContainsAny(FromBit(bitIndex));
/// <inheritdoc cref="Add(BitMask{T})"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BitMask<T> Add(byte bitIndex) => Add(FromBit(bitIndex));
/// <inheritdoc cref="Remove(BitMask{T})"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BitMask<T> Remove(byte bitIndex) => Remove(FromBit(bitIndex));
/// <inheritdoc cref="Set(BitMask{T}, bool)"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BitMask<T> Set(byte bitIndex, bool enabled) => Set(FromBit(bitIndex), enabled);
#endregion
#region Contains/Add/Remove/Set(mask)
/// <summary>
/// Does this mask entirely contain <paramref name="other"/>?
/// Ie, does this mask contain all the bits in <paramref name="other"/>?
/// <br/>
/// Similarly to <see cref="HashSet{T}.IsSupersetOf"/>, this method returns true if the set of bits
/// represented by <paramref name="other"/> is empty, even if the current mask is empty.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool ContainsAll(BitMask<T> other)
{
return (_value & other._value) == other._value;
}
/// Does this mask contain any of the bits in <paramref name="other"/>?
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool ContainsAny(BitMask<T> other)
{
return (_value & other._value) != T.Zero;
}
/// Add (set) the given bits to ours.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BitMask<T> Add(BitMask<T> other)
{
_value |= other._value;
return this;
}
/// Remove (unset) the other bits from ours.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BitMask<T> Remove(BitMask<T> other)
{
_value &= ~other._value;
return this;
}
/// Add/remove (set/unset) the other bits to/from ours.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BitMask<T> Set(BitMask<T> other, bool enabled) => enabled ? Add(other) : Remove(other);
#endregion
/// Is the mask empty? ie no bits set.
public bool IsEmpty => _value == default;
/// Is the mask full? ie all bits set.
public bool IsFull => _value == T.AllBitsSet;
/// Does the mask have only a single bit set?
public bool IsPow2 => T.IsPow2(_value);
/// If the mask has only a single bit set, return its index.
public bool TryGetBitIndex(out byte index) => BitOperations.TryGetBitIndex(_value, out index);
/// Return the inverse of this mask, ie all bits flipped.
public BitMask<T> Inversed => new(~_value);
#region ToString() - TODO: ISpanFormattable etc
public static readonly string[] BitNames = ComputeBitNames();
static string[] ComputeBitNames()
{
var names = new string[BitCount];
for (var i = 0; i < BitCount; i++)
{
names[i] = i.ToString();
}
return names;
}
static readonly ConcurrentDictionary<T, string> ToStringCache = new();
public override string ToString()
{
// try to get string from cache
if (ToStringCache.TryGetValue(_value, out var s))
{
return s;
}
if (IsEmpty)
return "(empty)";
if (IsFull)
return "(full)";
// compute string and cache it
using var tmpBitNames = SpanOwner<string>.Allocate(BitCount);
var tmpBitNameCount = 0;
for (byte i = 0; i < BitCount; i++)
if (Contains(i))
tmpBitNames.Span[tmpBitNameCount++] = BitNames[i];
ToStringCache[_value] = s = $"({string.Join(", ", tmpBitNames.Span[..tmpBitNameCount])})";
return s;
}
#endregion
#region equality members
public bool Equals(BitMask<T> other)
{
return _value.Equals(other._value);
}
public override bool Equals(object? obj)
{
return obj is BitMask<T> other && Equals(other);
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public static bool operator ==(BitMask<T> left, BitMask<T> right)
{
return left.Equals(right);
}
public static bool operator !=(BitMask<T> left, BitMask<T> right)
{
return !left.Equals(right);
}
#endregion
}

View file

@ -0,0 +1,93 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace Brutal.Enums;
/// Provides information about a given Enum type.
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public static class Enum<T>
where T : unmanaged, Enum
{
public static readonly int BitCount = Unsafe.SizeOf<T>() * 8;
public static readonly Type UnderlyingType = typeof(T).GetEnumUnderlyingType();
public static readonly T[] Values = (T[])Enum.GetValues(typeof(T));
public static readonly string[] Names = Enum.GetNames(typeof(T));
public static readonly int Count = Values.Length;
public static readonly T MinValue,
MaxValue;
public static readonly (T value, string name)[] Pairs = new (T value, string name)[Count];
static Enum()
{
for (var i = 0; i < Count; i++)
{
Pairs[i] = (Values[i], Names[i]);
}
if (Count > 0)
{
// values are already sorted
MinValue = Values[0];
MaxValue = Values[^1];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public static T CreateTruncating(int value) => EnumOperators.CreateTruncating<T>(value);
#region specific to mask / bit-field / [Flags] enums
/// Does this enum represent a bit-field? aka [Flags] enum.
public static readonly bool IsBitMask = typeof(T).GetCustomAttribute<FlagsAttribute>() != null;
/// For a bit-field enum, this a mask with all the enum's available flags/bits set.
/// Otherwise, 0 for non-bit-field enums.
public static readonly T KnownFlagsMask = ComputeKnownFlagsMask();
static T ComputeKnownFlagsMask()
{
if (!IsBitMask)
return default;
var all = default(T);
foreach (var flag in Values)
all |= flag;
return all;
}
#region single-bit values / compound values
/// For a bit-field enum, the list of available single-bit values (compound/multi-bit values are excluded).
/// Otherwise, empty for non-bit-field enums.
public static readonly T[] BitValues = ComputeBitValues(true);
/// For a bit-field enum, the list of available compound/multi-bit values.
/// Otherwise, empty for non-bit-field enums.
public static readonly T[] CompoundValues = ComputeBitValues(false);
static T[] ComputeBitValues(bool bitOrCompound)
{
if (!IsBitMask)
return [];
Span<T> bits = stackalloc T[Count];
var bitCount = 0;
for (var i = 0; i < Count; i++)
{
var v = Values[i];
if (v.IsPow2 == bitOrCompound)
{
bits[bitCount++] = v;
}
}
return bitCount > 0 ? bits[..bitCount].ToArray() : [];
}
#endregion
#endregion
}

View file

@ -0,0 +1,380 @@
// <auto-generated /> - edit EnumArithmetic.tt to modify
#nullable enable
using System.Numerics;
using static System.Runtime.CompilerServices.Unsafe;
// csharpier-ignore-start
namespace Brutal.Enums
{
/// Extension operators for enums, allowing for generic arithmetic
public static class EnumOperators
{
extension<T>(T) where T : unmanaged, Enum
{
/// TEnum.Equals() boxes, avoid it like the plague.
/// And unfortunately, we can't replace the builtin Equals through an extension.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool operator ==(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<T, byte>(a) == BitCast<T, byte>(b);
if (sizeof(T) == sizeof(ushort))
return BitCast<T, ushort>(a) == BitCast<T, ushort>(b);
if (sizeof(T) == sizeof(uint))
return BitCast<T, uint>(a) == BitCast<T, uint>(b);
if (sizeof(T) == sizeof(ulong))
return BitCast<T, ulong>(a) == BitCast<T, ulong>(b);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool operator !=(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<T, byte>(a) != BitCast<T, byte>(b);
if (sizeof(T) == sizeof(ushort))
return BitCast<T, ushort>(a) != BitCast<T, ushort>(b);
if (sizeof(T) == sizeof(uint))
return BitCast<T, uint>(a) != BitCast<T, uint>(b);
if (sizeof(T) == sizeof(ulong))
return BitCast<T, ulong>(a) != BitCast<T, ulong>(b);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool operator <(T a, T b)
{
if (typeof(T).GetEnumUnderlyingType() == typeof(byte))
return BitCast<T, byte>(a) < BitCast<T, byte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ushort))
return BitCast<T, ushort>(a) < BitCast<T, ushort>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(uint))
return BitCast<T, uint>(a) < BitCast<T, uint>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ulong))
return BitCast<T, ulong>(a) < BitCast<T, ulong>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(sbyte))
return BitCast<T, sbyte>(a) < BitCast<T, sbyte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(short))
return BitCast<T, short>(a) < BitCast<T, short>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(int))
return BitCast<T, int>(a) < BitCast<T, int>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(long))
return BitCast<T, long>(a) < BitCast<T, long>(b);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool operator >(T a, T b)
{
if (typeof(T).GetEnumUnderlyingType() == typeof(byte))
return BitCast<T, byte>(a) > BitCast<T, byte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ushort))
return BitCast<T, ushort>(a) > BitCast<T, ushort>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(uint))
return BitCast<T, uint>(a) > BitCast<T, uint>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ulong))
return BitCast<T, ulong>(a) > BitCast<T, ulong>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(sbyte))
return BitCast<T, sbyte>(a) > BitCast<T, sbyte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(short))
return BitCast<T, short>(a) > BitCast<T, short>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(int))
return BitCast<T, int>(a) > BitCast<T, int>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(long))
return BitCast<T, long>(a) > BitCast<T, long>(b);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool operator <=(T a, T b)
{
if (typeof(T).GetEnumUnderlyingType() == typeof(byte))
return BitCast<T, byte>(a) <= BitCast<T, byte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ushort))
return BitCast<T, ushort>(a) <= BitCast<T, ushort>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(uint))
return BitCast<T, uint>(a) <= BitCast<T, uint>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ulong))
return BitCast<T, ulong>(a) <= BitCast<T, ulong>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(sbyte))
return BitCast<T, sbyte>(a) <= BitCast<T, sbyte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(short))
return BitCast<T, short>(a) <= BitCast<T, short>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(int))
return BitCast<T, int>(a) <= BitCast<T, int>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(long))
return BitCast<T, long>(a) <= BitCast<T, long>(b);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool operator >=(T a, T b)
{
if (typeof(T).GetEnumUnderlyingType() == typeof(byte))
return BitCast<T, byte>(a) >= BitCast<T, byte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ushort))
return BitCast<T, ushort>(a) >= BitCast<T, ushort>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(uint))
return BitCast<T, uint>(a) >= BitCast<T, uint>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(ulong))
return BitCast<T, ulong>(a) >= BitCast<T, ulong>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(sbyte))
return BitCast<T, sbyte>(a) >= BitCast<T, sbyte>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(short))
return BitCast<T, short>(a) >= BitCast<T, short>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(int))
return BitCast<T, int>(a) >= BitCast<T, int>(b);
if (typeof(T).GetEnumUnderlyingType() == typeof(long))
return BitCast<T, long>(a) >= BitCast<T, long>(b);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator |(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) | BitCast<T, byte>(b)));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) | BitCast<T, ushort>(b)));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) | BitCast<T, uint>(b)));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) | BitCast<T, ulong>(b)));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator &(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) & BitCast<T, byte>(b)));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) & BitCast<T, ushort>(b)));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) & BitCast<T, uint>(b)));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) & BitCast<T, ulong>(b)));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator ^(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) ^ BitCast<T, byte>(b)));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) ^ BitCast<T, ushort>(b)));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) ^ BitCast<T, uint>(b)));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) ^ BitCast<T, ulong>(b)));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator ++(T a)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) + 1));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) + 1));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) + 1));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) + 1));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator --(T a)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) - 1));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) - 1));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) - 1));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) - 1));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator ~(T a)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)~BitCast<T, byte>(a));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)~BitCast<T, ushort>(a));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)~BitCast<T, uint>(a));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)~BitCast<T, ulong>(a));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
/// Convert from int to enum, unchecked: value will be truncated if out of underlying bounds
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public static unsafe T CreateTruncating(int value)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)value);
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)value);
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)value);
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)value);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
}
extension<T>(T value) where T : unmanaged, Enum
{
/// Convert this enum to int, unchecked: value will be truncated if out of int bounds
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public unsafe int ToIntTruncating()
{
if (sizeof(T) == sizeof(byte))
return (int)BitCast<T, byte>(value);
if (sizeof(T) == sizeof(ushort))
return (int)BitCast<T, ushort>(value);
if (sizeof(T) == sizeof(uint))
return (int)BitCast<T, uint>(value);
if (sizeof(T) == sizeof(ulong))
return (int)BitCast<T, ulong>(value);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
/// Left-shift this value: <c>1 &lt;&lt; value</c>, ie return a mask containing this value.
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public unsafe T ShiftLeft()
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(1u << (byte)BitCast<T, byte>(value)));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(1u << (byte)BitCast<T, ushort>(value)));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(1u << (byte)BitCast<T, uint>(value)));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(1ul << (byte)BitCast<T, ulong>(value)));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
/// Does the mask have only a single bit set?
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
public unsafe bool IsPow2
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (sizeof(T) == sizeof(byte))
return BitOperations.IsPow2(BitCast<T, byte>(value));
if (sizeof(T) == sizeof(ushort))
return BitOperations.IsPow2(BitCast<T, ushort>(value));
if (sizeof(T) == sizeof(uint))
return BitOperations.IsPow2(BitCast<T, uint>(value));
if (sizeof(T) == sizeof(ulong))
return BitOperations.IsPow2(BitCast<T, ulong>(value));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
}
/// If the mask has only a single bit set, get its index.
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe bool TryGetBitIndex(out byte index)
{
if (sizeof(T) == sizeof(byte))
return BitOperations.TryGetBitIndex(BitCast<T, byte>(value), out index);
if (sizeof(T) == sizeof(ushort))
return BitOperations.TryGetBitIndex(BitCast<T, ushort>(value), out index);
if (sizeof(T) == sizeof(uint))
return BitOperations.TryGetBitIndex(BitCast<T, uint>(value), out index);
if (sizeof(T) == sizeof(ulong))
return BitOperations.TryGetBitIndex(BitCast<T, ulong>(value), out index);
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
}
}
}
namespace Brutal.Enums.AdditionOperators
{
/// Extension operators for enums, allowing for generic arithmetic
public static class EnumAdditionOperators
{
extension<T>(T) where T : unmanaged, Enum
{
/// Binary addition operators, for writing generic code.
/// <br/>
/// Do not use in non-generic code, as enums normally can only operate with their underlying type, not themselves,
/// and we don't want to inadvertently inject that functionality in the language.
/// <br/>
/// So eg a byte enum will define TEnum + byte and byte + TEnum operators, but not a TEnum + TEnum operator.
/// We cannot define a TEnum + TUnderlying operator, as we have no way of generically accessing TUnderlying.
/// <br/>
/// We could define e.g. TEnum + long, but that would be misleading as long might not be the correct size.
/// TEnum + TEnum actually _is_ the correct size, if not the correct type.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator +(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) + BitCast<T, byte>(b)));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) + BitCast<T, ushort>(b)));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) + BitCast<T, uint>(b)));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) + BitCast<T, ulong>(b)));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
/// Binary addition operators, for writing generic code.
/// <br/>
/// Do not use in non-generic code, as enums normally can only operate with their underlying type, not themselves,
/// and we don't want to inadvertently inject that functionality in the language.
/// <br/>
/// So eg a byte enum will define TEnum + byte and byte + TEnum operators, but not a TEnum + TEnum operator.
/// We cannot define a TEnum + TUnderlying operator, as we have no way of generically accessing TUnderlying.
/// <br/>
/// We could define e.g. TEnum + long, but that would be misleading as long might not be the correct size.
/// TEnum + TEnum actually _is_ the correct size, if not the correct type.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T operator -(T a, T b)
{
if (sizeof(T) == sizeof(byte))
return BitCast<byte, T>((byte)(BitCast<T, byte>(a) - BitCast<T, byte>(b)));
if (sizeof(T) == sizeof(ushort))
return BitCast<ushort, T>((ushort)(BitCast<T, ushort>(a) - BitCast<T, ushort>(b)));
if (sizeof(T) == sizeof(uint))
return BitCast<uint, T>((uint)(BitCast<T, uint>(a) - BitCast<T, uint>(b)));
if (sizeof(T) == sizeof(ulong))
return BitCast<ulong, T>((ulong)(BitCast<T, ulong>(a) - BitCast<T, ulong>(b)));
throw new NotSupportedException($"unsupported type {typeof(T)} of size {sizeof(T)}");
}
}
}
}
// csharpier-ignore-end

View file

@ -0,0 +1,72 @@
namespace Brutal.Enums;
public static class EnumExtensions
{
/// <summary>
/// All the methods here are only relevant for [Flags] enums
/// (except for <see cref="ToMask"/>, which is only relevant for _non_-[Flags] enums).
///
/// Terms:
/// - A <b>flag</b> represents a single bit.
/// - A <b>mask</b> represents a combination of bits (compound enum value).
/// </summary>
extension<T>(ref T @this)
where T : unmanaged, Enum
{
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
/// Add (set) the other flag/mask to this mask.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Add(T other)
{
@this |= other;
return @this;
}
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
/// Remove (unset) the other flag/mask from this mask.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Remove(T other)
{
@this &= ~other;
return @this;
}
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
/// Add/remove (set/unset) the other flag/mask to/from this mask.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Set(T other, bool enabled)
{
return enabled ? @this.Add(other) : @this.Remove(other);
}
}
extension<T>(T @this)
where T : unmanaged, Enum
{
/// <summary>
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
/// Does this mask entirely contain <paramref name="other"/>?
/// Ie, does this mask contain all the flags in <paramref name="other"/>?
/// <br/>
/// Similarly to <see cref="HashSet{T}.IsSupersetOf"/>, this method returns true if the set of bits
/// represented by <paramref name="other"/> is empty, even if the current mask is empty.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool ContainsAll(T other)
{
return (@this & other) == other; // same as @this.HasFlag(mask);
}
/// <i>(Mask / bit-field / <c>[Flags]</c> enums only.)</i>
/// Does this mask contain any of the bits in <paramref name="other"/>?
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool ContainsAny(T other)
{
return (@this & other) != default;
}
/// Return an <see cref="EnumMask{T}"/> containing this value.
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public EnumMask<T> ToMask() => new(@this);
}
}

View file

@ -0,0 +1,129 @@
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
namespace Brutal.Enums;
public static class EnumUtf8Ex
{
extension(Enum)
{
/// <inheritdoc cref="Enum.TryFormat" />
/// <remarks>UTF8 version</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryFormat<T>(
T value,
Span<byte> destination,
out int bytesWritten,
[StringSyntax(StringSyntaxAttribute.EnumFormat)] ReadOnlySpan<char> format = default
)
where T : unmanaged, Enum
{
return TryFormatUnconstrained(value, destination, out bytesWritten, format);
}
/// <inheritdoc cref="Enum.TryFormat" />
/// <remarks>UTF8 version, unconstrained</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryFormatUnconstrained<TEnum>(
TEnum value,
Span<byte> destination,
out int bytesWritten,
[StringSyntax(StringSyntaxAttribute.EnumFormat)] ReadOnlySpan<char> format = default
)
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException($"Type {typeof(TEnum)} is not an enum.");
// try with a fixed-sized span first
Span<char> utf16 = stackalloc char[256];
if (TryFormatUnconstrained(null, value, utf16, out var charsWritten, format))
return TryGetBytes(utf16[..charsWritten], destination, out bytesWritten);
// fixed-sized pass failed: check if destination has more room available
if (destination.Length > utf16.Length)
{
// try again with a bigger buffer
var array16 = ArrayPool<char>.Shared.Rent(destination.Length); // UTF16 can't be larger than UTF8
try
{
utf16 = array16;
if (TryFormatUnconstrained(null, value, utf16, out charsWritten, format))
return TryGetBytes(utf16[..charsWritten], destination, out bytesWritten);
}
finally
{
ArrayPool<char>.Shared.Return(array16);
}
}
bytesWritten = 0;
return false;
// copy from Brutal.Strings.Utf8.TryGetBytes, which we can't reference from Common
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool TryGetBytes(ReadOnlySpan<char> chars, Span<byte> destination, out int bytesWritten)
{
if (
System.Text.Unicode.Utf8.FromUtf16(chars, destination, out _, out bytesWritten)
== OperationStatus.Done
)
return true;
bytesWritten = 0;
return false;
}
}
}
#region UnsafeAccessor for TryFormatUnconstrained
extension(Enum)
{
/// <inheritdoc cref="Enum.TryFormat" />
/// <remarks>UTF16 version, unconstrained</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryFormatUnconstrained<TEnum>(
TEnum value,
Span<char> destination,
out int charsWritten,
[StringSyntax(StringSyntaxAttribute.EnumFormat)] ReadOnlySpan<char> format = default
)
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException($"Type {typeof(TEnum)} is not an enum.");
return TryFormatUnconstrained(null, value, destination, out charsWritten, format);
}
}
[UnsafeAccessor(UnsafeAccessorKind.StaticMethod, Name = nameof(TryFormatUnconstrained))]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static extern bool TryFormatUnconstrained<TEnum>(
Enum? _, // required by [UnsafeAccessor] type-matching
TEnum value,
Span<char> destination,
out int charsWritten,
[StringSyntax(StringSyntaxAttribute.EnumFormat)] ReadOnlySpan<char> format = default
);
#endregion
}
public static class EnumUtf8Extensions
{
/// <inheritdoc cref="Enum.TryFormat" />
/// <remarks>
/// Expose Enum.TryFormat() as a member function, to emulate <see cref="IUtf8SpanFormattable"/> for enums,
/// and simplify generic support.</remarks>
/// <remarks><paramref name="provider"/> is ignored.</remarks>
public static bool TryFormat<T>(
this T value,
Span<byte> destination,
out int bytesWritten,
ReadOnlySpan<char> format = default,
IFormatProvider? provider = null
)
where T : unmanaged, Enum
{
return Enum.TryFormat(value, destination, out bytesWritten, format);
}
}

View file

@ -0,0 +1,259 @@
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using CommunityToolkit.HighPerformance.Buffers;
namespace Brutal.Enums;
/// Represents a mask for a regular enum, ie turns a non-[Flags] enum into a [Flags] enum.
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public struct EnumMask<T> : IEquatable<EnumMask<T>>, IBitwiseOperators<EnumMask<T>, EnumMask<T>, EnumMask<T>>
where T : unmanaged, Enum
{
public static readonly int BitCount = Unsafe.SizeOf<T>() * 8;
/// A mask with no flags set.
public static readonly EnumMask<T> Empty = default;
/// A mask with all the bits set.
public static readonly EnumMask<T> Full = FromMask(~default(T));
/// A mask with all the known flags set.
public static readonly EnumMask<T> KnownFlags;
static EnumMask()
{
if (Enum<T>.IsBitMask)
throw new NotSupportedException($"{typeof(T)} is already a [Flags] enum!");
if (Enum<T>.MinValue < default(T))
throw new NotSupportedException(
$"{typeof(T)}: unsupported enum member range, value {Enum<T>.MinValue} ({Enum<T>.MinValue:d}) is negative, only positive values are supported."
);
if (Enum<T>.MaxValue >= Enum<T>.CreateTruncating(BitCount))
throw new NotSupportedException(
$"{typeof(T)}: unsupported enum member range, value {Enum<T>.MaxValue} ({Enum<T>.MaxValue:d}) is bigger than the underlying size ({BitCount})."
);
// do these last in case T is non-compliant
KnownFlags = new(Enum<T>.Values);
BitNames = ComputeBitNames();
}
T _value;
/// Create a mask from a bit mask, ie no shifting.
public static EnumMask<T> FromMask(T mask)
{
EnumMask<T> result;
result._value = mask;
return result;
}
/// Create a mask from a flag, ie shifting it.
public static EnumMask<T> FromFlag(T flag) => new(flag);
/// Create a mask from a flag, ie shifting it.
public EnumMask(T flag)
{
_value = flag.ShiftLeft(); // 1 << flag
}
/// Create a mask with the given flags set.
public EnumMask(params ReadOnlySpan<T> flags)
{
foreach (var flag in flags)
_value |= flag.ShiftLeft(); // 1 << flag
}
public static implicit operator EnumMask<T>(T flag) => new(flag);
#region this[flag/mask] accessors
/// Get/set the value of a flag.
public bool this[T flag]
{
get => Contains(flag);
set => Set(flag, value);
}
/// Get/set the value of a mask.
public bool this[EnumMask<T> mask]
{
get => ContainsAll(mask);
set => Set(mask, value);
}
#endregion
#region operators
public static EnumMask<T> operator |(EnumMask<T> a, EnumMask<T> b) => FromMask(a._value | b._value);
public static EnumMask<T> operator &(EnumMask<T> a, EnumMask<T> b) => FromMask(a._value & b._value);
public static EnumMask<T> operator ^(EnumMask<T> a, EnumMask<T> b) => FromMask(a._value ^ b._value);
public static EnumMask<T> operator ~(EnumMask<T> a) => FromMask(~a._value);
#endregion
#region Contains/Add/Remove/Set(flag)
/// <inheritdoc cref="EnumExtensions.ContainsAny{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool Contains(T flag) => _value.ContainsAny(flag.ShiftLeft());
/// <inheritdoc cref="EnumExtensions.Add{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EnumMask<T> Add(T flag)
{
_value.Add(flag.ShiftLeft());
return this;
}
/// <inheritdoc cref="EnumExtensions.Remove{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EnumMask<T> Remove(T flag)
{
_value.Remove(flag.ShiftLeft());
return this;
}
/// <inheritdoc cref="EnumExtensions.Set{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EnumMask<T> Set(T flag, bool enabled) => enabled ? Add(flag) : Remove(flag);
#endregion
#region Contains/Add/Remove/Set(mask)
/// <inheritdoc cref="EnumExtensions.ContainsAll{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool ContainsAll(EnumMask<T> mask) => _value.ContainsAll(mask._value);
/// <inheritdoc cref="EnumExtensions.ContainsAll{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining), Pure]
public bool ContainsAny(EnumMask<T> mask) => _value.ContainsAny(mask._value);
/// <inheritdoc cref="EnumExtensions.Add{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EnumMask<T> Add(EnumMask<T> mask)
{
_value.Add(mask._value);
return this;
}
/// <inheritdoc cref="EnumExtensions.Remove{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EnumMask<T> Remove(EnumMask<T> mask)
{
_value.Remove(mask._value);
return this;
}
/// <inheritdoc cref="EnumExtensions.Set{T}"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EnumMask<T> Set(EnumMask<T> mask, bool enabled) => enabled ? Add(mask) : Remove(mask);
#endregion
/// Is the mask empty? ie no bits set.
public bool IsEmpty => _value == default;
/// Is the mask full? ie all bits set.
public bool IsFull => _value == ~default(T);
/// Does the mask have only a single bit set?
public bool IsPow2 => _value.IsPow2;
/// If the mask has only a single bit set, return it (ie its index).
public bool TryGetSingleFlag(out T flag)
{
var result = _value.TryGetBitIndex(out var index);
flag = Enum<T>.CreateTruncating(index);
return result;
}
/// Return the inverse of this mask, ie all bits flipped.
public EnumMask<T> Inversed => FromMask(~_value);
#region ToString() - TODO: ISpanFormattable etc
public static readonly string[] BitNames;
static string[] ComputeBitNames()
{
var names = new string?[BitCount];
// set names for known bits
foreach (var (value, name) in Enum<T>.Pairs)
{
names[value.ToIntTruncating()] = name;
}
// unknown bits = integer value
for (var i = 0; i < BitCount; i++)
{
names[i] ??= i.ToString();
}
return names!;
}
static readonly ConcurrentDictionary<T, string> ToStringCache = new();
public override string ToString()
{
// try to get string from cache
if (ToStringCache.TryGetValue(_value, out var s))
{
return s;
}
if (IsEmpty)
return "(empty)";
if (IsFull)
return "(full)";
// compute string and cache it
using var tmpBitNames = SpanOwner<string>.Allocate(BitCount);
var tmpBitNameCount = 0;
for (var i = 0; i < BitCount; i++)
if (Contains(Enum<T>.CreateTruncating(i)))
tmpBitNames.Span[tmpBitNameCount++] = BitNames[i];
ToStringCache[_value] = s = string.Join(", ", tmpBitNames.Span[..tmpBitNameCount]);
return s;
}
#endregion
#region equality members
public bool Equals(EnumMask<T> other)
{
return _value == other._value; // don't use Equals() as it boxes
}
public override bool Equals(object? obj)
{
return obj is EnumMask<T> other && Equals(other);
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
public static bool operator ==(EnumMask<T> left, EnumMask<T> right)
{
return left._value == right._value;
}
public static bool operator !=(EnumMask<T> left, EnumMask<T> right)
{
return left._value != right._value;
}
#endregion
}

View file

@ -0,0 +1,27 @@
namespace System.Numerics;
public static class BitOperationsEx
{
extension(BitOperations)
{
/// <summary>
/// If <paramref name="mask"/> has only a single bit set, output its <paramref name="index"/>, otherwise return false.
/// </summary>
/// <param name="mask">A bit-mask value that potentially only contains a single bit.</param>
/// <param name="index">The index of the single bit, if true.</param>
/// <returns>Whether <paramref name="mask"/> contains a single bit.</returns>
public static bool TryGetBitIndex<T>(T mask, out byte index)
where T : unmanaged, IBinaryInteger<T>
{
if (!T.IsPow2(mask))
{
index = 0;
return false;
}
var tzc = T.TrailingZeroCount(mask);
index = byte.CreateTruncating(tzc);
return true;
}
}
}

View file

@ -0,0 +1,35 @@
using CommunityToolkit.HighPerformance;
namespace Brutal.Extensions;
public static class SpanExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Contains<T>(this Span<T> span, T value)
where T : unmanaged, Enum
{
return ((ReadOnlySpan<T>)span).Contains(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool Contains<T>(this ReadOnlySpan<T> span, T value)
where T : unmanaged, Enum
{
return sizeof(T) switch
{
sizeof(byte) => span.Cast<T, byte>().Contains(Unsafe.BitCast<T, byte>(value)),
sizeof(short) => span.Cast<T, short>().Contains(Unsafe.BitCast<T, short>(value)),
sizeof(int) => span.Cast<T, int>().Contains(Unsafe.BitCast<T, int>(value)),
sizeof(long) => span.Cast<T, long>().Contains(Unsafe.BitCast<T, long>(value)),
_ => throw new NotSupportedException($"Enum of size {sizeof(T)} is not supported."),
};
}
/// <inheritdoc cref="ReadOnlySpan{T}.TryCopyTo"/>
public static bool TryCopyTo<T>(this ReadOnlySpan<T> value, Span<T> destination, out int elementsWritten)
{
var result = value.TryCopyTo(destination);
elementsWritten = result ? value.Length : 0;
return result;
}
}

View file

@ -0,0 +1,29 @@
namespace System.Text.Unicode;
public static class Utf8Ex
{
extension(Utf8)
{
/// <inheritdoc cref="Utf8.TryWrite(Span{byte}, ref Utf8.TryWriteInterpolatedStringHandler, out int)" />
public static bool TryFormat<T>(
T value,
Span<byte> destination,
out int bytesWritten,
string? format = null,
IFormatProvider? provider = null
)
{
// Hijack TryWriteInterpolatedStringHandler, which handles all cases,
// including some enum internals we don't have access to.
var handler = new Utf8.TryWriteInterpolatedStringHandler(0, 1, destination, provider, out _);
if (format == null)
handler.AppendFormatted(value);
else
handler.AppendFormatted(value, format);
// handler.AppendFormatted() already returns a success bool;
// we only call TryWrite() to access bytesWritten, which is internal
return Utf8.TryWrite([], ref handler, out bytesWritten);
}
}
}

View file

@ -0,0 +1,2 @@
global using System.Diagnostics.Contracts;
global using System.Runtime.CompilerServices;

View file

@ -0,0 +1,27 @@
namespace Brutal;
/// <summary>
/// Interface for a type that can be null
/// </summary>
public interface INullable
{
/// <summary>
/// Returns true if the instance is null
/// </summary>
public bool IsNull();
}
/// <summary>
/// Extensions for INullable
/// </summary>
public static class NullableExtensions
{
/// <summary>
/// Returns true if the instance is not null
/// </summary>
public static bool IsNotNull<T>(this T nullable)
where T : INullable
{
return !nullable.IsNull();
}
}

View file

@ -0,0 +1,22 @@
using Brutal.Pointers;
namespace Brutal;
public interface ISpanLike : INullable
{
public Ptr Ptr { get; }
public ElementCount Length { get; }
public ByteSize Stride { get; }
public bool IsEmpty { get; }
public Span<T> AsSpan<T>()
where T : unmanaged;
}
public interface ISpanLike<T> : ISpanLike
where T : unmanaged
{
public new Ptr<T> Ptr { get; }
public Span<T> AsSpan();
}

View file

@ -0,0 +1,32 @@
using System.Numerics;
namespace Brutal.Numerics;
public interface IArithmeticOperators<TSelf, TOther, TResult>
: IAdditionOperators<TSelf, TOther, TResult>,
ISubtractionOperators<TSelf, TOther, TResult>,
IMultiplyOperators<TSelf, TOther, TResult>,
IDivisionOperators<TSelf, TOther, TResult>
where TSelf : IArithmeticOperators<TSelf, TOther, TResult>?;
public interface IAssociativeArithmeticOperators<TSelf, TOther, TResult> : IArithmeticOperators<TSelf, TOther, TResult>
where TSelf : IAssociativeArithmeticOperators<TSelf, TOther, TResult>?
{
static abstract TResult operator +(TOther left, TSelf right);
static abstract TResult operator -(TOther left, TSelf right);
static abstract TResult operator *(TOther left, TSelf right);
static abstract TResult operator /(TOther left, TSelf right);
#pragma warning disable CS8604 // Possible null reference argument.
static virtual TResult operator checked +(TOther left, TSelf right) => unchecked(left + right);
static virtual TResult operator checked -(TOther left, TSelf right) => unchecked(left - right);
static virtual TResult operator checked *(TOther left, TSelf right) => unchecked(left * right);
static virtual TResult operator checked /(TOther left, TSelf right) => unchecked(left / right);
#pragma warning restore CS8604 // Possible null reference argument.
}

Some files were not shown because too many files have changed in this diff Show more