1 Star 1 Fork 0

卖菇凉小蘑菇 / cmd-parser

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
cmd.c 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
/*
* @Author: jiejie
* @Github: https://github.com/jiejieTop
* @Date: 2019-12-13 10:47:30
* @LastEditTime: 2019-12-17 13:38:02
* @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
*/
#include "cmd.h"
#include <stdio.h>
static cmd_t *_cmd_begin, *_cmd_end;
static int _cmd_to_lower(int c)
{
if ((c >= 'A') && (c <= 'Z'))
return c + ('a' - 'A');
return c;
}
static unsigned int _cmd_hash(const char* str)
{
unsigned int hash = CMD_HASH; /* 'jiejie' string hash */
int c = *str;
while(*str) {
hash = ((hash << 5) + (hash ^ c)) + (_cmd_to_lower(c));
str++;
c = *str;
}
return hash;
}
static void _cmd_init(const void *begin, const void *end)
{
_cmd_begin = (cmd_t*) begin;
_cmd_end = (cmd_t*) end;
}
static cmd_t* _get_next_cmd(cmd_t *cmd)
{
unsigned int *ptr;
ptr = (unsigned int*) (cmd + 1);
while ((*ptr == 0) && ((unsigned int*)ptr < (unsigned int*) _cmd_end))
ptr ++;
return (cmd_t*) ptr;
}
static int _cmd_match(const char *str, const char *cmd)
{
int c1, c2;
do {
c1 = _cmd_to_lower(*str++);
c2 = _cmd_to_lower(*cmd++);
} while((c1 == c2) && c1);
return c1 - c2;
}
static void _list(void)
{
cmd_t *index;
for (index = _cmd_begin; index < _cmd_end; index = _get_next_cmd(index)) {
printf("%s\n",index->cmd);
}
}
REGISTER_CMD(_list, _list);
void cmd_init(void)
{
cmd_t *index;
#if defined(__CC_ARM) || defined(__CLANG_ARM) /* ARM C Compiler */
extern const int CMDS$$Base;
extern const int CMDS$$Limit;
_cmd_init(&CMDS$$Base, &CMDS$$Limit);
#elif defined (__ICCARM__) || defined(__ICCRX__) /* for IAR Compiler */
_cmd_init(__section_begin("CMDS"), __section_end("CMDS"));
#endif
for (index = _cmd_begin; index < _cmd_end; index = _get_next_cmd(index)) {
index->hash = _cmd_hash(index->cmd);
}
}
void cmd_parsing(char *str)
{
cmd_t *index;
unsigned int hash = _cmd_hash(str);
for (index = _cmd_begin; index < _cmd_end; index = _get_next_cmd(index)) {
if (hash == index->hash) {
if (_cmd_match(str, index->cmd) == 0) {
index->handler();
break;
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/qq1847123212/cmd-parser.git
git@gitee.com:qq1847123212/cmd-parser.git
qq1847123212
cmd-parser
cmd-parser
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891