SOURCE DUMP v1

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

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
}