Debian Codegraph @

Objects/stringlib/repr.h

raw
1 /* stringlib: repr() implementation */
2
3 #ifndef STRINGLIB_FASTSEARCH_H
4 #error must include "stringlib/fastsearch.h" before including this module
5 #endif
6
7
8 static void
9 STRINGLIB(repr)(PyObject *unicode, Py_UCS4 quote,
10 STRINGLIB_CHAR *odata)
11 {
12 Py_ssize_t isize = PyUnicode_GET_LENGTH(unicode);
13 const void *idata = PyUnicode_DATA(unicode);
14 int ikind = PyUnicode_KIND(unicode);
15
16 *odata++ = quote;
17 for (Py_ssize_t i = 0; i < isize; i++) {
18 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
19
20 /* Escape quotes and backslashes */
21 if ((ch == quote) || (ch == '\\')) {
22 *odata++ = '\\';
23 *odata++ = ch;
24 continue;
25 }
26
27 /* Map special whitespace to '\t', \n', '\r' */
28 if (ch == '\t') {
29 *odata++ = '\\';
30 *odata++ = 't';
31 }
32 else if (ch == '\n') {
33 *odata++ = '\\';
34 *odata++ = 'n';
35 }
36 else if (ch == '\r') {
37 *odata++ = '\\';
38 *odata++ = 'r';
39 }
40
41 /* Map non-printable US ASCII to '\xhh' */
42 else if (ch < ' ' || ch == 0x7F) {
43 *odata++ = '\\';
44 *odata++ = 'x';
45 *odata++ = Py_hexdigits[(ch >> 4) & 0x000F];
46 *odata++ = Py_hexdigits[ch & 0x000F];
47 }
48
49 /* Copy ASCII characters as-is */
50 else if (ch < 0x7F) {
51 *odata++ = ch;
52 }
53
54 /* Non-ASCII characters */
55 else {
56 /* Map Unicode whitespace and control characters
57 (categories Z* and C* except ASCII space)
58 */
59 if (!Py_UNICODE_ISPRINTABLE(ch)) {
60 *odata++ = '\\';
61 /* Map 8-bit characters to '\xhh' */
62 if (ch <= 0xff) {
63 *odata++ = 'x';
64 *odata++ = Py_hexdigits[(ch >> 4) & 0x000F];
65 *odata++ = Py_hexdigits[ch & 0x000F];
66 }
67 /* Map 16-bit characters to '\uxxxx' */
68 else if (ch <= 0xffff) {
69 *odata++ = 'u';
70 *odata++ = Py_hexdigits[(ch >> 12) & 0xF];
71 *odata++ = Py_hexdigits[(ch >> 8) & 0xF];
72 *odata++ = Py_hexdigits[(ch >> 4) & 0xF];
73 *odata++ = Py_hexdigits[ch & 0xF];
74 }
75 /* Map 21-bit characters to '\U00xxxxxx' */
76 else {
77 *odata++ = 'U';
78 *odata++ = Py_hexdigits[(ch >> 28) & 0xF];
79 *odata++ = Py_hexdigits[(ch >> 24) & 0xF];
80 *odata++ = Py_hexdigits[(ch >> 20) & 0xF];
81 *odata++ = Py_hexdigits[(ch >> 16) & 0xF];
82 *odata++ = Py_hexdigits[(ch >> 12) & 0xF];
83 *odata++ = Py_hexdigits[(ch >> 8) & 0xF];
84 *odata++ = Py_hexdigits[(ch >> 4) & 0xF];
85 *odata++ = Py_hexdigits[ch & 0xF];
86 }
87 }
88 /* Copy characters as-is */
89 else {
90 *odata++ = ch;
91 }
92 }
93 }
94 *odata = quote;
95 }