aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua/vim/text.lua
diff options
context:
space:
mode:
authorJosh Rahm <joshuarahm@gmail.com>2025-02-05 23:09:29 +0000
committerJosh Rahm <joshuarahm@gmail.com>2025-02-05 23:09:29 +0000
commitd5f194ce780c95821a855aca3c19426576d28ae0 (patch)
treed45f461b19f9118ad2bb1f440a7a08973ad18832 /runtime/lua/vim/text.lua
parentc5d770d311841ea5230426cc4c868e8db27300a8 (diff)
parent44740e561fc93afe3ebecfd3618bda2d2abeafb0 (diff)
downloadrneovim-d5f194ce780c95821a855aca3c19426576d28ae0.tar.gz
rneovim-d5f194ce780c95821a855aca3c19426576d28ae0.tar.bz2
rneovim-d5f194ce780c95821a855aca3c19426576d28ae0.zip
Merge remote-tracking branch 'upstream/master' into mix_20240309HEADrahm
Diffstat (limited to 'runtime/lua/vim/text.lua')
-rw-r--r--runtime/lua/vim/text.lua24
1 files changed, 21 insertions, 3 deletions
diff --git a/runtime/lua/vim/text.lua b/runtime/lua/vim/text.lua
index d45c8021c6..f910ab3a1d 100644
--- a/runtime/lua/vim/text.lua
+++ b/runtime/lua/vim/text.lua
@@ -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