add item getter with type check to BList, just as in BDict

This commit is contained in:
mykola2312 2024-10-15 00:47:14 +03:00
parent 09f0e7dcee
commit 695d21f851
2 changed files with 38 additions and 0 deletions

View file

@ -2,6 +2,8 @@ package com.mykola2312.retracker.bencode;
import java.util.Iterator;
import com.mykola2312.retracker.bencode.error.BErrorValueCast;
public class BList extends BValue {
private BValue last = null;
private int length = 0;
@ -65,6 +67,16 @@ public class BList extends BValue {
return it.next();
}
@SuppressWarnings("unchecked")
public <T extends BValue> T get(BType type, int index) throws IndexOutOfBoundsException, BErrorValueCast {
BValue value = get(index);
if (!value.getType().equals(type)) {
throw new BErrorValueCast(this, Integer.toString(index), type, value.getType());
}
return (T)value;
}
public BValue find(BValue key) {
if (getLength() == 0) {
return null;

View file

@ -1,5 +1,6 @@
package com.mykola2312.retracker.bencode;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@ -9,6 +10,8 @@ import java.util.Iterator;
import org.junit.jupiter.api.Test;
import com.mykola2312.retracker.bencode.error.BErrorValueCast;
public class BListTest {
@Test
public void testEmptyList() {
@ -64,4 +67,27 @@ public class BListTest {
assertNotNull(list.find(new BInteger(2)));
assertNull(list.find(new BInteger(3)));
}
@Test
public void testGet() throws IndexOutOfBoundsException, BErrorValueCast {
BList list = new BList();
list.append(new BInteger(1));
assertDoesNotThrow(() -> {
BInteger value = list.get(BType.INTEGER, 0);
assertNotNull(value);
assertEquals(value, new BInteger(1));
});
}
@Test
public void testGetWrongCast() throws IndexOutOfBoundsException, BErrorValueCast {
BList list = new BList();
list.append(new BInteger(1));
assertThrows(BErrorValueCast.class, () -> {
BString wrong = list.get(BType.STRING, 0);
});
}
}