Skip to content

Fix struct.pack with padding bytes #4620

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 3 commits into from
Apr 20, 2021
Merged

Conversation

tannewt
Copy link
Member

@tannewt tannewt commented Apr 16, 2021

It used to validate the following arg could fit in a single byte.
Now, it always uses zero to pad.

Previous work on padding bytes in struct was done in #3405

It used to validate the following arg could fit in a single byte.
Now, it always uses zero to pad.
@tannewt tannewt added bug cpython api modules from cpython labels Apr 16, 2021
@tannewt tannewt requested a review from jepler April 16, 2021 19:41
@jepler
Copy link

jepler commented Apr 17, 2021

The built-in struct tests are using the "modstruct" version, so either we need to circuitpythonify the "unix" build so it can use the shared-bindings version, or you need to

diff --git a/py/modstruct.c b/py/modstruct.c
index 1c5319608..8f78fa234 100644
--- a/py/modstruct.c
+++ b/py/modstruct.c
@@ -214,9 +214,11 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c
             p += cnt;
         } else {
             while (cnt--) {
-                mp_binary_set_val(fmt_type, *fmt, args[i], &p);
                 // Pad bytes don't have a corresponding argument.
-                if (*fmt != 'x') {
+                if (*fmt == 'x') {
+                    mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p);
+                } else {
+                    mp_binary_set_val(fmt_type, *fmt, args[i], &p);
                     i++;
                 }
             }

Copy link

@jepler jepler left a comment

Choose a reason for hiding this comment

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

thanks! seems good to go.

@jepler jepler merged commit 18548fc into adafruit:main Apr 20, 2021
@jepler
Copy link

jepler commented Apr 20, 2021

As far as I recall, this fix isn't needed upstream, as they truncated values in struct.pack as a code-saving / convenience measure, so packing 0x100 into an x wasn't an issue.

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

Successfully merging this pull request may close these issues.

3 participants