mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-12-08 01:59:14 +08:00
修复StrUtil.str(ByteBuffer, Charset) 方法修改入参 ByteBuffer 的 position,导致入参变化
This commit is contained in:
parent
7bd0585a39
commit
28f267c5a7
@ -228,7 +228,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();
|
||||
}
|
||||
// endregion
|
||||
|
||||
|
||||
@ -22,6 +22,8 @@ import cn.hutool.v7.core.util.RandomUtil;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@ -654,4 +656,21 @@ public class StrUtilTest {
|
||||
|
||||
assertEquals("start12middle3end", concat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testByteBufferSideEffect() {
|
||||
final String originalText = "Hello";
|
||||
final ByteBuffer buffer = ByteBuffer.wrap(originalText.getBytes(StandardCharsets.UTF_8));
|
||||
// 此时 buffer.remaining() == 5
|
||||
assertEquals(5, buffer.remaining());
|
||||
|
||||
// 调用工具类转换,打印buffer内容
|
||||
final String result = StrUtil.str(buffer, StandardCharsets.UTF_8);
|
||||
assertEquals(originalText, result);
|
||||
|
||||
// 预期:
|
||||
// 工具类不应该修改原 buffer 的指针,remaining 应该依然为 5
|
||||
// 再次调用工具类转换,输出结果应该不变
|
||||
assertEquals(originalText, StrUtil.str(buffer, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user