   else
     json.replace /[\u007f-\uffff]/g, (c) ->
       '\\u' + ('0000' + c.charCodeAt(0).toString 16).slice -4
+
+# Calculates the byte length for either a string or a Buffer.
+byteLength = (msg) ->
+  if _.isString msg then Buffer.byteLength msg else msg.length
 
 exports.unpackMessage = (data) ->
   # Int64 to read the 64bit Int from the buffer

exports.mpub = (topic, data) ->
  throw new Error "MPUB requires an array of message" unless _.isArray data
  messages = _.map data, (message) ->
    # Calculate the message length
    length = if _.isString message
      Buffer.byteLength message
    else
      message.length

    buffer = new Buffer(4 + length)
    buffer.writeInt32BE length, 0

    if _.isString message
      buffer.write message, 4

  parametersStr = parameters.join ' '
  header = cmd + parametersStr + '\n'

  buffers.push new Buffer header

  # Body into output buffer it is not empty
  if body?
    # Write the size of the payload
    lengthBuffer = new Buffer 4
    lengthBuffer.writeInt32BE byteLength(body), 0
    buffers.push lengthBuffer

    if _.isString body
