diff --git a/docs/arraybuffer.md b/docs/arraybuffer.md index cf883c3..fbf8bb4 100644 --- a/docs/arraybuffer.md +++ b/docs/arraybuffer.md @@ -448,34 +448,40 @@ Float64Array.BYTES_PER_ELEMENT // 8 ### ArrayBuffer 与字符串的互相转换 -`ArrayBuffer`转为字符串,或者字符串转为`ArrayBuffer`,有一个前提,即字符串的编码方法是确定的。假定字符串采用 UTF-16 编码(JavaScript 的内部编码方式),可以自己编写转换函数。 +`ArrayBuffer` 和字符串相互转换, 使用原生 `TextEncoder` `TextDecoder` 类方法转换任何字符集字符串 +outputEncoding 输出编码一般保持默认值(utf-8),可选值见文档: +- https://encoding.spec.whatwg.org +- https://nodejs.org/api/util.html#util_whatwg_supported_encodings -```javascript -// ArrayBuffer 转为字符串,参数为 ArrayBuffer 对象 -function ab2str(buf) { - // 注意,如果是大型二进制数组,为了避免溢出, - // 必须一个一个字符地转 - if (buf && buf.byteLength < 1024) { - return String.fromCharCode.apply(null, new Uint16Array(buf)); - } - - const bufView = new Uint16Array(buf); - const len = bufView.length; - const bstr = new Array(len); - for (let i = 0; i < len; i++) { - bstr[i] = String.fromCharCode.call(null, bufView[i]); - } - return bstr.join(''); +```ts +/** + * Convert ArrayBuffer/TypedArray to String via TextDecoder + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder + */ +function ab2str( + input: ArrayBuffer | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array, + outputEncoding: string = 'utf8', +): string { + const decoder = new TextDecoder(outputEncoding) + return decoder.decode(input) } -// 字符串转为 ArrayBuffer 对象,参数为字符串 -function str2ab(str) { - const buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节 - const bufView = new Uint16Array(buf); - for (let i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); - } - return buf; +/** + * Convert String to ArrayBuffer via TextEncoder + * + * @see https://developer.mozilla.org/zh-CN/docs/Web/API/TextEncoder + */ +function str2ab(input: string): ArrayBuffer { + const view = str2Uint8Array(input) + return view.buffer +} + +/** Convert String to Uint8Array */ +function str2Uint8Array(input: string): Uint8Array { + const encoder = new TextEncoder() + const view = encoder.encode(input) + return view } ```