@@ -29,6 +29,14 @@ static PyTypeObject cstring_type;
29
29
30
30
#define CSTRING_ALLOC (tp , len ) ((struct cstring *)(tp)->tp_alloc((tp), (len)))
31
31
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
+
32
40
static PyObject * _cstring_new (PyTypeObject * type , const char * value , Py_ssize_t len ) {
33
41
struct cstring * new = CSTRING_ALLOC (type , len + 1 );
34
42
if (!new )
@@ -58,7 +66,6 @@ static PyObject *cstring_new_empty(void) {
58
66
return _cstring_new (& cstring_type , "" , 0 );
59
67
}
60
68
61
-
62
69
static const char * _obj_as_string_and_size (PyObject * o , Py_ssize_t * s ) {
63
70
if (PyUnicode_Check (o ))
64
71
return PyUnicode_AsUTF8AndSize (o , s );
@@ -74,13 +81,14 @@ static const char *_obj_as_string_and_size(PyObject *o, Py_ssize_t *s) {
74
81
return buffer ;
75
82
}
76
83
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
+ }
81
89
82
90
* s = -1 ;
83
- return NULL ;
91
+ return _bad_argument_type ( o ) ;
84
92
}
85
93
86
94
static PyObject * cstring_new (PyTypeObject * type , PyObject * args , PyObject * kwargs ) {
@@ -277,18 +285,6 @@ static PyObject *cstring_subscript(PyObject *self, PyObject *key) {
277
285
return NULL ;
278
286
}
279
287
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
-
292
288
static Py_ssize_t _fix_index (Py_ssize_t i , Py_ssize_t len ) {
293
289
Py_ssize_t result = i ;
294
290
if (result < 0 )
@@ -316,7 +312,7 @@ static struct _substr_params *_parse_substr_args(PyObject *self, PyObject *args,
316
312
return NULL ;
317
313
318
314
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 );
320
316
if (!substr )
321
317
return NULL ;
322
318
0 commit comments