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