Python中的字符串对象(Python 源码剖析第三章)
时间:2010-11-12 来源:Ray Z
PyString_FromString
1 PyObject* PyString_FromString(const char *str)
2 {
3 register size_t size;
4 register PyStringObject *op;
5
6 assert(str != NULL);
7 size = strlen(str);
8 if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
9 PyErr_SetString(PyExc_OverflowError,
10 "string is too long for a Python string");
11 return NULL;
12 }
13 if (size == 0 && (op = nullstring) != NULL) {
14 #ifdef COUNT_ALLOCS
15 null_strings++;
16 #endif
17 Py_INCREF(op);
18 return (PyObject *)op;
19 }
20 if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
21 #ifdef COUNT_ALLOCS
22 one_strings++;
23 #endif
24 Py_INCREF(op);
25 return (PyObject *)op;
26 }
27
28 /* Inline PyObject_NewVar */
29 op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
30 if (op == NULL)
31 return PyErr_NoMemory();
32 PyObject_INIT_VAR(op, &PyString_Type, size);
33 op->ob_shash = -1;
34 op->ob_sstate = SSTATE_NOT_INTERNED;
35 Py_MEMCPY(op->ob_sval, str, size+1);
36 /* share short strings */
37 if (size == 0) {
38 PyObject *t = (PyObject *)op;
39 PyString_InternInPlace(&t);
40 op = (PyStringObject *)t;
41 nullstring = op;
42 Py_INCREF(op);
43 } else if (size == 1) {
44 PyObject *t = (PyObject *)op;
45 PyString_InternInPlace(&t);
46 op = (PyStringObject *)t;
47 characters[*str & UCHAR_MAX] = op;
48 Py_INCREF(op);
49 }
50 return (PyObject *) op;
51 }
2 {
3 register size_t size;
4 register PyStringObject *op;
5
6 assert(str != NULL);
7 size = strlen(str);
8 if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
9 PyErr_SetString(PyExc_OverflowError,
10 "string is too long for a Python string");
11 return NULL;
12 }
13 if (size == 0 && (op = nullstring) != NULL) {
14 #ifdef COUNT_ALLOCS
15 null_strings++;
16 #endif
17 Py_INCREF(op);
18 return (PyObject *)op;
19 }
20 if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
21 #ifdef COUNT_ALLOCS
22 one_strings++;
23 #endif
24 Py_INCREF(op);
25 return (PyObject *)op;
26 }
27
28 /* Inline PyObject_NewVar */
29 op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
30 if (op == NULL)
31 return PyErr_NoMemory();
32 PyObject_INIT_VAR(op, &PyString_Type, size);
33 op->ob_shash = -1;
34 op->ob_sstate = SSTATE_NOT_INTERNED;
35 Py_MEMCPY(op->ob_sval, str, size+1);
36 /* share short strings */
37 if (size == 0) {
38 PyObject *t = (PyObject *)op;
39 PyString_InternInPlace(&t);
40 op = (PyStringObject *)t;
41 nullstring = op;
42 Py_INCREF(op);
43 } else if (size == 1) {
44 PyObject *t = (PyObject *)op;
45 PyString_InternInPlace(&t);
46 op = (PyStringObject *)t;
47 characters[*str & UCHAR_MAX] = op;
48 Py_INCREF(op);
49 }
50 return (PyObject *) op;
51 }
相关阅读 更多 +