Created
May 3, 2023 16:50
-
-
Save nomnomab/d6feeba758f2b2f5fe22036674c6e229 to your computer and use it in GitHub Desktop.
Unity editor enum compression for invalid states
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static class EnumCache<T> where T : Enum { | |
public static T[] Values { get; } = (T[])Enum.GetValues(typeof(T)); | |
} | |
// 32-bit max enum simplification | |
private static int SimplifyEnum<T>(T e) where T: Enum { | |
var values = EnumCache<T>.Values; | |
var max = 0; | |
var number = Convert.ToInt32(e); | |
for (int i = 0; i < values.Length; i++) { | |
var bit = (int)values.GetValue(i); | |
if (bit == number) { | |
return bit; | |
} | |
if (bit > max) { | |
max |= bit; | |
} | |
} | |
// can't convert back to T without boxing | |
// so just returns the number | |
return number & max; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: