package the8472.test.bencode;

import static org.junit.Assert.*;
import static the8472.bencode.Utils.buf2str;
import static the8472.bencode.Utils.str2buf;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import the8472.bencode.BEncoder;

public class EncoderTest {

	@Test
	public void test() {
		Map<String, Object> root = new HashMap<>();
		List<Object> l = new ArrayList<>();
		l.add(1234L);
		l.add(str2buf("foo"));
		
		root.put("zz", 3L);
		root.put("xx", 1L);
		root.put("yy", 1L);
		root.put("aa", 1L);
		root.put("bb", 1L);
		root.put("c", l);
		
		BEncoder enc = new BEncoder();
		ByteBuffer out = enc.encode(root, 1024);
		
		assertEquals(str2buf("d2:aai1e2:bbi1e1:cli1234e3:fooe2:xxi1e2:yyi1e2:zzi3ee"), out);
	}

}

@@ -61,9 +61,20 @@
 ert.
-*
+assertEquals
 ;%0D%0Ai
@@ -241,16 +241,79 @@
 va.util.
+Arrays;%0D%0Aimport java.util.Collections;%0D%0Aimport java.util.Linked
 HashMap;
@@ -480,16 +480,22 @@
 oid test
+Basics
 () %7B%0D%0A%09%09
@@ -525,16 +525,22 @@
 t = new 
+Linked
 HashMap%3C
@@ -853,16 +853,16 @@
 );%0D%0A%09%09%0D%0A
-
 %09%09assert
@@ -944,14 +944,875 @@
 t);%0D%0A%09%7D%0D
+%0A%09%0D%0A%09@Test%0D%0A%09public void testSorting() %7B%0D%0A%09%09Map%3CString, Object%3E root = new LinkedHashMap%3C%3E();%0D%0A%09%09%0D%0A%09%09String%5B%5D keys = new String%5B256%5D;%0D%0A%09%09%0D%0A%09%09Arrays.setAll(keys, (i) -%3E buf2str(ByteBuffer.wrap(new byte%5B%5D %7B(byte) i%7D)));%0D%0A%09%09// clone to shuffle independently of original order%0D%0A%09%09List%3CString%3E keyList = Arrays.asList(keys);%0D%0A%09%09List%3CString%3E shuffledKeys = Arrays.asList(keys.clone());%0D%0A%09%09Collections.shuffle(shuffledKeys);%0D%0A%09%09%0D%0A%09%09shuffledKeys.forEach(s -%3E root.put(s, 1L));%0D%0A%09%09%0D%0A%09%09BEncoder enc = new BEncoder();%0D%0A%09%09ByteBuffer out = enc.encode(root, 2048);%0D%0A%09%09%0D%0A%09%09StringBuilder reference = new StringBuilder();%0D%0A%09%09%0D%0A%09%09reference.append(%22d%22);%0D%0A%09%09%0D%0A%09%09keyList.forEach(str -%3E %7B%0D%0A%09%09%09reference.append(%221:%22);%0D%0A%09%09%09reference.append(str);%0D%0A%09%09%09reference.append(%22i1e%22);%0D%0A%09%09%7D);%0D%0A%09%09%0D%0A%09%09%0D%0A%09%09reference.append(%22e%22);%0D%0A%09%09%0D%0A%09%09%0D%0A%09%09%0D%0A%09%09assertEquals(str2buf(reference.toString()), out);%0D%0A%09%7D%0D
 %0A%0D%0A%7D%0D%0A

test bencoding key sorting correctness for whole 0x00 - 0xff range