Skip to content

Instantly share code, notes, and snippets.

@nomnomab
Created May 3, 2023 16:50
Show Gist options
  • Save nomnomab/d6feeba758f2b2f5fe22036674c6e229 to your computer and use it in GitHub Desktop.
Save nomnomab/d6feeba758f2b2f5fe22036674c6e229 to your computer and use it in GitHub Desktop.
Unity editor enum compression for invalid states
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;
}
@nomnomab
Copy link
Author

nomnomab commented May 3, 2023

Usage:

MyEnum value = (MyEnum)SimplifyEnum(enumValue);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment