minor optimizations and added comments to some util functions

This commit is contained in:
Hielke Morsink 2015-11-29 16:00:05 +01:00
parent 8274ea1842
commit 63184052be
1 changed files with 23 additions and 37 deletions

View File

@ -55,62 +55,48 @@ bool filename_valid_characters(const utf8 *filename)
const char *path_get_filename(const utf8 *path)
{
const char *result, *ch;
// Find last slash or backslash in the path
char *filename = strrchr(path, '/');
if (filename == NULL)
filename = strrchr(path, '\\');
result = path;
for (ch = path; *ch != 0; ch++) {
if (*ch == '/' || *ch == '\\') {
if (*(ch + 1) != 0)
result = ch + 1;
}
}
assert(filename != NULL);
return result;
// Increase pointer by one, to get rid of the slashes
filename++;
return filename;
}
const char *path_get_extension(const utf8 *path)
{
const char *extension = NULL;
const char *ch = path;
while (*ch != 0) {
if (*ch == '.')
extension = ch;
// Try to find the most-right dot in the path
char *extension = strrchr(path, '.');
ch++;
}
// When NULL was returned, return a pointer to the null-terminator
if (extension == NULL)
extension = ch;
extension = strrchr(path, '\0');
return extension;
}
void path_set_extension(utf8 *path, const utf8 *newExtension)
{
char *extension = NULL;
char *ch = path;
while (*ch != 0) {
if (*ch == '.')
extension = ch;
ch++;
}
if (extension == NULL)
extension = ch;
// Append a dot to the filename if the new extension doesn't start with it
char *endOfString = strrchr(path, '\0');
if (newExtension[0] != '.')
*extension++ = '.';
*endOfString++ = '.';
strcpy(extension, newExtension);
// Append the extension to the path
// No existing extensions should be removed ("ride.TD6" -> "ride.TD6.TD6")
safe_strncpy(endOfString, newExtension, MAX_PATH - (endOfString - path) - 1);
}
void path_remove_extension(utf8 *path)
{
char *ch = path + strlen(path);
for (--ch; ch >= path; --ch) {
if (*ch == '.') {
*ch = '\0';
break;
}
}
// Find last dot in filename, and replace it with a null-terminator
char *lastDot = strrchr(path, '.');
if (*lastDot) *lastDot = '\0';
}
bool readentirefile(const utf8 *path, void **outBuffer, int *outLength)