webmcp

diff framework/env/encode/mime/base64.lua @ 0:9fdfb27f8e67

Version 1.0.0
author jbe/bsw
date Sun Oct 25 12:00:00 2009 +0100 (2009-10-25)
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/framework/env/encode/mime/base64.lua	Sun Oct 25 12:00:00 2009 +0100
     1.3 @@ -0,0 +1,45 @@
     1.4 +local alphabet = {
     1.5 +  "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
     1.6 +  "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
     1.7 +  "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
     1.8 +  "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
     1.9 +  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"
    1.10 +}
    1.11 +
    1.12 +function encode.mime.base64(str)
    1.13 +  local parts = {}
    1.14 +  local pos = 1
    1.15 +  local block_count = 0
    1.16 +  while pos <= #str do
    1.17 +    local s = string.sub(str, pos, pos + 2)
    1.18 +    local n = 0
    1.19 +    for i = 1, 3 do
    1.20 +      n = n * 256
    1.21 +      if i <= #s then
    1.22 +        n = n + string.byte(string.sub(s, i, i))
    1.23 +      end
    1.24 +    end
    1.25 +    parts[#parts+1] = alphabet[math.floor(n / 262144) + 1]
    1.26 +    parts[#parts+1] = alphabet[math.floor(n / 4096) % 64 + 1]
    1.27 +    if #s > 1 then
    1.28 +      parts[#parts+1] = alphabet[math.floor(n / 64) % 64 + 1]
    1.29 +    else
    1.30 +      parts[#parts+1] = "="
    1.31 +    end
    1.32 +    if #s > 2 then
    1.33 +      parts[#parts+1] = alphabet[n % 64 + 1]
    1.34 +    else
    1.35 +      parts[#parts+1] = "="
    1.36 +    end
    1.37 +    block_count = block_count + 1
    1.38 +    if block_count == 19 then
    1.39 +      parts[#parts+1] = "\r\n"
    1.40 +      block_count = 0
    1.41 +    end
    1.42 +    pos = pos + #s
    1.43 +  end
    1.44 +  if block_count > 0 then
    1.45 +    parts[#parts+1] = "\r\n"
    1.46 +  end
    1.47 +  return table.concat(parts)
    1.48 +end

Impressum / About Us