8000 Add rindex() method · atpalmer-python/python-cstring@b028f4d · GitHub
[go: up one dir, main page]

Skip to content

Commit b028f4d

Browse files
committed
Add rindex() method
1 parent 322821a commit b028f4d

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,16 @@ Notes:
5151
* `start` and `end`, if provided, are _byte_ indexes.
5252

5353

54+
### rindex(substring [,start [,end]])
55+
56+
See: https://docs.python.org/3/library/stdtypes.html#str.rindex
57+
58+
Notes:
59+
60+
* `substring` may be a `cstring` or Python `str` object.
61+
* `start` and `end`, if provided, are _byte_ indexes.
62+
63+
5464
## TODO
5565

5666
* Write docs (see `str` type docs)

src/cstring.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,22 @@ PyObject *cstring_rfind(PyObject *self, PyObject *args) {
321321
return PyLong_FromSsize_t(p - CSTRING_VALUE(self));
322322
}
323323

324+
PyDoc_STRVAR(rindex__doc__, "");
325+
PyObject *cstring_rindex(PyObject *self, PyObject *args) {
326+
struct _substr_params params;
327+
328+
if(!_parse_substr_args(self, args, &params))
329+
return NULL;
330+
331+
const char *p = _substr_params_rstr(&params);
332+
if(!p) {
333+
PyErr_SetString(PyExc_ValueError, "substring not found");
334+
return NULL;
335+
}
336+
337+
return PyLong_FromSsize_t(p - CSTRING_VALUE(self));
338+
}
339+
324340
static PySequenceMethods cstring_as_sequence = {
325341
.sq_length = cstring_len,
326342
.sq_concat = cstring_concat,
@@ -339,6 +355,7 @@ static PyMethodDef cstring_methods[] = {
339355
{"find", cstring_find, METH_VARARGS, find__doc__},
340356
{"index", cstring_index, METH_VARARGS, index__doc__},
341357
{"rfind", cstring_rfind, METH_VARARGS, rfind__doc__},
358+
{"rindex", cstring_rindex, METH_VARARGS, rindex__doc__},
342359
{0},
343360
};
344361

test/test_methods.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,24 @@ def test_rfind_missing():
7272
target = cstring('hello')
7373
assert target.rfind('lo', 0, 4) == -1
7474

75+
76+
def test_rindex():
77+
target = cstring('hello')
78+
assert target.rindex('o') == 4
79+
80+
81+
def test_rindex_empty():
82+
target = cstring('hello')
83+
assert target.rindex('') == 5
84+
85+
86+
def test_rindex_with_start():
87+
target = cstring('hello')
88+
assert target.rindex('lo', 3) == 3
89+
90+
91+
def test_rindex_missing():
92+
target = cstring('hello')
93+
with pytest.raises(ValueError):
94+
return target.rindex('lo', 0, 4)
95+

0 commit comments

Comments
 (0)
0