Переглянути джерело

daemon command pointers are in a hash map

To determine the command the command string is passed to a hash map
which will return the function pointer for the command function
Jonas Pflanzer 5 роки тому
батько
коміт
dbe179b096
2 змінених файлів з 24 додано та 15 видалено
  1. 8 0
      daemon/include/JsonCommander.h
  2. 16 15
      daemon/src/JsonCommander.cpp

+ 8 - 0
daemon/include/JsonCommander.h

@@ -62,6 +62,14 @@ private:
    */
   const std::string protocolVersion = "0.2";
 
+  /**
+   * Map of all commands
+   *
+   * Used to find the command function fast
+   */
+  std::map<std::string, Response (JsonCommander::*)(const Json::Value &)>
+      commandsMap;
+
   /**
    * file manager for reading and writing files
    */

+ 16 - 15
daemon/src/JsonCommander.cpp

@@ -2,27 +2,28 @@
 #include "../include/base64.h"
 
 JsonCommander::JsonCommander(FileManager &fileManager)
-    : fileManager(fileManager) {}
+    : fileManager(fileManager) {
+  commandsMap["status"] = &JsonCommander::executeStatus;
+  commandsMap["close"] = &JsonCommander::executeClose;
+  commandsMap["list"] = &JsonCommander::executeList;
+  commandsMap["put"] = &JsonCommander::executePut;
+  commandsMap["putdata"] = &JsonCommander::executePutdata;
+  commandsMap["get"] = &JsonCommander::executeGet;
+  commandsMap["getdata"] = &JsonCommander::executeGetdata;
+}
 
 JsonCommander::~JsonCommander() {}
 
 JsonCommander::Response JsonCommander::execute(const Json::Value &message) {
   JsonCommander::Response response;
-  if (message["command"].asString().compare("status") == 0) {
-    response = executeStatus(message);
-  } else if (message["command"].asString().compare("close") == 0) {
-    response = executeClose(message);
-  } else if (message["command"].asString().compare("list") == 0) {
-    response = executeList(message);
-  } else if (message["command"].asString().compare("put") == 0) {
-    response = executePut(message);
-  } else if (message["command"].asString().compare("putdata") == 0) {
-    response = executePutdata(message);
-  } else if (message["command"].asString().compare("get") == 0) {
-    response = executeGet(message);
-  } else if (message["command"].asString().compare("getdata") == 0) {
-    response = executeGetdata(message);
+
+  Response (JsonCommander::*commandExecutor)(const Json::Value &) =
+      commandsMap[message["command"].asString()];
+
+  if (commandExecutor != nullptr) {
+    response = (this->*commandExecutor)(message);
   } else {
+    // command does not exist
     response.action = close;
   }