Mercurial > prosody-hg
comparison util/hex.lua @ 6545:ec566d7cd518
util.hex: Pedantic optimization, 1 table lookup per byte instead of 3 function calls makes it go faster
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Mon, 12 Jan 2015 15:10:37 +0100 |
| parents | 3f4809d01783 |
| children | 442019e955dc |
comparison
equal
deleted
inserted
replaced
| 6544:2f709bc35575 | 6545:ec566d7cd518 |
|---|---|
| 1 local s_char = string.char; | 1 local s_char = string.char; |
| 2 local s_format = string.format; | |
| 3 local s_gsub = string.gsub; | |
| 2 | 4 |
| 3 local function char_to_hex(c) | 5 local char_to_hex = {}; |
| 4 return ("%02x"):format(c:byte()) | 6 local hex_to_char = {}; |
| 5 end | |
| 6 | 7 |
| 7 local function hex_to_char(h) | 8 do |
| 8 return s_char(tonumber(h, 16)); | 9 local char, hex; |
| 10 for i = 0,255 do | |
| 11 char, hex = s_char(i), s_format("%02x", i); | |
| 12 char_to_hex[char] = hex; | |
| 13 hex_to_char[hex] = char; | |
| 14 end | |
| 9 end | 15 end |
| 10 | 16 |
| 11 local function to(s) | 17 local function to(s) |
| 12 return s:gsub(".", char_to_hex); | 18 return (s_gsub(s, ".", char_to_hex)); |
| 13 end | 19 end |
| 14 | 20 |
| 15 local function from(s) | 21 local function from(s) |
| 16 return s:gsub("..", hex_to_char); | 22 return (s_gsub(s, "..", hex_to_char)); |
| 17 end | 23 end |
| 18 | 24 |
| 19 return { to = to, from = from } | 25 return { to = to, from = from } |
