Merge pull request #4153 from ZhonglinGui/v5-dev

修复StrUtil.str(ByteBuffer, Charset) 方法修改入参 ByteBuffer 的 position,导致入参变化
This commit is contained in:
Golden Looly 2025-11-25 18:52:00 +08:00 committed by GitHub
commit a8cc614fa6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 1 deletions

View File

@ -261,7 +261,7 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
if (null == charset) {
charset = Charset.defaultCharset();
}
return charset.decode(data).toString();
return charset.decode(data.duplicate()).toString();
}
/**

View File

@ -1,6 +1,7 @@
package cn.hutool.core.io;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
@ -63,4 +64,21 @@ public class BufferUtilTest {
// 读取剩余部分
assertEquals("cc", StrUtil.utf8Str(BufferUtil.readBytes(buffer)));
}
@Test
public void testByteBufferSideEffect() {
String originalText = "Hello";
ByteBuffer buffer = ByteBuffer.wrap(originalText.getBytes(StandardCharsets.UTF_8));
// 此时 buffer.remaining() == 5
assertEquals(5, buffer.remaining());
// 调用工具类转换打印buffer内容
String result = StrUtil.str(buffer, StandardCharsets.UTF_8);
assertEquals(originalText, result);
// 预期
// 工具类不应该修改原 buffer 的指针remaining 应该依然为 5
// 再次调用工具类转换输出结果应该不变
assertEquals(originalText, StrUtil.str(buffer, StandardCharsets.UTF_8));
}
}