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.

PiperOrigin-RevId: 603786237
  • Loading branch information
PINS Team authored and verios-google committed Feb 3, 2024
1 parent 2407548 commit 4c28cae
Show file tree
Hide file tree
Showing 2 changed files with 13 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
11 changes: 11 additions & 0 deletions p4_constraints/backend/interpreter_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1287,6 +1287,17 @@ 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'};
uint hex_sum = 0;
for (char c : hex_string) {
hex_sum <<= 8;
hex_sum += c;
}
EXPECT_THAT(ParseP4RTInteger(hex_string), Eq(hex_sum));
}

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

0 comments on commit 4c28cae

Please sign in to comment.