core-legacy/util.cpp
author David Anderson <dvander@alliedmods.net>
Wed Feb 25 20:26:19 2009 -0500 (2009-02-25)
changeset 649 a0e24af92af0
parent 580 783e91c5f445
child 662 5a936e981523
permissions -rw-r--r--
Bumped all versions.
     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 bool UTIL_PathCmp(const char *path1, const char *path2)
    86 {
    87 	size_t pos1 = 0, pos2 = 0;
    88 
    89 	while (true)
    90 	{
    91 		if (path1[pos1] == '\0' || path2[pos2] == '\0')
    92 		{
    93 			return (path1[pos1] == path2[pos2]);
    94 		}
    95 
    96 		if (path1[pos1] == PATH_SEP_CHAR)
    97 		{
    98 			if (path2[pos2] != PATH_SEP_CHAR)
    99 			{
   100 				return false;
   101 			}
   102 
   103 			/* Look for extra path chars */
   104 			while (path1[++pos1])
   105 			{
   106 				if (path1[pos1] != PATH_SEP_CHAR)
   107 				{
   108 					break;
   109 				}
   110 			}
   111 			while (path2[++pos2])
   112 			{
   113 				if (path2[pos2] != PATH_SEP_CHAR)
   114 				{
   115 					break;
   116 				}
   117 			}
   118 			continue;
   119 		}
   120 
   121 		/* If we're at a different non-alphanumeric, the next character MUST match */
   122 		if (!isalpha(path1[pos1]) && (path1[pos1] != path2[pos2]))
   123 		{
   124 			return false;
   125 		}
   126 
   127 	#ifdef WIN32
   128 		if (toupper(path1[pos1]) != toupper(path2[pos2]))
   129 	#else
   130 		if (path1[pos1] != path2[pos2])
   131 	#endif
   132 		{
   133 			return false;
   134 		}
   135 
   136 		pos1++;
   137 		pos2++;
   138 	}
   139 }
   140 
   141 size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...)
   142 {
   143 	va_list ap;
   144 
   145 	va_start(ap, fmt);
   146 	size_t len = vsnprintf(buffer, maxlength, fmt, ap);
   147 	va_end(ap);
   148 
   149 	if (len >= maxlength)
   150 	{
   151 		len = maxlength - 1;
   152 		buffer[len] = '\0';
   153 	}
   154 
   155 	return len;
   156 }
   157 
   158 inline bool pathchar_isalpha(char a)
   159 {
   160 	return (((a & 1<<7) == 0) && isalpha(a));
   161 }
   162 
   163 inline bool pathchar_sep(char a)
   164 {
   165 #if defined WIN32
   166 	return (a == '/' || a == '\\');
   167 #elif defined __linux__
   168 	return (a == '/');
   169 #endif
   170 }
   171 
   172 inline bool pathstr_isabsolute(const char *str)
   173 {
   174 #if defined WIN32
   175 	return (pathchar_isalpha(str[0]) 
   176 		&& str[1] == ':' 
   177 		&& pathchar_sep(str[2]));
   178 #elif defined __linux__
   179 	return (str[0] == '/');
   180 #endif
   181 }
   182 
   183 inline bool pathchar_cmp(char a, char b)
   184 {
   185 #if defined WIN32
   186 	if (pathchar_isalpha(a) && pathchar_isalpha(b))
   187 	{
   188 		return (tolower(a) == tolower(b));
   189 	}
   190 	/* Either path separator is acceptable */
   191 	if (pathchar_sep(a))
   192 	{
   193 		return pathchar_sep(b);
   194 	}
   195 #endif
   196 	return (a == b);
   197 }
   198 
   199 /**
   200  * @brief Forms a relative path given two absolute paths.
   201  *
   202  * @param buffer		Buffer to store relative path in.
   203  * @param maxlength		Maximum length of the output buffer.
   204  * @param relTo			Destination folder to use as a working directory.
   205  *						Final folder name should not be pathchar-terminated.
   206  * @param relFrom		Source file or folder to use as a target.
   207  * @return				True on success, false on failure.
   208  */
   209 bool UTIL_Relatize(char buffer[],
   210 				   size_t maxlength,
   211 				   const char *relTo,
   212 				   const char *relFrom)
   213 {
   214 	/* We don't allow relative paths in here, force
   215 	 * the user to resolve these himself!
   216 	 */
   217 	if (!pathstr_isabsolute(relTo)
   218 		|| !pathstr_isabsolute(relFrom))
   219 	{
   220 		return false;
   221 	}
   222 
   223 #if defined WIN32
   224 	/* Relative paths across drives are not possible */
   225 	if (!pathchar_cmp(relTo[0], relFrom[0]))
   226 	{
   227 		return false;
   228 	}
   229 	/* Get rid of the drive and semicolon part */
   230 	relTo = &relTo[2];
   231 	relFrom = &relFrom[2];
   232 #endif
   233 
   234 	/* Eliminate the common root between the paths */
   235 	const char *rootTo = NULL;
   236 	const char *rootFrom = NULL;
   237 	while (*relTo != '\0' && *relFrom != '\0')
   238 	{
   239 		/* If we get to a new path sequence, start over */
   240 		if (pathchar_sep(*relTo)
   241 			&& pathchar_sep(*relFrom))
   242 		{
   243 			rootTo = relTo;
   244 			rootFrom = relFrom;
   245 		/* If the paths don't compare, stop looking for a common root */
   246 		} else if (!pathchar_cmp(*relTo, *relFrom)) {
   247 			break;
   248 		}
   249 		relTo++;
   250 		relFrom++;
   251 	}
   252 
   253 	/* NULLs shouldn't happen! */
   254 	if (rootTo == NULL
   255 		|| rootFrom == NULL)
   256 	{
   257 		return false;
   258 	}
   259 
   260 	size_t numLevels = 0;
   261 
   262 	/* The root case is special! 
   263 	 * Don't count anything from it.
   264 	 */
   265 	if (*(rootTo + 1) != '\0')
   266 	{
   267 		/* Search for how many levels we need to go up.
   268 	 	 * Since the root pointer points to a '/', we increment
   269 		 * the initial pointer by one.
   270 		 */
   271 		while (*rootTo != '\0')
   272 		{
   273 			if (pathchar_sep(*rootTo))
   274 			{
   275 				/* Check for an improper trailing slash,
   276 				 * just to be nice even though the user 
   277 				 * should NOT have done this!
   278 				 */
   279 				if (*(rootTo + 1) == '\0')
   280 				{
   281 					break;
   282 				}
   283 				numLevels++;
   284 			}
   285 			rootTo++;
   286 		}
   287 	}
   288 
   289 	/* Now build the new relative path. */
   290 	size_t len, total = 0;
   291 	while (numLevels--)
   292 	{
   293 		len = _snprintf(&buffer[total], maxlength - total, ".." PATH_SEP_STR);
   294 		if (len >= maxlength - total)
   295 		{
   296 			/* Not enough space in the buffer */
   297 			return false;
   298 		}
   299 		total += len;
   300 	}
   301 
   302 	/* Add the absolute path. */
   303 	len = _snprintf(&buffer[total], maxlength - total, "%s", &rootFrom[1]);
   304 	if (len >= maxlength - total)
   305 	{
   306 		return false;
   307 	}
   308 
   309 	return true;
   310 }
   311 
   312 size_t UTIL_FormatArgs(char *buffer, size_t maxlength, const char *fmt, va_list params)
   313 {
   314 	size_t len = vsnprintf(buffer, maxlength, fmt, params);
   315 
   316 	if (len >= maxlength)
   317 	{
   318 		len = maxlength - 1;
   319 		buffer[len] = '\0';
   320 	}
   321 
   322 	return len;
   323 }
   324 
   325 bool UTIL_VerifySignature(const void *addr, const char *sig, size_t len)
   326 {
   327 	unsigned char *addr1 = (unsigned char *) addr;
   328 	unsigned char *addr2 = (unsigned char *) sig;
   329 
   330 	for (size_t i = 0; i < len; i++)
   331 	{
   332 		if (addr2[i] == '*')
   333 			continue;
   334 		if (addr1[i] != addr2[i])
   335 			return false;
   336 	}
   337 
   338 	return true;
   339 }