From f6321fbd323034d9763e53a56af014872a8a625a Mon Sep 17 00:00:00 2001 From: Vsevolod Stakhov Date: Fri, 18 Jun 2021 12:56:50 +0100 Subject: [PATCH] [Minor] Add a simple utility to find a value in a map like stuff as an optional --- src/libserver/css/css_property.cxx | 7 ++++--- src/libserver/css/css_tokeniser.cxx | 6 +++--- src/libutil/cxx/util.hxx | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/libserver/css/css_property.cxx b/src/libserver/css/css_property.cxx index 2a463f8da..1dd73026d 100644 --- a/src/libserver/css/css_property.cxx +++ b/src/libserver/css/css_property.cxx @@ -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; diff --git a/src/libserver/css/css_tokeniser.cxx b/src/libserver/css/css_tokeniser.cxx index 22544053c..2391140dd 100644 --- a/src/libserver/css/css_tokeniser.cxx +++ b/src/libserver/css/css_tokeniser.cxx @@ -154,10 +154,10 @@ css_parser_token::adjust_dim(const css_parser_token &dim_token) -> bool auto num = std::get(value); auto sv = std::get(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; diff --git a/src/libutil/cxx/util.hxx b/src/libutil/cxx/util.hxx index fa9aa1802..11c134d1f 100644 --- a/src/libutil/cxx/util.hxx +++ b/src/libutil/cxx/util.hxx @@ -21,6 +21,7 @@ #include #include #include +#include /* * Common C++ utilities @@ -76,6 +77,20 @@ constexpr auto array_of(T&&... t) -> std::array return {{ std::forward(t)... }}; } +template + && std::is_constructible_v, bool> = false> +constexpr auto find_map(const C &c, const K &k) -> std::optional> +{ + auto f = c.find(k); + + if (f != c.end()) { + return std::cref(f->second); + } + + return std::nullopt; +} + } #endif //RSPAMD_UTIL_HXX -- 2.39.5