summaryrefslogtreecommitdiff
path: root/compat.py
diff options
context:
space:
mode:
Diffstat (limited to 'compat.py')
-rw-r--r--compat.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/compat.py b/compat.py
index 7338c479fb..e1bc0ed673 100644
--- a/compat.py
+++ b/compat.py
@@ -14,6 +14,17 @@ if sys.version_info < (3,):
return x
def iteritems(d):
return d.iteritems()
+ def escape_string(s):
+ if isinstance(s, unicode):
+ s = s.encode('ascii')
+ result = ''
+ for c in s:
+ if not (32 <= ord(c) < 127) or c in ('\\', '"'):
+ result += '\\%03o' % ord(c)
+ else:
+ result += c
+ return result
+
else:
def isbasestring(s):
return isinstance(s, (str, bytes))
@@ -29,3 +40,21 @@ else:
return codecs.utf_8_encode(x)[0]
def iteritems(d):
return iter(d.items())
+ def charcode_to_c_escapes(c):
+ rev_result = []
+ while c >= 256:
+ c, low = (c // 256, c % 256)
+ rev_result.append('\\%03o' % low)
+ rev_result.append('\\%03o' % c)
+ return ''.join(reversed(rev_result))
+ def escape_string(s):
+ result = ''
+ if isinstance(s, str):
+ s = s.encode('utf-8')
+ for c in s:
+ if not(32 <= c < 127) or c in (ord('\\'), ord('"')):
+ result += charcode_to_c_escapes(c)
+ else:
+ result += chr(c)
+ return result
+