utf8.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // -------------------------------------------------
  2. // ------------------ UTF8 Helpers -----------------
  3. // -------------------------------------------------
  4. "use strict";
  5. var UTF8 = {};
  6. /** @constructor */
  7. function UTF8StreamToUnicode() {
  8. this.stream = new Uint8Array(5);
  9. this.ofs = 0;
  10. this.Put = function(key) {
  11. this.stream[this.ofs] = key;
  12. this.ofs++;
  13. switch(this.ofs) {
  14. case 1:
  15. if (this.stream[0] < 128) {
  16. this.ofs = 0;
  17. return this.stream[0];
  18. }
  19. break;
  20. case 2:
  21. if ((this.stream[0]&0xE0) == 0xC0)
  22. if ((this.stream[1]&0xC0) == 0x80) {
  23. this.ofs = 0;
  24. return ((this.stream[0]&0x1F)<<6) | (this.stream[1]&0x3F);
  25. }
  26. break;
  27. case 3:
  28. break;
  29. case 4:
  30. break;
  31. default:
  32. return -1;
  33. //this.ofs = 0;
  34. //break;
  35. }
  36. return -1;
  37. };
  38. }
  39. function UnicodeToUTF8Stream(key)
  40. {
  41. if (key < 0x80) return [key];
  42. if (key < 0x800) return [0xC0|((key>>6)&0x1F), 0x80|(key&0x3F)];
  43. }
  44. UTF8.UTF8Length = function(s)
  45. {
  46. var length = 0;
  47. for(var i=0; i<s.length; i++) {
  48. var c = s.charCodeAt(i);
  49. length += c<128?1:2;
  50. }
  51. return length;
  52. };