Program Listing for File main_free_cmem.cpp

Return to documentation for file (main_free_cmem.cpp)

#include "cmem_user.hpp"
#include "ers/ers.h"
#include "felixtag.h"
#include <exception>
#include "docopt/docopt.h"
#include <stdlib.h>
#include <format>
#include <charconv>
#include <string>

ERS_DECLARE_ISSUE(felix_log, free_cmem_issue, issue_message, ((const std::string&)issue_message))

int main(int argc, char** argv)
{
    ers::warning(felix_log::free_cmem_issue("This application is deprecated, there should be no need to manually free cmem_rcc segments"));

    const std::string USAGE = std::format("Usage: {} <handle_or_name>\n", argv[0]);
    std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc });

    cmem::Driver cmem_driver {};

    if (args["<handle_or_name>"]) {
        std::string input = args["<handle_or_name>"].asString();

        int handle = 0;
        auto [ptr, ec] = std::from_chars(input.data(), input.data() + input.size(), handle);

        if (ec == std::errc::result_out_of_range) {
            ers::error(felix_log::free_cmem_issue(std::format("Handle value {} is too big to fit into an integer.", input)));

        } else if (ec == std::errc{} && ptr == input.data() + input.size()) {
            try {
                cmem_driver.unlock_memory(handle);
                cmem_driver.free_memory(handle);
                ERS_INFO(std::format("Unlocked and freed segment with handle: {}", handle));
            } catch (std::exception &e) {
                ers::warning(felix_log::free_cmem_issue(std::format("Memory might have been already free. Failed unlock_and_free with warning -> {}.", e.what())));
            }

        } else {
            try {
                cmem_driver.unlock_and_free_memory(input);
                ERS_INFO(std::format("Unlocked and freed segment with name: {}", input));
            } catch (std::exception &e) {
                ers::warning(felix_log::free_cmem_issue(std::format("Memory might have been already free. Failed unlock_and_free with warning -> {}.", e.what())));
            }
        }
    }

  return 0;
}