core/smn_string.cpp
author Scott Ehlert <ds@alliedmods.net>
Sun Aug 24 04:35:48 2008 +0000 (2008-08-24)
changeset 2237 4403a982ec91
parent 2193 db7c6362f3f2
child 2271 b15123c83b57
permissions -rw-r--r--
Improved bot detection slightly. This was meant to go along with the fix for amb1801.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <string.h>
    33 #include <stdlib.h>
    34 #include "sm_globals.h"
    35 #include "sm_stringutil.h"
    36 #include <ITextParsers.h>
    37 #include <ctype.h>
    38 
    39 inline const char *_strstr(const char *str, const char *substr)
    40 {
    41 #ifdef PLATFORM_WINDOWS
    42 	return strstr(str, substr);
    43 #elif defined PLATFORM_LINUX
    44 	return (const char *)strstr(str, substr);
    45 #endif
    46 }
    47 
    48 /*********************************************
    49 *                                            *
    50 * STRING MANIPULATION NATIVE IMPLEMENTATIONS *
    51 *                                            *
    52 *********************************************/
    53 
    54 static cell_t sm_strlen(IPluginContext *pCtx, const cell_t *params)
    55 {
    56 	char *str;
    57 	pCtx->LocalToString(params[1], &str);
    58 
    59 	return strlen(str);
    60 }
    61 
    62 static cell_t sm_contain(IPluginContext *pCtx, const cell_t *params)
    63 {
    64 	typedef const char *(*STRSEARCH)(const char *, const char *);
    65 	STRSEARCH func;
    66 	char *str, *substr;
    67 
    68 	pCtx->LocalToString(params[1], &str);
    69 	pCtx->LocalToString(params[2], &substr);
    70 
    71 	func = (params[3]) ? _strstr : stristr;
    72 	const char *pos = func(str, substr);
    73 	if (pos)
    74 	{
    75 		return (pos - str);
    76 	}
    77 
    78 	return -1;
    79 }
    80 
    81 static cell_t sm_strcmp(IPluginContext *pCtx, const cell_t *params)
    82 {
    83 	typedef int (*STRCOMPARE)(const char *, const char *);
    84 	STRCOMPARE func;
    85 	char *str1, *str2;
    86 
    87 	pCtx->LocalToString(params[1], &str1);
    88 	pCtx->LocalToString(params[2], &str2);
    89 
    90 	func = (params[3]) ? strcmp : stricmp;
    91 
    92 	return (func(str1, str2));
    93 }
    94 
    95 static cell_t sm_strncmp(IPluginContext *pCtx, const cell_t *params)
    96 {
    97 	char *str1, *str2;
    98 
    99 	pCtx->LocalToString(params[1], &str1);
   100 	pCtx->LocalToString(params[2], &str2);
   101 	
   102 	if  (params[4])
   103 	{
   104 		return strncmp(str1, str2, (size_t)params[3]);
   105 	} else {
   106 		return strncasecmp(str1, str2, (size_t)params[3]);
   107 	}
   108 }
   109 
   110 static cell_t sm_strcopy(IPluginContext *pCtx, const cell_t *params)
   111 {
   112 	char *dest, *src;
   113 
   114 	pCtx->LocalToString(params[1], &dest);
   115 	pCtx->LocalToString(params[3], &src);
   116 
   117 	return strncopy(dest, src, params[2]);
   118 }
   119 
   120 static cell_t sm_strconvint(IPluginContext *pCtx, const cell_t *params)
   121 {
   122 	char *str, *dummy;
   123 	pCtx->LocalToString(params[1], &str);
   124 
   125 	return static_cast<cell_t>(strtol(str, &dummy, params[2]));
   126 }
   127 
   128 static cell_t StringToIntEx(IPluginContext *pCtx, const cell_t *params)
   129 {
   130 	char *str, *dummy = NULL;
   131 	cell_t *addr;
   132 	pCtx->LocalToString(params[1], &str);
   133 	pCtx->LocalToPhysAddr(params[2], &addr);
   134 
   135 	*addr = static_cast<cell_t>(strtol(str, &dummy, params[3]));
   136 
   137 	return dummy - str;
   138 }
   139 
   140 static cell_t sm_numtostr(IPluginContext *pCtx, const cell_t *params)
   141 {
   142 	char *str;
   143 	pCtx->LocalToString(params[2], &str);
   144 	size_t res = UTIL_Format(str, params[3], "%d", params[1]);
   145 
   146 	return static_cast<cell_t>(res);
   147 }
   148 
   149 static cell_t sm_strtofloat(IPluginContext *pCtx, const cell_t *params)
   150 {
   151 	char *str, *dummy;
   152 	pCtx->LocalToString(params[1], &str);
   153 
   154 	float val = (float)strtod(str, &dummy);
   155 
   156 	return sp_ftoc(val);
   157 }
   158 
   159 static cell_t StringToFloatEx(IPluginContext *pCtx, const cell_t *params)
   160 {
   161 	char *str, *dummy = NULL;
   162 	cell_t *addr;
   163 	pCtx->LocalToString(params[1], &str);
   164 	pCtx->LocalToPhysAddr(params[2], &addr);
   165 
   166 	float val = (float)strtod(str, &dummy);
   167 
   168 	*addr = sp_ftoc(val);
   169 
   170 	return dummy - str;
   171 }
   172 
   173 static cell_t sm_floattostr(IPluginContext *pCtx, const cell_t *params)
   174 {
   175 	char *str;
   176 	pCtx->LocalToString(params[2], &str);
   177 	size_t res = UTIL_Format(str, params[3], "%f", sp_ctof(params[1]));
   178 
   179 	return static_cast<cell_t>(res);
   180 }
   181 
   182 static cell_t sm_formatex(IPluginContext *pCtx, const cell_t *params)
   183 {
   184 	char *buf, *fmt;
   185 	size_t res;
   186 	int arg = 4;
   187 
   188 	pCtx->LocalToString(params[1], &buf);
   189 	pCtx->LocalToString(params[3], &fmt);
   190 	res = atcprintf(buf, static_cast<size_t>(params[2]), fmt, pCtx, params, &arg);
   191 
   192 	return static_cast<cell_t>(res);
   193 }
   194 
   195 static char g_formatbuf[2048];
   196 static cell_t sm_format(IPluginContext *pCtx, const cell_t *params)
   197 {
   198 	char *buf, *fmt, *destbuf;
   199 	cell_t start_addr, end_addr, maxparam;
   200 	size_t res, maxlen;
   201 	int arg = 4;
   202 	bool copy = false;
   203 
   204 	pCtx->LocalToString(params[1], &destbuf);
   205 	pCtx->LocalToString(params[3], &fmt);
   206 
   207 	maxlen = static_cast<size_t>(params[2]);
   208 	start_addr = params[1];
   209 	end_addr = params[1] + maxlen;
   210 	maxparam = params[0];
   211 
   212 	for (cell_t i=3; i<=maxparam; i++)
   213 	{
   214 		if ((params[i] >= start_addr) && (params[i] <= end_addr))
   215 		{
   216 			copy = true;
   217 			break;
   218 		}
   219 	}
   220 	buf = (copy) ? g_formatbuf : destbuf;
   221 	res = atcprintf(buf, maxlen, fmt, pCtx, params, &arg);
   222 
   223 	if (copy)
   224 	{
   225 		memcpy(destbuf, g_formatbuf, res+1);
   226 	}
   227 
   228 	return static_cast<cell_t>(res);
   229 }
   230 
   231 static cell_t sm_vformat(IPluginContext *pContext, const cell_t *params)
   232 {
   233 	int vargPos = static_cast<int>(params[4]);
   234 
   235 	/* Get the parent parameter array */
   236 	cell_t *local_params = pContext->GetLocalParams();
   237 
   238 	cell_t max = local_params[0];
   239 	if (vargPos > (int)max + 1)
   240 	{
   241 		return pContext->ThrowNativeError("Argument index is invalid: %d", vargPos);
   242 	}
   243 
   244 	cell_t addr_start = params[1];
   245 	cell_t addr_end = addr_start + params[2];
   246 	bool copy = false;
   247 	for (int i=vargPos; i<=max; i++)
   248 	{
   249 		/* Does this clip bounds? */
   250 		if ((local_params[i] >= addr_start)
   251 			&& (local_params[i] <= addr_end))
   252 		{
   253 			copy = true;
   254 			break;
   255 		}
   256 	}
   257 
   258 	/* Get destination info */
   259 	char *format, *destination;
   260 	size_t maxlen = static_cast<size_t>(params[2]);
   261 
   262 	if (copy)
   263 	{
   264 		destination = g_formatbuf;
   265 	} else {
   266 		pContext->LocalToString(params[1], &destination);
   267 	}
   268 
   269 	pContext->LocalToString(params[3], &format);
   270 
   271 	size_t total = atcprintf(destination, maxlen, format, pContext, local_params, &vargPos);
   272 
   273 	/* Perform copy-on-write if we need to */
   274 	if (copy)
   275 	{
   276 		pContext->StringToLocal(params[1], maxlen, g_formatbuf);
   277 	}
   278 
   279 	return total;
   280 }
   281 
   282 /* :TODO: make this UTF8 safe */
   283 static cell_t BreakString(IPluginContext *pContext, const cell_t *params)
   284 {
   285 	const char *input;
   286 	char *out;
   287 	size_t outMax;
   288 
   289 	/* Get parameters */
   290 	pContext->LocalToString(params[1], (char **)&input);
   291 	pContext->LocalToString(params[2], &out);
   292 	outMax = params[3];
   293 
   294 	const char *inptr = input;
   295 	/* Eat up whitespace */
   296 	while (*inptr != '\0' && textparsers->IsWhitespace(inptr))
   297 	{
   298 		inptr++;
   299 	}
   300 
   301 	if (*inptr == '\0')
   302 	{
   303 		if (outMax)
   304 		{
   305 			*out = '\0';
   306 		}
   307 		return -1;
   308 	}
   309 
   310 	const char *start, *end = NULL;
   311 
   312 	bool quoted = (*inptr == '"');
   313 	if (quoted)
   314 	{
   315 		inptr++;
   316 		start = inptr;
   317 		/* Read input until we reach a quote. */
   318 		while (*inptr != '\0' && *inptr != '"')
   319 		{
   320 			/* Update the end point, increment the stream. */
   321 			end = inptr++;
   322 		}
   323 		/* Read one more token if we reached an end quote */
   324 		if (*inptr == '"')
   325 		{
   326 			inptr++;
   327 		}
   328 	} else {
   329 		start = inptr;
   330 		/* Read input until we reach a space */
   331 		while (*inptr != '\0' && !textparsers->IsWhitespace(inptr))
   332 		{
   333 			/* Update the end point, increment the stream. */
   334 			end = inptr++;
   335 		}
   336 	}
   337 
   338 	/* Copy the string we found, if necessary */
   339 	if (end == NULL)
   340 	{
   341 		if (outMax)
   342 		{
   343 			*out = '\0';
   344 		}
   345 	} else if (outMax) {
   346 		char *outptr = out;
   347 		outMax--;
   348 		for (const char *ptr=start;
   349 			(ptr <= end) && ((unsigned)(outptr - out) < (outMax));
   350 			ptr++, outptr++)
   351 			{
   352 			*outptr = *ptr;
   353 		}
   354 		*outptr = '\0';
   355 	}
   356 
   357 	/* Consume more of the string until we reach non-whitespace */
   358 	while (*inptr != '\0' && textparsers->IsWhitespace(inptr))
   359 	{
   360 		inptr++;
   361 	}
   362 
   363 	if (*inptr == '\0')
   364 	{
   365 		return -1;
   366 	}
   367 
   368 	return inptr - input;
   369 }
   370 
   371 static cell_t GetCharBytes(IPluginContext *pContext, const cell_t *params)
   372 {
   373 	char *str;
   374 	pContext->LocalToString(params[1], &str);
   375 
   376 	return _GetUTF8CharBytes(str);
   377 };
   378 
   379 static cell_t IsCharAlpha(IPluginContext *pContext, const cell_t *params)
   380 {
   381 	char chr = params[1];
   382 
   383 	if (_GetUTF8CharBytes(&chr) != 1)
   384 	{
   385 		return 0;
   386 	}
   387 
   388 	return isalpha(chr);
   389 }
   390 
   391 static cell_t IsCharNumeric(IPluginContext *pContext, const cell_t *params)
   392 {
   393 	char chr = params[1];
   394 
   395 	if (_GetUTF8CharBytes(&chr) != 1)
   396 	{
   397 		return 0;
   398 	}
   399 
   400 	return isdigit(chr);
   401 }
   402 
   403 static cell_t IsCharSpace(IPluginContext *pContext, const cell_t *params)
   404 {
   405 	char chr = params[1];
   406 
   407 	if (_GetUTF8CharBytes(&chr) != 1)
   408 	{
   409 		return 0;
   410 	}
   411 
   412 	return isspace(chr);
   413 }
   414 
   415 static cell_t IsCharMB(IPluginContext *pContext, const cell_t *params)
   416 {
   417 	char chr = params[1];
   418 
   419 	unsigned int bytes = _GetUTF8CharBytes(&chr);
   420 	if (bytes == 1)
   421 	{
   422 		return 0;
   423 	}
   424 
   425 	return bytes;
   426 }
   427 
   428 static cell_t IsCharUpper(IPluginContext *pContext, const cell_t *params)
   429 {
   430 	char chr = params[1];
   431 
   432 	if (_GetUTF8CharBytes(&chr) != 1)
   433 	{
   434 		return 0;
   435 	}
   436 
   437 	return isupper(chr);
   438 }
   439 
   440 static cell_t IsCharLower(IPluginContext *pContext, const cell_t *params)
   441 {
   442 	char chr = params[1];
   443 
   444 	if (_GetUTF8CharBytes(&chr) != 1)
   445 	{
   446 		return 0;
   447 	}
   448 
   449 	return islower(chr);
   450 }
   451 
   452 static cell_t ReplaceString(IPluginContext *pContext, const cell_t *params)
   453 {
   454 	char *text, *search, *replace;
   455 	size_t maxlength;
   456 	
   457 	pContext->LocalToString(params[1], &text);
   458 	pContext->LocalToString(params[3], &search);
   459 	pContext->LocalToString(params[4], &replace);
   460 	maxlength = (size_t)params[2];
   461 
   462 	if (search[0] == '\0')
   463 	{
   464 		return pContext->ThrowNativeError("Cannot replace searches of empty strings");
   465 	}
   466 
   467 	return UTIL_ReplaceAll(text, maxlength, search, replace);
   468 }
   469 
   470 static cell_t ReplaceStringEx(IPluginContext *pContext, const cell_t *params)
   471 {
   472 	char *text, *search, *replace;
   473 	size_t maxlength;
   474 
   475 	pContext->LocalToString(params[1], &text);
   476 	pContext->LocalToString(params[3], &search);
   477 	pContext->LocalToString(params[4], &replace);
   478 	maxlength = (size_t)params[2];
   479 
   480 	size_t searchLen = (params[5] == -1) ? strlen(search) : (size_t)params[5];
   481 	size_t replaceLen = (params[6] == -1) ? strlen(replace) : (size_t)params[6];
   482 
   483 	if (searchLen == 0)
   484 	{
   485 		return pContext->ThrowNativeError("Cannot replace searches of empty strings");
   486 	}
   487 
   488 	char *ptr = UTIL_ReplaceEx(text, maxlength, search, searchLen, replace, replaceLen);
   489 
   490 	if (ptr == NULL)
   491 	{
   492 		return -1;
   493 	}
   494 
   495 	return ptr - text;
   496 }
   497 
   498 static cell_t TrimString(IPluginContext *pContext, const cell_t *params)
   499 {
   500 	char *str;
   501 	pContext->LocalToString(params[1], &str);
   502 
   503 	size_t chars = strlen(str);
   504 
   505 	if (chars == 0)
   506 	{
   507 		return 0;
   508 	}
   509 
   510 	char *end = str + chars - 1;
   511 
   512 	/* Iterate backwards through string until we reach first non-whitespace char */
   513 	while (end >= str && textparsers->IsWhitespace(end))
   514 	{
   515 		end--;
   516 	}
   517 
   518 	/* Replace first whitespace char (at the end) with null terminator */
   519 	*(end + 1) = '\0';
   520 
   521 	/* Iterate forwards through string until first non-whitespace char is reached */
   522 	while (textparsers->IsWhitespace(str))
   523 	{
   524 		str++;
   525 	}
   526 
   527 	size_t bytes;
   528 	pContext->StringToLocalUTF8(params[1], chars + 1, str, &bytes);
   529 
   530 	return bytes;
   531 }
   532 
   533 static cell_t SplitString(IPluginContext *pContext, const cell_t *params)
   534 {
   535 	char *text, *split;
   536 	
   537 	pContext->LocalToString(params[1], &text);
   538 	pContext->LocalToString(params[2], &split);
   539 
   540 	size_t maxLen = (size_t)params[4];
   541 	size_t textLen = strlen(text);
   542 	size_t splitLen = strlen(split);
   543 
   544 	if (splitLen > textLen)
   545 	{
   546 		return -1;
   547 	}
   548 
   549 	/**
   550 	 * Note that it's <= ... you could also just add 1,
   551 	 * but this is a bit nicer
   552 	 */
   553 	for (size_t i=0; i<=textLen - splitLen; i++)
   554 	{
   555 		if (strncmp(&text[i], split, splitLen) == 0)
   556 		{
   557 			/* Split hereeeee */
   558 			if (i >= maxLen)
   559 			{
   560 				pContext->StringToLocalUTF8(params[3], maxLen, text, NULL);
   561 			} else {
   562 				pContext->StringToLocalUTF8(params[3], i+1, text, NULL);
   563 			}
   564 			return (cell_t)(i + splitLen);
   565 		}
   566 	}
   567 
   568 	return -1;
   569 }
   570 
   571 static cell_t StripQuotes(IPluginContext *pContext, const cell_t *params)
   572 {
   573 	char *text;
   574 	size_t length;
   575 
   576 	pContext->LocalToString(params[1], &text);
   577 	length = strlen(text);
   578 
   579 	if (text[0] == '"' && text[length-1] == '"')
   580 	{
   581 		/* Null-terminate */
   582 		text[--length] = '\0';
   583 		/* Move the remaining bytes (including null terminator) down by one */
   584 		memmove(&text[0], &text[1], length);
   585 
   586 		return 1;
   587 	}
   588 
   589 	return 0;	
   590 }
   591 
   592 REGISTER_NATIVES(basicStrings)
   593 {
   594 	{"BreakString",			BreakString},
   595 	{"FloatToString",		sm_floattostr},
   596 	{"Format",				sm_format},
   597 	{"FormatEx",			sm_formatex},
   598 	{"GetCharBytes",		GetCharBytes},
   599 	{"IntToString",			sm_numtostr},
   600 	{"IsCharAlpha",			IsCharAlpha},
   601 	{"IsCharLower",			IsCharLower},
   602 	{"IsCharMB",			IsCharMB},
   603 	{"IsCharNumeric",		IsCharNumeric},
   604 	{"IsCharSpace",			IsCharSpace},
   605 	{"IsCharUpper",			IsCharUpper},
   606 	{"ReplaceString",		ReplaceString},
   607 	{"ReplaceStringEx",		ReplaceStringEx},
   608 	{"SplitString",			SplitString},
   609 	{"strlen",				sm_strlen},
   610 	{"StrContains",			sm_contain},
   611 	{"strcmp",				sm_strcmp},
   612 	{"strncmp",				sm_strncmp},
   613 	{"strcopy",				sm_strcopy},
   614 	{"StringToInt",			sm_strconvint},
   615 	{"StringToIntEx",		StringToIntEx},
   616 	{"StringToFloat",		sm_strtofloat},
   617 	{"StringToFloatEx",		StringToFloatEx},
   618 	{"StripQuotes",			StripQuotes},
   619 	{"TrimString",			TrimString},
   620 	{"VFormat",				sm_vformat},
   621 	{NULL,					NULL},
   622 };