'Should correctly parse message + in two packets from socket' : function(test) {    
   // Connection dummy object
   var connectionObject = {"connection": {}, "sizeOfMessage": 0, "bytesRead": 0, "buffer": new Buffer(0), "stubBuffer": new Buffer(0)}
   // Data object
   var index = 0;
   var buffer = new Buffer(10);
   var value = 10;
   // Encode length at start according to wire protocol
   buffer[index + 3] = (value >> 24) & 0xff;      
   buffer[index + 2] = (value >> 16) & 0xff;
   buffer[index + 1] = (value >> 8) & 0xff;
   buffer[index] = value & 0xff;            
   
   // Self environment dummy
   var self = {poolByReference:{1:connectionObject}, 'emit':function(type, data) {
     test.equal('data', type);
     // Compare the buffers content
     for(var i = 0; i < buffer.length; i++) {
       test.equal(buffer[i], data[i]);
     }
   }};
   
   // Trigger the connection listener
   var connectionListener = Connection._receiveListenerCreator(self);
   connectionListener(buffer.slice(0, 6), 1)
   connectionListener(buffer.slice(6), 1)
   // Sequential execution :)
   test.done();      
 },
Example #2
0
    runs(function () {
      var data = new Buffer(200)
      data.slice(0, 100).fill(0)
      data.slice(100).fill(16)

      lz4.decode(lz4.encode(data))
    })
 'Corrupt the message baby' : function(test) {
   // Data object
   var index = 0;
   var buffer = new Buffer(40);
   var value = -40;
   // Encode length at start according to wire protocol
   buffer[index + 3] = (value >> 24) & 0xff;      
   buffer[index + 2] = (value >> 16) & 0xff;
   buffer[index + 1] = (value >> 8) & 0xff;
   buffer[index] = value & 0xff;                
 
   // Dummy object for receiving message
   var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) {
     test.equal('parseError', message)
     // test.equal('socketHandler', data.err)
   }};
   
   // Create a connection object
   var dataHandler = Connection.createDataHandler(self);
 
   // Execute parsing of message
   dataHandler(buffer.slice(0, 6));
   dataHandler(buffer.slice(6, 15));
   dataHandler(buffer.slice(15, 27));
   test.done();
 },
test('decoder.write - A mixed ascii and non-ascii string', function (t) {
  // Test stolen from deps/v8/test/cctest/test-strings.cc
  // U+02E4 -> CB A4
  // U+0064 -> 64
  // U+12E4 -> E1 8B A4
  // U+0030 -> 30
  // U+3045 -> E3 81 85
  var expected = '\u02e4\u0064\u12e4\u0030\u3045';
  var buffer = new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4,
                           0x30, 0xE3, 0x81, 0x85]);
  var charLengths = [0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5];

  // Split the buffer into 3 segments
  //  |----|------|-------|
  //  0    i      j       buffer.length
  // Scan through every possible 3 segment combination
  // and make sure that the string is always parsed.
  for (var j = 2; j < buffer.length; j++) {
    for (var i = 1; i < j; i++) {
      var decoder = new StringDecoder('utf8');

      var sum = decoder.write(buffer.slice(0, i));

      // just check that we've received the right amount
      // after the first write
      t.equal(charLengths[i], sum.length);

      sum += decoder.write(buffer.slice(i, j));
      sum += decoder.write(buffer.slice(j, buffer.length));
      t.equal(expected, sum);
    }
  }

  t.end();
});
test('decoder.write - three byte char', function (t) {
  var buffer = new Buffer('€');
  t.deepEqual('', decoder.write(buffer.slice(0, 1)));
  t.deepEqual('', decoder.write(buffer.slice(1, 2)));
  t.deepEqual('€', decoder.write(buffer.slice(2, 3)));
  t.end();
});
  'Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then partial message' : function(test) {    
    // Connection dummy object
    var connectionObject = {"connection": {}, "sizeOfMessage": 0, "bytesRead": 0, "buffer": new Buffer(0), "stubBuffer": new Buffer(0)}
    // Data object
    var index = 0;
    var buffer = new Buffer(40);
    var value = 10;
    // Encode length at start according to wire protocol
    buffer[index + 3] = (value >> 24) & 0xff;      
    buffer[index + 2] = (value >> 16) & 0xff;
    buffer[index + 1] = (value >> 8) & 0xff;
    buffer[index] = value & 0xff;            

    var value = 20;
    // Adjust the index
    index = index + 10;
    // Encode length at start according to wire protocol
    buffer[index + 3] = (value >> 24) & 0xff;      
    buffer[index + 2] = (value >> 16) & 0xff;
    buffer[index + 1] = (value >> 8) & 0xff;
    buffer[index] = value & 0xff;            

    var value = 15;
    // Adjust the index
    index = index + 20;
    // Encode length at start according to wire protocol
    buffer[index + 3] = (value >> 24) & 0xff;      
    buffer[index + 2] = (value >> 16) & 0xff;
    buffer[index + 1] = (value >> 8) & 0xff;
    buffer[index] = value & 0xff;            
    
    // Self environment dummy
    var self = {poolByReference:{1:connectionObject}, 'emit':function(type, data) {
      test.equal('data', type);      
    }};
    
    // Trigger the connection listener
    var connectionListener = Connection._receiveListenerCreator(self);
    connectionListener(buffer.slice(0, 6), 1)
    connectionListener(buffer.slice(6, 15), 1)
    connectionListener(buffer.slice(15, 27), 1)

    // Do asserts
    test.equal(20, connectionObject.sizeOfMessage);
    test.equal(17, connectionObject.bytesRead);
    test.equal(17, connectionObject.buffer.length);
    test.equal(0, connectionObject.stubBuffer.length);
    // Check against message
    var partialMessage = buffer.slice(10, 27);    
    for(var i = 0; i < 5; i++) {
      test.equal(partialMessage[i], connectionObject.buffer[i]);
    }
    
    // Sequential execution :)
    test.done();      
  },
Example #7
0
function tlv_close() {
	var tlv_hdr_len_offset = 4;
	var tlv_hdr_crc_offset = 8;

	tlv_crc_buf = tlv_buf.slice(tlv_hdr_len, tlv_buf_offset);

	tlv_buf.writeUInt32LE(tlv_buf_offset, tlv_hdr_len_offset, 4, 'hex');
	tlv_buf.writeUInt32LE(wmcrc.crc32(tlv_crc_buf), tlv_hdr_crc_offset, 4, 'hex');
	tlv_buf = tlv_buf.slice(0, tlv_buf_offset);
}
test('decoder.write - four byte char', function (t) {
  var buffer = new Buffer([0xF0, 0xA4, 0xAD, 0xA2]);
  var s = '';
  s += decoder.write(buffer.slice(0, 1));
  s += decoder.write(buffer.slice(1, 2));
  s += decoder.write(buffer.slice(2, 3));
  s += decoder.write(buffer.slice(3, 4));
  t.ok(s.length > 0);
  t.end();
});
Example #9
0
Protocol.prototype.execute = function(d) {
  var res = this.res;
  res.raw += d;

  switch (this.state) {
    case 'headers':
      var endHeaderIndex = res.raw.indexOf('\r\n\r\n');

      if (endHeaderIndex < 0) break;

      var rawHeader = res.raw.slice(0, endHeaderIndex);
      var endHeaderByteIndex = Buffer.byteLength(rawHeader, 'utf8');
      var lines = rawHeader.split('\r\n');
      for (var i = 0; i < lines.length; i++) {
        var kv = lines[i].split(/: +/);
        res.headers[kv[0]] = kv[1];
      }

      this.contentLength = +res.headers['Content-Length'];
      this.bodyStartByteIndex = endHeaderByteIndex + 4;

      this.state = 'body';

      var len = Buffer.byteLength(res.raw, 'utf8');
      if (len - this.bodyStartByteIndex < this.contentLength) {
        break;
      }
      // falls through
    case 'body':
      var resRawByteLength = Buffer.byteLength(res.raw, 'utf8');

      if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) {
        var buf = new Buffer(resRawByteLength);
        buf.write(res.raw, 0, resRawByteLength, 'utf8');
        res.body =
            buf.slice(this.bodyStartByteIndex,
                      this.bodyStartByteIndex +
                      this.contentLength).toString('utf8');
        // JSON parse body?
        res.body = res.body.length ? JSON.parse(res.body) : {};

        // Done!
        this.onResponse(res);

        this._newRes(buf.slice(this.bodyStartByteIndex +
                               this.contentLength).toString('utf8'));
      }
      break;

    default:
      throw new Error('Unknown state');
  }
};
Example #10
0
 it("should accept string from buffers with multibyte characters", function (done) {
   var strings = concat({ encoding: "string" }, function(e, out) {
     expect(typeof out).toEqual("string");
     expect(out).toEqual("☃☃☃☃☃☃☃☃");
     done();
   });
   var snowman = new Buffer("☃"),
       i;
   for (i = 0; i < 8; i++) {
     strings.write(snowman.slice(0, 1));
     strings.write(snowman.slice(1));
   }
   strings.end();
 });
 'Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then partial message' : function(test) {    
   // Data object
   var index = 0;
   var buffer = new Buffer(40);
   var value = 10;
   // Encode length at start according to wire protocol
   buffer[index + 3] = (value >> 24) & 0xff;      
   buffer[index + 2] = (value >> 16) & 0xff;
   buffer[index + 1] = (value >> 8) & 0xff;
   buffer[index] = value & 0xff;            
 
   var value = 20;
   // Adjust the index
   index = index + 10;
   // Encode length at start according to wire protocol
   buffer[index + 3] = (value >> 24) & 0xff;      
   buffer[index + 2] = (value >> 16) & 0xff;
   buffer[index + 1] = (value >> 8) & 0xff;
   buffer[index] = value & 0xff;            
 
   var value = 15;
   // Adjust the index
   index = index + 20;
   // Encode length at start according to wire protocol
   buffer[index + 3] = (value >> 24) & 0xff;      
   buffer[index + 2] = (value >> 16) & 0xff;
   buffer[index + 1] = (value >> 8) & 0xff;
   buffer[index] = value & 0xff;            
 
   // Dummy object for receiving message
   var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) {
     assertBuffersEqual(test, buffer.slice(0, 10), data);
   }};
   
   // Create a connection object
   var dataHandler = Connection.createDataHandler(self);
 
   // Execute parsing of message
   dataHandler(buffer.slice(0, 6));
   dataHandler(buffer.slice(6, 15));
   dataHandler(buffer.slice(15, 27));
   
   // Check status of the parser
   test.equal(17, self.bytesRead);
   test.equal(20, self.sizeOfMessage);
   test.equal(null, self.stubBuffer);
   assertBuffersEqual(test, buffer.slice(10, 27), self.buffer.slice(0, 17));
   // Test done
   test.done();
 },
