From 4351e7a1a1b364895ec49e4cd140fa4fc9611f65 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Sun, 19 Jul 2009 19:30:40 +0000 Subject: [PATCH] Applying Arnaud Brunet's patch from LANG-355 to make StrBuilder implement CharSequence git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@795600 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/commons/lang/text/StrBuilder.java | 18 +++++++++- .../commons/lang/text/StrBuilderTest.java | 33 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/java/org/apache/commons/lang/text/StrBuilder.java b/src/java/org/apache/commons/lang/text/StrBuilder.java index 263f52c3a..79cffa79a 100644 --- a/src/java/org/apache/commons/lang/text/StrBuilder.java +++ b/src/java/org/apache/commons/lang/text/StrBuilder.java @@ -71,7 +71,7 @@ * @since 2.2 * @version $Id$ */ -public class StrBuilder { +public class StrBuilder implements CharSequence { /** * The extra capacity for new builders. @@ -1917,6 +1917,22 @@ public boolean endsWith(String str) { } //----------------------------------------------------------------------- + /** + * {@inheritDoc} + */ + public CharSequence subSequence(int startIndex, int endIndex) { + if (startIndex < 0) { + throw new StringIndexOutOfBoundsException(startIndex); + } + if (endIndex > size) { + throw new StringIndexOutOfBoundsException(endIndex); + } + if (startIndex > endIndex) { + throw new StringIndexOutOfBoundsException(endIndex - startIndex); + } + return substring(startIndex, endIndex); + } + /** * Extracts a portion of this string builder as a string. * diff --git a/src/test/org/apache/commons/lang/text/StrBuilderTest.java b/src/test/org/apache/commons/lang/text/StrBuilderTest.java index 39d7c96ee..cdb304aab 100644 --- a/src/test/org/apache/commons/lang/text/StrBuilderTest.java +++ b/src/test/org/apache/commons/lang/text/StrBuilderTest.java @@ -1099,6 +1099,39 @@ public void testEndsWith() { } //----------------------------------------------------------------------- + public void testSubSequenceIntInt() { + StrBuilder sb = new StrBuilder ("hello goodbye"); + // Start index is negative + try { + sb.subSequence(-1, 5); + fail(); + } catch (IndexOutOfBoundsException e) {} + + // End index is negative + try { + sb.subSequence(2, -1); + fail(); + } catch (IndexOutOfBoundsException e) {} + + // End index greater than length() + try { + sb.subSequence(2, sb.length() + 1); + fail(); + } catch (IndexOutOfBoundsException e) {} + + // Start index greater then end index + try { + sb.subSequence(3, 2); + fail(); + } catch (IndexOutOfBoundsException e) {} + + // Normal cases + assertEquals ("hello", sb.subSequence(0, 5)); + assertEquals ("hello goodbye".subSequence(0, 6), sb.subSequence(0, 6)); + assertEquals ("goodbye", sb.subSequence(6, 13)); + assertEquals ("hello goodbye".subSequence(6,13), sb.subSequence(6, 13)); + } + public void testSubstringInt() { StrBuilder sb = new StrBuilder ("hello goodbye"); assertEquals ("goodbye", sb.substring(6));