Map keys must be unique.

This commit is contained in:
akwizgran
2011-09-07 11:04:03 +01:00
parent 478a22c8db
commit e80ede4429
2 changed files with 25 additions and 2 deletions

View File

@@ -497,7 +497,10 @@ class ReaderImpl implements Reader {
return readMap(k, v, readLength());
} else if(next == Tag.MAP_START) {
Map<K, V> m = new HashMap<K, V>();
while(!hasEnd()) m.put(readObject(k), readObject(v));
while(!hasEnd()) {
if(m.put(readObject(k), readObject(v)) != null)
throw new FormatException(); // Duplicate key
}
readEnd();
return m;
} else {
@@ -511,7 +514,10 @@ class ReaderImpl implements Reader {
assert size >= 0;
if(size == 0) return Collections.emptyMap();
Map<K, V> m = new HashMap<K, V>();
for(int i = 0; i < size; i++) m.put(readObject(k), readObject(v));
for(int i = 0; i < size; i++) {
if(m.put(readObject(k), readObject(v)) != null)
throw new FormatException(); // Duplicate key
}
return m;
}

View File

@@ -248,6 +248,23 @@ public class ReaderImplTest extends TestCase {
assertTrue(r.eof());
}
@Test
public void testMapKeysMustBeUnique() throws Exception {
setContents("B" + "2" + "83666F6F" + "01" + "83626172" + "02" +
"B" + "2" + "83666F6F" + "01" + "83666F6F" + "02");
// The first map has unique keys
Map<String, Byte> m = r.readMap(String.class, Byte.class);
assertNotNull(m);
assertEquals(2, m.size());
assertEquals(Byte.valueOf((byte) 1), m.get("foo"));
assertEquals(Byte.valueOf((byte) 2), m.get("bar"));
// The second map has a duplicate key
try {
r.readMap(String.class, Byte.class);
fail();
} catch(FormatException expected) {}
}
@Test
public void testReadDelimitedList() throws Exception {
setContents("F3" + "01" + "83666F6F" + "FC0080" + "F1");