// Collection of code snippets by Arne VajhÃ¸j 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UTest {
    private static final Pattern p = Pattern.compile("\\\\u([0-9A-F]{4})");
    public static String U2U(String s) {
        StringBuffer res = new StringBuffer(s);
        Matcher m = p.matcher(res);
        int ix = 0;
        while(m.find(ix)) {
            res = res.replace(m.start(), m.end(), Character.toString((char)Integer.parseInt(m.group(1), 16)));
            ix = m.start() + 1;
        }
        return res.toString();   
    }
    public static String unescape(String s) {
        int i=0,len=s.length(); char c; StringBuffer sb = new StringBuffer(len);
        while (i<len) {
            c = s.charAt(i++);
            if (c=='\\') {
                if (i<len) {
                    c = s.charAt(i++);
                    if (c=='u') {
                        c = (char) Integer.parseInt(s.substring(i,i+4),16);
                        i += 4;
                    }
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }
    private final static int N = 1000000;
    private static void test(String input, String expected) {
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            if(!U2U(input).equals(expected)) {
                System.out.println("Oops");
                System.exit(1);
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println("U2U: " + (t2-t1));
        long t3 = System.currentTimeMillis();
        for(int i = 0; i < N; i++) {
            if(!unescape(input).equals(expected)) {
                System.out.println("Oops");
                System.exit(1);
            }
        }
        long t4 = System.currentTimeMillis();
        System.out.println("unescape: " + (t4-t3));
    }
    public static void main(String[] args) {
        test("En Espa\\u00F1ol", "En Español");
        test("Plain ASCII", "Plain ASCII");
        test("\\u0041\\u0042\\u0043\\u000A\\u0031\\u0032\\u0033", "ABC\n123");
    }
}
