decode_helpers.nim 890 B

12345678910111213141516171819202122232425
  1. # Include file that implements 'decodePercent' and friends. Do not import it!
  2. proc handleHexChar(c: char, x: var int, f: var bool) {.inline.} =
  3. case c
  4. of '0'..'9': x = (x shl 4) or (ord(c) - ord('0'))
  5. of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10)
  6. of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10)
  7. else: f = true
  8. proc decodePercent(s: string, i: var int): char =
  9. ## Converts `%xx` hexadecimal to the charracter with ordinal number `xx`.
  10. ##
  11. ## If `xx` is not a valid hexadecimal value, it is left intact: only the
  12. ## leading `%` is returned as-is, and `xx` characters will be processed in the
  13. ## next step (e.g. in `uri.decodeUrl`) as regular characters.
  14. result = '%'
  15. if i+2 < s.len:
  16. var x = 0
  17. var failed = false
  18. handleHexChar(s[i+1], x, failed)
  19. handleHexChar(s[i+2], x, failed)
  20. if not failed:
  21. result = chr(x)
  22. inc(i, 2)