com.onegini.sdk.util.EnumEncoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of idp-sdk Show documentation
Show all versions of idp-sdk Show documentation
Java SDK to connect to the Onegini platform
/*
* Copyright 2013-2020 Onegini b.v.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onegini.sdk.util;
import java.lang.reflect.InvocationTargetException;
import java.util.EnumSet;
import java.util.Map;
/**
* Encodes Enums to their bit value based on the {@link StableOrdinal} of the Enum. We use bit shifting to append all
* enums in an EnumSet to represent the entire {@link EnumSet} as a single long which means we can only encode enums
* which contain 64 or less enum values as we otherwise would go over the {@link Long#MAX_VALUE}
* This solution is inspired by a Stackoverflow article.
*
* @see Stackoverflow article
*/
public final class EnumEncoder {
private EnumEncoder() {
throw new UnsupportedOperationException();
}
public static & StableOrdinal> long encode(final EnumSet set) {
long ret = 0;
for (final E val : set) {
ret |= (1 << val.getStableOrdinal());
}
return ret;
}
@SuppressWarnings("unchecked")
public static & StableOrdinal> EnumSet decode(final long code, final Class enumType) {
long c = code;
final EnumSet result = EnumSet.noneOf(enumType);
final Map values;
try {
values = (Map) enumType.getMethod("valuesWithStableOrdinal").invoke(null);
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
throw new RuntimeException("Cannot decode EnumSet", ex);
}
while (c != 0) {
final int stableOrdinal = Long.numberOfTrailingZeros(c);
c ^= Long.lowestOneBit(c);
result.add(values.get(stableOrdinal));
}
return result;
}
}