Feature or enhancement
Proposal:
We have an AC converter for size_t and ssize_t but none for ssize_t that is positive. I currently need it because it could unify error messages where we would only want ssize_t values that are > 0. One reason is that most of our interface uses Py_ssize_t when we want to indicate some size (e.g., PyBytes_FromStringAndSize), but in general, external C APIs use size_t directly. To prevent casts and to prevent additional code path where we check that the argument is indeed positive, I suggest adding an AC converter for that. It will then be safe to cast the Py_ssize_t value to a size_t without a change of meaning:
Before
/*[clinic input]
_hashlib.HASHXOF.digest
length: Py_ssize_t
[clinic start generated code]*/
static PyObject *
_hashlib_HASHXOF_digest_impl(HASHobject *self, Py_ssize_t length)
[...]
{
if (length < 0) { raise(); }
call_openssl_api(..., (size_t)length);
return ...;
}
After
/*[clinic input]
_hashlib.HASHXOF.digest
length: Py_ssize_t(allow_negative=False)
[clinic start generated code]*/
static PyObject *
_hashlib_HASHXOF_digest_impl(HASHobject *self, Py_ssize_t length)
[...]
{
assert(length >= 0);
call_openssl_api(..., (size_t)length);
return ...;
}
This can also help when invoking PyBytes_FromStringAndSize, where we wouldn't need to check for the length parameter inside the implementation. I suggest having the parameter named reported to the user even if it's positional-only as it's part of the signature, e.g., "'length' must be positive".
More generally, it would be good to also specify bounds.
cc @serhiy-storchaka
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Linked PRs
Feature or enhancement
Proposal:
We have an AC converter for size_t and ssize_t but none for ssize_t that is positive. I currently need it because it could unify error messages where we would only want ssize_t values that are > 0. One reason is that most of our interface uses
Py_ssize_twhen we want to indicate some size (e.g.,PyBytes_FromStringAndSize), but in general, external C APIs usesize_tdirectly. To prevent casts and to prevent additional code path where we check that the argument is indeed positive, I suggest adding an AC converter for that. It will then be safe to cast thePy_ssize_tvalue to asize_twithout a change of meaning:Before
After
This can also help when invoking
PyBytes_FromStringAndSize, where we wouldn't need to check for the length parameter inside the implementation. I suggest having the parameter named reported to the user even if it's positional-only as it's part of the signature, e.g., "'length' must be positive".More generally, it would be good to also specify bounds.
cc @serhiy-storchaka
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Linked PRs
Py_ssize_t(allow_negative=False)#138394