mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-19 14:00:35 +00:00
use hexchar in stdlib (#16290)
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user