Fredrik Lundh | b947948 | 2006-05-26 17:22:38 +0000 | [diff] [blame] | 1 | /* stringlib: partition implementation */ |
| 2 | |
| 3 | #ifndef STRINGLIB_PARTITION_H |
| 4 | #define STRINGLIB_PARTITION_H |
| 5 | |
| 6 | #include "stringlib/fastsearch.h" |
| 7 | |
| 8 | Py_LOCAL(PyObject*) |
| 9 | partition(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, |
| 10 | PyObject* sep_obj, const STRINGLIB_CHAR* sep, Py_ssize_t sep_len) |
| 11 | { |
| 12 | PyObject* out; |
| 13 | Py_ssize_t pos; |
| 14 | |
| 15 | if (sep_len == 0) { |
| 16 | PyErr_SetString(PyExc_ValueError, "empty separator"); |
| 17 | return NULL; |
| 18 | } |
| 19 | |
| 20 | out = PyTuple_New(3); |
| 21 | if (!out) |
| 22 | return NULL; |
| 23 | |
| 24 | pos = fastsearch(str, str_len, sep, sep_len, FAST_SEARCH); |
| 25 | |
| 26 | if (pos < 0) { |
| 27 | Py_INCREF(str_obj); |
| 28 | PyTuple_SET_ITEM(out, 0, (PyObject*) str_obj); |
| 29 | Py_INCREF(STRINGLIB_EMPTY); |
| 30 | PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); |
| 31 | Py_INCREF(STRINGLIB_EMPTY); |
| 32 | PyTuple_SET_ITEM(out, 2, (PyObject*) STRINGLIB_EMPTY); |
| 33 | return out; |
| 34 | } |
| 35 | |
| 36 | PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(str, pos)); |
| 37 | Py_INCREF(sep_obj); |
| 38 | PyTuple_SET_ITEM(out, 1, sep_obj); |
| 39 | pos += sep_len; |
| 40 | PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(str + pos, str_len - pos)); |
| 41 | |
| 42 | if (PyErr_Occurred()) { |
| 43 | Py_DECREF(out); |
| 44 | return NULL; |
| 45 | } |
| 46 | |
| 47 | return out; |
| 48 | } |
| 49 | |
| 50 | #endif |