Skip to content

Commit ae26652

Browse files
committed
Implement endswith() method
1 parent 51aeba9 commit ae26652

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

README.md

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

7373

74+
### endswith(substring [,start [,end]])
75+
76+
See: https://docs.python.org/3/library/stdtypes.html#str.endswith
77+
78+
Notes:
79+
80+
* `substring` may be a `cstring` or Python `str` object.
81+
* `start` and `end`, if provided, are _byte_ indexes.
82+
83+
7484
## TODO
7585

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

src/cstring.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,17 @@ PyObject *cstring_startswith(PyObject *self, PyObject *args) {
344344
return PyBool_FromLong(cmp == 0);
345345
}
346346

347+
PyDoc_STRVAR(endswith__doc__, "");
348+
PyObject *cstring_endswith(PyObject *self, PyObject *args) {
349+
struct _substr_params params;
350+
if(!_parse_substr_args(self, args, &params))
351+
return NULL;
352+
if(params.end - params.start < params.substr_len)
353+
return PyBool_FromLong(0);
354+
int cmp = memcmp(params.end - params.substr_len, params.substr, params.substr_len);
355+
return PyBool_FromLong(cmp == 0);
356+
}
357+
347358
static PySequenceMethods cstring_as_sequence = {
348359
.sq_length = cstring_len,
349360
.sq_concat = cstring_concat,
@@ -364,6 +375,7 @@ static PyMethodDef cstring_methods[] = {
364375
{"rfind", cstring_rfind, METH_VARARGS, rfind__doc__},
365376
{"rindex", cstring_rindex, METH_VARARGS, rindex__doc__},
366377
{"startswith", cstring_startswith, METH_VARARGS, startswith__doc__},
378+
{"endswith", cstring_endswith, METH_VARARGS, endswith__doc__},
367379
{0},
368380
};
369381

test/test_methods.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,23 @@ def test_startswith_with_start_and_end():
113113
target = cstring('hello, world')
114114
assert target.startswith('wo', 7, 8) is False
115115

116+
117+
def test_endswith():
118+
target = cstring('hello, world')
119+
assert target.endswith('world') is True
120+
121+
122+
def test_endswith_not():
123+
target = cstring('hello, world')
124+
assert target.endswith('hello') is False
125+
126+
127+
def test_endswith_with_start():
128+
target = cstring('hello, world')
129+
assert target.endswith('world', 8) is False
130+
131+
132+
def test_endswith_with_start_and_end():
133+
target = cstring('hello, world')
134+
assert target.endswith('wo', 7, 9) is True
135+

0 commit comments

Comments
 (0)