Example #12
0
  tape(alg + ': NIST vector ' + i, function (t) {
    if (verbose) {
      console.log(v)
      console.log('VECTOR', i)
      console.log('INPUT', v.input)
      console.log(hexpp(new Buffer(v.input, 'base64')))
      console.log(new Buffer(v.input, 'base64').toString('hex'))
    }

    var buf = new Buffer(v.input, 'base64')
    t.equal(createHash(alg).update(buf).digest('hex'), v[alg])

    i = ~~(buf.length / 2)
    var buf1 = buf.slice(0, i)
    var buf2 = buf.slice(i, buf.length)

    console.log(buf1.length, buf2.length, buf.length)
    console.log(createHash(alg)._block.length)

    t.equal(
      createHash(alg)
        .update(buf1)
        .update(buf2)
        .digest('hex'),
      v[alg]
    )

    var j, buf3

    i = ~~(buf.length / 3)
    j = ~~(buf.length * 2 / 3)
    buf1 = buf.slice(0, i)
    buf2 = buf.slice(i, j)
    buf3 = buf.slice(j, buf.length)

    t.equal(
      createHash(alg)
        .update(buf1)
        .update(buf2)
        .update(buf3)
        .digest('hex'),
      v[alg]
    )

    setTimeout(function () {
      // avoid "too much recursion" errors in tape in firefox
      t.end()
    })
  })
 'Corrupt the message baby but catch the log error' : function(test) {
   // Data object
   var index = 0;
   var buffer = new Buffer(40);
   for(var i = 0; i < buffer.length; i++) buffer[i] = 0;
   var value = -40;
   // Encode length at start according to wire protocol
   buffer[index + 3] = (value >> 24) & 0xff;      
   buffer[index + 2] = (value >> 16) & 0xff;
   buffer[index + 1] = (value >> 8) & 0xff;
   buffer[index] = value & 0xff;                
 
   // Dummy object for receiving message
   var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) {
     test.equal('parseError', message)
   }};
   
   // Count the number of errors
   var totalCountOfErrors = 0;
   
   // Add a logger object
   self.logger = {
     doDebug:true,
     doError:true,
     doLog:true,
     
     error:function(message, object) {
       totalCountOfErrors = totalCountOfErrors + 1;
       if(totalCountOfErrors == 3) {
         test.done();
       }
     }, 
     
     log:function(message, object) {        
     }, 
     
     debug:function(message, object) {
     }
   }
   
   // Create a connection object
   var dataHandler = Connection.createDataHandler(self);
 
   // Execute parsing of message
   dataHandler(buffer.slice(0, 6));
   dataHandler(buffer.slice(6, 15));
   dataHandler(buffer.slice(15, 27));
 },
  'Corrupt the message baby' : function(test) {
    // Connection dummy object
    var connectionObject = {"connection": {}, "sizeOfMessage": 0, "bytesRead": 0, "buffer": new Buffer(0), "stubBuffer": new Buffer(0)}
    // Data object
    var index = 0;
    var buffer = new Buffer(40);
    var value = -40;
    // Encode length at start according to wire protocol
    buffer[index + 3] = (value >> 24) & 0xff;      
    buffer[index + 2] = (value >> 16) & 0xff;
    buffer[index + 1] = (value >> 8) & 0xff;
    buffer[index] = value & 0xff;                

    // Self environment dummy
    var self = {poolByReference:{1:connectionObject}, 'emit':function(type, data) {
      test.equal('unparsable',data.err);
      test.equal(-40, data.parseState.sizeOfMessage);
      test.equal(0, data.parseState.bytesRead);
      test.equal(0, data.parseState.buffer.length);
      test.equal(0, data.parseState.stubBuffer.length);
      test.equal('error', type);      
      test.done();
    }};

    // Trigger the connection listener
    var connectionListener = Connection._receiveListenerCreator(self);
    connectionListener(buffer.slice(0, 40), 1);
  },
Example #15
0
DBCSEncoder.prototype.end = function() {
    if (this.leadSurrogate === -1 && this.seqObj === undefined)
        return; // All clean. Most often case.

    var newBuf = new Buffer(10), j = 0;

    if (this.seqObj) { // We're in the sequence.
        var dbcsCode = this.seqObj[DEF_CHAR];
        if (dbcsCode !== undefined) { // Write beginning of the sequence.
            if (dbcsCode < 0x100) {
                newBuf[j++] = dbcsCode;
            }
            else {
                newBuf[j++] = dbcsCode >> 8;   // high byte
                newBuf[j++] = dbcsCode & 0xFF; // low byte
            }
        } else {
            // See todo above.
        }
        this.seqObj = undefined;
    }

    if (this.leadSurrogate !== -1) {
        // Incomplete surrogate pair - only lead surrogate found.
        newBuf[j++] = this.defaultCharSingleByte;
        this.leadSurrogate = -1;
    }

    return newBuf.slice(0, j);
}
Example #16
0
File: bn.js Project: feng92f/dht.js
bn.add = function add(a, b) {
  // a should be the bigger one buffer
  if (a.length < b.length) {
    var t = a;
    a = b;
    b = t;
  }

  var result = new Buffer(a.length + 2),
      over = 0;

  for (var i = a.length - 2, j = b.length - 2; i >= 0; i -= 2, j -= 2) {
    var aword = a.readUInt16BE(i),
        bword = j >= 0 ? b.readUInt16BE(j) : 0,
        rword = aword + bword + over;

    over = rword >> 16;
    result.writeUInt16BE(rword & 0xffff, i);
  }
  // Write last overflowed word
  result.writeUInt16BE(over, i);

  // Do not return last byte if overflow hasn't happened
  return over ? result : result.slice(0, result.length - 2);
};
 var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) {
   assertBuffersEqual(test, buffer.slice(resultIndex, resultIndex + 10), data);
   resultIndex = resultIndex + 10;
   
   if(resultIndex === buffer.length) {
     test.done();
   }
 }};
(function() {
  var buf = new Buffer('0123456789');
  assert.equal(buf.slice(-10, 10), '0123456789');
  assert.equal(buf.slice(-20, 10), '0123456789');
  assert.equal(buf.slice(-20, -10), '');
  assert.equal(buf.slice(0, -1), '012345678');
  assert.equal(buf.slice(2, -2), '234567');
  assert.equal(buf.slice(0, 65536), '0123456789');
  assert.equal(buf.slice(65536, 0), '');
  for (var i = 0, s = buf.toString(); i < buf.length; ++i) {
    assert.equal(buf.slice(-i), s.slice(-i));
    assert.equal(buf.slice(0, -i), s.slice(0, -i));
  }
})();
Example #19
0
  $scope.$watch('txHex', function() {
    if ($scope.txHex === '') return;

    var txBuff = new Buffer($scope.txHex, 'hex');
    var tx = {};

    // Version
    tx.version = txBuff.readUInt32LE(0);

    // Tx inputs
    tx.inputsCount = util.readVarInt(txBuff, 4).res;
    var offset = util.readVarInt(txBuff, 4).offset;


    tx.inputs = [];

    for (var i = 0; i < tx.inputsCount; i++) {
      var input = parseVin(txBuff.slice(offset));
      tx.inputs.push(input);
      offset += input.size;
    }

    // Tx outputs
    var outputsCount = util.readVarInt(txBuff, offset);
    offset = outputsCount.offset;
    tx.outputsCount = outputsCount.res;

    tx.outputs = [];

    for (i = 0; i < tx.outputsCount; i++) {
      var output = parseVout(txBuff.slice(offset));
      tx.outputs.push(output);
      offset += output.size;
    }

    // lockTime
    tx.lockTime = txBuff.readUInt32LE(offset);

    // binds the tx to the DOM
    $scope.tx = tx;

    var a = decodeScriptPubKey(new Buffer($scope.tx.outputs[0].scriptPubKey, 'hex'));
  });// end $watch
Example #20
0
    var emitData = function() {
        var len = Math.min(
            min + Math.floor(Math.random() * (max - min)),
            buf.length
        );

        var b = buf.slice(0, len);

        if (len < buf.length) {
            buf = buf.slice(len, buf.length);
            process.nextTick(emitData);
        } else {
            process.nextTick(function() {
                self.emit('end')
            });
        }

        self.emit('data', b);
    };
Example #21
0
// connection: the connection
// channel: the channel to send this on
// size: size in bytes of the following message
// properties: an object containing any of the following:
// - contentType (default 'application/octet-stream')
// - contentEncoding
// - headers
// - deliveryMode
// - priority (0-9)
// - correlationId
// - replyTo
// - experation
// - messageId
// - timestamp
// - userId
// - appId
// - clusterId
function sendHeader (connection, channel, size, properties) {
  var b = new Buffer(maxFrameBuffer); // FIXME allocating too much.
                                      // use freelist?
  b.used = 0;

  var classInfo = classes[60]; // always basic class.

  // 7 OCTET FRAME HEADER

  b[b.used++] = 2; // constants.frameHeader

  serializeInt(b, 2, channel);

  var lengthStart = b.used;

  serializeInt(b, 4, 0 /*dummy*/); // length

  var bodyStart = b.used;

  // HEADER'S BODY

  serializeInt(b, 2, classInfo.index);   // class 60 for Basic
  serializeInt(b, 2, 0);                 // weight, always 0 for rabbitmq
  serializeInt(b, 8, size);              // byte size of body

  // properties - first propertyFlags
  var props = {'contentType': 'application/octet-stream'};
  mixin(props, properties);
  var propertyFlags = 0;
  for (var i = 0; i < classInfo.fields.length; i++) {
    if (props[classInfo.fields[i].name]) propertyFlags |= 1 << (15-i);
  }
  serializeInt(b, 2, propertyFlags);
  // now the actual properties.
  serializeFields(b, classInfo.fields, props, false);

  //serializeTable(b, props);

  var bodyEnd = b.used;

  // Go back to the header and write in the length now that we know it.
  b.used = lengthStart;
  serializeInt(b, 4, bodyEnd - bodyStart);
  b.used = bodyEnd;

  // 1 OCTET END

  b[b.used++] = 206; // constants.frameEnd;

  var s = b.slice(0, b.used);

  //debug('header sent: ' + JSON.stringify(s));

  connection.write(s);
}
Example #22
0
	fs.read(f, buffer, 0, conf.versions["2"][head.ver].extheader.maxsize, conf.versions["2"].headsize, function (){ //rerr, num) {
		var size = conf.versions["2"][head.ver].extheader.maxsize;
		if (conf.versions["2"][head.ver].extheader.calcsize) {
			size =
				conf.versions["2"][head.ver].extheader.sizebase +
				helper.sizecalc(buffer.slice(0, 4));
		} else {
			size =
				conf.versions["2"][head.ver].extheader.sizebase +
				buffer.readInt32BE(0);
		}
		if (size > conf.versions["2"][head.ver].extheader.maxsize) {
			callback({"code": 5, "dscr": "extended header size is too big!"}, undefined);
			return;
		}
		// since we have the size we can strip the buffer to header size
		buffer = buffer.slice(0, size);

		callback({}, buffer);
	});
Example #23
0
  fs.read(file_handle, file_data, 0, 10, 0, function(err, data) {

    if (err !== null) {

      return cb(err);

    }

    if (file_data.slice(0, 3).toString() !== 'ID3') {

      return cb("No ID3 Tag");

    }

    var data_size = id3Size(file_data.slice(6,10)); 
    var version = '2.'+file_data.readUInt8(3)+'.'+file_data.readUInt8(4);

    return cb(null, file_handle, data_size, version);

  });
Example #24
0
    var beq = function(as, pay, payStart, payEnd, bufLen, bufOff) {
        var buf = new Buffer(ns.nsWriteLength(bufLen));
        var nsLen = ns.nsWrite.call(this, pay, payStart, payEnd, buf, bufOff)
        as.ok(nsLen >= 3);

        var bb = buf.slice(bufOff, bufOff + nsLen);
        as.equal(
            bb.toString(),
            ns.nsWrite(pay, payStart, payEnd)
        );
    };
Example #25
0
      runs(function () {
        expect(decoded_data_valid).toBeDefined()

        var encoded_data = new Buffer(lz4.encodeBound(decoded_data_valid.length) + 4)
        var decoded_data = new Buffer(decoded_data_valid.length)

        expect(encoded_data).toBeDefined()
        expect(decoded_data).toBeDefined()

        var n = lz4.encodeBlock(decoded_data_valid, encoded_data, 4)
        expect(n).toBeDefined()
        if (n > 0) {
          encoded_data = encoded_data.slice(4, n)
          n = lz4.decodeBlock(encoded_data, decoded_data)

          expect(n).toEqual(decoded_data_valid.length)

          decoded_data = decoded_data.slice(0, n)
          expect( decoded_data.toString() ).toEqual( decoded_data_valid.toString() )
        }
      })
Example #26
0
exports.oscBundleToBuffer = function (bundle) { 
    var i, j, k, size, offset = 0,
    buffer = new Buffer(1000);
    
    offset += writeOSCString("#bundle", buffer, offset);
    offset += writeOSCString("0000001", buffer, offset);
    
    for (i = 0; i < bundle.addresses.length; i += 1) {
        
        // Calculate the size of the message
        size = bundle.addresses[i].length;
        while ((size % 4) !== 0) {
            size += 1;
        }
        size += bundle.typeTags[i].length;
        while ((size % 4) !== 0) { 
            size += 1;
        }
        for (j = 0; j < bundle.typeTags[i].length; j += 1) {
            if (bundle.typeTags[i].charAt(j) === 'i') {
                size += 4;
            } else if (bundle.typeTags[i].charAt(j) === 'f') {
                size += 4;
            } else {
                size += bundle.datas[i][j].length;
                while ((size % 4) !== 0) {
                    size += 1;
                }
            }
        }
        
        offset += writeOSCInt(size, buffer, offset);
        offset += writeOSCString(bundle.addresses[i], buffer, offset);
        offset += writeOSCString(',' + bundle.typeTags[i], buffer, offset);
        
        for (j = 0; j < bundle.datas[i].length; j += 1) {
            switch (bundle.typeTags[i].charAt(j)) {
            case "i":
                offset += writeOSCInt(bundle.datas[i][j], buffer, offset);
                break;
                
            case "f":             
                offset += writeOSCFloat(bundle.datas[i][j], buffer, offset);
                break;
                
            case "s":
                offset += writeOSCString(bundle.datas[i][j], buffer, offset);
                break;
            }
        }
    }
    return buffer.slice(0, offset);
};
Example #27
0
function kdf_d(data, prev, iter) {
  var d = new Buffer(prev.length + data.length );
  prev.copy( d );
  data.copy( d, prev.length );

  for ( var i = 0 ; i < iter ; ++i ) {
    var digest = new Hash('md5');
    digest.update( d );
    d = digest.digest();
  }
  return d.slice(0,16);
}
Example #28
0
exports.oscToBuffer = function (osc) {
    var buffer, offset = 0, i, j;
    
    // This could be more efficient:
    buffer = new Buffer(osc.address.length + osc.typeTags.length + (osc.data.length * 4) + 80);
    
    offset += writeOSCString(osc.address, buffer, offset);    
    offset += writeOSCString(',' + osc.typeTags, buffer, offset);
    
    for (i = 0; i < osc.data.length; i += 1) {
        switch (osc.typeTags.charAt(i)) {
        case "i":
            offset += writeOSCInt(osc.data[i], buffer, offset);
            break;

        case "f":
            offset += writeOSCFloat(osc.data[i], buffer, offset);
            break;

        case "s":
            offset += writeOSCString(osc.data[i], buffer, offset);        
            break;
        
        case "b":
            // TODO:  OSC-blob
            break;

        default:
            break;
        /*
        TODO:
        OSC Type Tags that must be used for certain nonstandard argument types
        OSC Type Tag	Type of corresponding argument
        h	64 bit big-endian two's complement integer
        t	OSC-timetag
        d	64 bit ("double") IEEE 754 floating point number
        S	Alternate type represented as an OSC-string (for example, for systems that differentiate "symbols" from "strings")
        c	an ascii character, sent as 32 bits
        r	32 bit RGBA color
        m	4 byte MIDI message. Bytes from MSB to LSB are: port id, status byte, data1, data2
        T	True. No bytes are allocated in the argument data.
        F	False. No bytes are allocated in the argument data.
        N	Nil. No bytes are allocated in the argument data.
        I	Infinitum. No bytes are allocated in the argument data.
        [	Indicates the beginning of an array. The tags following are for data in the Array until a close brace tag is reached.
        ]	Indicates the end of an array.
        */
        }
    }
    return buffer.slice(0, offset);
};
Example #29
0
    var onData = function(dataReceived) {        
        data = Buffer.concat([data,dataReceived],data.length + dataReceived.length);        
        if (!gotHelo && policyRegExp.test(data.toString())){
           // Посылаем XML и закрываем сокет:
           conn.end(self._crossdomainXML);
           return;
        }
        
        if (!gotHelo && data.length < helo_bl) return;        

        // Wrong helo?        
        if (!gotHelo && data.toString('utf8',0,helo_bl) != self.heloFromServer) {                        
            self.connection.end("WRONG HELO");
            return;
        } 
          
        if(!gotHelo) {
            // Если HELO подошел мы должны обрезать данные, чтобы передать их дальше.
            data = data.slice(helo_bl);
            gotHelo = true;
        }     

        if (!gotCIDMarker && data.length === 0) return;        
        if(CIDMarker === null) {            
            CIDMarker = data.toString('utf8',0,1);
            gotCIDMarker = true;
            data = data.slice(1);
        }       

        if(CIDMarker === "@" && data.length > 0) {                        
            self.connection.removeListener('data',onData);
            // data is CID
            self.emit('connect', data);
        } else if (CIDMarker === "#") {
            self.connection.removeListener('data',onData);
            self.emit('connect', cid);
        }
    };
Example #30
0
test('Behavior when input is a subarray 2', function (t) {
	var origBuf = new Buffer(10)
	for (var i = 0; i < 10; i++) {
		origBuf[i] = i
	}
	var buf = origBuf.slice(0, 9)

	var ab = toArrayBuffer(buf)

	t.equals(ab.byteLength, 9, 'correct length')
	t.ok(elementsEqual(ab, buf), 'elements equal')
	t.notOk(ab === buf.buffer, 'the underlying ArrayBuffer is not returned when incorrect')
	t.end()
})