avoid converting CharSequence to String to save memory

This commit is contained in:
Alexey Kudravtsev
2018-10-02 14:00:01 +03:00
parent 7722e61379
commit 92e6112ba4
2 changed files with 26 additions and 2 deletions
@@ -2024,13 +2024,25 @@ public class StringUtil extends StringUtilRt {
@NotNull
@Contract(pure = true)
public static CharSequence first(@NotNull CharSequence text, final int length, final boolean appendEllipsis) {
return text.length() > length ? text.subSequence(0, length) + (appendEllipsis ? "..." : "") : text;
if (text.length() <= length) {
return text;
}
if (appendEllipsis) {
return text.subSequence(0, length) + "...";
}
return text.subSequence(0, length);
}
@NotNull
@Contract(pure = true)
public static CharSequence last(@NotNull CharSequence text, final int length, boolean prependEllipsis) {
return text.length() > length ? (prependEllipsis ? "..." : "") + text.subSequence(text.length() - length, text.length()) : text;
if (text.length() <= length) {
return text;
}
if (prependEllipsis) {
return "..." + text.subSequence(text.length() - length, text.length());
}
return text.subSequence(text.length() - length, text.length());
}
@NotNull
@@ -743,4 +743,16 @@ public class StringUtilTest {
assertEquals(LineColumn.of(2, 1), StringUtil.offsetToLineColumn("abc\n\nabc", 6));
assertEquals(LineColumn.of(1, 1), StringUtil.offsetToLineColumn("abc\r\nabc", 6));
}
@Test
public void testFirstLastDontConvertCharSequenceToString() {
CharSequence s = ByteArrayCharSequence.convertToBytesIfAsciiString("test");
assertTrue(s instanceof ByteArrayCharSequence);
CharSequence first = StringUtil.first(s, 1, false);
assertTrue(String.valueOf(first.getClass()), first instanceof CharSequenceSubSequence);
assertEquals("t", first.toString());
CharSequence last = StringUtil.last(s, 1, false);
assertTrue(String.valueOf(last.getClass()), last instanceof CharSequenceSubSequence);
assertEquals("t", last.toString());
}
}