All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.comroid.api.BitmaskEnum Maven / Gradle / Ivy

The newest version!
package org.comroid.api;

import org.comroid.util.Bitmask;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;

public interface BitmaskEnum> extends IntEnum, SelfDeclared {
    @Override
    int getValue();

    static  & BitmaskEnum> Set valueOf(int mask, Class viaEnum) {
        return valueOf(mask, viaEnum, Class::getEnumConstants);
    }

    static  & BitmaskEnum> Set valueOf(
            int mask,
            Class viaEnum,
            Function, T[]> valuesProvider) {
        if (!viaEnum.isEnum())
            throw new IllegalArgumentException("Only enums allowed as parameter 'viaEnum'");

        final T[] constants = valuesProvider.apply(viaEnum);
        HashSet yields = new HashSet<>();

        for (T constant : constants) {
            if (constant.isFlagSet(mask))
                yields.add(constant);
        }

        return Collections.unmodifiableSet(yields);
    }

    default boolean hasFlag(BitmaskEnum other) {
        return Bitmask.isFlagSet(getValue(), other.getValue());
    }

    default boolean isFlagSet(int inMask) {
        return Bitmask.isFlagSet(inMask, getValue());
    }

    default int apply(int toMask, boolean newState) {
        return Bitmask.modifyFlag(toMask, getValue(), newState);
    }
}