+def escapify(x):
+ out = StringIO()
+ for ch in bin(x):
+ k = byteord(ch)
+ if k == 9: out.write("\\t")
+ elif k == 10: out.write("\\n")
+ elif k == 13: out.write("\\r")
+ elif k == 39: out.write("\\'")
+ elif k == 92: out.write("\\\\")
+ elif 20 <= k <= 126: out.write(chr(k))
+ else: out.write("\\x%02x" % k)
+ return out.getvalue()
+
+R_STRESC = RX.compile(r"\\ (?: x ([0-9A-Fa-f]{2}) | (.))",
+ RX.VERBOSE)
+def unescapify(x):
+ str = BytesIO()
+ i, n = 0, len(x)
+ while True:
+ m = R_STRESC.search(x, i)
+ if m is not None: j = m.start(0)
+ else: j = n
+ str.write(bin(str[i:j]))
+ if m is None: break
+ k, e = m.group(1), m.group(2)
+ if k is not None: ch = int(k, 16)
+ elif ch == "a": ch = 7
+ elif ch == "b": ch = 8
+ elif ch == "f": ch = 12
+ elif ch == "n": ch = 10
+ elif ch == "r": ch = 13
+ elif ch == "t": ch = 9
+ elif ch == "v": ch = 11
+ else: ch = byteord(e)
+ str.write(bytechr(ch))
+ i = m.end(0)
+ return text(out.getvalue())
+