time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

BufferList.js (2059B)


      1 'use strict';
      2 
      3 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
      4 
      5 var Buffer = require('safe-buffer').Buffer;
      6 var util = require('util');
      7 
      8 function copyBuffer(src, target, offset) {
      9   src.copy(target, offset);
     10 }
     11 
     12 module.exports = function () {
     13   function BufferList() {
     14     _classCallCheck(this, BufferList);
     15 
     16     this.head = null;
     17     this.tail = null;
     18     this.length = 0;
     19   }
     20 
     21   BufferList.prototype.push = function push(v) {
     22     var entry = { data: v, next: null };
     23     if (this.length > 0) this.tail.next = entry;else this.head = entry;
     24     this.tail = entry;
     25     ++this.length;
     26   };
     27 
     28   BufferList.prototype.unshift = function unshift(v) {
     29     var entry = { data: v, next: this.head };
     30     if (this.length === 0) this.tail = entry;
     31     this.head = entry;
     32     ++this.length;
     33   };
     34 
     35   BufferList.prototype.shift = function shift() {
     36     if (this.length === 0) return;
     37     var ret = this.head.data;
     38     if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
     39     --this.length;
     40     return ret;
     41   };
     42 
     43   BufferList.prototype.clear = function clear() {
     44     this.head = this.tail = null;
     45     this.length = 0;
     46   };
     47 
     48   BufferList.prototype.join = function join(s) {
     49     if (this.length === 0) return '';
     50     var p = this.head;
     51     var ret = '' + p.data;
     52     while (p = p.next) {
     53       ret += s + p.data;
     54     }return ret;
     55   };
     56 
     57   BufferList.prototype.concat = function concat(n) {
     58     if (this.length === 0) return Buffer.alloc(0);
     59     if (this.length === 1) return this.head.data;
     60     var ret = Buffer.allocUnsafe(n >>> 0);
     61     var p = this.head;
     62     var i = 0;
     63     while (p) {
     64       copyBuffer(p.data, ret, i);
     65       i += p.data.length;
     66       p = p.next;
     67     }
     68     return ret;
     69   };
     70 
     71   return BufferList;
     72 }();
     73 
     74 if (util && util.inspect && util.inspect.custom) {
     75   module.exports.prototype[util.inspect.custom] = function () {
     76     var obj = util.inspect({ length: this.length });
     77     return this.constructor.name + ' ' + obj;
     78   };
     79 }