DataType.java

/*
MIT License

Copyright (c) 2019 Gleethos

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   _____        _     _______
  |  __ \      | |   |__   __|
  | |  | | __ _| |_ __ _| |_   _ _ __   ___
  | |  | |/ _` | __/ _` | | | | | '_ \ / _ \
  | |__| | (_| | || (_| | | |_| | |_) |  __/
  |_____/ \__,_|\__\__,_|_|\__, | .__/ \___|
                            __/ | |
                           |___/|_|

 */

package neureka.dtype;


import neureka.common.utility.LogUtil;
import neureka.dtype.custom.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 *  This class is a Multiton implementation for wrapping and representing type classes.
 *  Every {@link DataType} instance uniquely wraps a {@link Class} instance which will always differ
 *  from instances wrapped by other {@link DataType} instances.
 *  This is because the Multiton implementation utilizes a hash map where classes are the
 *  keys and their corresponding values are DataType instances.
 *
 * @param <T> The type parameter of the type class whose instances ought to be represented.
*/
public final class DataType<T>
{

    private final static int _CAPACITY = 128;

    private static final Map<Class<?>, DataType> _instances = new LinkedHashMap<Class<?>, DataType>() {
        @Override
        protected boolean removeEldestEntry(final Map.Entry eldest) {
            return size() > _CAPACITY;
        }
    };

    private final Logger _log;

    private final Class<T> _typeClass;


    /**
     *  This method finds the corresponding NumericType implementation representing
     *  the passed type class or simply the provided class if no representation has been found.
     *
     * @param typeClass The type class whose "actual" / representation ought to be determined.
     * @return The true representation or simply itself if no NumericType representation has been found.
     */
    private static Class<?> _numericTypeRepresentationOf( Class<?> typeClass ) {
        Class<?> realTypeClass = typeClass; // The or case is for kotlin!
        if      ( typeClass == Double.class  || typeClass.getSimpleName().equals("double")) realTypeClass = F64.class;
        else if ( typeClass == Float.class   || typeClass.getSimpleName().equals("float") ) realTypeClass = F32.class;
        else if ( typeClass == Integer.class || typeClass.getSimpleName().equals("int")   ) realTypeClass = I32.class;
        else if ( typeClass == Short.class   || typeClass.getSimpleName().equals("short") ) realTypeClass = I16.class;
        else if ( typeClass == Long.class    || typeClass.getSimpleName().equals("long")  ) realTypeClass = I64.class;
        else if ( typeClass == Byte.class    || typeClass.getSimpleName().equals("byte")  ) realTypeClass = I8.class;
        return realTypeClass;
    }

    public static <T> DataType<T> of( Class<T> typeClass )
    {
        LogUtil.nullArgCheck(typeClass, "typeClass", Class.class);
        Class<?> realTypeClass = _numericTypeRepresentationOf( typeClass );

        if ( _instances.containsKey( realTypeClass ) ) {
            return _instances.get( realTypeClass );
        }
        DataType<T> dt = new DataType( realTypeClass );
        _instances.put( realTypeClass, dt );
        return dt;
    }

    private DataType( Class<T> type ) {
        _typeClass = type;
        _log = LoggerFactory.getLogger(
                    DataType.class.getSimpleName() + ".of(" + _typeClass.getSimpleName() + ")"
                );
    }

    /**
     * @return An instance of the type class if possible.
     */
    public <T extends NumericType<?,?,?,?>> T getTypeClassInstance( Class<T> type )
    {
        LogUtil.nullArgCheck( type, "type", Class.class );
        if ( !type.isAssignableFrom(_typeClass) )
            throw new IllegalArgumentException("This data type does not support built in numeric type utilities!");
        Constructor<?>[] constructors = _typeClass.getDeclaredConstructors();
        Constructor<?> constructor = null;
        for ( Constructor<?> current : constructors ) {
            constructor = current;
            if (current.getGenericParameterTypes().length == 0)
                break;
        }

        try {
            constructor.setAccessible( true );
            return (T) constructor.newInstance();
        } catch ( Exception e ) {
            _log.error("Could not instantiate type class '"+ _typeClass.getSimpleName()+"': "+e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param interfaceClass The type class which ought to be checked for compatibility.
     * @return True if the provided type is a sub-type of the type represented by this instance.
     */
    public boolean typeClassImplements( Class<?> interfaceClass ) {
        LogUtil.nullArgCheck( interfaceClass, "interfaceClass", Class.class );
        return interfaceClass.isAssignableFrom( _typeClass );
    }

    public Class<?> dataArrayType() {
        if ( this.typeClassImplements( NumericType.class ) )
            return ( (NumericType<?,?,?,?>) Objects.requireNonNull( getTypeClassInstance(NumericType.class) ) ).holderArrayType();
        else if ( this.getItemTypeClass() == Character.class )
            return char[].class;
        else if ( this.getItemTypeClass() == Boolean.class )
            return boolean[].class;
        else
            return Object[].class;
    }

    public boolean equals(final Object o) {
        if ( o == this ) return true;
        if ( !(o instanceof DataType) ) return false;
        final DataType<?> other = (DataType<?>) o;
        return Objects.equals(this._typeClass, other._typeClass);
    }

    public int hashCode() { return _typeClass.hashCode() * 31; }

    public String toString() {
        String representative = (getRepresentativeType() != getItemTypeClass() ? "("+getRepresentativeType().getSimpleName()+")" : "");
        return "DataType[class=" + getItemTypeClass().getSimpleName() + representative + "]";
    }

    public Class<?> getRepresentativeType() { return _typeClass; }

    public Class<T> getItemTypeClass() {
        if ( this.typeClassImplements(NumericType.class) )
            return (this.getTypeClassInstance(NumericType.class)).holderType();
        else
            return _typeClass;
    }
}