8000 gh-76961: Fix the PEP3118 format string for ctypes.Structure by eric-wieser · Pull Request #5561 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-76961: Fix the PEP3118 format string for ctypes.Structure #5561

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Feb 5, 2023
Prev Previous commit
Next Next commit
remove the heap allocation as requested
  • Loading branch information
eric-wieser committed Aug 15, 2022
commit e300e164394695c5219189fb178cb6849de4754f
28 changes: 3 additions & 25 deletions Modules/_ctypes/stgdict.c
Original file line number Diff line number Diff line change
Expand Up @@ -340,28 +340,14 @@ MakeAnonFields(PyObject *type)
return 0;
}

/*
Compute `floor(log10(x)) + 1`, for the purpose of determining string lengths.
*/
static Py_ssize_t
num_digits_of(Py_ssize_t n)
{
Py_ssize_t log_n = 0;
while (n > 0) {
log_n++;
n /= 10;
}
return log_n;
}

/*
Append {padding}x to the PEP3118 format string.
*/
char *
_ctypes_alloc_format_padding(const char *prefix, Py_ssize_t padding)
{
char *result;
char *buf;
/* int64 decimal characters + x + null */
char buf[19 + 1 + 1];

assert(padding > 0);

Expand All @@ -370,16 +356,8 @@ _ctypes_alloc_format_padding(const char *prefix, Py_ssize_t padding)
return _ctypes_alloc_format_string(prefix, "x");
}

/* decimal characters + x + null */
buf = PyMem_Malloc(num_digits_of(padding) + 2);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
sprintf(buf, "%zdx", padding);
result = _ctypes_alloc_format_string(prefix, buf);
PyMem_Free(buf);
return result;
return _ctypes_alloc_format_string(prefix, buf);
}

/*
Expand Down
0