PageRenderTime 82ms CodeModel.GetById 50ms app.highlight 5ms RepoModel.GetById 26ms app.codeStats 0ms

/js/lib/Socket.IO-node/lib/socket.io/utils.js

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
JavaScript | 105 lines | 42 code | 18 blank | 45 comment | 10 complexity | 5aa8f2909ab7aa1b7908ed6a83cb349b MD5 | raw file
  1
  2/*!
  3 * Socket.IO - utils
  4 * Copyright (c) 2010-2011 Guillermo Rauch <guillermo@learnboost.com>
  5 * MIT Licensed
  6 */
  7
  8/**
  9 * Object#toString.
 10 */
 11
 12var toString = Object.prototype.toString
 13
 14/**
 15 * Frame marker.
 16 */
 17
 18var marker = '~m~'
 19  , markerLength = marker.length;
 20
 21/**
 22 * Merge `src` into `dest`.
 23 *
 24 * @param {Object} dest
 25 * @param {Object} src
 26 * @return {Object} dest
 27 * @api private
 28 */
 29
 30exports.merge = function(dest, src){
 31  for (var k in src) dest[k] = src[k];
 32  return dest;
 33};
 34
 35/**
 36 * Stringify the given `message`. when an object
 37 * is given it will be converted to JSON.
 38 *
 39 * @param {String|Object} message
 40 * @return {String}
 41 * @api private
 42 */
 43
 44function stringify(message){
 45  if ('[object Object]' == toString.call(message)){
 46    return '~j~' + JSON.stringify(message);
 47  } else {
 48    return String(message);
 49  }
 50};
 51
 52/**
 53 * Encode the given `messages`, framed as 
 54 *
 55 *      <marker> <len> <marker> <data>
 56 *
 57 * @param {String|Array} messages
 58 * @return {String}
 59 * @api private
 60 */
 61
 62exports.encode = function(messages){
 63  var messages = Array.isArray(messages) ? messages : [messages]
 64    , len = messages.length
 65    , ret = ''
 66    , message;
 67
 68  for (var i = 0; i < len; ++i){
 69    message = null == messages[i] ? '' : stringify(messages[i]);
 70    ret += marker + message.length + marker + message;
 71  }
 72
 73  return ret;
 74};
 75
 76/**
 77 * Decode `data`.
 78 *
 79 * @param {String} data
 80 * @return {Array}
 81 * @api private
 82 */
 83
 84exports.decode = function(data){
 85  var messages = []
 86    , len = data.length
 87    , bytes;
 88
 89  for (var i = 0; i < len; ++i) {
 90    // <marker<> <len> <marker>
 91    if (i == data.indexOf(marker, i)) {
 92      i += markerLength;
 93      bytes = data.substring(i, data.indexOf(marker, i));
 94      i += bytes.length + markerLength;
 95      if (isNaN(bytes)) continue;
 96
 97      // <data>
 98      bytes = parseInt(bytes, 10);
 99      messages.push(data.substr(i, bytes))
100      i += bytes - 1;
101    }
102  }
103
104  return messages;
105};