@@ -212,17 +212,25 @@ termios_tcsetattr_impl(PyObject *module, int fd, int when, PyObject *term)
212
212
return PyErr_SetFromErrno (state -> TermiosError );
213
213
}
214
214
215
- mode .c_iflag = (tcflag_t ) PyLong_AsLong (PyList_GetItem (term , 0 ));
216
- mode .c_oflag = (tcflag_t ) PyLong_AsLong (PyList_GetItem (term , 1 ));
217
- mode .c_cflag = (tcflag_t ) PyLong_AsLong (PyList_GetItem (term , 2 ));
218
- mode .c_lflag = (tcflag_t ) PyLong_AsLong (PyList_GetItem (term , 3 ));
219
- speed_t ispeed = (speed_t ) PyLong_AsLong (PyList_GetItem (term , 4 ));
220
- speed_t ospeed = (speed_t ) PyLong_AsLong (PyList_GetItem (term , 5 ));
221
- PyObject * cc = PyList_GetItem (term , 6 );
222
- if (PyErr_Occurred ()) {
223
- return NULL ;
224
- }
225
-
215
+ speed_t ispeed , ospeed ;
216
+ #define SET_FROM_LIST (TYPE , VAR , LIST , N ) do { \
217
+ PyObject *item = PyList_GET_ITEM(LIST, N); \
218
+ long num = PyLong_AsLong(item); \
219
+ if (num == -1 && PyErr_Occurred()) { \
220
+ return NULL; \
221
+ } \
222
+ VAR = (TYPE)num; \
223
+ } while (0)
224
+
225
+ SET_FROM_LIST (tcflag_t , mode .c_iflag , term , 0 );
226
+ SET_FROM_LIST (tcflag_t , mode .c_oflag , term , 1 );
227
+ SET_FROM_LIST (tcflag_t , mode .c_cflag , term , 2 );
228
+ SET_FROM_LIST (tcflag_t , mode .c_lflag , term , 3 );
229
+ SET_FROM_LIST (speed_t , ispeed , term , 4 );
230
+ SET_FROM_LIST (speed_t , ospeed , term , 5 );
231
+ #undef SET_FROM_LIST
232
+
233
+ PyObject * cc = PyList_GET_ITEM (term , 6 );
226
234
if (!PyList_Check (cc ) || PyList_Size (cc ) != NCCS ) {
227
235
PyErr_Format (PyExc_TypeError ,
228
236
"tcsetattr: attributes[6] must be %d element list" ,
@@ -237,8 +245,13 @@ termios_tcsetattr_impl(PyObject *module, int fd, int when, PyObject *term)
237
245
238
246
if (PyBytes_Check (v ) && PyBytes_Size (v ) == 1 )
239
247
mode .c_cc [i ] = (cc_t ) * PyBytes_AsString (v );
240
- else if (PyLong_Check (v ))
241
- mode .c_cc [i ] = (cc_t ) PyLong_AsLong (v );
248
+ else if (PyLong_Check (v )) {
249
+ long num = PyLong_AsLong (v );
250
+ if (num == -1 && PyErr_Occurred ()) {
251
+ return NULL ;
252
+ }
253
+ mode .c_cc [i ] = (cc_t )num ;
254
+ }
242
255
else {
243
256
PyErr_SetString (PyExc_TypeError ,
244
257
"tcsetattr: elements of attributes must be characters or integers" );
0 commit comments