Skip to content

Makes zigzag encoding and decoding save wrt. undefined behavior, see #28 #35

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/streamvbyte_zigzag.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

static inline
uint32_t _zigzag_encode_32 (int32_t val) {
return (val + val) ^ (val >> 31);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The signed val + val here is the issue wrt. overflow causing undefined behavior

return ((uint32_t)val << (uint32_t)1) ^ (uint32_t)(-(int32_t)((uint32_t)val >> (uint32_t)31));
}

void zigzag_encode(const int32_t * in, uint32_t * out, size_t N) {
Expand All @@ -19,7 +19,7 @@ void zigzag_delta_encode(const int32_t * in, uint32_t * out, size_t N, int32_t p

static inline
int32_t _zigzag_decode_32 (uint32_t val) {
return (val >> 1) ^ -(val & 1);
return (int32_t)((val >> (uint32_t)1) ^ (uint32_t)(-(int32_t)(val & (uint32_t)1)));
}


Expand Down
30 changes: 30 additions & 0 deletions tests/unit.c
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,36 @@ int zigzagtests() {
return isok;
}

// Fixtures from https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
int zigzagfixturestests() {
const int32_t original[] = {0, -1, 1, -2, 2147483647, -2147483648};
const uint32_t encoded[] = {0, 1, 2, 3, 4294967294, 4294967295};

uint32_t out[] = {0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa};

zigzag_encode(original, out, 6);

for (size_t i = 0; i < 6; ++i) {
if (encoded[i] != out[i]) {
printf("[zigzag_encode] %ju != %ju\n", (uintmax_t)encoded[i], (uintmax_t)out[i]);
return -1;
}
}

int32_t roundtrip[] = {0x55555555, 0x55555555, 0x55555555, 0x55555555, 0x55555555, 0x55555555};

zigzag_decode((const uint32_t *)out, roundtrip, 6);

for (size_t i = 0; i < 6; ++i) {
if (original[i] != roundtrip[i]) {
printf("[zigzag_decode] %jd != %jd\n", (intmax_t)original[i], (intmax_t)roundtrip[i]);
return -1;
}
}

return 0;
}

// return -1 in case of failure
int basictests() {
int N = 4096;
Expand Down