From ee8b20097db019648c75fcc51a5f9c295402aab4 Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Sun, 13 Oct 2024 10:08:10 +0300 Subject: [PATCH] working on bencode lists, test covering --- .../mykola2312/retracker/bencode/BList.java | 62 +++++++++++++++++++ .../retracker/bencode/BListTest.java | 16 +++++ 2 files changed, 78 insertions(+) create mode 100644 src/main/java/com/mykola2312/retracker/bencode/BList.java create mode 100644 src/test/java/com/mykola2312/retracker/bencode/BListTest.java diff --git a/src/main/java/com/mykola2312/retracker/bencode/BList.java b/src/main/java/com/mykola2312/retracker/bencode/BList.java new file mode 100644 index 0000000..8cf8b49 --- /dev/null +++ b/src/main/java/com/mykola2312/retracker/bencode/BList.java @@ -0,0 +1,62 @@ +package com.mykola2312.retracker.bencode; + +import java.util.Iterator; + +public class BList extends BValue { + private BValue last = null; + private int length = 0; + + @Override() + public BType getType() { + return BType.LIST; + } + + protected BValue getFirst() { + return getChild(); + } + + protected void setFirst(BValue first) { + setChild(first); + } + + protected BValue getLast() { + return last; + } + + protected void setLast(BValue last) { + this.last = last; + } + + // builder + public BList append(BValue item) { + BValue first = getFirst(); + if (first == null) { + setFirst(item); + setLast(item); + } else { + BValue last = getLast(); + last.setNext(item); + setLast(item); + } + + length++; + return this; + } + + public int getLength() { + return length; + } + + public BValue get(int index) throws IndexOutOfBoundsException { + Iterator it = iterator(); + if (index < 0 || index >= length) { + throw new IndexOutOfBoundsException(); + } + + while (--index > 0) { + it.next(); + } + + return it.next(); + } +} diff --git a/src/test/java/com/mykola2312/retracker/bencode/BListTest.java b/src/test/java/com/mykola2312/retracker/bencode/BListTest.java new file mode 100644 index 0000000..a261e74 --- /dev/null +++ b/src/test/java/com/mykola2312/retracker/bencode/BListTest.java @@ -0,0 +1,16 @@ +package com.mykola2312.retracker.bencode; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +public class BListTest { + @Test + public void testEmptyList() { + BList empty = new BList(); + + assertEquals(0, empty.getLength()); + assertNull(empty.getChild()); + } +}