Skip to content

[mypyc] feat: new primitive for int.bit_length #19673

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

Open
wants to merge 15 commits into
base: master
Choose a base branch
from

Conversation

BobTheBuidler
Copy link
Contributor

@BobTheBuidler BobTheBuidler commented Aug 16, 2025

This PR adds a new primitive for int.bit_length and is already ready for review.


// int.bit_length()
CPyTagged CPyTagged_BitLength(CPyTagged self) {
PyObject *pyint = CPyTagged_StealAsObject(self);
Copy link
Contributor Author

@BobTheBuidler BobTheBuidler Aug 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this PyLong_Check?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's always an instance of int.

Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! bit_length can be useful in low-level code, where a generic method call can really slow things down.


// int.bit_length()
CPyTagged CPyTagged_BitLength(CPyTagged self) {
PyObject *pyint = CPyTagged_StealAsObject(self);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's always an instance of int.

#if defined(__GNUC__) || defined(__clang__)
bits = (int)(CPY_BITS - CPY_CLZ(absval));
#else
// Fallback to loop if no builtin
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

def bit_length(n: int) -> int:
return n.bit_length()
def test_bit_length() -> None:
assert bit_length(0) == 0
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: This would be a bit more robust if you'd have say bit_length_python function that does return getattr(n, "bit_length")() and you can assert that bit_length(n) == bit_length_python(n).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants