package org.bouncycastle.asn1;

import java.io.IOException;

import org.bouncycastle.util.Arrays;

/**
 * ASN.1 UniversalString object - encodes UNICODE (ISO 10646) characters using 32-bit format. In Java we
 * have no way of representing this directly so we rely on byte arrays to carry these.
 */
public abstract class ASN1UniversalString
    extends ASN1Primitive
    implements ASN1String
{
    static final ASN1UniversalType TYPE = new ASN1UniversalType(ASN1UniversalString.class, BERTags.UNIVERSAL_STRING)
    {
        ASN1Primitive fromImplicitPrimitive(DEROctetString octetString)
        {
            return createPrimitive(octetString.getOctets());
        }
    };

    private static final char[]  table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    /**
     * Return a Universal String from the passed in object.
     *
     * @param obj an ASN1UniversalString or an object that can be converted into
     *            one.
     * @exception IllegalArgumentException if the object cannot be converted.
     * @return an ASN1UniversalString instance, or null
     */
    public static ASN1UniversalString getInstance(Object obj)
    {
        if (obj == null || obj instanceof ASN1UniversalString)
        {
            return (ASN1UniversalString)obj;
        }
        if (obj instanceof ASN1Encodable)
        {
            ASN1Primitive primitive = ((ASN1Encodable)obj).toASN1Primitive();
            if (primitive instanceof ASN1UniversalString)
            {
                return (ASN1UniversalString)primitive;
            }
        }
        if (obj instanceof byte[])
        {
            try
            {
                return (ASN1UniversalString)TYPE.fromByteArray((byte[])obj);
            }
            catch (Exception e)
            {
                throw new IllegalArgumentException("encoding error getInstance: " + e.toString());
            }
        }

        throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
    }

    /**
     * Return a Universal String from a tagged object.
     *
     * @param obj      the tagged object holding the object we want
     * @param explicit true if the object is meant to be explicitly tagged false
     *                 otherwise.
     * @exception IllegalArgumentException if the tagged object cannot be converted.
     * @return a ASN1UniversalString instance, or null
     */
    public static ASN1UniversalString getInstance(ASN1TaggedObject taggedObject, boolean explicit)
    {
        return (ASN1UniversalString)TYPE.getContextInstance(taggedObject, explicit);
    }

    final byte[] contents;

    ASN1UniversalString(byte[] contents, boolean clone)
    {
        this.contents = clone ? Arrays.clone(contents) : contents;
    }

    public final String getString()
    {
        StringBuffer buf = new StringBuffer("#");

        byte[] string;
        try
        {
            string = getEncoded();
        }
        catch (IOException e)
        {
           throw new ASN1ParsingException("internal error encoding UniversalString");
        }

        for (int i = 0; i != string.length; i++)
        {
            buf.append(table[(string[i] >>> 4) & 0xf]);
            buf.append(table[string[i] & 0xf]);
        }
        
        return buf.toString();
    }

    public String toString()
    {
        return getString();
    }

    public final byte[] getOctets()
    {
        return Arrays.clone(contents);
    }

    final boolean encodeConstructed()
    {
        return false;
    }

    final int encodedLength(boolean withTag)
    {
        return ASN1OutputStream.getLengthOfEncodingDL(withTag, contents.length);
    }

    final void encode(ASN1OutputStream out, boolean withTag) throws IOException
    {
        out.writeEncodingDL(withTag, BERTags.UNIVERSAL_STRING, contents);
    }

    final boolean asn1Equals(ASN1Primitive other)
    {
        if (!(other instanceof ASN1UniversalString))
        {
            return false;
        }

        ASN1UniversalString that = (ASN1UniversalString)other;

        return Arrays.areEqual(this.contents, that.contents);
    }

    public final int hashCode()
    {
        return Arrays.hashCode(contents);
    }

    static ASN1UniversalString createPrimitive(byte[] contents)
    {
        return new DERUniversalString(contents, false);
    }
}

@@ -2841,32 +2841,66 @@
 tString()%0A    %7B%0A
+        int dl = contents.length;%0A
         StringBu
@@ -2931,240 +2931,116 @@
 fer(
-%22#%22);%0A%0A        byte%5B%5D string;%0A        try%0A        %7B%0A            string = getEncoded();%0A        %7D%0A        catch (IOException e)%0A        %7B%0A           throw new ASN1ParsingException(%22internal error encoding UniversalString%22);%0A        %7D
+3 + 2 * (ASN1OutputStream.getLengthOfDL(dl) + dl));%0A        buf.append(%22#1C%22);%0A        encodeHexDL(buf, dl);
 %0A%0A  
@@ -3067,29 +3067,17 @@
 ; i 
-!= string.length
+%3C dl
 ; 
-i
 ++
+i
 )%0A  
@@ -3100,96 +3100,37 @@
     
-buf.append(table%5B(string%5Bi%5D %3E%3E%3E 4) & 0xf%5D);%0A            buf.append(table%5Bstring%5Bi%5D & 0xf
+encodeHexByte(buf, contents%5Bi
 %5D);%0A
@@ -3139,24 +3139,16 @@
       %7D%0A
-        
 %0A       
@@ -4222,11 +4222,715 @@
 );%0A    %7D
+%0A%0A    private static void encodeHexByte(StringBuffer buf, int i)%0A    %7B%0A        buf.append(table%5B(i %3E%3E%3E 4) & 0xF%5D);%0A        buf.append(table%5Bi & 0xF%5D);%0A    %7D%0A%0A    private static void encodeHexDL(StringBuffer buf, int dl)%0A    %7B%0A        if (dl %3C 128)%0A        %7B%0A            encodeHexByte(buf, dl);%0A            return;%0A        %7D%0A%0A        byte%5B%5D stack = new byte%5B5%5D;%0A        int pos = 5;%0A%0A        do%0A        %7B%0A            stack%5B--pos%5D = (byte)dl;%0A            dl %3E%3E%3E= 8;%0A        %7D%0A        while (dl != 0);%0A%0A        int count = stack.length - pos;%0A        stack%5B--pos%5D = (byte)(0x80 %7C count);%0A%0A        do%0A        %7B%0A            encodeHexByte(buf, stack%5Bpos++%5D);%0A        %7D%0A        while (pos %3C stack.length);%0A    %7D
 %0A%7D%0A

Optimise getString