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

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.
}

46
Brutal.Core/Platform.cs Normal file
View file

@ -0,0 +1,46 @@
namespace Brutal;
/// <summary>
/// Utility class to determine the current platform
/// </summary>
public static class Platform
{
/// <summary> Enum representing supported platform families /// </summary>
public enum Family
{
Windows,
Linux,
MacOS,
}
/// <summary>The current runtime platform</summary>
public static readonly Family CurrentFamily;
public static bool IsWindows => CurrentFamily == Family.Windows;
public static bool IsLinux => CurrentFamily == Family.Linux;
public static bool IsMacOS => CurrentFamily == Family.MacOS;
public static bool IsUnix => CurrentFamily.IsUnix();
static Platform()
{
if (OperatingSystem.IsWindows())
CurrentFamily = Family.Windows;
else if (OperatingSystem.IsLinux())
CurrentFamily = Family.Linux;
else if (OperatingSystem.IsMacOS())
CurrentFamily = Family.MacOS;
else
throw new PlatformNotSupportedException("Unsupported platform");
}
}
public static class PlatformFamilyExtensions
{
/// <summary>
/// Get the OperatingSystem instance for the given PlatformFamily
/// </summary>
public static bool IsUnix(this Platform.Family family)
{
return family is Platform.Family.Linux or Platform.Family.MacOS;
}
}

View file

@ -0,0 +1,62 @@
using System.Runtime.InteropServices;
using Brutal.Attributes;
namespace Brutal.Pointers.Extensions;
/// <summary>
/// Extensions for Span and ReadOnlySpan as pointers
/// </summary>
public static class PointerExtensions
{
/// <summary>
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
/// </summary>
/// <param name="span">Span of native memory</param>
/// <returns>Unsafe pointer to block of memory</returns>
public static unsafe T* AsPointer<T>(this Span<T> span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
/// <summary>
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
/// </summary>
/// <param name="span">ReadOnlySpan of native memory</param>
/// <returns>Unsafe pointer to block of memory</returns>
public static unsafe T* AsPointer<T>(this ReadOnlySpan<T> span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
/// <summary>
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
/// </summary>
/// <param name="span">Span of native memory</param>
/// <returns>Unsafe pointer to block of memory</returns>
public static unsafe Ptr<T> AsPtr<T>(this Span<T> span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
/// <summary>
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
/// </summary>
/// <param name="span">ReadOnlySpan of native memory</param>
/// <returns>Unsafe pointer to block of memory</returns>
public static unsafe Ptr<T> AsPtr<T>([Fixed] this ReadOnlySpan<T> span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
}

103
Brutal.Core/Pointers/Ptr.cs Normal file
View file

@ -0,0 +1,103 @@
using Brutal.Attributes;
namespace Brutal.Pointers;
/// <summary>
/// A wrapper for an untyped pointer.
/// </summary>
public readonly unsafe struct Ptr(void* pointer) : INullable, IEquatable<Ptr>
{
/// <summary>
/// The raw void pointer.
/// </summary>
public void* Pointer => pointer;
/// <summary>
/// Returns a new <see cref="Ptr"/>, offset by the given byte count.
/// </summary>
public Ptr Offset(ByteSize byteOffset)
{
return new Ptr((byte*)Pointer + byteOffset);
}
/// <summary>
/// Converts the pointer to a Span of the given type and length.
/// </summary>
[return: Fixed]
public Span<TValueType> AsSpan<TValueType>(ElementCount length)
{
return new Span<TValueType>(Pointer, length);
}
/// <summary>
/// Casts the pointer to a typed pointer.
/// </summary>
public Ptr<TCastType> Cast<TCastType>()
where TCastType : unmanaged
{
return new Ptr<TCastType>((TCastType*)Pointer);
}
/// <inheritdoc />
public bool IsNull()
{
return Pointer == null;
}
/// <summary>
/// Implicit conversion from void* to <see cref="Ptr"/>
/// </summary>
public static implicit operator Ptr(void* pointer)
{
return new Ptr(pointer);
}
/// <summary>
/// Implicit conversion from <see cref="Ptr"/> to void*.
/// </summary>
public static implicit operator void*(Ptr ptr)
{
return ptr.Pointer;
}
/// <summary>
/// Explicit conversion from nint to <see cref="Ptr"/>.
/// </summary>
public static explicit operator Ptr(nint ptr)
{
return new Ptr((void*)ptr);
}
/// <summary>
/// Explicit cast to nint.
/// </summary>
public static explicit operator nint(Ptr ptr)
{
return (nint)ptr.Pointer;
}
public bool Equals(Ptr other)
{
return Pointer == other.Pointer;
}
public override bool Equals(object? obj)
{
return obj is Ptr other && Equals(other);
}
public override int GetHashCode()
{
return ((nint)Pointer).GetHashCode();
}
public static bool operator ==(Ptr left, Ptr right)
{
return left.Equals(right);
}
public static bool operator !=(Ptr left, Ptr right)
{
return !left.Equals(right);
}
}

View file

@ -0,0 +1,130 @@
using Brutal.Attributes;
using Brutal.Pointers.Extensions;
namespace Brutal.Pointers;
/// <summary>
/// A wrapper for a typed pointer.
/// </summary>
public readonly unsafe struct Ptr<TValueType>(TValueType* pointer) : INullable
where TValueType : unmanaged
{
/// <summary>
/// The raw pointer of type <typeparamref name="TValueType"/>.
/// </summary>
public TValueType* Pointer => pointer;
/// <summary>
/// A reference to the first value at the pointer address.
/// </summary>
public ref TValueType Value => ref *Pointer;
/// <summary>
/// Returns a new <see cref="Ptr{T}"/>, offset by the given byte count.
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public Ptr<TValueType> Offset(ElementCount count)
{
return new Ptr<TValueType>(Pointer + count);
}
/// <summary>
/// Converts the pointer to a <see cref="Span{T}"/> of the given length.
/// </summary>
[return: Fixed]
public Span<TValueType> AsSpan(ElementCount length)
{
return new Span<TValueType>(Pointer, length);
}
/// <summary>
/// Converts the pointer to an untyped <see cref="Ptr"/>.
/// </summary>
public Ptr AsPtr()
{
return new Ptr(Pointer);
}
/// <summary>
/// Cast this pointer to a different type.
/// </summary>
/// <typeparam name="TCastType"></typeparam>
/// <returns></returns>
public Ptr<TCastType> Cast<TCastType>()
where TCastType : unmanaged
{
return new Ptr<TCastType>((TCastType*)Pointer);
}
/// <inheritdoc />
public bool IsNull()
{
return Pointer == null;
}
/// <summary>
/// Gets a reference to the value at the given index.
/// </summary>
public ref TValueType this[int index] => ref Pointer[index];
/// <summary>
/// Implicit conversion from a <see cref="Ptr{T}"/> to an untyped <see cref="Ptr"/>.
/// </summary>
public static implicit operator Ptr(Ptr<TValueType> ptr)
{
return ptr.AsPtr();
}
/// <summary>
/// Implicit conversion from a typed pointer to a <see cref="Ptr{T}"/>.
/// </summary>
public static implicit operator Ptr<TValueType>(TValueType* pointer)
{
return new Ptr<TValueType>(pointer);
}
/// <summary>
/// Implicit conversion from a <see cref="Ptr{T}"/> to <typeparamref name="TValueType"/>*.
/// </summary>
/// <param name="ptr"></param>
/// <returns></returns>
public static implicit operator TValueType*(Ptr<TValueType> ptr)
{
return ptr.Pointer;
}
/// <summary>
/// Implicit conversion from a <see cref="Ptr{T}"/> to void pointer.
/// </summary>
public static implicit operator void*(Ptr<TValueType> ptr)
{
return ptr.Pointer;
}
public static implicit operator Ptr<TValueType>([Fixed] ReadOnlySpan<TValueType> span)
{
return span.AsPtr();
}
public static implicit operator Ptr<TValueType>([Fixed] Span<TValueType> span)
{
return span.AsPtr();
}
/// <summary>
/// Explicit cast from nint to Ptr.
/// </summary>
public static explicit operator Ptr<TValueType>(nint ptr)
{
return new Ptr<TValueType>((TValueType*)ptr);
}
/// <summary>
/// Explicit cast to nint.
/// </summary>
public static explicit operator nint(Ptr<TValueType> ptr)
{
return (nint)ptr.Pointer;
}
}

View file

@ -0,0 +1,90 @@
using Brutal.Attributes;
namespace Brutal.Pointers;
/// <summary>
/// Wraps a pointer to a pointer.
/// </summary>
public readonly unsafe struct PtrPtr(void** pointerPointer) : INullable
{
/// <summary>
/// The pointer-pointer.
/// </summary>
public void** Pointer => pointerPointer;
/// <summary>
/// Convert the pointer to a span of pointers.
/// </summary>
[return: Fixed]
public Span<Ptr> AsSpan(ElementCount length)
{
// Ptr is equivalent to void*,
// So we can cast void** to Ptr*,
// Or so we will hope
return new Span<Ptr>((Ptr*)Pointer, length);
}
/// <summary>
/// Convert the pointer to a span of pointers.
/// </summary>
public Span<Ptr<T>> AsSpan<T>(ElementCount length)
where T : unmanaged
{
// Ptr<T> is equivalent to T*,
// So we can cast void** to Ptr<T>,
// Or so we will hope
return new Span<Ptr<T>>((Ptr<T>*)Pointer, length);
}
/// <inheritdoc />
public bool IsNull()
{
return Pointer == null;
}
/// <summary>
/// Get the value of the pointer as a reference.
/// </summary>
public ref void* Value => ref *Pointer;
/// <summary>
/// Access the pointer at the given index.
/// </summary>
public Ptr this[int index]
{
get => Pointer[index];
set => Pointer[index] = value.Pointer;
}
/// <summary>
/// Implicit conversion from void** to PtrPtr.
/// </summary>
public static implicit operator PtrPtr(void** address)
{
return new PtrPtr(address);
}
/// <summary>
/// Implicit conversion from PtrPtr to void**
/// </summary>
public static implicit operator void**(PtrPtr ptr)
{
return ptr.Pointer;
}
/// <summary>
/// Explicit conversion from nint to PtrPtr.
/// </summary>
public static explicit operator PtrPtr(nint ptr)
{
return new PtrPtr((void**)ptr);
}
/// <summary>
/// Explicit cast to nint.
/// </summary>
public static explicit operator nint(PtrPtr ptr)
{
return (nint)ptr.Pointer;
}
}

View file

@ -0,0 +1,84 @@
namespace Brutal.Pointers;
/// <summary>
/// Wrapper for a pointer to a pointer of type TValueType.
/// </summary>
public readonly unsafe struct PtrPtr<TValueType>(TValueType** address) : INullable
where TValueType : unmanaged
{
/// <summary>
/// The pointer-pointer.
/// </summary>
public TValueType** Pointer => address;
/// <summary>
/// Convert the pointer to a span of pointers of type TValueType.
/// </summary>
public Span<Ptr<TValueType>> AsSpan(ElementCount length)
{
// Ptr<TValueType> is equivalent to TValueType*,
// So we can cast TValueType** to Ptr<TValueType>*,
// Or so we will hope
return new Span<Ptr<TValueType>>((Ptr<TValueType>*)Pointer, length);
}
/// <inheritdoc />
public bool IsNull()
{
return Pointer == null;
}
/// <summary>
/// Get the value of the pointer as a reference.
/// </summary>
public ref TValueType* Value => ref *Pointer;
/// <summary>
/// Access the pointer at the given index.
/// </summary>
public Ptr<TValueType> this[int index]
{
get => Pointer[index];
set => Pointer[index] = value.Pointer;
}
/// <summary>
/// Implicit conversion from void** to PtrPtr.
/// </summary>
public static implicit operator PtrPtr<TValueType>(TValueType** address)
{
return new PtrPtr<TValueType>(address);
}
/// <summary>
/// Implicit conversion from PtrPtr to void**.
/// </summary>
public static implicit operator void**(PtrPtr<TValueType> ptr)
{
return (void**)ptr.Pointer;
}
/// <summary>
/// Implicit conversion from PtrPtr to TValueType**
/// </summary>
public static implicit operator TValueType**(PtrPtr<TValueType> ptr)
{
return ptr.Pointer;
}
/// <summary>
/// Explicit conversion from nint to PtrPtr.
/// </summary>
public static explicit operator PtrPtr<TValueType>(nint ptr)
{
return new PtrPtr<TValueType>((TValueType**)ptr);
}
/// <summary>
/// Explicit cast to nint.
/// </summary>
public static explicit operator nint(PtrPtr<TValueType> ptr)
{
return (nint)ptr.Pointer;
}
}

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