text.lua 802 B

123456789101112131415161718192021222324252627282930313233343536
  1. -- Text processing functions.
  2. local M = {}
  3. --- Hex encode a string.
  4. ---
  5. --- @param str string String to encode
  6. --- @return string : Hex encoded string
  7. function M.hexencode(str)
  8. local enc = {} ---@type string[]
  9. for i = 1, #str do
  10. enc[i] = string.format('%02X', str:byte(i, i + 1))
  11. end
  12. return table.concat(enc)
  13. end
  14. --- Hex decode a string.
  15. ---
  16. --- @param enc string String to decode
  17. --- @return string? : Decoded string
  18. --- @return string? : Error message, if any
  19. function M.hexdecode(enc)
  20. if #enc % 2 ~= 0 then
  21. return nil, 'string must have an even number of hex characters'
  22. end
  23. local str = {} ---@type string[]
  24. for i = 1, #enc, 2 do
  25. local n = assert(tonumber(enc:sub(i, i + 1), 16))
  26. str[#str + 1] = string.char(n)
  27. end
  28. return table.concat(str), nil
  29. end
  30. return M