MCPcopy Index your code
hub / github.com/RustPython/RustPython / unicodeescape_string

Function unicodeescape_string

Lib/_pycodecs.py:1082–1145  ·  view source on GitHub ↗
(s, size, quotes)

Source from the content-addressed store, hash-verified

1080
1081
1082def unicodeescape_string(s, size, quotes):
1083 p = []
1084 if quotes:
1085 if s.find("'") != -1 and s.find('"') == -1:
1086 p.append(b'"')
1087 else:
1088 p.append(b"'")
1089 pos = 0
1090 while pos < size:
1091 ch = s[pos]
1092 # /* Escape quotes */
1093 if quotes and (ch == p[1] or ch == "\\"):
1094 p.append(b"\\%c" % ord(ch))
1095 pos += 1
1096 continue
1097
1098 # ifdef Py_UNICODE_WIDE
1099 # /* Map 21-bit characters to '\U00xxxxxx' */
1100 elif ord(ch) >= 0x10000:
1101 p.append(b"\\U%08x" % ord(ch))
1102 pos += 1
1103 continue
1104 # endif
1105 # /* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
1106 elif ord(ch) >= 0xD800 and ord(ch) < 0xDC00:
1107 pos += 1
1108 ch2 = s[pos]
1109
1110 if ord(ch2) >= 0xDC00 and ord(ch2) <= 0xDFFF:
1111 ucs = (((ord(ch) & 0x03FF) << 10) | (ord(ch2) & 0x03FF)) + 0x00010000
1112 p.append(b"\\U%08x" % ucs)
1113 pos += 1
1114 continue
1115
1116 # /* Fall through: isolated surrogates are copied as-is */
1117 pos -= 1
1118
1119 # /* Map 16-bit characters to '\uxxxx' */
1120 if ord(ch) >= 256:
1121 p.append(b"\\u%04x" % ord(ch))
1122
1123 # /* Map special whitespace to '\t', \n', '\r' */
1124 elif ch == "\t":
1125 p.append(b"\\t")
1126
1127 elif ch == "\n":
1128 p.append(b"\\n")
1129
1130 elif ch == "\r":
1131 p.append(b"\\r")
1132
1133 elif ch == "\\":
1134 p.append(b"\\\\")
1135
1136 # /* Map non-printable US ASCII to '\xhh' */
1137 elif ch < " " or ch >= chr(0x7F):
1138 p.append(b"\\x%02x" % ord(ch))
1139 # /* Copy everything else as-is */

Callers 1

unicode_escape_encodeFunction · 0.85

Calls 4

ordFunction · 0.85
chrFunction · 0.85
findMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected