Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/main/java/org/apache/commons/lang3/RandomStringUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,19 @@ public static String random(int count, int start, int end, final boolean letters
"Parameter end (" + end + ") must be greater than start (" + start + ")");
} else if (start < 0 || end < 0) {
throw new IllegalArgumentException("Character positions MUST be >= 0");
} else if (chars != null && (start >= chars.length || end > chars.length)) {
final StringBuilder errorMsg = new StringBuilder();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is all too complicated IMO, we don't gather all possible invalid inputs elsewhere in the method. Please rebase on git master, fail-fast and use String.format(), so that would end up being 2 throws.

final int charsLength = chars.length;
if (start >= charsLength) {
errorMsg.append("Parameter start (").append(start).append(") must be less than chars array length ").append(charsLength);
}
if (end > charsLength) {
if (errorMsg.length() > 0) {
errorMsg.append("; ");
}
errorMsg.append("Parameter end (").append(end).append(") must be less than or equal to chars array length ").append(charsLength);
}
throw new IllegalArgumentException(errorMsg.toString());
}

if (end > Character.MAX_CODE_POINT) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ void testExceptionsRandom() {
assertIllegalArgumentException(() -> RandomStringUtils.random(8, 32, 48, false, true));
assertIllegalArgumentException(() -> RandomStringUtils.random(8, 32, 65, true, false));
assertIllegalArgumentException(() -> RandomStringUtils.random(1, Integer.MIN_VALUE, -10, false, false, null));
assertIllegalArgumentException(() -> RandomStringUtils.random(2, 4, 5, false, false, new char[] { 'a', 'b', 'c', 'd' }, new Random()));
assertIllegalArgumentException(() -> RandomStringUtils.random(2, 1, 5, false, false, new char[] { 'a', 'b', 'c', 'd' }, new Random()));
}

@ParameterizedTest
Expand Down