* @file commctx.h
* @author Radosław Korzeniewski (radoslaw@korzeniewski.net)
* @brief This is a Bacula plugin command context switcher template.
- * @version 1.1.0
- * @date 2020-12-23
+ * @version 1.2.0
+ * @date 2020-01-05
*
- * @copyright Copyright (c) 2020 All rights reserved. IP transferred to Bacula Systems according to agreement.
+ * @copyright Copyright (c) 2021 All rights reserved.
+ * IP transferred to Bacula Systems according to agreement.
*/
-#ifndef COMMCTX_H
-#define COMMCTX_H
+#ifndef PLUGINLIB_COMMCTX_H
+#define PLUGINLIB_COMMCTX_H
#include "pluginlib.h"
#include "smartalist.h"
T * switch_command(const char *command);
bool check_command(const char *command);
void foreach_command(void (*func)(T *, void *), void *param);
+ bRC foreach_command_status(bRC (*func)(T *, void *), void *param);
};
}
}
-#endif /* COMMCTX_H */
+/**
+ * @brief Iterate on all command context to execute function and return status.
+ *
+ * @tparam T is command context type.
+ * @param param is the execution function param.
+ */
+template<typename T>
+bRC COMMCTX<T>::foreach_command_status(bRC(*func)(T*, void*), void* param)
+{
+ CMD * cmdctx;
+ bRC status = bRC_OK;
+
+ foreach_alist(cmdctx, &_command_list)
+ {
+ ctx = cmdctx->ptr;
+ bRC rc = func(ctx, param);
+ if (rc != bRC_OK)
+ status = rc;
+ }
+
+ return status;
+}
+
+#endif // PLUGINLIB_COMMCTX_H
bInfo *binfo;
static int referencenumber = 0;
+static int dosomethingvariable = 0;
struct testctx : public SMARTALLOC
{
~testctx() { referencenumber--; };;
};
+void do_something(testctx*, void*data)
+{
+ dosomethingvariable++;
+
+ if (data != NULL)
+ {
+ int *var = (int *)data;
+ dosomethingvariable += *var;
+ }
+}
+
+bRC do_status(testctx*, void*data)
+{
+ if (data != NULL)
+ {
+ return bRC_OK;
+ }
+
+ return bRC_Error;
+}
+
int main()
{
Unittests pluglib_test("commctx_test");
{
COMMCTX<testctx> ctx;
- nok(ctx.check_command("TEST1"), "test empty ctx list");
+ nok(ctx.check_command(TEST1), "test empty ctx list");
ok(referencenumber == 0, "check no allocation yet");
auto testctx1 = ctx.switch_command(TEST1);
ok(referencenumber == 0, "check smart free");
+ {
+ COMMCTX<testctx> ctx;
+
+ auto testctx1 = ctx.switch_command(TEST1);
+ ok(testctx1 != nullptr, "test switch command1");
+ ok(referencenumber == 1, "check ref allocation1");
+
+ auto testctx2 = ctx.switch_command(TEST2);
+ ok(testctx2 != nullptr, "test switch command2");
+ ok(referencenumber == 2, "check allocation2");
+
+ int append = 2;
+ ctx.foreach_command(do_something, &append);
+ ok(dosomethingvariable == 6, "dosomethingvariable");
+
+ dosomethingvariable = 0;
+ ctx.foreach_command(do_something, NULL);
+ ok(dosomethingvariable == 2, "do_something with NULL");
+
+ auto status = ctx.foreach_command_status(do_status, &append);
+ ok(status != bRC_Error, "do_status");
+
+ status = ctx.foreach_command_status(do_status, NULL);
+ ok(status == bRC_Error, "do_status with NULL");
+ }
+
return report();
}