toz85

function toz85( str ) --> z85str, err

Description

Encodes a data string to a Z85 string. The data string must be divisible by 4.

Parameters

z85str

The data string that should be encoded.

Return Values

str

The Z85 encoded string.

err

A message that explains the error, otherwise nil.

Code

--ZFUNC-toz85-v1
local function toz85( str ) --> z85str
   local z85Encoder = "0123456789"..
                      "abcdefghijklmnopqrstuvwxyz"..
                      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"..
                      ".-:+=^!/*?&<>()[]{}@%$#"
   local errlen = "invalid length: %d - must be a multiple of 4"

   if ( #str % 4 ) ~= 0 then return nil, string.format( errlen, #str ) end

   local result = {}

   local value = 0
   for i = 1, #str do
      local b = string.byte( str, i )
      value = ( value * 256 ) + b
      if ( i % 4 ) == 0 then
         local divisor = 85 * 85 * 85 * 85
         while divisor ~= 0 do
            local index = ( math.floor( value / divisor ) % 85 ) + 1
            table.insert( result, z85Encoder:sub( index, index ) )
            divisor = math.floor( divisor / 85 )
         end
         value = 0
      end
   end

   return table.concat( result )
end

return toz85

Examples

local t = require( "tapered" )
local toz85 = require( "toz85" )

--http://rfc.zeromq.org/spec:32
local data = string.char( 0x86, 0x4f, 0xd2, 0x6f, 0xb5, 0x59, 0xf7, 0x5b )
t.is( toz85( data ), "HelloWorld" )

--https://github.com/msealand/z85.node/blob/master/test/encode.test.js
t.is( toz85( "1234" ), "f!$Kw" )

--wrong length error
local res, err = toz85( "abcdefghi" )
t.nok( res )
t.is( err, "invalid length: 9 - must be a multiple of 4" )

t.done()

See also