Skip to content

Commit

Permalink
Implement AbslStringify for crc32c_t in order to support absl::StrFor…
Browse files Browse the repository at this point in the history
…mat natively

PiperOrigin-RevId: 552940359
Change-Id: I925764757404c0c9f2a13ed729190d51f4ac46cf
  • Loading branch information
Abseil Team authored and copybara-github committed Aug 1, 2023
1 parent fc1dcc0 commit e945c8d
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions absl/crc/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ cc_test(
deps = [
":crc32c",
"//absl/strings",
"//absl/strings:str_format",
"@com_google_googletest//:gtest_main",
],
)
Expand Down
1 change: 1 addition & 0 deletions absl/crc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ absl_cc_test(
DEPS
absl::crc32c
absl::strings
absl::str_format
GTest::gtest_main
)

Expand Down
5 changes: 5 additions & 0 deletions absl/crc/crc32c.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ class crc32c_t final {

friend bool operator!=(crc32c_t lhs, crc32c_t rhs) { return !(lhs == rhs); }

template <typename Sink>
friend void AbslStringify(Sink& sink, crc32c_t crc) {
absl::Format(&sink, "%08x", static_cast<uint32_t>(crc));
}

private:
uint32_t crc_;
};
Expand Down
14 changes: 14 additions & 0 deletions absl/crc/crc32c_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "gtest/gtest.h"
#include "absl/crc/internal/crc32c.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"

namespace {
Expand Down Expand Up @@ -210,4 +211,17 @@ TEST(CRC32C, InsertionOperator) {
EXPECT_EQ(buf.str(), "00000011");
}
}

TEST(CRC32C, AbslStringify) {
// StrFormat
EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{0xc99465aa}), "c99465aa");
EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{0}), "00000000");
EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{17}), "00000011");

// StrCat
EXPECT_EQ(absl::StrCat(absl::crc32c_t{0xc99465aa}), "c99465aa");
EXPECT_EQ(absl::StrCat(absl::crc32c_t{0}), "00000000");
EXPECT_EQ(absl::StrCat(absl::crc32c_t{17}), "00000011");
}

} // namespace

0 comments on commit e945c8d

Please sign in to comment.