Skip to content

Instantly share code, notes, and snippets.

@DHager
Created April 5, 2011 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DHager/902963 to your computer and use it in GitHub Desktop.
Save DHager/902963 to your computer and use it in GitHub Desktop.
Problem with simple String lists in Preon
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import org.codehaus.preon.Codec;
import org.codehaus.preon.Codecs;
import org.codehaus.preon.DecodingException;
import org.codehaus.preon.annotation.BoundList;
import org.codehaus.preon.annotation.BoundNumber;
import org.codehaus.preon.annotation.BoundString;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
/**
*
* @author Darien Hager
*/
public class StringArrayTest {
private static interface TestStruct{
public List<String> getStrings();
}
public static class Alpha implements TestStruct{
@BoundNumber
public int numStrings;
@BoundList(size = "numStrings", type = String.class)
public List<String> items;
public List<String> getStrings() {
return items;
}
}
public static class Beta implements TestStruct{
@BoundNumber
public int numStrings;
@BoundList(size = "numStrings", type = String.class)
@BoundString()
public List<String> items;
public List<String> getStrings() {
return items;
}
}
private String[] strings = new String[]{"hello", "world"};
private byte[] bytes = assembleBytes(strings);
public static byte[] assembleBytes(String... strings) {
LinkedList<Byte> list = new LinkedList<Byte>();
for (String s : strings) {
for (byte b : s.getBytes(Charset.forName("US-ASCII"))) {
list.add(b);
}
list.add(new Byte((byte) 0x00));
}
list.push((byte) strings.length);
byte[] ret = new byte[list.size()];
int i = 0;
for (Byte b : list) {
ret[i] = b.byteValue();
i++;
}
return ret;
}
protected void tryCodec(Class<?> target) throws DecodingException {
// Try the same test with different classes
Codec c = Codecs.create(target);
Codecs.decode(c, this.bytes);
}
@Test
public void testAlpha() throws DecodingException{
tryCodec(Alpha.class);
}
@Test
public void testBeta() throws DecodingException{
tryCodec(Beta.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment