utf16.native.js 1012 B

12345678910111213141516171819202122
  1. import { encodeApi, decodeApiDecoders, decodeApiJS } from './fallback/utf16.js'
  2. import { nativeDecoder } from './fallback/platform.native.js'
  3. function checkDecoders() {
  4. // Not all barebone engines with TextDecoder support something except utf-8
  5. // Also workerd specifically has a broken utf-16le implementation
  6. if (!nativeDecoder) return false
  7. try {
  8. const a = new TextDecoder('utf-16le').decode(Uint8Array.of(1, 2, 3, 0xd8))
  9. const b = new TextDecoder('utf-16be').decode(Uint8Array.of(2, 1, 0xd8, 3))
  10. return a === b && a === '\u0201\uFFFD'
  11. } catch {}
  12. return false
  13. }
  14. const decode = checkDecoders() ? decodeApiDecoders : decodeApiJS
  15. export const utf16fromString = (str, format = 'uint16') => encodeApi(str, false, format)
  16. export const utf16fromStringLoose = (str, format = 'uint16') => encodeApi(str, true, format)
  17. export const utf16toString = (arr, format = 'uint16') => decode(arr, false, format)
  18. export const utf16toStringLoose = (arr, format = 'uint16') => decode(arr, true, format)