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

PUBLIC:[P4-constraints] Don't use c strings so that trailing zeros are not discarded when parsing an int from a bytestring. #128

Merged
merged 1 commit into from
Feb 3, 2024
Merged
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
6 changes: 2 additions & 4 deletions p4_constraints/backend/interpreter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,13 @@ Integer ParseP4RTInteger(std::string int_str) {
// allowing for non-canonical bytestrings.
int_str.erase(0, int_str.find_first_not_of('\0'));
mpz_class integer;
const char* chars = int_str.c_str();
const size_t char_count = strlen(chars);
constexpr int most_significant_first = 1;
constexpr size_t char_size = sizeof(char);
static_assert(char_size == 1, "expected sizeof(char) == 1");
constexpr int endian = 0; // system default
constexpr size_t nails = 0; // don't skip any bits
mpz_import(integer.get_mpz_t(), char_count, most_significant_first, char_size,
endian, nails, chars);
mpz_import(integer.get_mpz_t(), int_str.size(), most_significant_first,
char_size, endian, nails, int_str.data());
return integer;
}

Expand Down
6 changes: 6 additions & 0 deletions p4_constraints/backend/interpreter_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1287,6 +1287,12 @@ TEST(ParseP4RTInteger, ParsesZeroCorrectly) {
ASSERT_EQ(zero_string.at(0), '\0');
EXPECT_THAT(ParseP4RTInteger(zero_string), Eq(0));
}

TEST(ParseP4RTInteger, ParsesTrailingZeroCorrectly) {
std::string hex_string = {'\xe0', '\x00', '\x00', '\x00'};
EXPECT_THAT(ParseP4RTInteger(hex_string), Eq(0xe0000000U));
}

} // namespace
} // namespace internal_interpreter
} // namespace p4_constraints
Loading