Skip to content

Commit 8fa6bd1

Browse files
committed
simplify XML exception creation
1 parent 8288f36 commit 8fa6bd1

File tree

1 file changed

+16
-26
lines changed

1 file changed

+16
-26
lines changed

Modules/pyexpat.c

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ CALL_XML_HANDLER_SETTER(const struct HandlerInfo *handler_info,
125125
}
126126

127127
static int
128-
set_error_code(PyObject *err, enum XML_Error code)
128+
set_xml_error_attr_code(PyObject *err, enum XML_Error code)
129129
{
130130
PyObject *v = PyLong_FromLong((long)code);
131131
int ok = v != NULL && PyObject_SetAttr(err, &_Py_ID(code), v) != -1;
@@ -137,7 +137,7 @@ set_error_code(PyObject *err, enum XML_Error code)
137137
* false on an exception.
138138
*/
139139
static int
140-
set_error_location(PyObject *err, const char *name, XML_Size value)
140+
set_xml_error_attr_location(PyObject *err, const char *name, XML_Size value)
141141
{
142142
PyObject *v = PyLong_FromSize_t((size_t)value);
143143
int ok = v != NULL && PyObject_SetAttrString(err, name, v) != -1;
@@ -146,42 +146,32 @@ set_error_location(PyObject *err, const char *name, XML_Size value)
146146
}
147147

148148

149-
static PyObject *
150-
format_xml_error(enum XML_Error code, XML_Size lineno, XML_Size column)
151-
{
152-
const char *errmsg = XML_ErrorString(code);
153-
PyUnicodeWriter *writer = PyUnicodeWriter_Create(strlen(errmsg) + 1);
154-
if (writer == NULL) {
155-
return NULL;
156-
}
157-
if (PyUnicodeWriter_Format(writer,
158-
"%s: line %zu, column %zu",
159-
errmsg, (size_t)lineno, (size_t)column) < 0)
160-
{
161-
PyUnicodeWriter_Discard(writer);
162-
return NULL;
163-
}
164-
return PyUnicodeWriter_Finish(writer);
165-
}
166-
167149
static PyObject *
168150
set_xml_error(pyexpat_state *state,
169151
enum XML_Error code, XML_Size lineno, XML_Size column,
170152
const char *errmsg)
171153
{
172-
PyObject *arg = errmsg == NULL
173-
? format_xml_error(code, lineno, column)
174-
: PyUnicode_FromStringAndSize(errmsg, strlen(errmsg));
154+
PyObject *arg;
155+
if (errmsg == NULL) {
156+
arg = PyUnicode_FromFormat(
157+
"%s: line %zu, column %zu",
158+
XML_ErrorString(code),
159+
(size_t)lineno, (size_t)column
160+
);
161+
}
162+
else {
163+
arg = PyUnicode_FromStringAndSize(errmsg, strlen(errmsg));
164+
}
175165
if (arg == NULL) {
176166
return NULL;
177167
}
178168
PyObject *res = PyObject_CallOneArg(state->error, arg);
179169
Py_DECREF(arg);
180170
if (
181171
res != NULL
182-
&& set_error_code(res, code)
183-
&& set_error_location(res, "lineno", lineno)
184-
&& set_error_location(res, "offset", column)
172+
&& set_xml_error_attr_code(res, code)
173+
&& set_xml_error_attr_location(res, "lineno", lineno)
174+
&& set_xml_error_attr_location(res, "offset", column)
185175
) {
186176
PyErr_SetObject(state->error, res);
187177
}

0 commit comments

Comments
 (0)