diff options
Diffstat (limited to 'src/google/protobuf/stubs/map-util.h')
-rw-r--r-- | src/google/protobuf/stubs/map-util.h | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/src/google/protobuf/stubs/map-util.h b/src/google/protobuf/stubs/map-util.h index f5c9d6b6..775848b9 100644 --- a/src/google/protobuf/stubs/map-util.h +++ b/src/google/protobuf/stubs/map-util.h @@ -68,6 +68,30 @@ FindOrNull(const Collection& collection, return &it->second; } +// Perform a lookup in a map or hash_map, assuming that the key exists. +// Crash if it does not. +// +// This is intended as a replacement for operator[] as an rvalue (for reading) +// when the key is guaranteed to exist. +// +// operator[] is discouraged for several reasons: +// * It has a side-effect of inserting missing keys +// * It is not thread-safe (even when it is not inserting, it can still +// choose to resize the underlying storage) +// * It invalidates iterators (when it chooses to resize) +// * It default constructs a value object even if it doesn't need to +// +// This version assumes the key is printable, and includes it in the fatal log +// message. +template <class Collection> +const typename Collection::value_type::second_type& +FindOrDie(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + GOOGLE_CHECK(it != collection.end()) << "Map key not found: " << key; + return it->second; +} + // Perform a lookup in a map or hash_map whose values are pointers. // If the key is present a const pointer to the associated value is returned, // otherwise a NULL pointer is returned. |