This class can map strings(commands) and functions receiving no arguments returning an int value.

Dependents:   Interference_Simple StrCommandHandler_Demo

StrCommandHandler.cpp

Committer:
aktk
Date:
2019-10-31
Revision:
0:024213917a9f
Child:
2:a4873d38a32c

File content as of revision 0:024213917a9f:

#include "StrCommandHandler.h"

StrCommandHandler::StrCommandHandler (
    int const arg_num_ofcommands
):
    m_num_ofcommands(arg_num_ofcommands)
{
    m_command_name = new char[m_num_ofcommands][16];
    m_function = new (int (* [m_num_ofcommands])(void));
}

int StrCommandHandler::map(
    const char * const   arg_command,
    int (*arg_pfunc)(void)
)
{
    static int itr_push = 0;


    //  Reallocation
    if (itr_push == m_num_ofcommands) {
        m_num_ofcommands += 5;
        char (*tmp_cm)[16]  = new char[m_num_ofcommands][16];
        int (**tmp_fu)(void)= new (int (* [m_num_ofcommands])(void));

        memcpy(tmp_cm, m_command_name,  sizeof(char) * (m_num_ofcommands - 5) * 16);
        memcpy(tmp_fu, m_function,      sizeof(int (*)()) * (m_num_ofcommands - 5));

        delete[] m_command_name;
        delete[] m_function;

        m_command_name  = tmp_cm;
        m_function      = tmp_fu;
    }

    //  Register the command name
    for (int i = 0; i < 16; i++) {
        m_command_name[itr_push][i] = arg_command[i];
        if (arg_command[i] == '\0') break;
    }
    m_command_name[itr_push][15] = '\0';

    //  Register the pointer to function
    m_function[itr_push] = arg_pfunc;

    itr_push++;
    return 0;
}


int StrCommandHandler::exe(
    const char* const   arg_command
)
{
    int key = 0;

    //  Exception: NULL pointer
    if ( arg_command == NULL) return 0xFFFFFFFF;

    //  Exception: Null character
    if ( arg_command[0] == '\0') return 0xFFFFFFFE;

    //  Exception: Over length of Command's name
    for ( int i = 1; i < 16; i++ ) {
        if (arg_command[i] == '\0') break;
        if (i == 15) return 0xFFFFFFFD;
    }

    //  Search the command list
    while (
        key < m_num_ofcommands
        &&  strcmp(m_command_name[key], arg_command) != 0
    ) {
        key++;
    }

    //  Exception: Not registered Command
    if ( key == m_num_ofcommands ) return 0xFFFFFFFC;

    return (*m_function[key])();;
}

void StrCommandHandler::list()
{
    puts("\n\n---------------");
    puts("---------------\n");
    puts("list of command\n");
    for(int i = 0; i < m_num_ofcommands; i++) {
        if(m_function[i] != NULL) {
            printf("%02d: %16s", i, m_command_name[i]);
            //printf(" / result: %d", (*m_function[i])());
            puts("\n");
        }
    }
    puts("---------------\n");
}