]> source.dussan.org Git - rspamd.git/commitdiff
[Minor] Add a simple utility to find a value in a map like stuff as an optional
authorVsevolod Stakhov <vsevolod@highsecure.ru>
Fri, 18 Jun 2021 11:56:50 +0000 (12:56 +0100)
committerVsevolod Stakhov <vsevolod@highsecure.ru>
Fri, 18 Jun 2021 11:56:50 +0000 (12:56 +0100)
src/libserver/css/css_property.cxx
src/libserver/css/css_tokeniser.cxx
src/libutil/cxx/util.hxx

index 2a463f8da5b2b0af3586acdde6b6b32386d07e7a..1dd73026dc9a23c2c0a747b7674d8f2134b8c083 100644 (file)
@@ -17,6 +17,7 @@
 #include "css_property.hxx"
 #include "frozen/unordered_map.h"
 #include "frozen/string.h"
+#include "libutil/cxx/util.hxx"
 
 namespace rspamd::css {
 
@@ -43,10 +44,10 @@ auto token_string_to_property(const std::string_view &inp)
 
        css_property_type ret = css_property_type::PROPERTY_NYI;
 
-       auto known_type = prop_names_map.find(inp);
+       auto known_type = find_map(prop_names_map, inp);
 
-       if (known_type != prop_names_map.end()) {
-               ret = known_type->second;
+       if (known_type) {
+               ret = known_type.value().get();
        }
 
        return ret;
index 22544053c0f1ff6c5ad8dec6f40b27ca56553b75..2391140dd8844c90b56c8afdde5a0f4c37759ba7 100644 (file)
@@ -154,10 +154,10 @@ css_parser_token::adjust_dim(const css_parser_token &dim_token) -> bool
        auto num = std::get<float>(value);
        auto sv = std::get<std::string_view>(dim_token.value);
 
-       auto dim_found = dimensions_map.find(sv);
+       auto dim_found = find_map(dimensions_map, sv);
 
-       if (dim_found != dimensions_map.end()) {
-               auto dim_elt = dim_found->second;
+       if (dim_found) {
+               auto dim_elt = dim_found.value().get();
                dimension_type = dim_elt.dtype;
                flags |= css_parser_token::number_dimension;
                num *= dim_elt.mult;
index fa9aa180249c3684b86809ad494a0587b7468a11..11c134d1f3b4764a07389d3070c2fe223b4f3630 100644 (file)
@@ -21,6 +21,7 @@
 #include <memory>
 #include <array>
 #include <string_view>
+#include <optional>
 
 /*
  * Common C++ utilities
@@ -76,6 +77,20 @@ constexpr auto array_of(T&&... t) -> std::array<V, sizeof...(T)>
        return {{ std::forward<T>(t)... }};
 }
 
+template<class C, class K, class V = typename C::mapped_type, typename std::enable_if_t<
+               std::is_constructible_v<typename C::key_type, K>
+               && std::is_constructible_v<typename C::mapped_type, V>, bool> = false>
+constexpr auto find_map(const C &c, const K &k) -> std::optional<std::reference_wrapper<const V>>
+{
+       auto f = c.find(k);
+
+       if (f != c.end()) {
+               return std::cref<V>(f->second);
+       }
+
+       return std::nullopt;
+}
+
 }
 
 #endif //RSPAMD_UTIL_HXX