C-chat
Macros
commands.h File Reference

Defines macros to aim to handle commands. More...

#include "ui.h"
#include <string.h>

Go to the source code of this file.

Macros

#define COMMAND_HANDLER(NAME, commands)
 Defines a command handler. More...
 
#define COMMAND(NAME, usage, next)
 Defines a command. More...
 

Detailed Description

Defines macros to aim to handle commands.

Macro Definition Documentation

◆ COMMAND

#define COMMAND (   NAME,
  usage,
  next 
)
Value:
{ \
unsigned int listLength = strlen(listOfCommands); \
unsigned int commandLength = strlen(usage); \
char* listOfCommandsCopy = malloc(listLength + 1 + commandLength + 1); \
memcpy(listOfCommandsCopy, listOfCommands, listLength); \
listOfCommandsCopy[listLength] = '\n'; \
memcpy(listOfCommandsCopy + listLength + 1, usage, commandLength); \
listOfCommandsCopy[listLength + 1 + commandLength] = '\0'; \
free(listOfCommands); \
listOfCommands = listOfCommandsCopy; \
} \
if ( \
strncmp(#NAME, command, strlen(#NAME)) == 0 && strlen(#NAME) == strlen(command) || \
strncmp(#NAME, command, strlen(#NAME)) == 0 && strncmp(" ", command + strlen(#NAME), 1) == 0 \
) {\
command = command + strlen(#NAME); \
int commandLength##NAME = strlen(command); \
while (commandLength##NAME > 0 && command[0] == ' ') { \
command += 1; \
commandLength##NAME = strlen(command); \
} \
next; \
ui_errorMessage(usage); \
return;\
};

Defines a command.

This macro must be called as a parameter of COMMAND_HANDLER macro (see COMMAND_HANDLER macro documentation). Multiple COMMAND call can be nested and once a command is handled, a return call must be made to avoid error message display.

Example of COMMAND macro call :

COMMAND(users, "users <create | delete | list>", COMMAND(delete, "users delete <user>", if (strlen(command) > 0) { // Delete user return; } ) COMMAND(create, "users create <user>", if (strlen(command) > 0) { // Create user return; } ) COMMAND(list, "users list", // List users return; ) )

Parameters
NAMEThe command name (raw identifier)
usageThe command usage (string)
nextThe code to execute on command match

◆ COMMAND_HANDLER

#define COMMAND_HANDLER (   NAME,
  commands 
)
Value:
void NAME##Handler (const char* command) { \
char* listOfCommands = malloc(16); \
memcpy(listOfCommands, "Known commands:", 16); \
listOfCommands[15] = '\0'; \
commands; \
ui_errorMessage(listOfCommands); \
free(listOfCommands); \
}

Defines a command handler.

Defines a function named NAMEHandler where NAME if the given name. The produced function signature is: void NAMEHandler(const char* command); Example:

COMMAND_HANDLER(commands, COMMAND(...) COMMAND(...) COMMAND(...) )

Will create the function : void commandsHandler(const char* command)

The body of the function MUST be generated by COMMAND macros.

Parameters
NAMEThe prefix for the produced command handle
commandsSuccessive calls to COMMAND macro