DIV CSS 佈局教程網

JavaScript 前端實作二進位讀寫:TinyStream 字節流封裝
編輯:關於JavaScript     

瀏覽器受限於安全模型,無法像 Node.js 那樣直接操作二進位資料流。但實際專案裡經常需要處理二進位:解析 WebSocket 傳來的封包、與自訂協定溝通、處理 MQTT 訊息等等。為此可以自己做一個輕量的字節流工具。

以下這個名為 TinyStream 的類別用 UMD 模式封裝,同時支援 CommonJS、AMD 與瀏覽器全域三種載入方式,內部以陣列儲存字節,並提供 UTF-8 編碼、各型別讀寫與 ArrayBuffer 轉換。

!function (entrance) {
  "use strict";
  if ("object" === typeof exports && "undefined" !== typeof module) {
    module.exports = entrance();
  } else if ("function" === typeof define && define.amd) {
    define([], entrance());
  } else {
    var f;
    if ("undefined" !== typeof window) { f = window; }
    else { throw new Error('wrong execution environment'); }
    f.TinyStream = entrance();
  }
}(function () {
  var binaryPot = {
    /**
     * 初始化字節流:把 -128~128 的區間轉為 0~255,便於計算
     * @param {Array} array 字節流陣列
     * @return {Array}
     */
    init: function (array) {
      for (var i = 0; i < array.length; i++) {
        array[i] *= 1;
        if (array[i] < 0)   array[i] += 256;
        if (array[i] > 255) throw new Error('不合法字節流');
      }
      return array;
    },

    /**
     * 把字串以 UTF-8 編碼寫入緩衝區
     * @param {String} str
     * @param {Boolean} isGetBytes 是否只回傳內容字節(不含開頭兩位長度佔位)
     * @returns {Array}
     */
    writeUTF: function (str, isGetBytes) {
      var back = [], byteSize = 0;
      for (var i = 0; i < str.length; i++) {
        var code = str.charCodeAt(i);
        if (code >= 0 && code <= 127) {
          byteSize += 1;
          back.push(code);
        } else if (code >= 128 && code <= 2047) {
          byteSize += 2;
          back.push((192 | (31 & (code >> 6))));
          back.push((128 | (63 & code)));
        } else if (code >= 2048 && code <= 65535) {
          byteSize += 3;
          back.push((224 | (15 & (code >> 12))));
          back.push((128 | (63 & (code >> 6))));
          back.push((128 | (63 & code)));
        }
      }
      for (i = 0; i < back.length; i++) {
        if (back[i] > 255) back[i] &= 255;
      }
      if (isGetBytes) return back;
      if (byteSize <= 255) return [0, byteSize].concat(back);
      return [byteSize >> 8, byteSize & 255].concat(back);
    },

    /**
     * 把字節流依 UTF-8 讀回字串
     * @param arr 字節流
     * @returns {String}
     */
    readUTF: function (arr) {
      if (Object.prototype.toString.call(arr) == "[object String]") return arr;
      var UTF = "", _arr = this.init(arr);
      for (var i = 0; i < _arr.length; i++) {
        var one = _arr[i].toString(2),
            v = one.match(/^1+?(?=?0)/);
        if (v && one.length == 8) {
          var bytesLength = v[0].length,
              store = _arr[i].toString(2).slice(7 - bytesLength);
          for (var st = 1; st < bytesLength; st++) {
            store += _arr[st + i].toString(2).slice(2);
          }
          UTF += String.fromCharCode(parseInt(store, 2));
          i += bytesLength - 1;
        } else {
          UTF += String.fromCharCode(_arr[i]);
        }
      }
      return UTF;
    },

    convertStream: function (x) {
      return (x instanceof Stream) ? x : new Stream(x);
    },

    toMQttString: function (str) {
      return this.writeUTF(str);
    }
  };

  /**
   * 讀取指定長度的字節到目標陣列
   */
  function baseRead(m, i, a) {
    var t = a ? a : [];
    for (var start = 0; start < i; start++) t[start] = m.pool[m.position++];
    return t;
  }

  var supportArrayBuffer = (function () { return !!window.ArrayBuffer; })();

  /**
   * 字節流處理實體
   * @param {String|Array|ArrayBuffer} array
   * @constructor
   */
  function Stream(array) {
    if (!(this instanceof Stream)) return new Stream(array);
    this.pool = [];
    if (Object.prototype.toString.call(array) === '[object Array]') {
      this.pool = binaryPot.init(array);
    } else if (Object.prototype.toString.call(array) == "[object ArrayBuffer]") {
      var arr = new Int8Array(array);
      this.pool = binaryPot.init([].slice.call(arr));
    } else if (typeof array === 'string') {
      this.pool = binaryPot.writeUTF(array);
    }
    var self = this;
    this.position = 0;   // 目前讀取位置
    this.writen   = 0;   // 已寫入字節數
    this.check = function () { return self.position >= self.pool.length; };
  }

  Stream.parse = function (x) { return binaryPot.convertStream(x); };

  Stream.prototype = {
    /** 讀取 4 個字節並轉為整數,position 前移 4 位;已讀完則回傳 -1 */
    readInt: function () {
      if (this.check()) return -1;
      var end = "";
      for (var i = 0; i < 4; i++) end += this.pool[this.position++].toString(16);
      return parseInt(end, 16);
    },

    /** 讀取 1 個字節,position 前移 1 位 */
    readByte: function () {
      if (this.check()) return -1;
      var val = this.pool[this.position++];
      if (val > 255) val &= 255;
      return val;
    },

    /** 讀取 1 個字節,或把指定長度的字節讀入傳入陣列 */
    read: function (bytesArray) {
      if (this.check()) return -1;
      return bytesArray ? baseRead(this, bytesArray.length | 0, bytesArray) : this.readByte();
    },

    /** 從目前位置以 UTF-8 讀取字串 */
    readUTF: function () {
      var big = (this.readByte() << 8) | this.readByte();
      return binaryPot.readUTF(this.pool.slice(this.position, this.position += big));
    },

    /** 寫入字節或字節陣列 */
    write: function (_byte) {
      var b = _byte;
      if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") {
        [].push.apply(this.pool, b);
        this.writen += b.length;
      } else if (+b == b) {
        if (b > 255) b &= 255;
        this.pool.push(b);
        this.writen++;
      }
      return b;
    },

    /** 以 char 形式寫入(大端序 2 字節) */
    writeChar: function (v) {
      if (+v != v) throw new Error("writeChar:arguments type is error");
      this.write((v >> 8) & 255);
      this.write(v & 255);
      this.writen += 2;
    },

    /** 以 UTF-8 寫入字串 */
    writeUTF: function (str) {
      var val = binaryPot.writeUTF(str);
      [].push.apply(this.pool, val);
      this.writen += val.length;
    },

    /** 把 0~255 區間轉回 -128~128 */
    toComplements: function () {
      var _tPool = this.pool;
      for (var i = 0; i < _tPool.length; i++) {
        if (_tPool[i] > 128) _tPool[i] -= 256;
      }
      return _tPool;
    },

    /** 取得整個緩衝區字節 */
    getBytesArray: function (isCom) {
      return isCom ? this.toComplements() : this.pool;
    },

    /** 轉為 ArrayBuffer */
    toArrayBuffer: function () {
      if (supportArrayBuffer) return new ArrayBuffer(this.getBytesArray());
      throw new Error('not support arraybuffer');
    },

    clear: function () {
      this.pool = [];
      this.writen = this.position = 0;
    }
  };

  return Stream;
});

使用方式相當直觀:

<script src="binary.js"></script>
<script>
var ts = TinyStream('我叫張亞濤');
ts.writeUTF('你好');
console.log('緩衝區字節流:', ts.getBytesArray());
console.log('position:', ts.position, 'writen:', ts.writen);
console.log('讀取第一段 UTF-8:', ts.readUTF());
console.log('position:', ts.position, 'writen:', ts.writen);
console.log('讀取第二段 UTF-8:', ts.readUTF());
console.log('position:', ts.position, 'writen:', ts.writen);
</script>

設計上值得注意的幾點:position 與 writen 分成兩個游標,讓「讀取進度」與「寫入長度」互不干擾;writeUTF 在開頭寫入兩字節長度,讓 readUTF 能自行判定邊界,這也是 MQTT 等協定常見的字串編碼方式;init() 統一把負數歸正到 0~255,避免後續位元運算出錯。

若要在現代專案中使用,建議把 this.pool 換成真正的 DataView/Uint8Array,並用 TextEncoder/TextDecoder 取代手寫的 UTF-8 編解碼,效能與正確性都會更好——手寫版本對代理對(surrogate pair,也就是 emoji 這類超出 BMP 的字元)的處理並不完整。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved