optimized + fixed parsing in strbreak()

This commit is contained in:
David Anderson 2006-02-01 12:10:26 +00:00
parent 314392bffe
commit eb010688af

View File

@ -678,73 +678,66 @@ static cell AMX_NATIVE_CALL amx_strtok(AMX *amx, cell *params)
//strbreak(String[], First[], FirstLen, Rest[], RestLen) //strbreak(String[], First[], FirstLen, Rest[], RestLen)
static cell AMX_NATIVE_CALL strbreak(AMX *amx, cell *params) /* 5 param */ static cell AMX_NATIVE_CALL strbreak(AMX *amx, cell *params) /* 5 param */
{ {
bool quote_flag = false; int _len;
bool done_flag = false; bool in_quote = false;
int left_pos = 0; bool had_quotes = false;
int right_pos = 0; size_t i = 0;
int l = 0; size_t beg = 0;
unsigned int i = 0;
char hold = '"';
char *string = get_amxstring(amx, params[1], 0, l); char *string = get_amxstring(amx, params[1], 0, _len);
char *left = new char[strlen(string) + 1]; cell *left = get_amxaddr(amx, params[2]);
char *right = new char[strlen(string) + 1]; cell *right = get_amxaddr(amx, params[4]);
int LeftMax = params[3]; int LeftMax = params[3];
int RightMax = params[5]; int RightMax = params[5];
for (i = 0; i < (unsigned int)l; i++) size_t len = (size_t)_len;
while (isspace(string[i]) && i<len)
i++;
beg = i;
for (; i<len; i++)
{ {
if (string[i] == '"' && !quote_flag) if (string[i] == '"' && !in_quote)
{ {
quote_flag = true; in_quote = (had_quotes = true);
} } else if (string[i] == '"' && in_quote) {
else if (string[i] == '"' && quote_flag) in_quote = false;
{ if (i == len-1)
quote_flag = false; goto do_copy;
}
if (isspace(string[i]) && !quote_flag && !done_flag)
{
done_flag = true;
i++;
}
if (!done_flag && string[i]!='"')
{
if (left_pos < LeftMax)
{
left[left_pos] = string[i];
if (left[left_pos] == '\'')
{
left[left_pos] = hold;
}
left_pos++;
} else {
done_flag = true;
}
} else { } else {
if (right_pos < RightMax && string[i]!='"') if (isspace(string[i]) && !in_quote)
{ {
right[right_pos] = string[i]; do_copy:
size_t pos = i;
if (right[right_pos] == '\'') while (isspace(string[i]))
i++;
const char *start = had_quotes ? &(string[beg+1]) : &(string[beg]);
size_t _end = had_quotes ? (i==len-1 ? 1 : 2) : 0;
size_t end = (pos - _end > RightMax) ? RightMax : pos - _end;
size_t to_go = end-beg;
if (end && to_go)
{ {
right[right_pos] = hold; while (to_go--)
*left++ = (cell)*start++;
} }
*left = '\0';
right_pos++; end = (len-i+1 > LeftMax) ? LeftMax : len-i+1;
if (end)
{
start = &(string[i]);
while (end--)
*right++ = (cell)*start++;
}
*right = '\0';
return 1;
} }
} }
} }
left[left_pos] = '\0'; //if we got here, there was nothing to break
right[right_pos] = '\0'; set_amxstring(amx, params[2], &(string[beg]), params[3]);
set_amxstring(amx, params[2], left, params[3]); if (RightMax)
set_amxstring(amx, params[4], right, params[5]); *right = '\0';
delete [] left;
delete [] right;
return 1; return 1;
} }