core-legacy/util.cpp
author David Anderson <dvander@alliedmods.net>
Fri Nov 14 05:02:00 2008 -0600 (2008-11-14)
changeset 545 07e5df11f9fc
parent 541 core-1.4/util.cpp@35a8cda28485
child 580 783e91c5f445
permissions -rw-r--r--
Renamed core-1.4 to core-legacy.
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2008 Metamod:Source Development Team
     3  * No warranties of any kind
     4  *
     5  * License: zlib/libpng
     6  *
     7  * Author(s): David "BAILOPAN" Anderson
     8  * ============================
     9  */
    10 
    11 #include <ctype.h>
    12 #include <string.h>
    13 #include <stdio.h>
    14 #include "util.h"
    15 #include "oslink.h"
    16 
    17 /**
    18  * @brief Utility functions
    19  * @file util.cpp
    20  */
    21 
    22 const char *UTIL_GetExtension(const char *file)
    23 {
    24 	int len = strlen(file);
    25 	int i = 0;
    26 
    27 	for (i = len - 1; i >= 0; i--)
    28 	{
    29 		if (file[i] == '/' || file[i] == '\\')
    30 		{
    31 			return NULL;
    32 		}
    33 
    34 		if ((file[i] == '.') && (i != len - 1))
    35 		{
    36 			return (const char *)&(file[i + 1]);
    37 		}
    38 	}
    39 
    40 	return NULL;
    41 }
    42 
    43 void UTIL_TrimLeft(char *buffer)
    44 {
    45 	/* Let's think of this as our iterator */
    46 	char *i = buffer;
    47 
    48 	/* Make sure the buffer isn't null */
    49 	if (i && *i)
    50 	{
    51 		/* Add up number of whitespace characters */
    52 		while(isspace((unsigned char) *i))
    53 		{
    54 			i++;
    55 		}
    56 
    57 		/* If whitespace chars in buffer then adjust string so first non-whitespace char is at start of buffer */
    58 		if (i != buffer)
    59 		{
    60 			memmove(buffer, i, (strlen(i) + 1) * sizeof(char));
    61 		}
    62 	}
    63 }
    64 
    65 void UTIL_TrimRight(char *buffer)
    66 {
    67 	/* Make sure buffer isn't null */
    68 	if (buffer)
    69 	{
    70 		size_t len = strlen(buffer);
    71 
    72 		/* Loop through buffer backwards while replacing whitespace chars with null chars */
    73 		for (size_t i = len - 1; i >= 0; i--)
    74 		{
    75 			if (isspace((unsigned char) buffer[i]))
    76 			{
    77 				buffer[i] = '\0';
    78 			} else {
    79 				break;
    80 			}
    81 		}
    82 	}
    83 }
    84 
    85 /* :TODO: this should skip string literals */
    86 void UTIL_TrimComments(char *buffer)
    87 {
    88 	int num_sc = 0;
    89 	size_t len = strlen(buffer);
    90 	if (buffer)
    91 	{
    92 		for (int i = len - 1; i >= 0; i--)
    93 		{
    94 			if (buffer[i] == '/')
    95 			{
    96 				if (++num_sc >= 2 && i==0)
    97 				{
    98 					buffer[i] = '\0';
    99 					return;
   100 				}
   101 			} else {
   102 				if (num_sc >= 2)
   103 				{
   104 					buffer[i] = '\0';
   105 					return;
   106 				}
   107 				num_sc = 0;
   108 			}
   109 			/* size_t won't go below 0, manually break out */
   110 			if (i == 0)
   111 			{
   112 				break;
   113 			}
   114 		}
   115 	}
   116 }
   117 
   118 void UTIL_KeySplit(const char *str, char *buf1, size_t len1, char *buf2, size_t len2)
   119 {
   120 	size_t start;
   121 	size_t len = strlen(str);
   122 
   123 	for (start = 0; start < len; start++)
   124 	{
   125 		if (!isspace(str[start]))
   126 		{
   127 			break;
   128 		}
   129 	}
   130 
   131 	size_t end;
   132 	for (end = start; end < len; end++)
   133 	{
   134 		if (isspace(str[end]))
   135 		{
   136 			break;
   137 		}
   138 	}
   139 	
   140 	size_t i, c = 0;
   141 	for (i = start; i < end; i++, c++)
   142 	{
   143 		if (c >= len1)
   144 		{
   145 			break;
   146 		}
   147 		buf1[c] = str[i];
   148 	}
   149 	buf1[c] = '\0';
   150 
   151 	for (start = end; start < len; start++)
   152 	{
   153 		if (!isspace(str[start]))
   154 		{
   155 			break;
   156 		}
   157 	}
   158 
   159 	for (c = 0; start < len; start++, c++)
   160 	{
   161 		if (c >= len2)
   162 		{
   163 			break;
   164 		}
   165 		buf2[c] = str[start];
   166 	}
   167 	buf2[c] = '\0';
   168 }
   169 
   170 bool UTIL_PathCmp(const char *path1, const char *path2)
   171 {
   172 	size_t pos1 = 0, pos2 = 0;
   173 
   174 	while (true)
   175 	{
   176 		if (path1[pos1] == '\0' || path2[pos2] == '\0')
   177 		{
   178 			return (path1[pos1] == path2[pos2]);
   179 		}
   180 
   181 		if (path1[pos1] == PATH_SEP_CHAR)
   182 		{
   183 			if (path2[pos2] != PATH_SEP_CHAR)
   184 			{
   185 				return false;
   186 			}
   187 
   188 			/* Look for extra path chars */
   189 			while (path1[++pos1])
   190 			{
   191 				if (path1[pos1] != PATH_SEP_CHAR)
   192 				{
   193 					break;
   194 				}
   195 			}
   196 			while (path2[++pos2])
   197 			{
   198 				if (path2[pos2] != PATH_SEP_CHAR)
   199 				{
   200 					break;
   201 				}
   202 			}
   203 			continue;
   204 		}
   205 
   206 		/* If we're at a different non-alphanumeric, the next character MUST match */
   207 		if (!isalpha(path1[pos1]) && (path1[pos1] != path2[pos2]))
   208 		{
   209 			return false;
   210 		}
   211 
   212 	#ifdef WIN32
   213 		if (toupper(path1[pos1]) != toupper(path2[pos2]))
   214 	#else
   215 		if (path1[pos1] != path2[pos2])
   216 	#endif
   217 		{
   218 			return false;
   219 		}
   220 
   221 		pos1++;
   222 		pos2++;
   223 	}
   224 }
   225 
   226 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
   227 {
   228 	va_list ap;
   229 
   230 	va_start(ap, fmt);
   231 	size_t len = vsnprintf(buffer, maxlength, fmt, ap);
   232 	va_end(ap);
   233 
   234 	if (len >= maxlength)
   235 	{
   236 		len = maxlength - 1;
   237 		buffer[len] = '\0';
   238 	}
   239 
   240 	return len;
   241 }
   242 
   243 inline bool pathchar_isalpha(char a)
   244 {
   245 	return (((a & 1<<7) == 0) && isalpha(a));
   246 }
   247 
   248 inline bool pathchar_sep(char a)
   249 {
   250 #if defined WIN32
   251 	return (a == '/' || a == '\\');
   252 #elif defined __linux__
   253 	return (a == '/');
   254 #endif
   255 }
   256 
   257 inline bool pathstr_isabsolute(const char *str)
   258 {
   259 #if defined WIN32
   260 	return (pathchar_isalpha(str[0]) 
   261 		&& str[1] == ':' 
   262 		&& pathchar_sep(str[2]));
   263 #elif defined __linux__
   264 	return (str[0] == '/');
   265 #endif
   266 }
   267 
   268 inline bool pathchar_cmp(char a, char b)
   269 {
   270 #if defined WIN32
   271 	if (pathchar_isalpha(a) && pathchar_isalpha(b))
   272 	{
   273 		return (tolower(a) == tolower(b));
   274 	}
   275 	/* Either path separator is acceptable */
   276 	if (pathchar_sep(a))
   277 	{
   278 		return pathchar_sep(b);
   279 	}
   280 #endif
   281 	return (a == b);
   282 }
   283 
   284 /**
   285  * @brief Forms a relative path given two absolute paths.
   286  *
   287  * @param buffer		Buffer to store relative path in.
   288  * @param maxlength		Maximum length of the output buffer.
   289  * @param relTo			Destination folder to use as a working directory.
   290  *						Final folder name should not be pathchar-terminated.
   291  * @param relFrom		Source file or folder to use as a target.
   292  * @return				True on success, false on failure.
   293  */
   294 bool UTIL_Relatize(char buffer[],
   295 				   size_t maxlength,
   296 				   const char *relTo,
   297 				   const char *relFrom)
   298 {
   299 	/* We don't allow relative paths in here, force
   300 	 * the user to resolve these himself!
   301 	 */
   302 	if (!pathstr_isabsolute(relTo)
   303 		|| !pathstr_isabsolute(relFrom))
   304 	{
   305 		return false;
   306 	}
   307 
   308 #if defined WIN32
   309 	/* Relative paths across drives are not possible */
   310 	if (!pathchar_cmp(relTo[0], relFrom[0]))
   311 	{
   312 		return false;
   313 	}
   314 	/* Get rid of the drive and semicolon part */
   315 	relTo = &relTo[2];
   316 	relFrom = &relFrom[2];
   317 #endif
   318 
   319 	/* Eliminate the common root between the paths */
   320 	const char *rootTo = NULL;
   321 	const char *rootFrom = NULL;
   322 	while (*relTo != '\0' && *relFrom != '\0')
   323 	{
   324 		/* If we get to a new path sequence, start over */
   325 		if (pathchar_sep(*relTo)
   326 			&& pathchar_sep(*relFrom))
   327 		{
   328 			rootTo = relTo;
   329 			rootFrom = relFrom;
   330 		/* If the paths don't compare, stop looking for a common root */
   331 		} else if (!pathchar_cmp(*relTo, *relFrom)) {
   332 			break;
   333 		}
   334 		relTo++;
   335 		relFrom++;
   336 	}
   337 
   338 	/* NULLs shouldn't happen! */
   339 	if (rootTo == NULL
   340 		|| rootFrom == NULL)
   341 	{
   342 		return false;
   343 	}
   344 
   345 	size_t numLevels = 0;
   346 
   347 	/* The root case is special! 
   348 	 * Don't count anything from it.
   349 	 */
   350 	if (*(rootTo + 1) != '\0')
   351 	{
   352 		/* Search for how many levels we need to go up.
   353 	 	 * Since the root pointer points to a '/', we increment
   354 		 * the initial pointer by one.
   355 		 */
   356 		while (*rootTo != '\0')
   357 		{
   358 			if (pathchar_sep(*rootTo))
   359 			{
   360 				/* Check for an improper trailing slash,
   361 				 * just to be nice even though the user 
   362 				 * should NOT have done this!
   363 				 */
   364 				if (*(rootTo + 1) == '\0')
   365 				{
   366 					break;
   367 				}
   368 				numLevels++;
   369 			}
   370 			rootTo++;
   371 		}
   372 	}
   373 
   374 	/* Now build the new relative path. */
   375 	size_t len, total = 0;
   376 	while (numLevels--)
   377 	{
   378 		len = _snprintf(&buffer[total], maxlength - total, ".." PATH_SEP_STR);
   379 		if (len >= maxlength - total)
   380 		{
   381 			/* Not enough space in the buffer */
   382 			return false;
   383 		}
   384 		total += len;
   385 	}
   386 
   387 	/* Add the absolute path. */
   388 	len = _snprintf(&buffer[total], maxlength - total, "%s", &rootFrom[1]);
   389 	if (len >= maxlength - total)
   390 	{
   391 		return false;
   392 	}
   393 
   394 	return true;
   395 }
   396 
   397 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list params)
   398 {
   399 	size_t len = vsnprintf(buffer, maxlength, fmt, params);
   400 
   401 	if (len >= maxlength)
   402 	{
   403 		len = maxlength - 1;
   404 		buffer[len] = '\0';
   405 	}
   406 
   407 	return len;
   408 }
   409 
   410 bool UTIL_VerifySignature(const void *addr, const char *sig, size_t len)
   411 {
   412 	unsigned char *addr1 = (unsigned char *) addr;
   413 	unsigned char *addr2 = (unsigned char *) sig;
   414 
   415 	for (size_t i = 0; i < len; i++)
   416 	{
   417 		if (addr2[i] == '*')
   418 			continue;
   419 		if (addr1[i] != addr2[i])
   420 			return false;
   421 	}
   422 
   423 	return true;
   424 }