Skip to content

Commit 51aeba9

Browse files
committed
Implement startswith() method
1 parent 503c8a1 commit 51aeba9

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
@@ -61,6 +61,16 @@ Notes:
6161
* `start` and `end`, if provided, are _byte_ indexes.
6262

6363

64+
### startswith(substring [,start [,end]])
65+
66+
See: https://docs.python.org/3/library/stdtypes.html#str.startswith
67+
68+
Notes:
69+
70+
* `substring` may be a `cstring` or Python `str` object.
71+
* `start` and `end`, if provided, are _byte_ indexes.
72+
73+
6474
## TODO
6575

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

src/cstring.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,17 @@ PyObject *cstring_rindex(PyObject *self, PyObject *args) {
333333
return PyLong_FromSsize_t(p - CSTRING_VALUE(self));
334334
}
335335

336+
PyDoc_STRVAR(startswith__doc__, "");
337+
PyObject *cstring_startswith(PyObject *self, PyObject *args) {
338+
struct _substr_params params;
339+
if(!_parse_substr_args(self, args, &params))
340+
return NULL;
341+
if(params.end - params.start < params.substr_len)
342+
return PyBool_FromLong(0);
343+
int cmp = memcmp(params.start, params.substr, params.substr_len);
344+
return PyBool_FromLong(cmp == 0);
345+
}
346+
336347
static PySequenceMethods cstring_as_sequence = {
337348
.sq_length = cstring_len,
338349
.sq_concat = cstring_concat,
@@ -352,6 +363,7 @@ static PyMethodDef cstring_methods[] = {
352363
{"index", cstring_index, METH_VARARGS, index__doc__},
353364
{"rfind", cstring_rfind, METH_VARARGS, rfind__doc__},
354365
{"rindex", cstring_rindex, METH_VARARGS, rindex__doc__},
366+
{"startswith", cstring_startswith, METH_VARARGS, startswith__doc__},
355367
{0},
356368
};
357369

test/test_methods.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,23 @@ def test_rindex_missing():
9393
with pytest.raises(ValueError):
9494
return target.rindex('lo', 0, 4)
9595

96+
97+
def test_startswith():
98+
target = cstring('hello, world')
99+
assert target.startswith('hello,') is True
100+
101+
102+
def test_startswith_not():
103+
target = cstring('hello, world')
104+
assert target.startswith('world') is False
105+
106+
107+
def test_startswith_with_start():
108+
target = cstring('hello, world')
109+
assert target.startswith('world', 7) is True
110+
111+
112+
def test_startswith_with_start_and_end():
113+
target = cstring('hello, world')
114+
assert target.startswith('wo', 7, 8) is False
115+

0 commit comments

Comments
 (0)