Convert bytestring to the C string literal syntax (with necessary escaping). For example, b'foo\n' gets converted to 'foo\\n' (note that double quotes are not added).
(b: bytes)
| 1001 | |
| 1002 | |
| 1003 | def encode_c_string_literal(b: bytes) -> str: |
| 1004 | """Convert bytestring to the C string literal syntax (with necessary escaping). |
| 1005 | |
| 1006 | For example, b'foo\n' gets converted to 'foo\\n' (note that double quotes are not added). |
| 1007 | """ |
| 1008 | if not _translation_table: |
| 1009 | # Initialize the translation table on the first call. |
| 1010 | d = { |
| 1011 | ord("\n"): "\\n", |
| 1012 | ord("\r"): "\\r", |
| 1013 | ord("\t"): "\\t", |
| 1014 | ord('"'): '\\"', |
| 1015 | ord("\\"): "\\\\", |
| 1016 | } |
| 1017 | for i in range(256): |
| 1018 | if i not in d: |
| 1019 | if i < 32 or i >= 127: |
| 1020 | d[i] = "\\x%.2x" % i |
| 1021 | else: |
| 1022 | d[i] = chr(i) |
| 1023 | _translation_table.update(str.maketrans(d)) |
| 1024 | return b.decode("latin1").translate(_translation_table) |