Skip to content

Commit

Permalink
PUBLIC:[P4-constraints] Don't use c strings so that trailing zeros ar…
Browse files Browse the repository at this point in the history
…e not discarded when parsing an int from a bytestring. (#128)

PiperOrigin-RevId: 603786237

Co-authored-by: PINS Team <[email protected]>
  • Loading branch information
verios-google and PINS Team authored Feb 3, 2024
1 parent 2407548 commit 19be9f8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
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

0 comments on commit 19be9f8

Please sign in to comment.