perf(vim.text): use lookup table implementation for hex encoding (#30080)

Co-authored-by: glepnir <glephunter@gmail.com>
This commit is contained in:
Gregory Anders
2024-11-26 13:56:01 -06:00
committed by GitHub
parent e8450ef236
commit 99b5ffd688
3 changed files with 89 additions and 3 deletions

View File

@ -2,6 +2,18 @@
local M = {}
local alphabet = '0123456789ABCDEF'
local atoi = {} ---@type table<string, integer>
local itoa = {} ---@type table<integer, string>
do
for i = 1, #alphabet do
local char = alphabet:sub(i, i)
itoa[i - 1] = char
atoi[char] = i - 1
atoi[char:lower()] = i - 1
end
end
--- Hex encode a string.
---
--- @param str string String to encode
@ -9,7 +21,9 @@ local M = {}
function M.hexencode(str)
local enc = {} ---@type string[]
for i = 1, #str do
enc[i] = string.format('%02X', str:byte(i, i + 1))
local byte = str:byte(i)
enc[2 * i - 1] = itoa[math.floor(byte / 16)]
enc[2 * i] = itoa[byte % 16]
end
return table.concat(enc)
end
@ -26,8 +40,12 @@ function M.hexdecode(enc)
local str = {} ---@type string[]
for i = 1, #enc, 2 do
local n = assert(tonumber(enc:sub(i, i + 1), 16))
str[#str + 1] = string.char(n)
local u = atoi[enc:sub(i, i)]
local l = atoi[enc:sub(i + 1, i + 1)]
if not u or not l then
return nil, 'string must contain only hex characters'
end
str[(i + 1) / 2] = string.char(u * 16 + l)
end
return table.concat(str), nil
end