X-Git-Url: http://plrg.eecs.uci.edu/git/?a=blobdiff_plain;f=folly%2FMapUtil.h;h=b00bccff4d99b0122340397fcd7554fca89d2290;hb=140c62d25d930cdbdacaa337d254a2471875a4be;hp=fda6f3d704632f6cb328dad13599cae9b1920872;hpb=22afce906d7e98d95f8c45c3301072d9fd891d41;p=folly.git diff --git a/folly/MapUtil.h b/folly/MapUtil.h index fda6f3d7..b00bccff 100644 --- a/folly/MapUtil.h +++ b/folly/MapUtil.h @@ -1,5 +1,5 @@ /* - * Copyright 2014 Facebook, Inc. + * Copyright 2015 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,9 @@ #ifndef FOLLY_MAPUTIL_H_ #define FOLLY_MAPUTIL_H_ +#include +#include + namespace folly { /** @@ -32,6 +35,36 @@ typename Map::mapped_type get_default( return (pos != map.end() ? pos->second : dflt); } +/** + * Given a map and a key, return the value corresponding to the key in the map, + * or throw an exception of the specified type. + */ +template +typename Map::mapped_type get_or_throw( + const Map& map, const typename Map::key_type& key, + const std::string& exceptionStrPrefix = std::string()) { + auto pos = map.find(key); + if (pos != map.end()) { + return pos->second; + } + throw E(folly::to(exceptionStrPrefix, key)); +} + +/** + * Given a map and a key, return a Optional if the key exists and None if the + * key does not exist in the map. + */ +template +folly::Optional get_optional( + const Map& map, const typename Map::key_type& key) { + auto pos = map.find(key); + if (pos != map.end()) { + return folly::Optional(pos->second); + } else { + return folly::none; + } +} + /** * Given a map and a key, return a reference to the value corresponding to the * key in the map, or the given default reference if the key doesn't exist in @@ -69,4 +102,3 @@ typename Map::mapped_type* get_ptr( } // namespace folly #endif /* FOLLY_MAPUTIL_H_ */ -