utf8.js 1003 B

123456789101112131415161718192021
  1. try { module.exports = {dec:utf8_dec,enc:utf8_toByteArray}; } catch (e) { }
  2. // N4U UTF-8 Support
  3. function utf8_toByteArray(str) {
  4. var byteArray = [];
  5. if (str !== undefined && str !== null)
  6. for (var i = 0; i < str.length; i++)
  7. if (str.charCodeAt(i) <= 0x7F) byteArray.push(str.charCodeAt(i));
  8. else {
  9. var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
  10. for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)); }
  11. return {t:107,v:byteArray}; };
  12. function utf8_dec(ab) {
  13. if (!(ab instanceof ArrayBuffer)) ab = new Uint8Array(utf8_toByteArray(ab).v).buffer;
  14. var t=new DataView(ab),i=c=c1=c2=0,itoa=String.fromCharCode,s=[]; while (i<t.byteLength ) {
  15. c=t.getUint8(i); if (c<128) { s+=itoa(c); i++; } else
  16. if ((c>191) && (c<224)) { c2=t.getUint8(i+1); s+=itoa(((c&31)<<6)|(c2&63)); i+=2; }
  17. else { c2=t.getUint8(i+1); c3=t.getUint8(i+2); s+=itoa(((c&15)<<12)|((c2&63)<<6)|(c3&63));
  18. i+=3; } } return s; }