修复StrUtil.limitByByteLength在限制长度小于...时报错问题(issue#IDFTJS@Gitee)

This commit is contained in:
Looly
2025-12-27 13:06:11 +08:00
parent a1d0921ff8
commit c5c2f203f1
2 changed files with 13 additions and 4 deletions

View File

@@ -3600,7 +3600,7 @@ public class CharSequenceUtil extends StrValidator {
* @param charset 指定编码
* @param maxBytesLength 最大字节数
* @param factor 速算因子,取该编码下单个字符的最大可能字节数
* @param appendDots 截断后是否追加省略号(...)
* @param appendDots 截断后是否追加省略号...如果maxBytesLength小于省略号长度则不添加...
* @return 限制后的长度
*/
public static String limitByteLength(final CharSequence str, final Charset charset, final int maxBytesLength,
@@ -3614,9 +3614,11 @@ public class CharSequenceUtil extends StrValidator {
return toStringOrNull(str);
}
//限制字节数
final int dotsBytesLength = "...".getBytes(charset).length;
final int limitBytes;
if (appendDots) {
limitBytes = maxBytesLength - "...".getBytes(charset).length;
// issue#IDFTJS 修正截断后追加省略号...导致超出限制长度的问题
if (appendDots && maxBytesLength > dotsBytesLength) {
limitBytes = maxBytesLength - dotsBytesLength;
} else {
limitBytes = maxBytesLength;
}
@@ -3628,7 +3630,7 @@ public class CharSequenceUtil extends StrValidator {
decoder.decode(bb, cb, true);
decoder.flush(cb);
final String result = new String(cb.array(), 0, cb.position());
if (appendDots) {
if (appendDots && maxBytesLength > dotsBytesLength) {
return result + "...";
}
return result;

View File

@@ -544,4 +544,11 @@ public class CharSequenceUtilTest {
void concatTest() {
assertEquals("abc", CharSequenceUtil.concat(true, "a", "b", "c"));
}
@Test
public void issueTest() {
final String s = "abc";
final String r = StrUtil.limitByteLength(s, CharsetUtil.UTF_8, 2, 4, true);
assertEquals("ab", r);
}
}