| | 1 | | // Copyright (c) 2020-2024 dotBunny Inc. |
| | 2 | | // dotBunny licenses this file to you under the BSL-1.0 license. |
| | 3 | | // See the LICENSE file in the project root for more information. |
| | 4 | |
|
| | 5 | | using System; |
| | 6 | | using System.Runtime.CompilerServices; |
| | 7 | |
|
| | 8 | | namespace GDX |
| | 9 | | { |
| | 10 | | /// <summary> |
| | 11 | | /// Enumeration Based Extension Methods |
| | 12 | | /// </summary> |
| | 13 | | [VisualScriptingCompatible(2)] |
| | 14 | | public static class EnumExtensions |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Determine if the provide flags (<paramref name="needles" />) are found in the <paramref name="haystack" |
| | 18 | | /// </summary> |
| | 19 | | /// <param name="haystack">A predefined flag based enumeration.</param> |
| | 20 | | /// <param name="needles">A set of flags to search for in the predefined enumeration.</param> |
| | 21 | | /// <typeparam name="T">The enumeration's type.</typeparam> |
| | 22 | | /// <returns>true if the needles are found in the haystack, otherwise false.</returns> |
| | 23 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 24 | | static unsafe bool HasFlags<T>(T* haystack, T* needles) where T : unmanaged, Enum |
| 160 | 25 | | { |
| 160 | 26 | | byte* flags = (byte*)haystack; |
| 160 | 27 | | byte* query = (byte*)needles; |
| | 28 | |
|
| 456 | 29 | | for (int i = 0; i < sizeof(T); i++) |
| 194 | 30 | | { |
| 194 | 31 | | if ((flags[i] & query[i]) != query[i]) |
| 126 | 32 | | { |
| 126 | 33 | | return false; |
| | 34 | | } |
| 68 | 35 | | } |
| | 36 | |
|
| 34 | 37 | | return true; |
| 160 | 38 | | } |
| | 39 | |
|
| | 40 | | /// <summary> |
| | 41 | | /// Determine if the provide flags (<paramref name="needles" />) are found in the <paramref name="haystack" |
| | 42 | | /// </summary> |
| | 43 | | /// <remarks>Faster then <see cref="Enum.HasFlag" />.</remarks> |
| | 44 | | /// <param name="haystack">A predefined flag based enumeration.</param> |
| | 45 | | /// <param name="needles">A set of flags to search for in the predefined enumeration.</param> |
| | 46 | | /// <typeparam name="T">The enumeration's type.</typeparam> |
| | 47 | | /// <returns>true if the needles are found in the haystack, otherwise false.</returns> |
| | 48 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 49 | | public static unsafe bool HasFlags<T>(this T haystack, T needles) where T : unmanaged, Enum |
| 160 | 50 | | { |
| 160 | 51 | | return HasFlags(&haystack, &needles); |
| 160 | 52 | | } |
| | 53 | | } |
| | 54 | | } |