utf16le.js 732 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. function byteLength (string) {
  2. return string.length * 2
  3. }
  4. function toString (buffer) {
  5. const len = buffer.byteLength
  6. let result = ''
  7. for (let i = 0; i < len - 1; i += 2) {
  8. result += String.fromCharCode(buffer[i] + (buffer[i + 1] * 256))
  9. }
  10. return result
  11. }
  12. function write (buffer, string, offset = 0, length = byteLength(string)) {
  13. const len = Math.min(length, buffer.byteLength - offset)
  14. let units = len
  15. for (let i = 0; i < string.length; ++i) {
  16. if ((units -= 2) < 0) break
  17. const c = string.charCodeAt(i)
  18. const hi = c >> 8
  19. const lo = c % 256
  20. buffer[offset + i * 2] = lo
  21. buffer[offset + i * 2 + 1] = hi
  22. }
  23. return len
  24. }
  25. module.exports = {
  26. byteLength,
  27. toString,
  28. write
  29. }