3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
18 #include "sm_stringutil.h"
20 #include "PluginSys.h"
21 #include "Translator.h"
22 #include "PlayerManager.h"
24 #define LADJUST 0x00000004 /* left adjustment */
25 #define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */
26 #define UPPERDIGITS 0x00000200 /* make alpha digits uppercase */
27 #define to_digit(c) ((c) - '0')
28 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
30 #define CHECK_ARGS(x) \
31 if ((arg+x) > args) { \
32 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "String formatted incorrectly - parameter %d (total %d)", arg, args); \
36 size_t CorePlayerTranslate(int client, char *buffer, size_t maxlength, const char *phrase, void **params)
41 err = g_pCorePhrases->GetTranslation(phrase, g_Translator.GetServerLanguage(), &pTrans);
42 if (err != Trans_Okay && g_Translator.GetServerLanguage() != CORELANG_ENGLISH)
44 err = g_pCorePhrases->GetTranslation(phrase, CORELANG_ENGLISH, &pTrans);
47 if (err != Trans_Okay)
49 return UTIL_Format(buffer, maxlength, "%s", phrase);
52 return g_Translator.Translate(buffer, maxlength, params, &pTrans);
55 inline bool TryTranslation(CPlugin *pl, const char *key, unsigned int langid, unsigned int langcount, Translation *pTrans)
57 TransError err = Trans_BadLanguage;
60 for (size_t i=0; i<langcount && err!=Trans_Okay; i++)
62 phrfl = g_Translator.GetFileByIndex(pl->GetLangFileByIndex(i));
63 err = phrfl->GetTranslation(key, langid, pTrans);
66 return (err == Trans_Okay) ? true : false;
69 size_t Translate(char *buffer, size_t maxlen, IPluginContext *pCtx, const char *key, cell_t target, const cell_t *params, int *arg, bool *error)
74 CPlugin *pl = (CPlugin *)g_PluginSys.FindPluginByContext(pCtx->GetContext());
75 size_t langcount = pl->GetLangFileCount();
76 void *new_params[MAX_TRANSLATE_PARAMS];
77 unsigned int max_params = 0;
80 if (target == LANG_SERVER)
82 langid = g_Translator.GetServerLanguage();
83 } else if ((target >= 1) && (target <= g_Players.GetMaxClients())) {
84 langid = g_Translator.GetServerLanguage();
86 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Translation failed: invalid client index %d", target);
90 if (!TryTranslation(pl, key, langid, langcount, &pTrans))
92 if (target != LANG_SERVER)
96 } else if (langid != LANGUAGE_ENGLISH) {
97 if (!TryTranslation(pl, key, LANGUAGE_ENGLISH, langcount, &pTrans))
99 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key);
105 max_params = pTrans.fmt_count;
107 for (size_t i=0; i<max_params; i++)
109 pCtx->LocalToPhysAddr(params[*arg], reinterpret_cast<cell_t **>(&new_params[i]));
111 if ((*arg) + i > (size_t)params[0])
113 pCtx->ThrowNativeErrorEx(SP_ERROR_PARAMS_MAX, "Translation string formatted incorrectly - parameter %d (total %d)", (*arg) + i, params[0]);
118 return g_Translator.Translate(buffer, maxlen, new_params, &pTrans);
124 //:TODO: review this code before we choose a license
126 void AddString(char **buf_p, size_t &maxlen, const char *string, int width, int prec)
130 static char nlstr[] = {'(','n','u','l','l',')','\0'};
142 for (size = 0; size < prec; size++)
144 if (string[size] == '\0')
150 while (string[size++]);
154 if (size > (int)maxlen)
167 while ((width-- > 0) && maxlen)
176 void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec)
191 // write the float number
196 text[digits++] = '0' + val % 10;
202 text[digits++] = '-';
207 while ((digits < width) && maxlen)
214 while ((digits--) && maxlen)
216 *buf++ = text[digits];
226 // write the fraction
228 while (digits < prec)
233 text[digits++] = '0' + val % 10;
236 if ((digits > 0) && maxlen)
241 for (prec = 0; maxlen && (prec < digits); prec++)
250 void AddUInt(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
259 text[digits++] = '0' + val % 10;
265 if (!(flags & LADJUST))
267 while (digits < width && maxlen)
269 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
275 while (digits-- && maxlen)
277 *buf++ = text[digits];
284 while (width-- && maxlen)
286 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
294 void AddInt(char **buf_p, size_t &maxlen, int val, int width, int flags)
300 unsigned int unsignedVal;
306 /* we want the unsigned version */
307 unsignedVal = abs(val);
313 text[digits++] = '0' + unsignedVal % 10;
315 } while (unsignedVal);
319 text[digits++] = '-';
324 if (!(flags & LADJUST))
326 while ((digits < width) && maxlen)
328 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
334 while (digits-- && maxlen)
336 *buf++ = text[digits];
343 while (width-- && maxlen)
345 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
353 void AddHex(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags)
361 if (flags & UPPERDIGITS)
363 hexadjust = 'A' - '9' - 1;
365 hexadjust = 'a' - '9' - 1;
371 digit = ('0' + val % 16);
377 text[digits++] = digit;
383 if (!(flags & LADJUST))
385 while (digits < width && maxlen)
387 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
393 while (digits-- && maxlen)
395 *buf++ = text[digits];
402 while (width-- && maxlen)
404 *buf++ = (flags & ZEROPAD) ? '0' : ' ';
412 size_t gnprintf(char *buffer, size_t maxlen, const char *format, void **args)
414 if (!buffer || !maxlen)
428 size_t llen = maxlen - 1;
435 // run through the format string until we hit a '%' or '\0'
436 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
441 if ((ch == '\0') || (llen <= 0))
449 // reset formatting state
468 while(is_digit((ch = *fmt++)))
470 n = 10 * n + (ch - '0');
472 prec = (n < 0) ? -1 : n;
493 n = 10 * n + (ch - '0');
495 } while(is_digit(ch));
505 char *c = (char *)args[arg];
514 int *value = (int *)args[arg];
515 AddInt(&buf_p, llen, *value, width, flags);
521 unsigned int *value = (unsigned int *)args[arg];
522 AddUInt(&buf_p, llen, *value, width, flags);
528 float *value = (float *)args[arg];
529 AddFloat(&buf_p, llen, *value, width, prec);
535 const char *str = (const char *)args[arg];
536 AddString(&buf_p, llen, str, width, prec);
542 unsigned int *value = (unsigned int *)args[arg];
543 flags |= UPPERDIGITS;
544 AddHex(&buf_p, llen, *value, width, flags);
550 unsigned int *value = (unsigned int *)args[arg];
551 AddHex(&buf_p, llen, *value, width, flags);
591 return (maxlen - llen - 1);
594 size_t atcprintf(char *buffer, size_t maxlen, const char *format, IPluginContext *pCtx, const cell_t *params, int *param)
596 if (!buffer || !maxlen)
602 int args = params[0];
611 size_t llen = maxlen - 1;
619 // run through the format string until we hit a '%' or '\0'
620 for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++)
625 if ((ch == '\0') || (llen <= 0))
633 // reset formatting state
652 while(is_digit((ch = *fmt++)))
654 n = 10 * n + (ch - '0');
656 prec = (n < 0) ? -1 : n;
677 n = 10 * n + (ch - '0');
679 } while(is_digit(ch));
691 pCtx->LocalToString(params[arg], &c);
702 pCtx->LocalToPhysAddr(params[arg], &value);
703 AddInt(&buf_p, llen, static_cast<int>(*value), width, flags);
711 pCtx->LocalToPhysAddr(params[arg], &value);
712 AddUInt(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
720 pCtx->LocalToPhysAddr(params[arg], &value);
721 AddFloat(&buf_p, llen, sp_ctof(*value), width, prec);
730 if ((err=pCtx->LocalToString(params[arg], &str)) != SP_ERROR_NONE)
732 pCtx->ThrowNativeErrorEx(err, "Could not deference string");
735 AddString(&buf_p, llen, str, width, prec);
746 pCtx->LocalToPhysAddr(params[arg++], &target);
747 pCtx->LocalToString(params[arg++], &key);
748 res = Translate(buf_p, llen, pCtx, key, *target, params, &arg, &error);
763 cell_t target = g_SourceMod.GetGlobalTarget();
764 pCtx->LocalToString(params[arg++], &key);
765 res = Translate(buf_p, llen, pCtx, key, target, params, &arg, &error);
778 pCtx->LocalToPhysAddr(params[arg], &value);
779 flags |= UPPERDIGITS;
780 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
788 pCtx->LocalToPhysAddr(params[arg], &value);
789 AddHex(&buf_p, llen, static_cast<unsigned int>(*value), width, flags);
829 return (maxlen - llen - 1);
832 const char *stristr(const char *str, const char *substr)
836 return ((char *)str);
839 char *needle = (char *)substr;
840 char *prevloc = (char *)str;
841 char *haystack = (char *)str;
845 if (tolower(*haystack) == tolower(*needle))
853 haystack = ++prevloc;
854 needle = (char *)substr;
861 unsigned int strncopy(char *dest, const char *src, size_t count)
869 while ((*src) && (--count))
875 return (dest - start);
878 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
882 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
885 if (len >= maxlength)
887 buffer[maxlength - 1] = '\0';
888 return (maxlength - 1);
894 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list ap)
896 size_t len = vsnprintf(buffer, maxlength, fmt, ap);
898 if (len >= maxlength)
900 buffer[maxlength - 1] = '\0';
901 return (maxlength - 1);
907 char *sm_strdup(const char *str)
909 char *ptr = new char[strlen(str)+1];
914 unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search, const char *replace)
916 size_t searchLen = strlen(search);
917 size_t replaceLen = strlen(replace);
920 unsigned int total = 0;
921 while ((ptr = UTIL_ReplaceEx(ptr, maxlength, search, searchLen, replace, replaceLen)) != NULL)
934 * NOTE: Do not edit this for the love of god unless you have
935 * read the test cases and understand the code behind each one.
936 * While I don't guarantee there aren't mistakes, I do guarantee
937 * that plugins will end up relying on tiny idiosyncracies of this
938 * function, just like they did with AMX Mod X.
940 * There are explicitly more cases than the AMX Mod X version because
941 * we're not doing a blind copy. Each case is specifically optimized
942 * for what needs to be done. Even better, we don't have to error on
943 * bad buffer sizes. Instead, this function will smartly cut off the
944 * string in a way that pushes old data out.
946 char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen)
950 size_t textLen = strlen(subject);
952 /* It's not possible to search or replace */
953 if (searchLen > textLen || maxLen <= 1)
958 /* Subtract one off the maxlength so we can include the null terminator */
961 while (*ptr != '\0' && (browsed <= textLen - searchLen))
963 /* See if we get a comparison */
964 if (strncmp(ptr, search, searchLen) == 0)
967 if (replaceLen > searchLen)
969 /* First, see if we have enough space to do this operation */
970 if (maxLen - textLen < replaceLen - searchLen)
972 /* First, see if the replacement length goes out of bounds. */
973 if (browsed + replaceLen >= maxLen)
979 * Replace: DDDDDDDDDD
980 * OUTPUT : AADDDDDDDDD
983 /* If it does, we'll just bound the length and do a strcpy. */
984 replaceLen = maxLen - browsed;
985 /* Note, we add one to the final result for the null terminator */
986 strncopy(ptr, replace, replaceLen+1);
993 * OUTPUT : AADDDDDDDCC
996 /* We're going to have some bytes left over... */
997 size_t origBytesToCopy = (textLen - (browsed + searchLen)) + 1;
998 size_t realBytesToCopy = (maxLen - (browsed + replaceLen)) + 1;
999 char *moveFrom = ptr + searchLen + (origBytesToCopy - realBytesToCopy);
1000 char *moveTo = ptr + replaceLen;
1002 /* First, move our old data out of the way. */
1003 memmove(moveTo, moveFrom, realBytesToCopy);
1005 /* Now, do our replacement. */
1006 memcpy(ptr, replace, replaceLen);
1014 * OUTPUT : AADDDDCCC
1017 /* Yes, we have enough space. Do a normal move operation. */
1018 char *moveFrom = ptr + searchLen;
1019 char *moveTo = ptr + replaceLen;
1021 /* First move our old data out of the way. */
1022 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1023 memmove(moveTo, moveFrom, bytesToCopy);
1025 /* Now do our replacement. */
1026 memcpy(ptr, replace, replaceLen);
1028 } else if (replaceLen < searchLen) {
1037 /* If the replacement does not grow the string length, we do not
1038 * need to do any fancy checking at all. Yay!
1040 char *moveFrom = ptr + searchLen; /* Start after the search pointer */
1041 char *moveTo = ptr + replaceLen; /* Copy to where the replacement ends */
1043 /* Copy our replacement in, if any */
1046 memcpy(ptr, replace, replaceLen);
1049 /* Figure out how many bytes to move down, including null terminator */
1050 size_t bytesToCopy = (textLen - (browsed + searchLen)) + 1;
1052 /* Move the rest of the string down */
1053 memmove(moveTo, moveFrom, bytesToCopy);
1063 /* We don't have to move anything around, just do a straight copy */
1064 memcpy(ptr, replace, replaceLen);
1067 return ptr + replaceLen;