fixed a bug where UTIL_ReplaceAll() did not work on a buffer size of 1 even if the other inputs were valid
3 * =============================================================================
5 * Copyright (C) 2004-2007 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>.
35 #include "sm_stringutil.h"
37 #include "PluginSys.h"
38 #include "Translator.h"
39 #include "PlayerManager.h"
41 #define LADJUST 0x00000004 /* left adjustment */
42 #define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */
43 #define UPPERDIGITS 0x00000200 /* make alpha digits uppercase */
44 #define to_digit(c) ((c) - '0')
45 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
47 #define CHECK_ARGS(x) \
48 if ((arg+x) > args) { \
49 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "String formatted incorrectly - parameter %d (total %d)", arg, args); \
53 size_t CorePlayerTranslate(int client, char *buffer, size_t maxlength, const char *phrase, void **params)
58 err = g_pCorePhrases->GetTranslation(phrase, g_Translator.GetClientLanguage(client), &pTrans);
59 if (err != Trans_Okay)
61 err = g_pCorePhrases->GetTranslation(phrase, g_Translator.GetServerLanguage(), &pTrans);
62 if (err != Trans_Okay && g_Translator.GetServerLanguage() != CORELANG_ENGLISH)
64 err = g_pCorePhrases->GetTranslation(phrase, CORELANG_ENGLISH, &pTrans);
68 if (err != Trans_Okay)
70 return UTIL_Format(buffer, maxlength, "%s", phrase);
73 return g_Translator.Translate(buffer, maxlength, params, &pTrans);
76 inline bool TryTranslation(CPlugin *pl, const char *key, unsigned int langid, unsigned int langcount, Translation *pTrans)
78 TransError err = Trans_BadLanguage;
81 for (size_t i=0; i<langcount && err!=Trans_Okay; i++)
83 phrfl = g_Translator.GetFileByIndex(pl->GetLangFileByIndex(i));
84 err = phrfl->GetTranslation(key, langid, pTrans);
87 return (err == Trans_Okay) ? true : false;
90 size_t Translate(char *buffer, size_t maxlen, IPluginContext *pCtx, const char *key, cell_t target, const cell_t *params, int *arg, bool *error)
95 CPlugin *pl = (CPlugin *)g_PluginSys.FindPluginByContext(pCtx->GetContext());
96 size_t langcount = pl->GetLangFileCount();
97 void *new_params[MAX_TRANSLATE_PARAMS];
98 unsigned int max_params = 0;
101 if (target == LANG_SERVER)
103 langid = g_Translator.GetServerLanguage();
104 } else if ((target >= 1) && (target <= g_Players.GetMaxClients())) {
105 langid = g_Translator.GetClientLanguage(target);
107 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Translation failed: invalid client index %d", target);
111 if (!TryTranslation(pl, key, langid, langcount, &pTrans))
113 if (target != LANG_SERVER && langid != g_Translator.GetServerLanguage())
115 target = LANG_SERVER;
117 } else if (langid != LANGUAGE_ENGLISH) {
118 if (!TryTranslation(pl, key, LANGUAGE_ENGLISH, langcount, &pTrans))
120 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
124 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
129 max_params = pTrans.fmt_count;
133 /* Check if we're going to over the limit */
134 if ((*arg) + (max_params - 1) > (size_t)params[0])
136 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAMS_MAX,
137 "Translation string formatted incorrectly - missing at least %d parameters",
138 ((*arg + (max_params - 1)) - params[0])
143 /* Translate the parameters to raw pointers */
144 for (size_t i=0; i<max_params; i++)
146 pCtx->LocalToPhysAddr(params[*arg], reinterpret_cast<cell_t **>(&new_params[i]));
151 return g_Translator.Translate(buffer, maxlen, new_params, &pTrans);
157 //:TODO: review this code before we choose a license
159 void AddString(char **buf_p, size_t &maxlen, const char *string, int width, int prec)
163 static char nlstr[] = {'(','n','u','l','l',')','\0'};
175 for (size = 0; size < prec; size++)
177 if (string[size] == '\0')
183 while (string[size++]);
187 if (size > (int)maxlen)
200 while ((width-- > 0) && maxlen)
209 void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec)
224 // write the float number
229 text[digits++] = '0' + val % 10;
235 text[digits++] = '-';
240 while ((digits < width) && maxlen)
247 while ((digits--) && maxlen)
249 *buf++ = text[digits];
259 // write the fraction
261 while (digits < prec)
266 text[digits++] = '0' + val % 10;
269 if ((digits > 0) && maxlen)
274 for (prec = 0; maxlen && (prec < digits); prec++)
283 void AddUInt(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
292 text[digits++] = '0' + val % 10;
298 if (!(flags & LADJUST))
300 while (digits < width && maxlen)
302 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
308 while (digits-- && maxlen)
310 *buf++ = text[digits];
317 while (width-- && maxlen)
319 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
327 void AddInt(char **buf_p, size_t &maxlen, int val, int width, int flags)
333 unsigned int unsignedVal;
339 /* we want the unsigned version */
340 unsignedVal = abs(val);
346 text[digits++] = '0' + unsignedVal % 10;
348 } while (unsignedVal);
352 text[digits++] = '-';
357 if (!(flags & LADJUST))
359 while ((digits < width) && maxlen)
361 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
367 while (digits-- && maxlen)
369 *buf++ = text[digits];
376 while (width-- && maxlen)
378 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
386 void AddHex(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
394 if (flags & UPPERDIGITS)
396 hexadjust = 'A' - '9' - 1;
398 hexadjust = 'a' - '9' - 1;
404 digit = ('0' + val % 16);
410 text[digits++] = digit;
416 if (!(flags & LADJUST))
418 while (digits < width && maxlen)
420 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
426 while (digits-- && maxlen)
428 *buf++ = text[digits];
435 while (width-- && maxlen)
437 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
445 size_t gnprintf(char *buffer, size_t maxlen, const char *format, void **args)
447 if (!buffer || !maxlen)
461 size_t llen = maxlen - 1;
468 // run through the format string until we hit a '%' or '\0'
469 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
474 if ((ch == '\0') || (llen <= 0))
482 // reset formatting state
501 while(is_digit((ch = *fmt++)))
503 n = 10 * n + (ch - '0');
505 prec = (n < 0) ? -1 : n;
526 n = 10 * n + (ch - '0');
528 } while(is_digit(ch));
538 char *c = (char *)args[arg];
547 int *value = (int *)args[arg];
548 AddInt(&buf_p, llen, *value, width, flags);
554 unsigned int *value = (unsigned int *)args[arg];
555 AddUInt(&buf_p, llen, *value, width, flags);
561 float *value = (float *)args[arg];
562 AddFloat(&buf_p, llen, *value, width, prec);
568 const char *str = (const char *)args[arg];
569 AddString(&buf_p, llen, str, width, prec);
575 unsigned int *value = (unsigned int *)args[arg];
576 flags |= UPPERDIGITS;
577 AddHex(&buf_p, llen, *value, width, flags);
583 unsigned int *value = (unsigned int *)args[arg];
584 AddHex(&buf_p, llen, *value, width, flags);
624 return (maxlen - llen - 1);
627 size_t atcprintf(char *buffer, size_t maxlen, const char *format, IPluginContext *pCtx, const cell_t *params, int *param)
629 if (!buffer || !maxlen)
635 int args = params[0];
644 size_t llen = maxlen - 1;
652 // run through the format string until we hit a '%' or '\0'
653 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
658 if ((ch == '\0') || (llen <= 0))
666 // reset formatting state
685 while(is_digit((ch = *fmt++)))
687 n = 10 * n + (ch - '0');
689 prec = (n < 0) ? -1 : n;
710 n = 10 * n + (ch - '0');
712 } while(is_digit(ch));
724 pCtx->LocalToString(params[arg], &c);
735 pCtx->LocalToPhysAddr(params[arg], &value);
736 AddInt(&buf_p, llen, static_cast<int>(*value), width, flags);
744 pCtx->LocalToPhysAddr(params[arg], &value);
745 AddUInt(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
753 pCtx->LocalToPhysAddr(params[arg], &value);
754 AddFloat(&buf_p, llen, sp_ctof(*value), width, prec);
762 pCtx->LocalToPhysAddr(params[arg], &value);
766 CPlayer *player = g_Players.GetPlayerByIndex(*value);
767 if (!player || !player->IsConnected())
769 return pCtx->ThrowNativeError("Client index %d is invalid", *value);
771 const char *auth = player->GetAuthString();
772 if (!auth || auth[0] == '\0')
774 auth = "STEAM_ID_PENDING";
776 int userid = engine->GetPlayerUserId(player->GetEdict());
786 "Console<0><Console><Console>");
788 AddString(&buf_p, llen, buffer, width, prec);
796 pCtx->LocalToPhysAddr(params[arg], &value);
798 const char *name = "Console";
801 CPlayer *player = g_Players.GetPlayerByIndex(*value);
802 if (!player || !player->IsConnected())
804 return pCtx->ThrowNativeError("Client index %d is invalid", *value);
806 name = player->GetName();
808 AddString(&buf_p, llen, name, width, prec);
817 if ((err=pCtx->LocalToString(params[arg], &str)) != SP_ERROR_NONE)
819 pCtx->ThrowNativeErrorEx(err, "Could not deference string");
822 AddString(&buf_p, llen, str, width, prec);
833 pCtx->LocalToString(params[arg++], &key);
834 pCtx->LocalToPhysAddr(params[arg++], &target);
835 res = Translate(buf_p, llen, pCtx, key, *target, params, &arg, &error);
850 cell_t target = g_SourceMod.GetGlobalTarget();
851 pCtx->LocalToString(params[arg++], &key);
852 res = Translate(buf_p, llen, pCtx, key, target, params, &arg, &error);
865 pCtx->LocalToPhysAddr(params[arg], &value);
866 flags |= UPPERDIGITS;
867 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
875 pCtx->LocalToPhysAddr(params[arg], &value);
876 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
916 return (maxlen - llen - 1);
919 const char *stristr(const char *str, const char *substr)
923 return ((char *)str);
926 char *needle = (char *)substr;
927 char *prevloc = (char *)str;
928 char *haystack = (char *)str;
932 if (tolower(*haystack) == tolower(*needle))
940 haystack = ++prevloc;
941 needle = (char *)substr;
948 unsigned int strncopy(char *dest, const char *src, size_t count)
956 while ((*src) && (--count))
962 return (dest - start);
965 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
969 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
972 if (len >= maxlength)
974 buffer[maxlength - 1] = '\0';
975 return (maxlength - 1);
981 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list ap)
983 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
985 if (len >= maxlength)
987 buffer[maxlength - 1] = '\0';
988 return (maxlength - 1);
994 char *sm_strdup(const char *str)
996 char *ptr = new char[strlen(str)+1];
1001 unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search, const char *replace)
1003 size_t searchLen = strlen(search);
1004 size_t replaceLen = strlen(replace);
1006 char *ptr = subject;
1007 unsigned int total = 0;
1008 while ((ptr = UTIL_ReplaceEx(ptr, maxlength, search, searchLen, replace, replaceLen)) != NULL)
1021 * NOTE: Do not edit this for the love of god unless you have
1022 * read the test cases and understand the code behind each one.
1023 * While I don't guarantee there aren't mistakes, I do guarantee
1024 * that plugins will end up relying on tiny idiosyncracies of this
1025 * function, just like they did with AMX Mod X.
1027 * There are explicitly more cases than the AMX Mod X version because
1028 * we're not doing a blind copy. Each case is specifically optimized
1029 * for what needs to be done. Even better, we don't have to error on
1030 * bad buffer sizes. Instead, this function will smartly cut off the
1031 * string in a way that pushes old data out.
1033 char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen)
1035 char *ptr = subject;
1037 size_t textLen = strlen(subject);
1039 /* It's not possible to search or replace */
1040 if (searchLen > textLen)
1045 /* Handle the case of one byte replacement.
1046 * It's only valid in one case.
1050 /* If the search matches and the replace length is 0,
1051 * we can just terminate the string and be done.
1053 if (strcmp(subject, search) == 0 && replaceLen == 0)
1064 /* Subtract one off the maxlength so we can include the null terminator */
1067 while (*ptr != '\0' && (browsed <= textLen - searchLen))
1069 /* See if we get a comparison */
1070 if (strncmp(ptr, search, searchLen) == 0)
1072 if (replaceLen > searchLen)
1074 /* First, see if we have enough space to do this operation */
1075 if (maxLen - textLen < replaceLen - searchLen)
1077 /* First, see if the replacement length goes out of bounds. */
1078 if (browsed + replaceLen >= maxLen)
1084 * Replace: DDDDDDDDDD
1085 * OUTPUT : AADDDDDDDDD
1088 /* If it does, we'll just bound the length and do a strcpy. */
1089 replaceLen = maxLen - browsed;
1090 /* Note, we add one to the final result for the null terminator */
1091 strncopy(ptr, replace, replaceLen+1);
1098 * OUTPUT : AADDDDDDDCC
1101 /* We're going to have some bytes left over... */
1102 size_t origBytesToCopy = (textLen - (browsed + searchLen)) + 1;
1103 size_t realBytesToCopy = (maxLen - (browsed + replaceLen)) + 1;
1104 char *moveFrom = ptr + searchLen + (origBytesToCopy - realBytesToCopy);
1105 char *moveTo = ptr + replaceLen;
1107 /* First, move our old data out of the way. */
1108 memmove(moveTo, moveFrom, realBytesToCopy);
1110 /* Now, do our replacement. */
1111 memcpy(ptr, replace, replaceLen);
1119 * OUTPUT : AADDDDCCC
1122 /* Yes, we have enough space. Do a normal move operation. */
1123 char *moveFrom = ptr + searchLen;
1124 char *moveTo = ptr + replaceLen;
1126 /* First move our old data out of the way. */
1127 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1128 memmove(moveTo, moveFrom, bytesToCopy);
1130 /* Now do our replacement. */
1131 memcpy(ptr, replace, replaceLen);
1133 } else if (replaceLen < searchLen) {
1142 /* If the replacement does not grow the string length, we do not
1143 * need to do any fancy checking at all. Yay!
1145 char *moveFrom = ptr + searchLen; /* Start after the search pointer */
1146 char *moveTo = ptr + replaceLen; /* Copy to where the replacement ends */
1148 /* Copy our replacement in, if any */
1151 memcpy(ptr, replace, replaceLen);
1154 /* Figure out how many bytes to move down, including null terminator */
1155 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1157 /* Move the rest of the string down */
1158 memmove(moveTo, moveFrom, bytesToCopy);
1168 /* We don't have to move anything around, just do a straight copy */
1169 memcpy(ptr, replace, replaceLen);
1172 return ptr + replaceLen;