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

com.infomaximum.database.utils.EnumConverter Maven / Gradle / Ivy

The newest version!
package com.infomaximum.database.utils;

import com.google.common.primitives.UnsignedInts;
import com.infomaximum.database.schema.TypeConverter;

public abstract class EnumConverter & BaseEnum> implements TypeConverter {

    private final T[] enumConstants;

    protected EnumConverter(Class clazz) {
        this.enumConstants = clazz.getEnumConstants();
    }

    @Override
    public byte[] pack(T value) {
        return value != null ? TypeConvert.pack(value.intValue()) : TypeConvert.EMPTY_BYTE_ARRAY;
    }

    @Override
    public T unpack(byte[] value) {
        if (ByteUtils.isNullOrEmpty(value)) {
            return null;
        }

        int enumValue = TypeConvert.unpackInt(value);
        for(T e : enumConstants) {
            if(enumValue == e.intValue()) {
                return e;
            }
        }
        throw new RuntimeException("Not found enum value " + enumValue + " into " + getClass());
    }

    @Override
    public long buildHash(T value) {
        return value != null ? UnsignedInts.toLong(value.intValue()) : 0;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy