HDPath: add .parent() method

This commit is contained in:
Sean Gilligan 2022-04-16 16:59:30 -07:00 committed by Andreas Schildbach
parent 459df5fed0
commit 5367df8a7c
2 changed files with 32 additions and 0 deletions

View file

@ -40,6 +40,8 @@ import java.util.stream.Stream;
* where necessary in your code. Although it is recommended to use the {@code HDPath} type for clarity and for
* access to {@code HDPath}-specific functionality.
* <p>
* Note that it is possible for {@code HDPath} to be an empty list.
* <p>
* Take note of the overloaded factory methods {@link HDPath#M()} and {@link HDPath#m()}. These can be used to very
* concisely create HDPath objects (especially when statically imported.)
*/
@ -247,6 +249,21 @@ public class HDPath extends AbstractList<ChildNumber> {
return unmodifiableList;
}
/**
* Return the parent path.
* <p>
* Note that this method defines the parent of a root path as the empty path and the parent
* of the empty path as the empty path. This behavior is what one would expect
* of an unmodifiable, copy-on-modify list. If you need to check for edge cases, you can use
* {@link HDPath#isEmpty()} before or after using {@code HDPath#parent()}
* @return parent path (which can be empty -- see above)
*/
public HDPath parent() {
return unmodifiableList.size() > 1 ?
HDPath.of(hasPrivateKey, unmodifiableList.subList(0, unmodifiableList.size() - 1)) :
HDPath.of(hasPrivateKey, Collections.emptyList());
}
/**
* Return a list of all ancestors of this path
* @return unmodifiable list of ancestors

View file

@ -58,6 +58,21 @@ public class HDPathTest {
assertEquals("m/0H/1H/0H/1/0", path5.toString());
}
@Test
public void testParent() {
HDPath path1 = HDPath.parsePath("m/0H/1H");
assertEquals(HDPath.parsePath("m/0H"), path1.parent());
HDPath path2 = HDPath.parsePath("m/0H");
assertEquals(HDPath.parsePath(""), path2.parent());
HDPath path3 = HDPath.parsePath("");
assertEquals(HDPath.parsePath(""), path3.parent());
}
@Test
public void testAncestors() {
HDPath path = HDPath.parsePath("m/0H/1H/0H/1/0");