From 695d21f8512597a86b97563dae73fc2f707b678b Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Tue, 15 Oct 2024 00:47:14 +0300 Subject: [PATCH] add item getter with type check to BList, just as in BDict --- .../mykola2312/retracker/bencode/BList.java | 12 +++++++++ .../retracker/bencode/BListTest.java | 26 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/main/java/com/mykola2312/retracker/bencode/BList.java b/src/main/java/com/mykola2312/retracker/bencode/BList.java index 2387349..51cf97b 100644 --- a/src/main/java/com/mykola2312/retracker/bencode/BList.java +++ b/src/main/java/com/mykola2312/retracker/bencode/BList.java @@ -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 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; diff --git a/src/test/java/com/mykola2312/retracker/bencode/BListTest.java b/src/test/java/com/mykola2312/retracker/bencode/BListTest.java index 3fb2117..dd24707 100644 --- a/src/test/java/com/mykola2312/retracker/bencode/BListTest.java +++ b/src/test/java/com/mykola2312/retracker/bencode/BListTest.java @@ -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); + }); + } }