Skip to content

Commit 3c0c2b8

Browse files
committed
Make empty cstring singleton
1 parent 5e3ad61 commit 3c0c2b8

1 file changed

Lines changed: 9 additions & 2 deletions

File tree

src/cstring.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ static PyTypeObject cstring_type;
3636

3737
#define CSTRING_ALLOC(tp, len) ((struct cstring *)(tp)->tp_alloc((tp), (len)))
3838

39+
/* singleton, initialized in cstring_new_empty */
40+
static const struct cstring *cstring_EMPTY = NULL;
41+
3942
static void *_bad_argument_type(PyObject *o) {
4043
PyErr_Format(
4144
PyExc_TypeError,
@@ -70,8 +73,12 @@ static PyObject *_cstring_copy(PyObject *self) {
7073
}
7174

7275
static PyObject *cstring_new_empty(void) {
73-
/* TODO: empty cstring should be a singleton */
74-
return _cstring_new(&cstring_type, "", 0);
76+
if(!cstring_EMPTY) {
77+
cstring_EMPTY = (struct cstring *)_cstring_new(&cstring_type, "", 0);
78+
}
79+
/* leaking one reference for singleton cache (never cleaned up) */
80+
Py_INCREF(cstring_EMPTY);
81+
return (PyObject *)cstring_EMPTY;
7582
}
7683

7784
static const char *_obj_as_string_and_size(PyObject *o, Py_ssize_t *s) {

0 commit comments

Comments
 (0)