Skip to content

Commit 77b81cb

Browse files
committed
Implement len
1 parent 34110ca commit 77b81cb

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

src/cstring.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ static PyObject *cstring_str(PyObject *self) {
2828
return PyUnicode_FromString(CSTRING_VALUE(self));
2929
}
3030

31+
static Py_ssize_t cstring_len(PyObject *self) {
32+
return Py_SIZE(self) - 1;
33+
}
34+
35+
static PySequenceMethods cstring_as_sequence = {
36+
.sq_length = cstring_len,
37+
};
38+
3139
static PyTypeObject cstring_type = {
3240
PyVarObject_HEAD_INIT(NULL, 0)
3341
.tp_name = "cstring",
@@ -38,6 +46,7 @@ static PyTypeObject cstring_type = {
3846
.tp_new = cstring_new,
3947
.tp_dealloc = cstring_dealloc,
4048
.tp_str = cstring_str,
49+
.tp_as_sequence = &cstring_as_sequence,
4150
};
4251

4352
static struct PyModuleDef module = {

test/test_cstring.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,8 @@ def test_str():
55
result = cstring('hello, world')
66
assert str(result) == 'hello, world'
77

8+
9+
def test_len():
10+
result = cstring('hello, world')
11+
assert len(result) == 12
12+

0 commit comments

Comments
 (0)