LANG-1287: RandomStringUtils#random can enter infinite loop if end parameter is to small (closes #211)

1.) Fixed possible infinite loop that can be caused by generating either digits or letters by calling with a to low end param.

2.) Added (inclusive) and (exclusive) terms to javadoc of random method
This commit is contained in:
Ivan Morozov 2016-11-15 11:49:11 +01:00 committed by pascalschumacher
parent b0bcf4f60a
commit 695342cb1c
2 changed files with 21 additions and 2 deletions

View File

@ -327,8 +327,8 @@ public static String random(final int count, final int start, final int end, fin
* and predictably.</p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param start the position in set of chars to start at (inclusive)
* @param end the position in set of chars to end before (exclusive)
* @param letters only allow letters?
* @param numbers only allow numbers?
* @param chars the set of chars to choose randoms from, must not be empty.
@ -368,6 +368,17 @@ public static String random(int count, int start, int end, final boolean letters
}
}
final int zero_digit_ascii = 48;
final int first_letter_ascii = 65;
if (chars == null) {
if (numbers && end <= zero_digit_ascii
|| letters && end <= first_letter_ascii) {
throw new IllegalArgumentException("Parameter end (" + end + ") must be greater then (" + zero_digit_ascii + ") for generating digits " +
"or greater then (" + first_letter_ascii + ") for generating letters.");
}
}
final char[] buffer = new char[count];
final int gap = end - start;

View File

@ -206,6 +206,14 @@ public void testExceptions() {
RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random());
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(8, 32, 48, false, true);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(8, 32, 65, true, false);
fail();
} catch (final IllegalArgumentException ex) {}
}
/**