| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | |
| | | 5 | | namespace IceRpc.Transports.Internal; |
| | | 6 | | |
| | | 7 | | /// <summary>The flag enum extensions help with atomically set/get enumeration flags on an integer value. The |
| | | 8 | | /// enumeration underlying type must be an integer as well.</summary> |
| | | 9 | | internal static class FlagEnumExtensions |
| | | 10 | | { |
| | | 11 | | internal static bool TrySetFlag<T>(this ref int source, T flag) where T : Enum |
| | 167179 | 12 | | { |
| | 167179 | 13 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| | 167179 | 14 | | int previousValue = Interlocked.Or(ref source, flagValue); |
| | 167179 | 15 | | return previousValue != (previousValue | flagValue); |
| | 167179 | 16 | | } |
| | | 17 | | |
| | | 18 | | internal static bool TrySetFlag<T>(this ref int source, T flag, out int newValue) where T : Enum |
| | 25235 | 19 | | { |
| | 25235 | 20 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| | 25235 | 21 | | int previousValue = Interlocked.Or(ref source, flagValue); |
| | 25235 | 22 | | newValue = previousValue | flagValue; |
| | 25235 | 23 | | return previousValue != newValue; |
| | 25235 | 24 | | } |
| | | 25 | | |
| | | 26 | | internal static bool HasFlag<T>(this ref int source, T flag) where T : Enum |
| | 425187 | 27 | | { |
| | 425187 | 28 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| | 425187 | 29 | | return (Volatile.Read(ref source) & flagValue) == flagValue; |
| | 425187 | 30 | | } |
| | | 31 | | |
| | | 32 | | internal static void ClearFlag<T>(this ref int source, T flag) where T : Enum |
| | 153456 | 33 | | { |
| | 153456 | 34 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| | 153456 | 35 | | int previousValue = Interlocked.And(ref source, ~flagValue); |
| | 153456 | 36 | | if (previousValue == (previousValue & ~flagValue)) |
| | 0 | 37 | | { |
| | 0 | 38 | | throw new InvalidOperationException("The state was already cleared."); |
| | | 39 | | } |
| | 153456 | 40 | | } |
| | | 41 | | } |