GM特权指令实现

        处于开发测试需要,经常需要在程序中内嵌一些特权指令,用于快速到达、获取、实现想要的功能或物品。但是这些指令只能在测试期间生效,不能在线上生效。

        一般做法在于加上一个配置,用于标识release与debug环境。其次,根据不同权限可以实行不同级别的指令。所有的特权指令定义成为数组结构容器,容器中添加调用关键字、调用函数、权限、描述等等。

Gm GmCmds[] =
{
	{"test-gm", Gm::my_print, Gm::MODE_SUPER, "测试指令"},
	{ "test-gm-2", Gm::my_print_2, Gm::MODE_SUPER | Gm::MODE_GM | Gm::MODE_ROOT, "测试指令2" },
	{NULL, NULL, 0, NULL},
};

如上图,定义Gm对象的数组,对象由四部分构成,关键字“test-gm”,函数名"Gm::my_print",权限"Gm::MODE_SUPER",描述"测试指令"。

头文件:

//GM测试
struct Gm
{
	enum
	{
		MODE_FORMAL = 0,
		MODE_GM     = 1,
		MODE_SUPER  = 2,
		MODE_ROOT   = 4,
		MODE_ALL    = 7,
	};

	const char *pstCmd;
	bool(*pstParse)(const char *pstPara);
	int iPriv;
	const char *pstDesc;

	static bool exec(const char *pstCmd);
	static bool my_print(const char *pstPara);
	static bool my_print_2(const char *pstPara);
};

实现文件:

int iMyMode = Gm::MODE_FORMAL;
Gm GmCmds[] =
{
	{"test-gm", Gm::my_print, Gm::MODE_SUPER, "测试指令"},
	{ "test-gm-2", Gm::my_print_2, Gm::MODE_SUPER | Gm::MODE_GM | Gm::MODE_ROOT, "测试指令2" },
	{NULL, NULL, 0, NULL},
};
bool Gm::exec(const char *pstCmd)
{
	if (!pstCmd || strlen(pstCmd) <= 2)
		return false;
	if (pstCmd[0] == '/' && pstCmd[1] == '/')
	{
		std::string strParse = pstCmd + 2;
		for (int i = 0; i >= 0; ++i)
		{
			if (!GmCmds[i].pstCmd) break;
			if (strncmp(GmCmds[i].pstCmd, strParse.c_str(), strlen(GmCmds[i].pstCmd)) == 0)
			{
				if (0 == (iMyMode & GmCmds[i].iPriv))
				{
					cout << "权限不足" << endl;
					break;
				}
				//cout << "exec already find" << endl;
				return GmCmds[i].pstParse(strParse.c_str());
			}
		}
		//cout << "exec no find" << endl;
	}
	return false;
}
bool Gm::my_print(const char *pstPara)
{
	if (!pstPara)
		return false;
	cout << pstPara << endl;
	return true;
}
bool Gm::my_print_2(const char *pstPara)
{
	if (!pstPara)
		return false;
	cout << pstPara << endl;
	return true;
}
int main()
{
	Gm gm;
	iMyMode |= Gm::MODE_GM;
	char chTest[100] = "//test-gm";
	if (!gm.exec(chTest))
	{
		cout << "other handle: " <<chTest << endl;
	}

	iMyMode |= Gm::MODE_ALL;
	memset(chTest, 0, 100);
	strncpy(chTest, "//test-gm-2" , sizeof("//test-gm-2"));
	if (!gm.exec(chTest))
	{
		cout << "other handle: " << chTest << endl;
	}
    return 0;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值