package timingexp;

import java.io.*;
import sdsi.*;
import sdsi.sexp.*;
import Tools.*;
import proof.*;

/**
 * A race between base64'ing a canonical sexp and to/from readable
 * strings. I was trying to decide whether it was cheaper to transmit
 * canonical S-expressions in Base64, or to use the advanced S-expression
 * encoding. It turned out not to matter much; the overhead is dominated
 * by the generally abysmal S-expression parsing code.
 */
public class TheRace {
	SDSIObject getObject() {
		SDSIObject result = null;
		try {
			File file = new File("timingexp/race.data");
			return KeyTools.processFile(file);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex.toString());
		}
	}

	void toCanonicalAndBack(SDSIObject so) {
//		try {
			byte[] buf = so.getSrep().getCanonRep();
//			SexpString sexpString = new SexpString(buf);
//			String string = sexpString.toReadableString(0, 10240, 0);
//			SexpString sexpString2 = new SexpString(
//				new PushbackInputStream(
//					new ByteArrayInputStream(
//						string.getBytes())));
//			byte[] buf2 = sexpString2.bytesContent();

//			byte[] buf2 = buf;

			byte[] hexstr = Hex.bytesToHex(buf);
//			System.out.write(hexstr);
			byte[] buf2 = Hex.hexToBytes(hexstr);

			SDSIObject so2 = KeyTools.parseBytes(buf2);
			if (!so.equals(so2)) {
				throw new RuntimeException("results unequal");
			}
//		} catch (IOException ex) {
//			throw new RuntimeException(ex.toString());
//		}
	}

	void toReadableAndBack(SDSIObject so) {
		String str = so.toReadableString(10240);
		SDSIObject so2 = KeyTools.parseString(str);
		if (!so.equals(so2)) {
			throw new RuntimeException("results unequal");
		}
	}

	public static void main(String[] args) {
		(new TheRace()).realMain(args);
	}

	public void realMain(String[] args) {
		SDSIObject obj = getObject();
		for (int j=0; j<10; j++) {
			int i;
			Timer t;
			t = new Timer();
			for (i=0; i<10; i++) {
				toReadableAndBack(obj);
			}
			System.out.println(i+" iters readable: "+t);
			t = new Timer();
			for (i=0; i<10; i++) {
				toCanonicalAndBack(obj);
			}
			System.out.println(i+" iters canon: "+t);
		}
	}
}
