3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
34 #include "sm_globals.h"
35 #include "sm_stringutil.h"
36 #include <ITextParsers.h>
39 inline const char *_strstr(const char *str, const char *substr)
41 #ifdef PLATFORM_WINDOWS
42 return strstr(str, substr);
43 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
44 return (const char *)strstr(str, substr);
48 /*********************************************
50 * STRING MANIPULATION NATIVE IMPLEMENTATIONS *
52 *********************************************/
54 static cell_t sm_strlen(IPluginContext *pCtx, const cell_t *params)
57 pCtx->LocalToString(params[1], &str);
62 static cell_t sm_contain(IPluginContext *pCtx, const cell_t *params)
64 typedef const char *(*STRSEARCH)(const char *, const char *);
68 pCtx->LocalToString(params[1], &str);
69 pCtx->LocalToString(params[2], &substr);
71 func = (params[3]) ? _strstr : stristr;
72 const char *pos = func(str, substr);
81 static cell_t sm_strcmp(IPluginContext *pCtx, const cell_t *params)
83 typedef int (*STRCOMPARE)(const char *, const char *);
87 pCtx->LocalToString(params[1], &str1);
88 pCtx->LocalToString(params[2], &str2);
90 func = (params[3]) ? strcmp : stricmp;
92 return (func(str1, str2));
95 static cell_t sm_strncmp(IPluginContext *pCtx, const cell_t *params)
99 pCtx->LocalToString(params[1], &str1);
100 pCtx->LocalToString(params[2], &str2);
104 return strncmp(str1, str2, (size_t)params[3]);
106 return strncasecmp(str1, str2, (size_t)params[3]);
110 static cell_t sm_strcopy(IPluginContext *pCtx, const cell_t *params)
114 pCtx->LocalToString(params[1], &dest);
115 pCtx->LocalToString(params[3], &src);
117 return strncopy(dest, src, params[2]);
120 static cell_t sm_strconvint(IPluginContext *pCtx, const cell_t *params)
123 pCtx->LocalToString(params[1], &str);
125 return static_cast<cell_t>(strtol(str, &dummy, params[2]));
128 static cell_t StringToIntEx(IPluginContext *pCtx, const cell_t *params)
130 char *str, *dummy = NULL;
132 pCtx->LocalToString(params[1], &str);
133 pCtx->LocalToPhysAddr(params[2], &addr);
135 *addr = static_cast<cell_t>(strtol(str, &dummy, params[3]));
140 static cell_t sm_numtostr(IPluginContext *pCtx, const cell_t *params)
143 pCtx->LocalToString(params[2], &str);
144 size_t res = UTIL_Format(str, params[3], "%d", params[1]);
146 return static_cast<cell_t>(res);
149 static cell_t sm_strtofloat(IPluginContext *pCtx, const cell_t *params)
152 pCtx->LocalToString(params[1], &str);
154 float val = (float)strtod(str, &dummy);
159 static cell_t StringToFloatEx(IPluginContext *pCtx, const cell_t *params)
161 char *str, *dummy = NULL;
163 pCtx->LocalToString(params[1], &str);
164 pCtx->LocalToPhysAddr(params[2], &addr);
166 float val = (float)strtod(str, &dummy);
168 *addr = sp_ftoc(val);
173 static cell_t sm_floattostr(IPluginContext *pCtx, const cell_t *params)
176 pCtx->LocalToString(params[2], &str);
177 size_t res = UTIL_Format(str, params[3], "%f", sp_ctof(params[1]));
179 return static_cast<cell_t>(res);
182 static cell_t sm_formatex(IPluginContext *pCtx, const cell_t *params)
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);
192 return static_cast<cell_t>(res);
200 StaticCharBuf() : buffer(NULL), max_size(0)
207 char* GetWithSize(size_t len)
211 buffer = (char *)realloc(buffer, len);
218 static char g_formatbuf[2048];
219 static StaticCharBuf g_extrabuf;
220 static cell_t sm_format(IPluginContext *pCtx, const cell_t *params)
222 char *buf, *fmt, *destbuf;
223 cell_t start_addr, end_addr, maxparam;
229 pCtx->LocalToString(params[1], &destbuf);
230 pCtx->LocalToString(params[3], &fmt);
232 maxlen = static_cast<size_t>(params[2]);
233 start_addr = params[1];
234 end_addr = params[1] + maxlen;
235 maxparam = params[0];
237 for (cell_t i=3; i<=maxparam; i++)
239 if ((params[i] >= start_addr) && (params[i] <= end_addr))
248 if (maxlen > sizeof(g_formatbuf))
250 __copy_buf = g_extrabuf.GetWithSize(maxlen);
254 __copy_buf = g_formatbuf;
258 buf = (copy) ? __copy_buf : destbuf;
259 res = atcprintf(buf, maxlen, fmt, pCtx, params, &arg);
263 memcpy(destbuf, __copy_buf, res+1);
266 return static_cast<cell_t>(res);
269 static cell_t sm_vformat(IPluginContext *pContext, const cell_t *params)
271 int vargPos = static_cast<int>(params[4]);
273 /* Get the parent parameter array */
274 cell_t *local_params = pContext->GetLocalParams();
276 cell_t max = local_params[0];
277 if (vargPos > (int)max + 1)
279 return pContext->ThrowNativeError("Argument index is invalid: %d", vargPos);
282 cell_t addr_start = params[1];
283 cell_t addr_end = addr_start + params[2];
285 for (int i=vargPos; i<=max; i++)
287 /* Does this clip bounds? */
288 if ((local_params[i] >= addr_start)
289 && (local_params[i] <= addr_end))
296 /* Get destination info */
297 char *format, *destination;
298 size_t maxlen = static_cast<size_t>(params[2]);
302 destination = g_formatbuf;
304 pContext->LocalToString(params[1], &destination);
307 pContext->LocalToString(params[3], &format);
309 size_t total = atcprintf(destination, maxlen, format, pContext, local_params, &vargPos);
311 /* Perform copy-on-write if we need to */
314 pContext->StringToLocal(params[1], maxlen, g_formatbuf);
320 /* :TODO: make this UTF8 safe */
321 static cell_t BreakString(IPluginContext *pContext, const cell_t *params)
328 pContext->LocalToString(params[1], (char **)&input);
329 pContext->LocalToString(params[2], &out);
332 const char *inptr = input;
333 /* Eat up whitespace */
334 while (*inptr != '\0' && textparsers->IsWhitespace(inptr))
348 const char *start, *end = NULL;
350 bool quoted = (*inptr == '"');
355 /* Read input until we reach a quote. */
356 while (*inptr != '\0' && *inptr != '"')
358 /* Update the end point, increment the stream. */
361 /* Read one more token if we reached an end quote */
368 /* Read input until we reach a space */
369 while (*inptr != '\0' && !textparsers->IsWhitespace(inptr))
371 /* Update the end point, increment the stream. */
376 /* Copy the string we found, if necessary */
386 for (const char *ptr=start;
387 (ptr <= end) && ((unsigned)(outptr - out) < (outMax));
395 /* Consume more of the string until we reach non-whitespace */
396 while (*inptr != '\0' && textparsers->IsWhitespace(inptr))
406 return inptr - input;
409 static cell_t GetCharBytes(IPluginContext *pContext, const cell_t *params)
412 pContext->LocalToString(params[1], &str);
414 return _GetUTF8CharBytes(str);
417 static cell_t IsCharAlpha(IPluginContext *pContext, const cell_t *params)
419 char chr = params[1];
421 if (_GetUTF8CharBytes(&chr) != 1)
429 static cell_t IsCharNumeric(IPluginContext *pContext, const cell_t *params)
431 char chr = params[1];
433 if (_GetUTF8CharBytes(&chr) != 1)
441 static cell_t IsCharSpace(IPluginContext *pContext, const cell_t *params)
443 char chr = params[1];
445 if (_GetUTF8CharBytes(&chr) != 1)
453 static cell_t IsCharMB(IPluginContext *pContext, const cell_t *params)
455 char chr = params[1];
457 unsigned int bytes = _GetUTF8CharBytes(&chr);
466 static cell_t IsCharUpper(IPluginContext *pContext, const cell_t *params)
468 char chr = params[1];
470 if (_GetUTF8CharBytes(&chr) != 1)
478 static cell_t IsCharLower(IPluginContext *pContext, const cell_t *params)
480 char chr = params[1];
482 if (_GetUTF8CharBytes(&chr) != 1)
490 static cell_t ReplaceString(IPluginContext *pContext, const cell_t *params)
492 char *text, *search, *replace;
496 pContext->LocalToString(params[1], &text);
497 pContext->LocalToString(params[3], &search);
498 pContext->LocalToString(params[4], &replace);
499 maxlength = (size_t)params[2];
501 /* Account for old binary plugins that won't pass the last parameter */
504 caseSensitive = (bool)params[5];
508 caseSensitive = true;
511 if (search[0] == '\0')
513 return pContext->ThrowNativeError("Cannot replace searches of empty strings");
516 return UTIL_ReplaceAll(text, maxlength, search, replace, caseSensitive);
519 static cell_t ReplaceStringEx(IPluginContext *pContext, const cell_t *params)
521 char *text, *search, *replace;
525 pContext->LocalToString(params[1], &text);
526 pContext->LocalToString(params[3], &search);
527 pContext->LocalToString(params[4], &replace);
528 maxlength = (size_t)params[2];
530 size_t searchLen = (params[5] == -1) ? strlen(search) : (size_t)params[5];
531 size_t replaceLen = (params[6] == -1) ? strlen(replace) : (size_t)params[6];
533 /* Account for old binary plugins that won't pass the last parameter */
536 caseSensitive = (bool)params[7];
540 caseSensitive = true;
545 return pContext->ThrowNativeError("Cannot replace searches of empty strings");
548 char *ptr = UTIL_ReplaceEx(text, maxlength, search, searchLen, replace, replaceLen, caseSensitive);
558 static cell_t TrimString(IPluginContext *pContext, const cell_t *params)
561 pContext->LocalToString(params[1], &str);
563 size_t chars = strlen(str);
570 char *end = str + chars - 1;
572 /* Iterate backwards through string until we reach first non-whitespace char */
573 while (end >= str && textparsers->IsWhitespace(end))
578 /* Replace first whitespace char (at the end) with null terminator */
581 /* Iterate forwards through string until first non-whitespace char is reached */
582 while (textparsers->IsWhitespace(str))
588 pContext->StringToLocalUTF8(params[1], chars + 1, str, &bytes);
593 static cell_t SplitString(IPluginContext *pContext, const cell_t *params)
597 pContext->LocalToString(params[1], &text);
598 pContext->LocalToString(params[2], &split);
600 size_t maxLen = (size_t)params[4];
601 size_t textLen = strlen(text);
602 size_t splitLen = strlen(split);
604 if (splitLen > textLen)
610 * Note that it's <= ... you could also just add 1,
611 * but this is a bit nicer
613 for (size_t i=0; i<=textLen - splitLen; i++)
615 if (strncmp(&text[i], split, splitLen) == 0)
620 pContext->StringToLocalUTF8(params[3], maxLen, text, NULL);
622 pContext->StringToLocalUTF8(params[3], i+1, text, NULL);
624 return (cell_t)(i + splitLen);
631 static cell_t StripQuotes(IPluginContext *pContext, const cell_t *params)
636 pContext->LocalToString(params[1], &text);
637 length = strlen(text);
639 if (text[0] == '"' && text[length-1] == '"')
642 text[--length] = '\0';
643 /* Move the remaining bytes (including null terminator) down by one */
644 memmove(&text[0], &text[1], length);
652 REGISTER_NATIVES(basicStrings)
654 {"BreakString", BreakString},
655 {"FloatToString", sm_floattostr},
656 {"Format", sm_format},
657 {"FormatEx", sm_formatex},
658 {"GetCharBytes", GetCharBytes},
659 {"IntToString", sm_numtostr},
660 {"IsCharAlpha", IsCharAlpha},
661 {"IsCharLower", IsCharLower},
662 {"IsCharMB", IsCharMB},
663 {"IsCharNumeric", IsCharNumeric},
664 {"IsCharSpace", IsCharSpace},
665 {"IsCharUpper", IsCharUpper},
666 {"ReplaceString", ReplaceString},
667 {"ReplaceStringEx", ReplaceStringEx},
668 {"SplitString", SplitString},
669 {"strlen", sm_strlen},
670 {"StrContains", sm_contain},
671 {"strcmp", sm_strcmp},
672 {"strncmp", sm_strncmp},
673 {"strcopy", sm_strcopy},
674 {"StringToInt", sm_strconvint},
675 {"StringToIntEx", StringToIntEx},
676 {"StringToFloat", sm_strtofloat},
677 {"StringToFloatEx", StringToFloatEx},
678 {"StripQuotes", StripQuotes},
679 {"TrimString", TrimString},
680 {"VFormat", sm_vformat},