Skip to content

Commit 53dc633

Browse files
committed
Streamline StringUtils.truncate(String, int, int)
1 parent 951e81d commit 53dc633

File tree

2 files changed

+5
-8
lines changed

2 files changed

+5
-8
lines changed

src/changes/changes.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ The <action> type attribute can be add,update,fix,remove.
8484
<action type="fix" dev="ggregory" due-to="Gary Gregory">Speedup CharSequenceUtils.toCharArray(CharSequence) for StringBuilder input: 160-205% improvement (2-3x faster), see CharSequenceUtilsBenchmark.</action>
8585
<action type="fix" dev="ggregory" due-to="Gary Gregory">Speedup CharSequenceUtils.toCharArray(CharSequence) for StringBuffer input: 300-4,250% improvement (4-44x faster), see CharSequenceUtilsBenchmark.</action>
8686
<action type="fix" dev="ggregory" due-to="Gary Gregory">Speedup CharSequenceUtils.toCharArray(CharSequence) for String input: ~1-2% improvement (essentially identical).</action>
87+
<action type="fix" dev="ggregory" due-to="Gary Gregory">Streamline StringUtils.truncate(String, int, int).</action>
8788
<!-- ADD -->
8889
<!-- UPDATE -->
8990
<action type="update" dev="ggregory" due-to="Gary Gregory, Dependabot">Bump org.apache.commons:commons-parent from 92 to 93 #1498.</action>

src/main/java/org/apache/commons/lang3/StringUtils.java

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8876,14 +8876,10 @@ public static String truncate(final String str, final int offset, final int maxW
88768876
if (str == null) {
88778877
return null;
88788878
}
8879-
if (offset > str.length()) {
8880-
return EMPTY;
8881-
}
8882-
if (str.length() > maxWidth) {
8883-
final int ix = Math.min(offset + maxWidth, str.length());
8884-
return str.substring(offset, ix);
8885-
}
8886-
return str.substring(offset);
8879+
final int len = str.length();
8880+
final int start = Math.min(offset, len);
8881+
final int end = offset > len - maxWidth ? len : offset + maxWidth;
8882+
return str.substring(start, Math.min(end, len));
88878883
}
88888884

88898885
/**

0 commit comments

Comments
 (0)