Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ecd8bc1

Browse files
committed
Combine similar utility functions
1 parent 10291c9 commit ecd8bc1

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

src/cstring.c

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ static PyTypeObject cstring_type;
2929

3030
#define CSTRING_ALLOC(tp, len) ((struct cstring *)(tp)->tp_alloc((tp), (len)))
3131

32+
static void *_bad_argument_type(PyObject *o) {
33+
PyErr_Format(
34+
PyExc_TypeError,
35+
"Bad argument type: %s",
36+
Py_TYPE(o)->tp_name);
37+
return NULL;
38+
}
39+
3240
static PyObject *_cstring_new(PyTypeObject *type, const char *value, Py_ssize_t len) {
3341
struct cstring *new = CSTRING_ALLOC(type, len + 1);
3442
if(!new)
@@ -58,7 +66,6 @@ static PyObject *cstring_new_empty(void) {
5866
return _cstring_new(&cstring_type, "", 0);
5967
}
6068

61-
6269
static const char *_obj_as_string_and_size(PyObject *o, Py_ssize_t *s) {
6370
if(PyUnicode_Check(o))
6471
return PyUnicode_AsUTF8AndSize(o, s);
@@ -74,13 +81,14 @@ static const char *_obj_as_string_and_size(PyObject *o, Py_ssize_t *s) {
7481
return buffer;
7582
}
7683

77-
PyErr_Format(
78-
PyExc_TypeError,
79-
"Invalid initialization type: %s.",
80-
Py_TYPE(o)->tp_name);
84+
if(PyObject_TypeCheck(o, &cstring_type)) {
85+
/* TODO: implement buffer protocol for cstring */
86+
*s = Py_SIZE(o) - 1;
87+
return CSTRING_VALUE(o);
88+
}
8189

8290
*s = -1;
83-
return NULL;
91+
return _bad_argument_type(o);
8492
}
8593

8694
static PyObject *cstring_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
@@ -277,18 +285,6 @@ static PyObject *cstring_subscript(PyObject *self, PyObject *key) {
277285
return NULL;
278286
}
279287

280-
static const char *_obj_to_utf8(PyObject *o, Py_ssize_t *len_p) {
281-
if(PyUnicode_Check(o))
282-
return PyUnicode_AsUTF8AndSize(o, len_p);
283-
if(PyObject_TypeCheck(o, &cstring_type)) {
284-
*len_p = cstring_len(o);
285-
return CSTRING_VALUE(o);
286-
}
287-
PyErr_Format(
288-
PyExc_TypeError, "Object cannot be type %s.", Py_TYPE(o)->tp_name);
289-
return NULL;
290-
}
291-
292288
static Py_ssize_t _fix_index(Py_ssize_t i, Py_ssize_t len) {
293289
Py_ssize_t result = i;
294290
if(result < 0)
@@ -316,7 +312,7 @@ static struct _substr_params *_parse_substr_args(PyObject *self, PyObject *args,
316312
return NULL;
317313

318314
Py_ssize_t substr_len;
319-
const char *substr = _obj_to_utf8(substr_obj, &substr_len);
315+
const char *substr = _obj_as_string_and_size(substr_obj, &substr_len);
320316
if(!substr)
321317
return NULL;
322318

0 commit comments

Comments
 (0)