Skip to content

Commit a88c444

Browse files
Copilotgerlero
andcommitted
Address code review feedback: improve error handling and memory management
Co-authored-by: gerlero <[email protected]>
1 parent ba6b9bd commit a88c444

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

src/foamlib/_files/_parsing/_skip_ext.c

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,13 @@ skip(PyObject *self, PyObject *args, PyObject *kwargs)
7979
pos++;
8080
}
8181
if (!found) {
82-
/* Unclosed comment - raise error */
82+
/* Unclosed comment - raise error at end of file */
83+
/* Get the original object that owns the buffer */
84+
PyObject *contents_obj = buffer.obj;
85+
Py_INCREF(contents_obj);
8386
PyBuffer_Release(&buffer);
84-
PyObject *contents_obj = PyBytes_FromStringAndSize((const char *)contents, len);
85-
if (contents_obj == NULL) {
86-
return NULL;
87-
}
88-
/* Call FoamFileDecodeError with keyword argument expected */
87+
88+
/* Call FoamFileDecodeError with position at end of file */
8989
PyObject *kwargs = Py_BuildValue("{s:s}", "expected", "*/");
9090
if (kwargs == NULL) {
9191
Py_DECREF(contents_obj);
@@ -130,12 +130,36 @@ static PyMethodDef skip_methods[] = {
130130
{NULL, NULL, 0, NULL}
131131
};
132132

133+
static int
134+
skip_module_traverse(PyObject *m, visitproc visit, void *arg)
135+
{
136+
Py_VISIT(FoamFileDecodeError);
137+
return 0;
138+
}
139+
140+
static int
141+
skip_module_clear(PyObject *m)
142+
{
143+
Py_CLEAR(FoamFileDecodeError);
144+
return 0;
145+
}
146+
147+
static void
148+
skip_module_free(void *m)
149+
{
150+
skip_module_clear((PyObject *)m);
151+
}
152+
133153
static struct PyModuleDef skip_module = {
134154
PyModuleDef_HEAD_INIT,
135155
"_skip_ext",
136156
"C extension module for fast whitespace and comment skipping in OpenFOAM parser",
137157
-1,
138-
skip_methods
158+
skip_methods,
159+
NULL,
160+
skip_module_traverse,
161+
skip_module_clear,
162+
skip_module_free
139163
};
140164

141165
PyMODINIT_FUNC

0 commit comments

Comments
 (0)