Skip to content
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

WIP: Add signed kwarg to int.to_bytes #14275

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

projectgus
Copy link
Contributor

@projectgus projectgus commented Apr 10, 2024

After doing all the work for #13087 I figured I was 99% of the way to implementing support for the signed kwarg, so decided to try it out. See the second commit for the changes unique to this PR.

TODO

  • Sort out remaining test failures.
  • Add new test cases for converting positive integers with signed=True. (Mostly results are the same, but in some cases an additional byte is needed to ensure a 0 sign bit.)
  • Add new test cases verifying a failure occurs when converting negative integers with signed=False. This will be a breaking change compared to the current behaviour.
  • Check if any of the places in binary.c, etc, need any changes to correctly set as_signed argument.

Code size

Total size of unix "minimal" variant:

(Note: CI measurements are a bit worse than my measurements, see both PRs. I assume because of gcc versions.)

* No longer overflows if byte size is 0 (closes micropython#13041)
* Raises OverflowError in any case where number won't fit into byte length
  (Now matches CPython, previously MicroPython would return a truncated
  bytes object.)
* Document that micropython int.to_bytes() doesn't implement the optional
  signed kwarg, but will behave as if signed=True when the integer is
  negative (this is the current behaviour). Add tests for this also.

Requires changes for small ints, MPZ large ints, and "long long" large
ints.

Adds a new set of unit tests for ints between 32 and 64 bits to increase
coverage of "long long" large ints, which are otherwise untested.

Tested on unix port (64 bit small ints, MPZ long ints) and Zephyr STM32WB
board (32 bit small ints, long long large ints).

Untested on a port whose native format is big endian (don't have one at
hand).

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
Signed-off-by: Angus Gratton <angus@redyak.com.au>
Copy link

Code size report:

   bare-arm:  +176 +0.311% 
minimal x86:  +312 +0.167% [incl +32(data)]
   unix x64:  +448 +0.054% standard[incl +32(data)]
      stm32:  +312 +0.080% PYBV10
     mimxrt:  +320 +0.088% TEENSY40
        rp2:  +360 +0.107% RPI_PICO
       samd:  +364 +0.137% ADAFRUIT_ITSYBITSY_M4_EXPRESS

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

Successfully merging this pull request may close these issues.

None yet

1 participant