AtomicEnum
Provides basic atomic operations for arbitrary enum type.
using DotNext.Runtime;
using System;
using System.Runtime.CompilerServices;
using System.Threading;
namespace DotNext.Threading
{
public static class AtomicEnum
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TEnum VolatileRead<TEnum>(ref TEnum value) where TEnum : struct, Enum
{
switch (Unsafe.SizeOf<TEnum>()) {
case 1:
return Intrinsics.ReinterpretCast<byte, TEnum>(Volatile.Read(ref Unsafe.As<TEnum, byte>(ref value)));
case 2:
return Intrinsics.ReinterpretCast<ushort, TEnum>(Volatile.Read(ref Unsafe.As<TEnum, ushort>(ref value)));
case 4:
return Intrinsics.ReinterpretCast<uint, TEnum>(Volatile.Read(ref Unsafe.As<TEnum, uint>(ref value)));
case 8:
return Intrinsics.ReinterpretCast<ulong, TEnum>(Volatile.Read(ref Unsafe.As<TEnum, ulong>(ref value)));
default:
return value;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void VolatileWrite<TEnum>(ref TEnum value, TEnum newValue) where TEnum : struct, Enum
{
switch (Unsafe.SizeOf<TEnum>()) {
case 1:
Volatile.Write(ref Unsafe.As<TEnum, byte>(ref value), Intrinsics.ReinterpretCast<TEnum, byte>(newValue));
break;
case 2:
Volatile.Write(ref Unsafe.As<TEnum, ushort>(ref value), Intrinsics.ReinterpretCast<TEnum, ushort>(newValue));
break;
case 4:
Volatile.Write(ref Unsafe.As<TEnum, uint>(ref value), Intrinsics.ReinterpretCast<TEnum, uint>(newValue));
break;
case 8:
Volatile.Write(ref Unsafe.As<TEnum, ulong>(ref value), Intrinsics.ReinterpretCast<TEnum, ulong>(newValue));
break;
}
}
}
}