diff --git a/stringid.cpp b/stringid.cpp index df0b2df3..54dff9dc 100644 --- a/stringid.cpp +++ b/stringid.cpp @@ -13,9 +13,23 @@ using cruft::stringid; -//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// stringid::id_t -stringid::add (std::string key) { +stringid::operator[] (std::string_view const &key) +{ + if (auto const pos = m_map.find (key); pos != m_map.cend ()) + return pos->second; + + + auto const &[pos, success] = m_map.emplace (key, m_map.size ()); + return pos->second; +} + + +/////////////////////////////////////////////////////////////////////////////// +stringid::id_t +stringid::add (std::string key) +{ auto pos = m_map.find (key); if (pos != m_map.end ()) throw std::invalid_argument ("duplicate stringid key"); @@ -26,9 +40,10 @@ stringid::add (std::string key) { } -//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// stringid::id_t -stringid::find (const std::string &key) const { +stringid::find (const std::string &key) const +{ auto pos = m_map.find (key); if (pos == m_map.end ()) throw std::out_of_range ("invalid stringid key"); @@ -37,8 +52,9 @@ stringid::find (const std::string &key) const { } -//----------------------------------------------------------------------------- +/////////////////////////////////////////////////////////////////////////////// void -stringid::clear (void) { +stringid::clear (void) +{ m_map.clear (); } diff --git a/stringid.hpp b/stringid.hpp index 7b924689..b7f5e01f 100644 --- a/stringid.hpp +++ b/stringid.hpp @@ -19,6 +19,11 @@ namespace cruft { public: typedef size_t id_t; + /////////////////////////////////////////////////////////////////////// + /// Returns the ID for the supplied string, or creates and returns a + /// new ID if the string is not present. + id_t operator[] (std::string_view const&); + /////////////////////////////////////////////////////////////////////// id_t add (std::string); @@ -59,7 +64,7 @@ namespace cruft { private: - std::map m_map; + std::map> m_map; }; } diff --git a/test/stringid.cpp b/test/stringid.cpp index 785b8341..4a19df61 100644 --- a/test/stringid.cpp +++ b/test/stringid.cpp @@ -23,5 +23,10 @@ main (int, char**) { tap.expect_eq (id1 + 1, id2, "monotonically increasing IDs"); tap.expect_eq (id1, map.find ("first"), "first element still matches"); + tap.expect_eq (map["second"], id2, "index lookup invokes no change"); + + auto id3 = map["third"]; + tap.expect (id3 != id1 && id3 != id2, "index creation adds new value"); + return tap.status (); }