gpt4 book ai didi

c++ - 优化这个功能?

转载 作者:行者123 更新时间:2023-11-28 06:58:22 24 4
gpt4 key购买 nike

<分区>

这段代码是我写的(使用 V8 库)。我经历了几次,感觉这是我能写出这样的东西的唯一方式。该函数的目的是替换 JavaScript .split() 函数;因为当使用带有限制的函数时,返回数组中不包含数组的最后一部分。例如:

var str = "Test split string with limit";
var out = str.split(' ', 2);

数组 out 将包含:[Test, split]。我希望它包含:[Test, split, string with limit].

我知道有纯 JS 方法可以做到这一点,但我发现它们很笨拙,而且可能比单个 C++ 绑定(bind)调用更慢(?)。

这是我的功能:

/**
* Explodes a string but limits the tokens
* @param input
* @param delim
* @param limit
* @return
*/
void ASEngine::Engine::ASstrtok(const v8::FunctionCallbackInfo<v8::Value>& args)
{
Assert(3, args);

Isolate* isolate = args.GetIsolate();

/* Get args */
String::Utf8Value a1(args[0]);
String::Utf8Value a2(args[1]);
Local<Uint32> a3 = args[2]->ToUint32();

std::string input = std::string(*a1);
std::string delim = std::string(*a2);
unsigned int limit = a3->Int32Value();

unsigned int inputLen = input.length();

// Declare a temporary array to shove into the return later
std::vector<char*> tmp;
tmp.reserve(limit);

unsigned int delimlen = delim.length();
char* cp = (char*) malloc(inputLen);
char* cursor = cp + inputLen; // Cursor
char* cpp = (char*) cp; // Keep the start of the string

// Copy the haystack into a modifyable char ptr
memset(cp + inputLen, 0x00, 1);
memcpy(cp, input.c_str(), inputLen);

unsigned int arrayIndex = 0;
for(unsigned int i=0;i<limit;i++)
{
if((cursor = strstr(cp, delim.c_str())) == NULL)
{
cursor = (char*) cpp + inputLen;
break;
}

for(int j=0;j<delimlen;j++)
*(cursor+j) = 0x00;

tmp.push_back(cp);

cp = cursor + delimlen;
arrayIndex++;
}
if(*(cp) != '\0')
{
arrayIndex++;
tmp.push_back(cp);
}

Handle<Array> rtn = Array::New(args.GetIsolate(), arrayIndex);

/* Loop through the temporary array and assign
the variables to the V8 array */
for(unsigned int i=0;i<arrayIndex;i++)
{
rtn->Set(i, String::NewFromUtf8(
isolate, tmp[i], String::kNormalString, strlen(tmp[i])
));
}

/* Clean up memory */
delete cpp;
cp = NULL;
cpp = NULL;
cursor = NULL;
isolate = NULL;

/* Set the return */
args.GetReturnValue().Set(rtn);
}

如果您想知道:变量 cpp 在那里,所以我可以在完成后删除字符指针(调用 v8 的 String::NewFromUtf8() 函数拷贝字符串),我在函数执行过程中修改了 cp 指针。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com