Last active
August 29, 2015 14:14
-
-
Save Ellzord/000f7a5b201dc8b43fa3 to your computer and use it in GitHub Desktop.
Utility for creating constants to be used as states (bitwise).
This file contains 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
import java.util.Arrays; | |
public class States { | |
public static final int EMPTY = 0; | |
public static int create(int ref) { | |
return 1 << ref; | |
} | |
public static int add(int base, int... states) { | |
return Arrays.stream(states).reduce(base, | |
(current, state) -> current |= state); | |
} | |
public static int remove(int base, int... states) { | |
return Arrays.stream(states).reduce(base, | |
(current, state) -> current &= ~state); | |
} | |
public static boolean contains(int base, int... states) { | |
return Arrays.stream(states).allMatch(state -> (base & state) != 0); | |
} | |
public static int to(int... states) { | |
return add(EMPTY, states); | |
} | |
private States() { | |
throw new UnsupportedOperationException(); | |
} | |
} |
This file contains 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
public class StatesTest { | |
public static final int ON = States.create(0); | |
public static final int PAUSE = States.create(1); | |
public static final int OFF = States.create(2); | |
public static void main(String[] args) { | |
int state = States.to(ON, PAUSE); | |
System.out.println("START: " + state); | |
if (States.contains(state, PAUSE)) { | |
state = States.remove(state, PAUSE); | |
System.out.println("PAUSE REMOVED: " + state); | |
} | |
state = States.remove(state, ON); | |
System.out.println("ON REMOVED: " + state); | |
state = States.add(state, OFF); | |
System.out.println("OFF ADDED: " + state); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment