diff options
author | Dominik Picheta <dominikpicheta@googlemail.com> | 2013-01-25 21:43:54 +0000 |
---|---|---|
committer | Dominik Picheta <dominikpicheta@googlemail.com> | 2013-01-25 21:43:54 +0000 |
commit | c4743805d9a45cf4bd2fe1535e29a1b953cfe876 (patch) | |
tree | 8b3a22329b0fd31e998b3512930afa812c76601b /lib/pure | |
parent | 0e5e852f5cca7c4f03b4294120b6c0bb551e3211 (diff) | |
download | Nim-c4743805d9a45cf4bd2fe1535e29a1b953cfe876.tar.gz |
Added strutils.unescape and fixed issue with strutils.escape.
Diffstat (limited to 'lib/pure')
-rwxr-xr-x | lib/pure/strutils.nim | 40 |
1 files changed, 39 insertions, 1 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 8a5061037..8b64434d8 100755 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -850,13 +850,51 @@ proc escape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, for c in items(s): case c of '\0'..'\31', '\128'..'\255': - add(result, '\\') + add(result, "\\x") add(result, toHex(ord(c), 2)) of '\\': add(result, "\\\\") of '\'': add(result, "\\'") of '\"': add(result, "\\\"") else: add(result, c) add(result, suffix) + +proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, + rtl, extern: "nsuUnescape".} = + ## Unescapes a string `s`. This complements ``escape`` as it performs the + ## opposite operations. + ## + ## If `s` does not begin with ``prefix`` and end with ``suffix`` a EInvalidValue + ## exception will be raised. + result = newStringOfCap(s.len) + var i = 0 + if s[0 .. prefix.len-1] != prefix: + raise newException(EInvalidValue, + "String does not start with a prefix of: " & prefix) + i.inc() + while True: + if i == s.len-suffix.len: break + case s[i] + of '\\': + case s[i+1]: + of 'x': + let j = parseHexInt(s[i+2 .. i+3]) + result.add(chr(j)) + inc(i, 2) + of '\\': + result.add('\\') + of '\'': + result.add('\'') + of '\"': + result.add('\"') + else: result.add("\\" & s[i+1]) + inc(i) + of '\0': break + else: + result.add(s[i]) + i.inc() + if s[i .. -1] != suffix: + raise newException(EInvalidValue, + "String does not end with a suffix of: " & suffix) proc validIdentifier*(s: string): bool {.noSideEffect, rtl, extern: "nsuValidIdentifier".} = |