plugins/include/string.inc
author David Anderson <dvander@alliedmods.net>
Tue May 22 22:58:51 2007 +0000 (2007-05-22)
changeset 834 d6fac170d744
parent 833 732bedfcbe3e
child 839 4fd0161ef304
permissions -rw-r--r--
added string splitting, exploding, and imploding
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     7  *  This file is part of the SourceMod/SourcePawn SDK.  This file may only be used 
     8  * or modified under the Terms and Conditions of its License Agreement, which is found 
     9  * in LICENSE.txt.  The Terms and Conditions for making SourceMod extensions/plugins 
    10  * may change at any time.  To view the latest information, see:
    11  *   http://www.sourcemod.net/license.php
    12  *
    13  * Version: $Id$
    14  */
    15  
    16 #if defined _string_included
    17  #endinput
    18 #endif
    19 #define _string_included
    20 
    21 /**
    22  * @global Unless otherwise noted, all string functions which take in a 
    23  * writable buffer and maximum length should have the null terminator INCLUDED
    24  * in the length.  This means that this is valid: 
    25  * StrCopy(string, sizeof(string), ...)
    26  */
    27  
    28 /**
    29  * Calculates the length of a string.
    30  *
    31  * @param str			String to check.
    32  * @return				Length of string, in cells (NOT characters).
    33  */
    34 native strlen(const String:str[]);
    35 
    36 /**
    37  * Tests whether a string is found inside another string.
    38  *
    39  * @param str			String to search in.
    40  * @param substr		Substring to find inside the original string.
    41  * @param caseSensitive	If true (default), search is case sensitive.
    42  *						If false, search is case insensitive.
    43  * @return				-1 on failure (no match found). Any other value
    44  *						indicates a position in the string where the match starts.
    45  */
    46 native StrContains(const String:str[], const String:substr[], bool:caseSensitive=true);
    47 
    48 /**
    49  * Compares two strings lexographically.
    50  *
    51  * @param str1			First string (left).
    52  * @param str2			Second string (right).
    53  * @param caseSensitive	If true (default), comparison is case sensitive.
    54  *						If false, comparison is case insensitive.
    55  * @return				-1 if str1 < str2
    56  *						0 if str1 == str2
    57  *						1 if str1 > str2
    58  */
    59 native strcmp(const String:str1[], const String:str2[], bool:caseSensitive=true);
    60 
    61 /**
    62  * Compares two strings parts lexographically.
    63  *
    64  * @param str1			First string (left).
    65  * @param str2			Second string (right).
    66  * @param num			Number of characters to compare.
    67  * @param caseSensitive	If true (default), comparison is case sensitive.
    68  *						If false, comparison is case insensitive.
    69  * @return				-1 if str1 < str2
    70  *						0 if str1 == str2
    71  *						1 if str1 > str2
    72  */
    73 native strncmp(const String:str1[], const String:str2[], num, bool:caseSensitive=true);
    74 
    75 /**
    76  * Backwards compatible stock - StrCompare is now strcmp
    77  * @deprecated		Renamed to strcmp
    78  */
    79 stock StrCompare(const String:str1[], const String:str2[], bool:caseSensitive=true)
    80 {
    81 	return strcmp(str1, str2, caseSensitive);
    82 }
    83 
    84 /**
    85  * Returns whether two strings are equal.
    86  *
    87  * @param str1			First string (left).
    88  * @param str2			Second string (right).
    89  * @param caseSensitive	If true (default), comparison is case sensitive.
    90  * 						If false, comparison is case insensitive.
    91  * @return				True if equal, false otherwise.
    92  */
    93 stock bool:StrEqual(const String:str1[], const String:str2[], bool:caseSensitive=true)
    94 {
    95 	return (StrCompare(str1, str2, caseSensitive) == 0);
    96 }
    97 
    98 /**
    99  * Copies one string to another string.
   100  * @note If the destination buffer is too small to hold the source string, the 
   101  *       destination will be truncated.
   102  *
   103  * @param dest			Destination string buffer to copy to.
   104  * @param destlen		Destination buffer length (includes null terminator).
   105  * @param source		Source string buffer to copy from.
   106  * @return				Number of cells written.
   107  */
   108 native strcopy(String:dest[], destLen, const String:source[]);
   109 
   110 /**
   111  * Backwards compatibility stock - use strcopy
   112  * @deprecated			Renamed to strcopy
   113  */
   114 stock StrCopy(String:dest[], destLen, const String:source[])
   115 {
   116 	return strcopy(dest, destLen, source);
   117 }
   118 
   119 /**
   120  * Formats a string according to the SourceMod format rules (see documentation).
   121  *
   122  * @param buffer		Destination string buffer.
   123  * @param maxlength		Maximum length of output string buffer.
   124  * @param format		Formatting rules.
   125  * @param ...			Variable number of format parameters.
   126  * @return				Number of cells written.
   127  */
   128 native Format(String:buffer[], maxlength, const String:format[], any:...);
   129 
   130 /**
   131  * Formats a string according to the SourceMod format rules (see documentation).
   132  * @note This is the same as Format(), except none of the input buffers can 
   133  *       overlap the same memory as the output buffer.  Since this security 
   134  *       check is removed, it is slightly faster.
   135  *
   136  * @param buffer		Destination string buffer.
   137  * @param maxlength		Maximum length of output string buffer.
   138  * @param format		Formatting rules.
   139  * @param ...			Variable number of format parameters.
   140  * @return				Number of cells written.
   141  */
   142 native FormatEx(String:buffer[], maxlength, const String:format[], any:...);
   143 
   144 /**
   145  * Formats a string according to the SourceMod format rules (see documentation).
   146  * @note This is the same as Format(), except it grabs parameters from a 
   147  *       parent parameter stack, rather than a local.  This is useful for 
   148  *       implementing your own variable argument functions.
   149  *
   150  * @param buffer		Destination string buffer.
   151  * @param maxlength		Maximum length of output string buffer.
   152  * @param format		Formatting rules.
   153  * @param varpos		Argument number which contains the '...' symbol.
   154  *						Note: Arguments start at 1.
   155  * @return 				Number of bytes written.
   156  */
   157 native VFormat(String:buffer[], maxlength, const String:format[], varpos);
   158 
   159 /**
   160  * Converts a string to an integer.
   161  *
   162  * @param str			String to convert.
   163  * @param nBase			Numerical base to use.  10 is default.
   164  * @return				Integer conversion of string, or 0 on failure.
   165  */
   166 native StringToInt(const String:str[], nBase=10);
   167 
   168 /**
   169  * Converts an integer to a string.
   170  *
   171  * @param num			Integer to convert.
   172  * @param str			Buffer to store string in.
   173  * @param maxlength		Maximum length of string buffer.
   174  * @return				Number of cells written to buffer.
   175  */
   176 native IntToString(num, String:str[], maxlength);
   177 
   178 /** 
   179  * Converts a string to a floating point number.
   180  *
   181  * @param str			String to convert to a foat.
   182  * @return				Floating point result, or 0.0 on error.
   183  */
   184 native Float:StringToFloat(const String:str[]);
   185 
   186 /**
   187  * Converts a floating point number to a string.
   188  *
   189  * @param num			Floating point number to convert.
   190  * @param str			Buffer to store string in.
   191  * @param maxlength		Maximum length of string buffer.
   192  * @return				Number of cells written to buffer.
   193  */
   194 native FloatToString(Float:num, String:str[], maxlength);
   195 
   196 /**
   197  * Finds the first "argument" in a string; either a set of space
   198  * terminated characters, or a fully quoted string.  After the 
   199  * argument is found, whitespace is read until the next portion
   200  * of the string is reached.  If nothing remains, -1 is returned.
   201  * Otherwise, the index to the first character is returned.
   202  *
   203  * @param source		Source input string.
   204  * @param arg			Stores argument read from string.
   205  * @param argLen		Maximum length of argument buffer.
   206  * @return				Index to next piece of string, or -1 if none.
   207  */
   208 native BreakString(const String:source[], String:arg[], argLen);
   209 
   210 /**
   211  * Backwards compatibility stock - use BreakString
   212  * @deprecated			Renamed to BreakString.
   213  */
   214 stock StrBreak(const String:source[], String:arg[], argLen)
   215 {
   216 	return BreakString(source, arg, argLen);
   217 }
   218 
   219 /**
   220  * Returns text in a string up until a certain character sequence is reached.
   221  *
   222  * @param source		Source input string.
   223  * @param part			Buffer to store string part.
   224  * @param partLen		Maximum length of the string part buffer.
   225  * @param split			A string which specifies a search point to break at.
   226  * @return				-1 if no match was found; otherwise, an index into source
   227  *						marking the first index after the searched text.  The
   228  *						index is always relative to the start of the input string.
   229  */
   230 native SplitString(const String:source[], const String:split[], String:part[], partLen);
   231 
   232 /**
   233  * Given a string, replaces all occurrences of a search string with a 
   234  * replacement string.
   235  *
   236  * @param text			String to perform search and replacements on.
   237  * @param maxlength		Maximum length of the string buffer.
   238  * @param search		String to search for.
   239  * @param replace		String to replace the search string with.
   240  * @return				Number of replacements that were performed.
   241  */
   242 native ReplaceString(String:text[], maxlength, const String:search[], const String:replace[]);
   243 
   244 /**
   245  * Given a string, replaces the first occurrence of a search string with a 
   246  * replacement string.
   247  *
   248  * @param text			String to perform search and replacements on.
   249  * @param maxlength		Maximum length of the string buffer.
   250  * @param search		String to search for.
   251  * @param replace		String to replace the search string with.
   252  * @param searchLen		If higher than -1, its value will be used instead of
   253  *						a strlen() call on the search parameter.
   254  * @param replaceLen	If higher than -1, its value will be used instead of
   255  *						a strlen() call on the replace parameter.
   256  * @return				Index into the buffer (relative to the start) from where
   257  *						the last replacement ended, or -1 if no replacements were
   258  *						made.
   259  */
   260 native ReplaceStringEx(String:text[], maxlength, const String:search[], const String:replace[], searchLen=-1, replaceLen=-1);
   261 
   262 /** 
   263  * Returns the number of bytes a character is using.  This is
   264  * for multi-byte characters (UTF-8).  For normal ASCII characters,
   265  * this will return 1.
   266  *
   267  * @param source		Source input string.
   268  * @return				Number of bytes the current character uses.
   269  */
   270 native GetCharBytes(const String:source[]);
   271 
   272 /**
   273  * Returns whether a character is an ASCII alphabet character.
   274  *
   275  * @note Multi-byte characters will always return false.
   276  *
   277  * @param char			Character to test.
   278  * @return				True if character is alphabetical, otherwise false.
   279  */
   280 native bool:IsCharAlpha(chr);
   281 
   282 /**
   283  * Returns whether a character is numeric.
   284  *
   285  * @note Multi-byte characters will always return false.
   286  *
   287  * @param char			Character to test.
   288  * @return				True if character is numeric, otherwise false.
   289  */
   290 native bool:IsCharNumeric(chr);
   291 
   292 /**
   293  * Returns whether a character is whitespace.
   294  *
   295  * @note Multi-byte characters will always return false.
   296  *
   297  * @param char			Character to test.
   298  * @return				True if character is whitespace, otherwise false.
   299  */
   300 native bool:IsCharSpace(chr);
   301 
   302 /**
   303  * Returns if a character is multi-byte or not.
   304  *
   305  * @param char			Character to test.
   306  * @return				0 for a normal 7-bit ASCII character,
   307  *						otherwise number of bytes in multi-byte character.
   308  */
   309 native IsCharMB(chr);
   310 
   311 /**
   312  * Returns whether an alphabetic character is uppercase.
   313  *
   314  * @note Multi-byte characters will always return false.
   315  *
   316  * @param char			Character to test.
   317  * @return				True if character is uppercase, otherwise false.
   318  */
   319 native bool:IsCharUpper(chr);
   320 
   321 /**
   322  * Returns whether an alphabetic character is lowercase.
   323  *
   324  * @note Multi-byte characters will always return false.
   325  *
   326  * @param char			Character to test.
   327  * @return				True if character is lowercase, otherwise false.
   328  */
   329 native bool:IsCharLower(chr);
   330 
   331 /**
   332  * Returns an uppercase character to a lowercase character.
   333  *
   334  * @param chr			Characer to convert.
   335  * @return				Lowercase character on success, 
   336  *						no change on failure.
   337  */
   338 stock CharToUpper(chr)
   339 {
   340 	if (IsCharLower(chr))
   341 	{
   342 		return (chr & ~(1<<5));
   343 	}
   344 	return chr;
   345 }
   346 
   347 /**
   348  * Returns a lowercase character to an uppercase character.
   349  *
   350  * @param chr			Characer to convert.
   351  * @return				Uppercase character on success, 
   352  *						no change on failure.
   353  */
   354 stock CharToLower(chr)
   355 {
   356 	if (IsCharUpper(chr))
   357 	{
   358 		return (chr | (1<<5));
   359 	}
   360 	return chr;
   361 }
   362 
   363 /**
   364  * Concatenates one string onto another.
   365  *
   366  * @param buffer		String to append to.
   367  * @param maxlength		Maximum length of entire buffer.
   368  * @param source		Source string to concatenate.
   369  * @return				Number of bytes written.
   370  */
   371 stock StrCat(String:buffer[], maxlength, const String:source[])
   372 {
   373 	new len = strlen(source);
   374 	if (len >= maxlength)
   375 	{
   376 		return 0;
   377 	}
   378 	
   379 	return Format(buffer[len], maxlength-len, "%s", source);
   380 }
   381 
   382 /**
   383  * Removes whitespace characters from the beginning and end of a string.
   384  *
   385  * @param str			The string to trim.
   386  * @return				Number of bytes written (UTF-8 safe).
   387  */
   388 native TrimString(String:str[]);
   389 
   390 /**
   391  * Breaks a string into pieces and stores each piece into an array of buffers.
   392  *
   393  * @param text				The string to split.
   394  * @param split				The string to use as a split delimiter.
   395  * @param buffers			An array of string buffers (2D array).
   396  * @param maxStrings		Number of string buffers (first dimension size).
   397  * @param maxStringLength	Maximum length of each string buffer.
   398  * @return					Number of strings retrieved.
   399  */
   400 stock ExplodeString(const String:text[], const String:split[], String:buffers[][], maxStrings, maxStringLength)
   401 {
   402 	new reloc_idx, idx, total;
   403 	
   404 	if (maxStrings < 1 || split[0] == '\0')
   405 	{
   406 		return 0;
   407 	}
   408 	
   409 	while ((idx = SplitString(text[reloc_idx], split, buffers[total], maxStringLength)) != -1)
   410 	{
   411 		reloc_idx += idx;
   412 		if (text[reloc_idx] == '\0')
   413 		{
   414 			break;
   415 		}
   416 		if (++total >= maxStrings)
   417 		{
   418 			return total;
   419 		}
   420 	}
   421 	
   422 	if (text[reloc_idx] != '\0' && total <= maxStrings - 1)
   423 	{
   424 		strcopy(buffers[total++], maxStringLength, text[reloc_idx]);
   425 	}
   426 	
   427 	return total;
   428 }
   429 
   430 /**
   431  * Joins an array of strings into one string, with a "join" string inserted in
   432  * between each given string.  This function complements ExplodeString.
   433  *
   434  * @param strings		An array of strings.
   435  * @param numStrings	Number of strings in the array.
   436  * @param join			The join string to insert between each string.
   437  * @param buffer		Output buffer to write the joined string to.
   438  * @param maxLength		Maximum length of the output buffer.
   439  * @return				Number of bytes written to the output buffer.
   440  */
   441 stock ImplodeStrings(const String:strings[][], numStrings, const String:join[], String:buffer[], maxLength)
   442 {
   443 	new total, length, part_length;
   444 	new join_length = strlen(join);
   445 	for (new i=0; i<numStrings; i++)
   446 	{
   447 		length = strcopy(buffer[total], maxLength-total, strings[i]);
   448 		total += length;
   449 		if (length < part_length)
   450 		{
   451 			break;
   452 		}
   453 		if (i != numStrings - 1)
   454 		{
   455 			length = strcopy(buffer[total], maxLength-total, join);
   456 			total += length;
   457 			if (length < join_length)
   458 			{
   459 				break;
   460 			}
   461 		}
   462 	}
   463 	return total;
   464 }