This commit is contained in:
Gregory Anders 2024-09-13 00:09:16 +01:00 committed by GitHub
commit 638d8db0ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 3 deletions

View File

@ -2,6 +2,17 @@
local M = {}
local alphabet = '0123456789ABCDEF'
local lookup = {} ---@type table<integer|string, integer|string>
do
for i = 1, #alphabet do
local char = alphabet:sub(i, i)
lookup[i - 1] = char
lookup[char] = i - 1
lookup[char:lower()] = i - 1
end
end
--- Hex encode a string.
---
--- @param str string String to encode
@ -9,7 +20,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[#enc + 1] = lookup[math.floor(byte / 16)] --[[@as string]]
enc[#enc + 1] = lookup[byte % 16] --[[@as string]]
end
return table.concat(enc)
end
@ -26,8 +39,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 = lookup[enc:sub(i, i)] --[[@as integer]]
local l = lookup[enc:sub(i + 1, i + 1)] --[[@as integer]]
if not u or not l then
return nil, 'string must contain only hex characters'
end
str[#str + 1] = string.char(u * 16 + l)
end
return table.concat(str), nil
end

View File

@ -26,5 +26,21 @@ describe('vim.text', function()
eq(output, vim.text.hexencode(input))
eq(input, vim.text.hexdecode(output))
end)
it('errors on invalid input', function()
-- Odd number of hex characters
do
local res, err = vim.text.hexdecode('ABC')
eq(nil, res)
eq('string must have an even number of hex characters', err)
end
-- Non-hexadecimal input
do
local res, err = vim.text.hexdecode('nothex')
eq(nil, res)
eq('string must contain only hex characters', err)
end
end)
end)
end)