| | 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 |
| 180915 | 12 | | { |
| 180915 | 13 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| 180915 | 14 | | int previousValue = Interlocked.Or(ref source, flagValue); |
| 180915 | 15 | | return previousValue != (previousValue | flagValue); |
| 180915 | 16 | | } |
| | 17 | |
|
| | 18 | | internal static bool TrySetFlag<T>(this ref int source, T flag, out int newValue) where T : Enum |
| 25345 | 19 | | { |
| 25345 | 20 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| 25345 | 21 | | int previousValue = Interlocked.Or(ref source, flagValue); |
| 25345 | 22 | | newValue = previousValue | flagValue; |
| 25345 | 23 | | return previousValue != newValue; |
| 25345 | 24 | | } |
| | 25 | |
|
| | 26 | | internal static bool HasFlag<T>(this ref int source, T flag) where T : Enum |
| 449080 | 27 | | { |
| 449080 | 28 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| 449080 | 29 | | return (Volatile.Read(ref source) & flagValue) == flagValue; |
| 449080 | 30 | | } |
| | 31 | |
|
| | 32 | | internal static void ClearFlag<T>(this ref int source, T flag) where T : Enum |
| 167175 | 33 | | { |
| 167175 | 34 | | int flagValue = Unsafe.As<T, int>(ref flag); |
| 167175 | 35 | | int previousValue = Interlocked.And(ref source, ~flagValue); |
| 167175 | 36 | | if (previousValue == (previousValue & ~flagValue)) |
| 0 | 37 | | { |
| 0 | 38 | | throw new InvalidOperationException("The state was already cleared."); |
| | 39 | | } |
| 167175 | 40 | | } |
| | 41 | | } |