]> git.ipfire.org Git - thirdparty/binutils-gdb.git/commitdiff
gdbsupport: add gdb::unordered_string_map
authorSimon Marchi <simon.marchi@efficios.com>
Mon, 9 Feb 2026 19:17:53 +0000 (14:17 -0500)
committerSimon Marchi <simon.marchi@polymtl.ca>
Fri, 13 Feb 2026 19:04:07 +0000 (14:04 -0500)
It occurred to me that when we use a

    gdb::unordered_map<std::string, T>

we construct a temporary std::string for each lookup from a
`const char *`, possibly doing dynamic allocation.  This is really
unnecessary, because it's easy to compare an existing `const char *` (or
std::string_view) with an std::string.  This can therefore be avoided by
having transparent hash and eq types.

Because this is a common enough case, add it to
gdbsupport/unordered_map.h, so it can easily be reused.  Define the
gdb::unordered_string_map type, which uses hash and eq types that work
on std::string_view.  Both `const char *` and `std::string` can
implicitly be converted to std::string_view, so this should be
sufficient.

Change-Id: Id93448d831696d25472f13c15212f13712ad8492
Approved-by: Kevin Buettner <kevinb@redhat.com>
gdbsupport/unordered_map.h

index b615f2422f62744f761537b291fa35283caef568..e0b97764d0b3f87fe9278eddede949bb9e7979d3 100644 (file)
@@ -32,6 +32,40 @@ using unordered_map
       <Key, T, Hash, KeyEqual, std::allocator<std::pair<Key, T>>,
        ankerl::unordered_dense::bucket_type::standard>;
 
+/* An unordered_map with std::string keys that supports transparent
+   lookup from std::string_view, avoiding the construction of temporary
+   std::string objects during lookups.  std::string_view is implicitly
+   constructible from `const char *` and `std::string`, so it covers those
+   too.  */
+
+namespace detail
+{
+
+struct unordered_string_map_hash
+{
+  using is_transparent = void;
+  using is_avalanching = void;
+
+  std::uint64_t operator() (std::string_view sv) const noexcept
+  { return ankerl::unordered_dense::hash<std::string_view> () (sv); }
+};
+
+struct unordered_string_map_eq
+{
+  using is_transparent = void;
+
+  bool operator() (std::string_view lhs, std::string_view rhs) const noexcept
+  { return lhs == rhs; }
+};
+
+} /* namespace detail */
+
+template<typename T>
+using unordered_string_map
+  = gdb::unordered_map<std::string, T,
+                      detail::unordered_string_map_hash,
+                      detail::unordered_string_map_eq>;
+
 } /* namespace gdb */
 
 #endif /* GDBSUPPORT_UNORDERED_MAP_H */