]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
common: add cmd_getval_cast_or()
authorRonen Friedman <rfriedma@redhat.com>
Wed, 12 Mar 2025 09:26:54 +0000 (04:26 -0500)
committerRonen Friedman <rfriedma@redhat.com>
Wed, 19 Mar 2025 07:12:02 +0000 (02:12 -0500)
This slight variation of cmd_getval_or() can be used where
the object type is different from the configuration item
type (as when the object is a wrapper around an integer).
It allows specifying the 'default' value in the object type.

Signed-off-by: Ronen Friedman <rfriedma@redhat.com>
src/common/cmdparse.h

index d4a5c11398f05b5633a2a9cd2665601fba7858c0..70c6045c3bb16b32225f1a9f94d41158bf053e33 100644 (file)
@@ -102,11 +102,34 @@ T cmd_getval_or(const cmdmap_t& cmdmap, std::string_view k,
                const V& defval)
 {
   auto found = cmdmap.find(k);
-  if (found == cmdmap.end()) {
+  if (found == cmdmap.cend()) {
     return T(defval);
   }
   try {
-    return boost::get<T>(cmdmap.find(k)->second);
+    return boost::get<T>(found->second);
+  } catch (boost::bad_get&) {
+    throw bad_cmd_get(k, cmdmap);
+  }
+}
+
+/**
+ * with default, to be used when the parameter type (which matches the type of the
+ * 'default' object) is not one of the limited set of parameters type.
+ * Added to support "safe types" - typed wrappers "around" simple types (e.g.
+ * shard_id_t which is a structure holding one int8_t), without requiring the
+ * user to specify the default in the 'internal type'.
+ *
+ * Throws if the key is found, but the type is not the expected one.
+ */
+template <typename CMD_TYPE, typename T>
+T cmd_getval_cast_or(const cmdmap_t& cmdmap, std::string_view k, T defval)
+{
+  auto found = cmdmap.find(k);
+  if (found == cmdmap.cend()) {
+    return defval;
+  }
+  try {
+    return T(boost::get<CMD_TYPE>(found->second));
   } catch (boost::bad_get&) {
     throw bad_cmd_get(k, cmdmap);
   }