Returns safe representation of a given basestring value >>> safecharencode(u'test123') == u'test123' True >>> safecharencode(u'test\x01\x02\xaf') == u'test\\\\x01\\\\x02\\xaf' True
(value)
| 40 | SLASH_MARKER = "__SLASH__" |
| 41 | |
| 42 | def safecharencode(value): |
| 43 | """ |
| 44 | Returns safe representation of a given basestring value |
| 45 | |
| 46 | >>> safecharencode(u'test123') == u'test123' |
| 47 | True |
| 48 | >>> safecharencode(u'test\x01\x02\xaf') == u'test\\\\x01\\\\x02\\xaf' |
| 49 | True |
| 50 | """ |
| 51 | |
| 52 | retVal = value |
| 53 | |
| 54 | if isinstance(value, string_types): |
| 55 | if any(_ not in SAFE_CHARS for _ in value): |
| 56 | retVal = retVal.replace(HEX_ENCODED_PREFIX, HEX_ENCODED_PREFIX_MARKER) |
| 57 | retVal = retVal.replace('\\', SLASH_MARKER) |
| 58 | |
| 59 | for char in SAFE_ENCODE_SLASH_REPLACEMENTS: |
| 60 | retVal = retVal.replace(char, repr(char).strip('\'')) |
| 61 | |
| 62 | for char in set(retVal): |
| 63 | if not (char in string.printable or isinstance(value, text_type) and ord(char) >= 160): |
| 64 | retVal = retVal.replace(char, '\\x%02x' % ord(char)) |
| 65 | |
| 66 | retVal = retVal.replace(SLASH_MARKER, "\\\\") |
| 67 | retVal = retVal.replace(HEX_ENCODED_PREFIX_MARKER, HEX_ENCODED_PREFIX) |
| 68 | elif isinstance(value, list): |
| 69 | for i in xrange(len(value)): |
| 70 | retVal[i] = safecharencode(value[i]) |
| 71 | |
| 72 | return retVal |
| 73 | |
| 74 | def safechardecode(value, binary=False): |
| 75 | """ |
no test coverage detected
searching dependent graphs…