From c6594c0b142133535c1d2d5b8d8084cf9e57592b Mon Sep 17 00:00:00 2001 From: laanwj <126646+laanwj@users.noreply.github.com> Date: Mon, 4 Nov 2024 18:19:00 +0100 Subject: [PATCH] memusage: Add DynamicUsage for std::string Add DynamicUsage(std::string) which Returns the dynamic allocation of a std::string, or 0 if none (in case of small string optimization). --- src/memusage.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/memusage.h b/src/memusage.h index 43407507ed8..9d9e549ef22 100644 --- a/src/memusage.h +++ b/src/memusage.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -90,6 +91,18 @@ static inline size_t DynamicUsage(const std::vector& v) return MallocUsage(v.capacity() * sizeof(T)); } +static inline size_t DynamicUsage(const std::string& s) +{ + const char* s_ptr = reinterpret_cast(&s); + // Don't count the dynamic memory used for string, if it resides in the + // "small string" optimization area (which stores data inside the object itself, up to some + // size; 15 bytes in modern libstdc++). + if (!std::less{}(s.data(), s_ptr) && !std::greater{}(s.data() + s.size(), s_ptr + sizeof(s))) { + return 0; + } + return MallocUsage(s.capacity()); +} + template static inline size_t DynamicUsage(const prevector& v) {