From e458d6afaa424b6d69d774ca103725985a0dbe32 Mon Sep 17 00:00:00 2001 From: hai007 Date: Mon, 6 Jan 2025 17:57:41 -0800 Subject: [PATCH] This fixes a discrepancy between the C++ and Java version of the ToFourDigitString() 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: 712709020 --- internal/platform/BUILD | 1 + internal/platform/byte_utils.cc | 3 ++- internal/platform/byte_utils_test.cc | 13 +++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/internal/platform/BUILD b/internal/platform/BUILD index 151aa999..2af6d684 100644 --- a/internal/platform/BUILD +++ b/internal/platform/BUILD @@ -403,6 +403,7 @@ cc_test( ":base", ":util", "@com_github_protobuf_matchers//protobuf-matchers", + "@com_google_absl//absl/strings:string_view", "@com_google_googletest//:gtest_main", ], ) diff --git a/internal/platform/byte_utils.cc b/internal/platform/byte_utils.cc index 19cb771f..5b6f6034 100644 --- a/internal/platform/byte_utils.cc +++ b/internal/platform/byte_utils.cc @@ -14,6 +14,7 @@ #include "internal/platform/byte_utils.h" +#include #include #include @@ -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(base_input_stream.ReadUint8()); + auto byte = static_cast(base_input_stream.ReadUint8()); hashCode = (hashCode + byte * multiplier) % kHashBasePrime; multiplier = multiplier * kHashBaseMultiplier % kHashBasePrime; } diff --git a/internal/platform/byte_utils_test.cc b/internal/platform/byte_utils_test.cc index f6ec6916..8b604972 100644 --- a/internal/platform/byte_utils_test.cc +++ b/internal/platform/byte_utils_test.cc @@ -14,7 +14,10 @@ #include "internal/platform/byte_utils.h" +#include + #include "gtest/gtest.h" +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" namespace nearby { @@ -22,6 +25,8 @@ 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)}; @@ -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;