OrderPreservingBase64 { public static byte[] encode(byte[] data) { return encode(data, 0, data.length); }  static byte[] encode(byte[] data); static byte[] encode(byte[] data, int offset, int len); static void encodeToStream(byte[] data, OutputStream out); static void encodeToStream(OutputStream out, byte[] data, int offset, int datalen); static void encodeToWriter(byte[] data, Writer out); static void encodeToWriter(Writer out, byte[] data, int offset, int datalen); static byte[] decode(byte[] data); static byte[] decode(byte[] data, int offset, int len);  }
@Test public void testOrder() { Random rand = new Random(); long nano = System.nanoTime(); int n = 1000000; for (int i = 0; i < n; i++) { byte[] a = new byte[(int) (Math.random() * 16)]; byte[] b = new byte[(int) (Math.random() * 16)]; rand.nextBytes(a); rand.nextBytes(b); int bytecomp = compareTo(a, 0, a.length, b, 0, b.length); int b64comp = new String(OrderPreservingBase64.encode(a), StandardCharsets.US_ASCII).compareTo(new String(OrderPreservingBase64.encode(b), StandardCharsets.US_ASCII)); Assert.assertTrue((bytecomp == 0 && b64comp == 0) || (bytecomp * b64comp > 0)); } System.out.println((System.nanoTime() - nano) / (double) n); }
@Test public void testPerf() { byte[] bytes = new byte[100000]; SecureRandom sr = new SecureRandom(); sr.nextBytes(bytes); int n = 100000; for (int i = 0; i < n; i++) { byte[] enc = OrderPreservingBase64.encode(bytes); } }
@Test public void testEncode() { byte[] data = new byte[] { -1 }; byte[] encoded = OrderPreservingBase64.encode(data); Assert.assertEquals(2, encoded.length); Assert.assertEquals("zk", new String(encoded)); data = new byte[] { -1, -1 }; encoded = OrderPreservingBase64.encode(data); Assert.assertEquals(3, encoded.length); Assert.assertEquals("zzw", new String(encoded)); data = new byte[] { -1, -1, -1 }; encoded = OrderPreservingBase64.encode(data); Assert.assertEquals(4, encoded.length); Assert.assertEquals("zzzz", new String(encoded)); data = new byte[] { -1, -1, -1, -1 }; encoded = OrderPreservingBase64.encode(data); Assert.assertEquals(6, encoded.length); Assert.assertEquals("zzzzzk", new String(encoded)); data = new byte[] { -1, -1, -1, -1, -1 }; encoded = OrderPreservingBase64.encode(data); Assert.assertEquals(7, encoded.length); Assert.assertEquals("zzzzzzw", new String(encoded)); }