Skip to content

Select enum constants from boolean[] or bit mask#44

Open
runeflobakk wants to merge 5 commits intomainfrom
select-enums-from-bits-n-bools
Open

Select enum constants from boolean[] or bit mask#44
runeflobakk wants to merge 5 commits intomainfrom
select-enums-from-bits-n-bools

Conversation

@runeflobakk
Copy link
Member

Use a bit mask to select constants from an enum, based on which indices which are set (1-bits):

<E extends Enum<E>> Stream<E> DiggEnums.selectByBitmask(BitSet, Class<E>)

Use an array of booleans to select constants from an enum, based on which indices which are true;

<E extends Enum<E>> Stream<E> DiggEnums.selectByIndexAsOrdinals(boolean[], Class<E>)

Use case

This is obviously a bit esoteric functionality. The intention is to ease the use of some APIs which may (probably for valid performance reasons, at least at the time the APIs were defined) return a kind of bitmask to represent a standardized set of possibly set or unset values.

An example of this is X509Certificate.getKeyUsage(), which returns an array of booleans, where each element's position in the array indicate if a known set of ordered values is true or false. This will enable e.g. the following:

/// Enum representation of the X.509 KeyUsage extension (OID = 2.5.29.15).
/// The order of constants reflect the order of the ASN.1 definition, see
/// [X509Certificate#getKeyUsage()].
enum KeyUsage {
    digitalSignature,
    nonRepudiation,
    keyEncipherment,
    dataEncipherment,
    keyAgreement,
    keyCertSign,
    cRLSign,
    encipherOnly,
    decipherOnly;

    static Stream<KeyUsage> allFrom(X509Certificate certificate) {
        return selectByIndexAsOrdinals(certificate.getKeyUsage(), KeyUsage.class);
    }
}

Note on EnumSet

Java already has a way to represent a set of enum constants using a compact and efficient bitmask, but no way to construct the EnumSet using a bitmask as the source.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants