Skip to content

Commit 9f015f5

Browse files
committed
bpo-29753: improve documentation PyCField_FromDesc relating packed bitfields
Signed-off-by: Filipe Laíns <[email protected]>
1 parent de3df46 commit 9f015f5

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

Modules/_ctypes/cfield.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,9 @@ PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
7373
}
7474

7575
#ifndef MS_WIN32
76-
if (pack && bitsize) { /* packed bitfield */
76+
/* if we have a packed bitfield, calculate the minimum number of bytes we
77+
need to fit it. otherwise use the specified size. */
78+
if (pack && bitsize) {
7779
size = (bitsize - 1) / 8 + 1;
7880
} else
7981
#endif
@@ -97,6 +99,8 @@ PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
9799
} else if (bitsize /* this is a bitfield request */
98100
&& *pfield_size /* we have a bitfield open */
99101
&& dict->size * 8 >= *pfield_size
102+
/* if this is a packed bitfield, always expand it.
103+
otherwise calculate if we need to expand it. */
100104
&& (((*pbitofs + bitsize) <= dict->size * 8) || pack)) {
101105
/* expand bit field */
102106
fieldtype = EXPAND_BITFIELD;
@@ -105,6 +109,8 @@ PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
105109
/* start new bitfield */
106110
fieldtype = NEW_BITFIELD;
107111
*pbitofs = 0;
112+
/* use our calculated size (size) instead of type size (dict->size),
113+
which can be different for packed bitfields */
108114
*pfield_size = size * 8;
109115
} else {
110116
/* not a bit field */
@@ -177,6 +183,9 @@ PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
177183
break;
178184

179185
case EXPAND_BITFIELD:
186+
/* increase the size if it is a packed bitfield.
187+
EXPAND_BITFIELD should not be selected for non-packed fields if the
188+
current size isn't already enough. */
180189
if (pack)
181190
size = (*pbitofs + bitsize - 1) / 8 + 1;
182191

0 commit comments

Comments
 (0)