use hexchar in stdlib (#16290)

This commit is contained in:
flywind
2020-12-17 06:41:05 -06:00
committed by GitHub
parent 8cd3655dee
commit e1e069dd6c
7 changed files with 68 additions and 75 deletions

View File

@@ -1,9 +1,25 @@
proc handleHexChar*(c: char, x: var int, f: var bool) {.inline.} =
proc handleHexChar*(c: char, x: var int): bool {.inline.} =
## Converts `%xx` hexadecimal to the ordinal number and adds the result to `x`.
## Returns `true` if `c` is hexadecimal.
##
## When `c` is hexadecimal, the proc is equal to `x = x shl 4 + hex2Int(c)`.
runnableExamples:
var x = 0
assert handleHexChar('a', x)
assert x == 10
assert handleHexChar('B', x)
assert x == 171 # 10 shl 4 + 11
assert not handleHexChar('?', x)
assert x == 171 # unchanged
result = true
case c
of '0'..'9': x = (x shl 4) or (ord(c) - ord('0'))
of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10)
of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10)
else: f = true
else:
result = false
proc decodePercent*(s: openArray[char], i: var int): char =
## Converts `%xx` hexadecimal to the character with ordinal number `xx`.
@@ -14,9 +30,6 @@ proc decodePercent*(s: openArray[char], i: var int): char =
result = '%'
if i+2 < s.len:
var x = 0
var failed = false
handleHexChar(s[i+1], x, failed)
handleHexChar(s[i+2], x, failed)
if not failed:
if handleHexChar(s[i+1], x) and handleHexChar(s[i+2], x):
result = chr(x)
inc(i, 2)