webmcp
diff framework/env/encode/mime/unstructured_header_line.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/unstructured_header_line.lua Sun Oct 25 12:00:00 2009 +0100 1.3 @@ -0,0 +1,71 @@ 1.4 +function encode.mime.unstructured_header_line(key, value) 1.5 + if not value then 1.6 + return "" 1.7 + end 1.8 + local charset = "UTF-8" -- TODO: support other charsets 1.9 + local key_length = #key + #(": ") 1.10 + if string.find(value, "^[\t -~]*$") then 1.11 + local need_encoding = false 1.12 + local parts = { key, ": " } 1.13 + local line_length = key_length 1.14 + local first_line = true 1.15 + for spaced_word in string.gmatch(value, "[\t ]*[^\t ]*") do 1.16 + if #spaced_word + line_length > 76 then 1.17 + if first_line or #spaced_word > 76 then 1.18 + need_encoding = true 1.19 + break 1.20 + end 1.21 + parts[#parts+1] = "\r\n" 1.22 + line_length = 0 1.23 + end 1.24 + parts[#parts+1] = spaced_word 1.25 + line_length = line_length + #spaced_word 1.26 + first_line = false 1.27 + end 1.28 + if not need_encoding then 1.29 + parts[#parts+1] = "\r\n" 1.30 + return table.concat(parts) 1.31 + end 1.32 + charset = "US-ASCII" 1.33 + end 1.34 + local parts = { key, ": " } 1.35 + local line_length 1.36 + local opening = "=?" .. charset .. "?Q?" 1.37 + local closing = "?=" 1.38 + local indentation = "" 1.39 + for i = 1, key_length do 1.40 + indentation = indentation .. " " 1.41 + end 1.42 + local open = false 1.43 + for char in string.gmatch(value, ".") do 1.44 + local encoded_char 1.45 + if string.find(char, "^[0-9A-Za-z%.%-]$") then 1.46 + encoded_char = char 1.47 + else 1.48 + local byte = string.byte(char) 1.49 + if byte == 32 then 1.50 + encoded_char = "_" 1.51 + else 1.52 + encoded_char = string.format("=%02X", byte) 1.53 + end 1.54 + end 1.55 + if open and line_length + #encoded_char > 76 then 1.56 + parts[#parts+1] = closing 1.57 + parts[#parts+1] = "\r\n" 1.58 + parts[#parts+1] = indentation 1.59 + open = false 1.60 + end 1.61 + if not open then 1.62 + parts[#parts+1] = opening 1.63 + line_length = key_length + #opening + #closing 1.64 + open = true 1.65 + end 1.66 + parts[#parts+1] = encoded_char 1.67 + line_length = line_length + #encoded_char 1.68 + end 1.69 + if open then 1.70 + parts[#parts+1] = "?=" 1.71 + end 1.72 + parts[#parts+1] = "\r\n" 1.73 + return table.concat(parts) 1.74 +end