Open
TextDecoder.decodeToString 字符串创建链路与 decodeWithStream 不一致,且解码结果含内嵌 U+0000 时触发 WARN 日志 #2541
jizaiyiAdd on 22 days ago
openharmony_ci
22 days ago Comments:
22 days ago Comments:
感谢提交Issue!关于Issue的交互操作,请访问OpenHarmony社区支持命令清单。如果有问题,请联系 [@weng-changcheng](https://gitcode.com/weng-changcheng) [@xliu-huanwei](https://gitcode.com/xliu-huanwei) [@gong_19901](https://gitcode.com/gong_19901) 。如果需要调整订阅PR、Issue的变更状态,请访问链接。
Thanks for submitting the issue. For more commands, please visit OpenHarmony Command List. If you have any questions, please refer to committer gitcode for help. If you need to change the subscription of a Pull Request or Issue, please visit the link.


22 days ago Added label: waiting_for_assign
22 days ago Associated pull request
问题描述
util.TextDecoder两个解码接口的结果字符串创建链路不一致:decodeWithStream→TextDecoder::Decode→ConvertToString()(UTF-16→UTF-8)→napi_create_string_utf8decodeToString→TextDecoder::DecodeToString→GetResultStr():纯 ASCII 压缩快路径已用napi_create_string_utf8,非 ASCII 兜底路径仍用napi_create_string_utf16(js_textdecoder.cpp)兜底路径使用
napi_create_string_utf16的问题:napi_create_string_utf16需引擎再做一次 UTF-16→UTF-8 转换,且入口处多一次char16 strlen全量扫描。GetResultStr传入的显式长度与引擎侧char16 strlen不一致,每次调用都会触发 ArkVMnapi_create_string_utf16的 HILOG_WARN("length not equals to strlen(str)")。复现步骤
import util from '@ohos.util'; const dec = util.TextDecoder.create('utf-8'); // 解码结果为 "a\u0000b"(3 个码元,第二个为 U+0000) const ret = dec.decodeToString(new Uint8Array([0x61, 0x00, 0x62]));每次调用 hilog 均输出一条 WARN。
预期行为
decodeToString 与 decodeWithStream 统一通过
napi_create_string_utf8创建结果字符串;对外行为完全不变(内嵌 U+0000 保留、BOM 处理、fatal/ignoreBOM 选项、流式模式均保持现状)。实际行为
非 ASCII 兜底路径使用
napi_create_string_utf16;结果含 U+0000 时触发 WARN 日志,且引擎侧存在冗余 UTF-16→UTF-8 转换与 strlen 扫描。修复思路
GetResultStr兜底路径改为按长度做 UTF-16→UTF-8 转换(std::u16string(ptr, len)+codecvt_utf8_utf16,与ConvertToString同一方案,但按显式长度构造以保留内嵌 U+0000),再调用napi_create_string_utf8。同步补充非 ASCII("你好")与内嵌 U+0000 的 UT 用例看护。验证
test_util_unittest495 用例,改动前后 A/B 逐例对比结果完全一致(新增 2 条用例在两版均通过,锁定行为不变);js_textdecoder.cpp无新增编译告警。环境信息