Skip to content

Commit

Permalink
Merge pull request #527 from scireum/feature/mko/SIRI-960-4
Browse files Browse the repository at this point in the history
Strings.limit - Fixes IndexOutOfBoundsException for length values lesser than 1
  • Loading branch information
mko-sci authored May 22, 2024
2 parents b7c851c + 7c0623d commit 8f606fe
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/main/java/sirius/kernel/commons/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -375,13 +375,13 @@ public static String limit(@Nullable Object input, int length) {
* Limits the length of the given string to the given length.
*
* @param input the object which string representation should be limited to the given length
* @param length the max. number of characters to return
* @param length the max. number of characters to return. Note: If the parameter is less than 1 an empty string is returned.
* @param showEllipsis whether to append three dots if <tt>input</tt> is longer than <tt>length</tt>
* @return a part of the string representation of the given <tt>input</tt>. If input is shorter
* than <tt>length</tt>, the full value is returned. If input is <tt>null</tt>, "" is returned.
* than <tt>length</tt>, the full value is returned. If input is <tt>null</tt> or empty, "" is returned. This also applies if <tt>length</tt> is less than 1.
*/
public static String limit(@Nullable Object input, int length, boolean showEllipsis) {
if (isEmpty(input)) {
if (isEmpty(input) || length <= 0) {
return "";
}
String str = String.valueOf(input).trim();
Expand Down
8 changes: 8 additions & 0 deletions src/test/kotlin/sirius/kernel/commons/StringsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -303,12 +303,20 @@ class StringsTest {
fun limit() {
assertEquals("", Strings.limit(null, 10, false))
assertEquals("", Strings.limit(null, 10, true))
assertEquals("", Strings.limit(null, -10, true))
assertEquals("", Strings.limit("", 10, false))
assertEquals("", Strings.limit("", 10, true))
assertEquals("", Strings.limit("", -10, true))
assertEquals("ABCDE", Strings.limit("ABCDE", 10, false))
assertEquals("ABCDE", Strings.limit("ABCDE", 10, true))
assertEquals("", Strings.limit("ABCDE", -10, true))
assertEquals("ABCDEFGHIJ", Strings.limit("ABCDEFGHIJKLMNOP", 10, false))
assertEquals("ABCDEFGHI…", Strings.limit("ABCDEFGHIJKLMNOP", 10, true))
assertEquals("", Strings.limit("ABCDEFGHIJKLMNOP", -10, true))
assertEquals("", Strings.limit("A", 0, true))
assertEquals("", Strings.limit("A", 0, false))
assertEquals("A", Strings.limit("A", 1, true))
assertEquals("A", Strings.limit("A", 1, false))
}

}

0 comments on commit 8f606fe

Please sign in to comment.