utf16.js 712 B

12345678910111213141516171819
  1. import { toArrayBuffer } from "../bytes/index.js";
  2. export function encode(text, options = {}) {
  3. const result = new ArrayBuffer(text.length * 2);
  4. const view = new DataView(result);
  5. for (let i = 0; i < text.length; i++) {
  6. view.setUint16(i * 2, text.charCodeAt(i), options.littleEndian ?? false);
  7. }
  8. return new Uint8Array(result);
  9. }
  10. export function decode(data, options = {}) {
  11. const buffer = toArrayBuffer(data);
  12. const view = new DataView(buffer);
  13. let result = "";
  14. for (let i = 0; i < buffer.byteLength; i += 2) {
  15. result += String.fromCharCode(view.getUint16(i, options.littleEndian ?? false));
  16. }
  17. return result;
  18. }
  19. export const utf16 = { encode, decode };