Skip to content

Commit

Permalink
This fixes a discrepancy between the C++ and Java version of the ToFo…
Browse files Browse the repository at this point in the history
…urDigitString() function, given byte array inputs that include negative signed byte values.

Added a unit test to verify that the output with negative signed bytes in the input will result in the same output as the Java version.

PiperOrigin-RevId: 707965044
  • Loading branch information
hai007 authored and copybara-github committed Dec 19, 2024
1 parent b1ef67d commit bb7fb14
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions internal/platform/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ cc_test(
":base",
":util",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/strings:string_view",
"@com_google_googletest//:gtest_main",
],
)
Expand Down
3 changes: 2 additions & 1 deletion internal/platform/byte_utils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

#include "internal/platform/byte_utils.h"

#include <cstdint>
#include <cstdlib>
#include <string>

Expand All @@ -29,7 +30,7 @@ std::string ByteUtils::ToFourDigitString(ByteArray& bytes) {

BaseInputStream base_input_stream{bytes};
while (base_input_stream.IsAvailable(1)) {
auto byte = static_cast<int>(base_input_stream.ReadUint8());
auto byte = static_cast<int8_t>(base_input_stream.ReadUint8());
hashCode = (hashCode + byte * multiplier) % kHashBasePrime;
multiplier = multiplier * kHashBaseMultiplier % kHashBasePrime;
}
Expand Down
13 changes: 13 additions & 0 deletions internal/platform/byte_utils_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@

#include "internal/platform/byte_utils.h"

#include <string>

#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "internal/platform/byte_array.h"

namespace nearby {

constexpr absl::string_view kFooBytes{"rawABCDE"};
constexpr absl::string_view kFooFourDigitsToken{"0392"};
constexpr absl::string_view kEmptyFourDigitsToken{"0000"};
constexpr absl::string_view kNegativeBytes{"raw\xd5\x01\xe4\x03\x81"};
constexpr absl::string_view kNegativeFourDigitsToken{"9084"};

TEST(ByteUtilsTest, ToFourDigitStringCorrect) {
ByteArray bytes{std::string(kFooBytes)};
Expand All @@ -31,6 +36,14 @@ TEST(ByteUtilsTest, ToFourDigitStringCorrect) {
EXPECT_EQ(std::string(kFooFourDigitsToken), four_digit_string);
}

TEST(ByteUtilsTest, ToFourDigitStringNegativeCorrect) {
ByteArray bytes{std::string(kNegativeBytes)};

auto four_digit_string = ByteUtils::ToFourDigitString(bytes);

EXPECT_EQ(std::string(kNegativeFourDigitsToken), kNegativeFourDigitsToken);
}

TEST(ByteUtilsTest, TestEmptyByteArrayCorrect) {
ByteArray bytes;

Expand Down

0 comments on commit bb7fb14

Please sign in to comment.