Skip to content

Instantly share code, notes, and snippets.

@Ellzord
Last active August 29, 2015 14:14
Show Gist options
  • Save Ellzord/000f7a5b201dc8b43fa3 to your computer and use it in GitHub Desktop.
Save Ellzord/000f7a5b201dc8b43fa3 to your computer and use it in GitHub Desktop.
Utility for creating constants to be used as states (bitwise).
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();
}
}
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