1 /**
  2  * @fileOverview Utilties
  3  */
  4 
  5 (function () {
  6   /**
  7    * @class
  8    * @export utils as utils
  9    */
 10   var utils = {
 11     /**
 12      * Translate buffer of arrays / strings to single string.
 13      */
 14     bufToStr: function (bufs, encodingSrc, encodingDest) {
 15       var results = [];
 16 
 17       encodingSrc = encodingSrc || null;
 18       encodingDest = encodingDest || 'utf8';
 19 
 20       bufs.forEach(function (buf) {
 21         // Start with assumption we have a correctly encoded string.
 22         var bufTrans = buf;
 23 
 24         // If have a string of wrong encoding, make back to a buffer.
 25         if (typeof buf === 'string' && encodingDest !== encodingSrc) {
 26           buf = new Buffer(buf, encodingSrc);
 27         }
 28 
 29         // If buffer, make a string.
 30         if (typeof buf !== 'string') {
 31           bufTrans = buf.toString(encodingDest);
 32         }
 33 
 34         bufs.push(bufTrans);
 35       });
 36 
 37       return bufs.join('');
 38     },
 39 
 40     /**
 41      * Extract headers, cloudHeaders, metadata properties into new object.
 42      */
 43     extractMeta: function (obj) {
 44       obj = obj || {};
 45       return {
 46         headers: obj.headers || {},
 47         cloudHeaders: obj.cloudHeaders || {},
 48         metadata: obj.metadata || {}
 49       };
 50     },
 51 
 52     /**
 53      * Create a new object with objects merged.
 54      *
 55      * @exports extend as utils.extend
 56      */
 57     extend: function () {
 58       var objs = Array.prototype.slice.call(arguments, 0),
 59         merged = {};
 60 
 61       objs.forEach(function (obj) {
 62         var keys,
 63           key,
 64           i,
 65           len;
 66 
 67         if (!obj) {
 68           return;
 69         }
 70 
 71         keys = Object.keys(obj);
 72         for (i = 0, len = keys.length; i < len; i += 1) {
 73           key = keys[i];
 74           merged[key] = obj[key];
 75         }
 76       });
 77 
 78       return merged;
 79     }
 80   };
 81 
 82   module.exports = utils;
 83 }());
 84