package org.bouncycastle.asn1;

import java.io.IOException;

import org.bouncycastle.util.Exceptions;

/**
 * A NULL object - use DERNull.INSTANCE for populating structures.
 */
public abstract class ASN1Null
    extends ASN1Primitive
{
    static final ASN1UniversalType TYPE = new ASN1UniversalType(ASN1Null.class, BERTags.NULL)
    {
        ASN1Primitive fromImplicitPrimitive(DEROctetString octetString)
        {
            return createPrimitive(octetString.getOctetsLength());            
        }
    };

    /**
     * Return an instance of ASN.1 NULL from the passed in object.
     * <p>
     * Accepted inputs:
     *  
     *   null &rarr; null
     *   {@link ASN1Null} object
     *   a byte[] containing ASN.1 NULL object
     * </ul>
     * </p>
     *
     * @param o object to be converted.
     * @return an instance of ASN1Null, or null.
     * @exception IllegalArgumentException if the object cannot be converted.
     */
    public static ASN1Null getInstance(Object o)
    {
        if (o instanceof ASN1Null)
        {
            return (ASN1Null)o;
        }

        if (o != null)
        {
            try
            {
                return (ASN1Null)TYPE.fromByteArray((byte[])o);
            }
            catch (IOException e)
            {
                throw Exceptions.illegalArgumentException("failed to construct NULL from byte[]", e);
            }
        }

        return null;
    }

    public static ASN1Null getInstance(ASN1TaggedObject taggedObject, boolean declaredExplicit)
    {
        return (ASN1Null)TYPE.getContextTagged(taggedObject, declaredExplicit);
    }

    public static ASN1Null getTagged(ASN1TaggedObject taggedObject, boolean declaredExplicit)
    {
        return (ASN1Null)TYPE.getTagged(taggedObject, declaredExplicit);
    }

    ASN1Null()
    {
    }

    public int hashCode()
    {
        return -1;
    }

    boolean asn1Equals(
        ASN1Primitive o)
    {
        if (!(o instanceof ASN1Null))
        {
            return false;
        }
        
        return true;
    }

    public String toString()
    {
         return "NULL";
    }

    private static void checkContentsLength(int contentsLength)
    {
        if (0 != contentsLength)
        {
            throw new IllegalStateException("malformed NULL encoding encountered");
        }
    }

    static ASN1Null createPrimitive(DefiniteLengthInputStream defIn) throws IOException
    {
        return createPrimitive(defIn.getRemaining());
    }

    private static ASN1Null createPrimitive(int contentsLength)
    {
        checkContentsLength(contentsLength);
        return DERNull.INSTANCE;
    }    
}
