Skip to content

Commit 7343d8e

Browse files
ac-patelcopybara-github
authored andcommitted
[PH2][Util] Add variant support to MemoryUsageOf (grpc#40487)
Closes grpc#40487 COPYBARA_INTEGRATE_REVIEW=grpc#40487 from ac-patel:memory_usage 88e25c1 PiperOrigin-RevId: 797602976
1 parent a299d3e commit 7343d8e

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

src/core/util/memory_usage.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,12 @@ size_t MemoryUsageOf(const std::tuple<Args...>& t) {
263263
[](const auto&... args) { return (MemoryUsageOf(args) + ... + 0); }, t);
264264
}
265265

266+
// This does not calculate the overhead of the variant itself.
267+
template <typename... T>
268+
size_t MemoryUsageOf(const std::variant<T...>& t) {
269+
return std::visit([](const auto& x) { return MemoryUsageOf(x); }, t);
270+
}
271+
266272
} // namespace grpc_core
267273

268274
#endif // GRPC_SRC_CORE_UTIL_MEMORY_USAGE_H

test/core/util/memory_usage_test.cc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,11 @@ TEST(MemoryUsageTest, EscapeHatch) {
8888
EXPECT_EQ(MemoryUsageOf(Foo()), 12345);
8989
}
9090

91+
TEST(MemoryUsageTest, Variant) {
92+
std::variant<int, std::string> v = 42;
93+
std::variant<int, std::string> v2 = "hello";
94+
EXPECT_EQ(MemoryUsageOf(v), sizeof(int));
95+
EXPECT_GE(MemoryUsageOf(v2), sizeof(std::string) + strlen("hello"));
96+
}
97+
9198
} // namespace grpc_core

0 commit comments

Comments
 (0)