Skip to content

Add a Clinic Convert for positive-only Py_ssize_t (but not size_t) #135763

Open
@picnixz

Description

@picnixz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic-argument-clinictriagedThe issue has been accepted as valid by a triager.type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions