From 88e81d7c6773e027a64871c1cd3ae77298dde084 Mon Sep 17 00:00:00 2001 From: Havoc Pennington <hp@pobox.com> Date: Thu, 17 Nov 2011 12:08:27 -0500 Subject: [PATCH] add Path.parent() and Path.last() methods Neither is very efficient, but we'll live. --- .../java/com/typesafe/config/impl/Path.java | 33 +++++++++++++++++++ .../com/typesafe/config/impl/PathTest.scala | 13 ++++++++ 2 files changed, 46 insertions(+) diff --git a/src/main/java/com/typesafe/config/impl/Path.java b/src/main/java/com/typesafe/config/impl/Path.java index 6d77979e..cf6d959f 100644 --- a/src/main/java/com/typesafe/config/impl/Path.java +++ b/src/main/java/com/typesafe/config/impl/Path.java @@ -53,10 +53,43 @@ final class Path { return first; } + /** + * + * @return path minus the first element or null if no more elements + */ Path remainder() { return remainder; } + /** + * + * @return path minus the last element or null if we have just one element + */ + Path parent() { + if (remainder == null) + return null; + + PathBuilder pb = new PathBuilder(); + Path p = this; + while (p.remainder != null) { + pb.appendKey(p.first); + p = p.remainder; + } + return pb.result(); + } + + /** + * + * @return last element in the path + */ + String last() { + Path p = this; + while (p.remainder != null) { + p = p.remainder; + } + return p.first; + } + Path prepend(Path toPrepend) { PathBuilder pb = new PathBuilder(); pb.appendPath(toPrepend); diff --git a/src/test/scala/com/typesafe/config/impl/PathTest.scala b/src/test/scala/com/typesafe/config/impl/PathTest.scala index d9eba8a6..ee9a5ffb 100644 --- a/src/test/scala/com/typesafe/config/impl/PathTest.scala +++ b/src/test/scala/com/typesafe/config/impl/PathTest.scala @@ -64,6 +64,19 @@ class PathTest extends TestUtils { assertEquals(2, path("foo", "bar").length()) } + @Test + def pathParent() { + assertNull(path("a").parent()) + assertEquals(path("a"), path("a", "b").parent()) + assertEquals(path("a", "b"), path("a", "b", "c").parent()) + } + + @Test + def pathLast() { + assertEquals("a", path("a").last()) + assertEquals("b", path("a", "b").last()) + } + @Test def pathsAreInvalid() { // this test is just of the Path.newPath() wrapper, the extensive