/* Copyright (c) 2014 Alex Diener This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Alex Diener alex@ludobloom.com */ #include "utilities/IOUtilities.h" #include #include #include #include #include #include #include #include #include #include #include #include "utilities/AutoFreePool.h" void * (* readResourceFile)(const char * fileIdentifier, size_t * outFileLength) = readFileSimple; struct memreadContext memreadContextInit(const void * data, size_t length) { struct memreadContext context; context.data = data; context.length = length; context.position = 0; return context; } bool memread(struct memreadContext * context, size_t nbytes, void * outData) { if (context->position + nbytes > context->length) { return false; } if (outData != NULL) { memcpy(outData, context->data + context->position, nbytes); } context->position += nbytes; return true; } struct memwriteContext memwriteContextInit(void * data, size_t length, size_t allocatedSize, bool reallocIfNeeded) { struct memwriteContext context; context.data = data; context.length = length; context.allocatedSize = allocatedSize; context.position = 0; context.realloc = reallocIfNeeded; return context; } bool memwrite(struct memwriteContext * context, size_t nbytes, const void * inData) { if (context->position + nbytes > context->allocatedSize) { if (!context->realloc) { return false; } if (context->allocatedSize == 0) { context->allocatedSize = context->position + nbytes; } else { while (context->position + nbytes > context->allocatedSize) { context->allocatedSize *= 2; } } context->data = realloc(context->data, context->allocatedSize); } if (inData == NULL) { memset(context->data + context->position, 0, nbytes); } else { memcpy(context->data + context->position, inData, nbytes); } context->position += nbytes; if (context->length < context->position) { context->length = context->position; } return true; } void * readFileSimple(const char * filePath, size_t * outFileLength) { FILE * file; size_t fileLength; void * fileContents; size_t bytesRead; file = fopen(filePath, "rb"); if (file == NULL) { if (outFileLength != NULL) { *outFileLength = 0; } return NULL; } fseek(file, 0, SEEK_END); fileLength = ftell(file); fseek(file, 0, SEEK_SET); fileContents = malloc(fileLength + 1); bytesRead = fread(fileContents, 1, fileLength, file); fclose(file); if (bytesRead < fileLength) { free(fileContents); if (outFileLength != NULL) { *outFileLength = 0; } return NULL; } ((char *) fileContents)[fileLength] = 0; if (outFileLength != NULL) { *outFileLength = fileLength; } return fileContents; } bool writeFileSimple(const char * filePath, const void * contents, size_t length) { FILE * file; file = fopen(filePath, "wb"); if (file == NULL) { return false; } fwrite(contents, 1, length, file); fclose(file); return true; } #ifndef WIN32 bool writeFileAtomic(const char * filePath, const void * contents, size_t length) { size_t pathSize = strlen(filePath); char temporaryFilePath[pathSize + 2]; memcpy(temporaryFilePath, filePath, pathSize); temporaryFilePath[pathSize] = '~'; temporaryFilePath[pathSize + 1] = 0; if (unlink(temporaryFilePath) == -1 && errno != ENOENT) { return false; } int fd = open(temporaryFilePath, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (fd == -1) { return false; } ssize_t writeResult = write(fd, contents, length); if (writeResult < 0 || (size_t) writeResult < length) { close(fd); unlink(temporaryFilePath); return false; } #ifdef __APPLE__ int fsyncResult = fcntl(fd, F_FULLFSYNC, NULL); #else int fsyncResult = fsync(fd); #endif if (fsyncResult == -1) { close(fd); unlink(temporaryFilePath); return false; } if (close(fd) == -1) { unlink(temporaryFilePath); return false; } if (rename(temporaryFilePath, filePath) == -1) { unlink(temporaryFilePath); return false; } return true; } #endif void * readStdinSimple(size_t * outLength) { int byte; size_t allocatedSize = 1; char * data; size_t length = 0; data = malloc(allocatedSize); for (;;) { byte = getchar(); if (feof(stdin)) { break; } if (length >= allocatedSize) { allocatedSize *= 2; data = realloc(data, allocatedSize); } data[length++] = byte; } if (outLength != NULL) { *outLength = length; } return data; } #ifdef WIN32 static int mkstemp(char * template) { int result = -1; mktemp(template); result = open(template, O_RDWR | O_BINARY | O_CREAT | O_EXCL | _O_SHORT_LIVED, _S_IREAD | _S_IWRITE); return result; } #endif const char * temporaryFilePath(const char * fileNameTemplate, int * outFD) { char * fileName; char * tempDirEnvironmentVariables[] = { "TMPDIR", "TEMPDIR", "TEMP", "TMP" }; unsigned int variableIndex; char * tempDir = NULL; int fd; for (variableIndex = 0; variableIndex < sizeof(tempDirEnvironmentVariables) / sizeof(char *); variableIndex++) { tempDir = getenv(tempDirEnvironmentVariables[variableIndex]); if (tempDir != NULL) { break; } } #ifndef WIN32 if (tempDir == NULL) { tempDir = "/tmp"; } #endif if (tempDir == NULL) { #ifdef DEBUG fprintf(stderr, "Warning: Couldn't find any of the expected temporary directory environment variables (%s", tempDirEnvironmentVariables[0]); for (variableIndex = 1; variableIndex < sizeof(tempDirEnvironmentVariables) / sizeof(char *); variableIndex++) { fprintf(stderr, ", %s", tempDirEnvironmentVariables[variableIndex]); } fprintf(stderr, "); unable to create a temporary file\n"); #endif return NULL; } fileName = malloc(strlen(tempDir) + strlen(fileNameTemplate) + 2); sprintf(fileName, "%s/%s", tempDir, fileNameTemplate); fd = mkstemp(fileName); if (fd == -1) { #ifdef DEBUG fprintf(stderr, "Warning: Couldn't create temporary file \"%s\"; errno = %d\n", fileName, errno); #endif return NULL; } if (outFD != NULL) { *outFD = fd; } return AutoFreePool_add(fileName); } const char * getFileExtension(const char * path) { size_t length = strlen(path); for (unsigned int charIndex = length; charIndex > 0; charIndex--) { if (path[charIndex - 1] == '.') { return path + charIndex; } if (path[charIndex - 1] == '/') { break; } #ifdef WIN32 if (path[charIndex - 1] == '\\') { break; } #endif } return path + length; } const char * getLastPathComponent(const char * path) { if (path == NULL) { return NULL; } size_t length = strlen(path); if (length == 0) { return path; } for (unsigned int charIndex = length - 1; charIndex > 0; charIndex--) { if (path[charIndex - 1] == '/') { return path + charIndex; } #ifdef WIN32 if (path[charIndex - 1] == '\\') { return path + charIndex; } #endif } return path; } const char * getDirectory(const char * path) { if (path == NULL) { return NULL; } size_t length = strlen(path); if (length == 0) { return path; } unsigned int charIndex; for (charIndex = length - 1; charIndex > 0; charIndex--) { if (path[charIndex - 1] == '/') { break; } #ifdef WIN32 if (path[charIndex - 1] == '\\') { break; } #endif } if (charIndex == 0 && path[0] == '/') { return path; } #ifdef WIN32 if (charIndex == 0) { if (path[0] == '\\') { return path; } if (length >= 2 && ((path[0] >= 'a' && path[0] <= 'z') || (path[0] >= 'A' && path[0] <= 'Z')) && path[1] == ':') { if (length == 2 || (length == 3 && (path[2] == '/' || path[2] == '\\'))) { return path; } } } #endif char * result = malloc(charIndex + 1); strncpy_safe(result, path, charIndex + 1); return AutoFreePool_add(result); } const char * getBaseName(const char * path) { if (path == NULL) { return NULL; } size_t length = strlen(path); if (length == 0) { return path; } unsigned int charIndex; for (charIndex = length - 1; charIndex > 0 && path[charIndex] != '.' && path[charIndex] != '/'; charIndex--); if (charIndex == 0 || path[charIndex] == '/') { charIndex = length; } char * result = malloc(charIndex + 1); memcpy(result, path, charIndex); result[charIndex] = 0; return AutoFreePool_add(result); } const char * getSiblingFilePath(const char * path, const char * siblingName) { const char * directory = getDirectory(path); size_t directoryLength = strlen(directory); size_t nameLength = strlen(siblingName); char * result = malloc(directoryLength + nameLength + 1); memcpy(result, directory, directoryLength); memcpy(result + directoryLength, siblingName, nameLength + 1); return AutoFreePool_add(result); } const char * getPathRelativeTo(const char * basePath, const char * targetPath) { size_t basePathLength = strlen(basePath), targetPathLength = strlen(targetPath); unsigned int sharedPrefixLength = 0, lastSharedSlash = 0; while (sharedPrefixLength < basePathLength && sharedPrefixLength < targetPathLength && basePath[sharedPrefixLength] == targetPath[sharedPrefixLength]) { if (basePath[sharedPrefixLength] == '/') { lastSharedSlash = sharedPrefixLength; } sharedPrefixLength++; } unsigned int unsharedSlashCount = 0; for (unsigned int baseCharIndex = sharedPrefixLength; baseCharIndex < basePathLength; baseCharIndex++) { if (basePath[baseCharIndex] == '/') { unsharedSlashCount++; } } char * result = malloc(unsharedSlashCount * 3 + targetPathLength - lastSharedSlash + 1); for (unsigned int unsharedSlashIndex = 0; unsharedSlashIndex < unsharedSlashCount; unsharedSlashIndex++) { result[unsharedSlashIndex * 3 + 0] = '.'; result[unsharedSlashIndex * 3 + 1] = '.'; result[unsharedSlashIndex * 3 + 2] = '/'; } memcpy(result + unsharedSlashCount * 3, targetPath + lastSharedSlash + 1, targetPathLength - lastSharedSlash); result[unsharedSlashCount * 3 + targetPathLength - lastSharedSlash] = 0; return AutoFreePool_add(result); } const char * getAbsolutePath(const char * basePath, const char * relativePath) { size_t basePathLength = strlen(basePath), relativePathLength = strlen(relativePath), resultLength; char * result; if (relativePath[0] == '/') { result = malloc(relativePathLength + 1); resultLength = 0; } else { result = malloc(basePathLength + relativePathLength + 1); memcpy(result, basePath, basePathLength); resultLength = basePathLength; while (resultLength > 0 && result[resultLength - 1] != '/') { resultLength--; } } size_t lastCharIndex = 0; for (size_t charIndex = 0; charIndex < relativePathLength; charIndex++) { if (relativePath[charIndex] == '/') { if (relativePath[lastCharIndex] == '.') { if (charIndex == lastCharIndex + 1) { lastCharIndex = charIndex + 1; continue; } if (charIndex == lastCharIndex + 2 && relativePath[lastCharIndex + 1] == '.') { if (resultLength > 1) { resultLength--; } while (resultLength > 1 && result[resultLength - 1] != '/') { resultLength--; } lastCharIndex = charIndex + 1; continue; } } while (lastCharIndex <= charIndex) { result[resultLength++] = relativePath[lastCharIndex++]; } } } if (lastCharIndex < relativePathLength) { do { if (relativePath[lastCharIndex] == '.') { if (relativePathLength == lastCharIndex + 1) { break; } if (relativePathLength == lastCharIndex + 2 && relativePath[lastCharIndex + 1] == '.') { if (resultLength > 1) { resultLength--; } while (resultLength > 1 && result[resultLength - 1] != '/') { resultLength--; } break; } } while (lastCharIndex < relativePathLength) { result[resultLength++] = relativePath[lastCharIndex++]; } } while (0); } result[resultLength] = 0; return AutoFreePool_add(result); } const char * uniqueFileInDirectory(const char * directory, const char * baseName, const char * extension, unsigned int limit) { size_t maxLength = strlen(directory) + 1 + strlen(baseName) + 1 + (log10(limit) + 1) + 1 + strlen(extension); char * filePath = malloc(maxLength + 1); struct stat statbuf; unsigned int pathSuffix = 0; snprintf_safe(filePath, maxLength, "%s/%s.%s", directory, baseName, extension); while (!stat(filePath, &statbuf)) { ++pathSuffix; if (pathSuffix > limit) { return NULL; } snprintf_safe(filePath, maxLength, "%s/%s_%u.%s", directory, baseName, pathSuffix, extension); } return AutoFreePool_add(filePath); } int snprintf_safe(char * restrict str, size_t size, const char * restrict format, ...) { if (size == 0) { return 0; } va_list ap; va_start(ap, format); int result = vsnprintf(str, size, format, ap); va_end(ap); str[size - 1] = 0; return result; } int vsnprintf_safe(char * restrict str, size_t size, const char * restrict format, va_list ap) { if (size == 0) { return 0; } int result = vsnprintf(str, size, format, ap); str[size - 1] = 0; return result; } char * strncpy_safe(char * restrict dst, const char * restrict src, size_t n) { if (n == 0) { return dst; } char * result = strncpy(dst, src, n); dst[n - 1] = 0; return result; } char * strncat_safe(char * restrict s1, const char * restrict s2, size_t n) { if (n == 0) { return s1; } char * result = strncat(s1, s2, n); s1[n - 1] = 0; return result; } int snprintf_append(char * restrict str, size_t size, const char * restrict format, ...) { va_list ap; va_start(ap, format); int result = vsnprintf_append(str, size, format, ap); va_end(ap); return result; } int vsnprintf_append(char * restrict str, size_t size, const char * restrict format, va_list ap) { size_t length = strlen(str); if (length > size) { length = size; } return vsnprintf_safe(str + length, size - length, format, ap); } char * strdup_nullSafe(const char * s) { return s == NULL ? NULL : strdup(s); } int strcmp_nullSafe(const char * s1, const char * s2) { if (s1 == NULL) { if (s2 == NULL) { return 0; } return -1; } if (s2 == NULL) { return 1; } return strcmp(s1, s2); } #ifdef STEM_PLATFORM_windows char * strndup(const char * s, size_t n) { size_t length = strlen(s); if (length > n) { length = n; } char * result = malloc(length + 1); memcpy(result, s, length); result[length] = 0; return result; } #endif char * strdup_length(const char * s, size_t n) { char * result = malloc(n + 1); memcpy(result, s, n); result[n] = 0; return result; } void * memdup(const void * data, size_t size) { if (size == 0) { return NULL; } void * result = malloc(size); memcpy(result, data, size); return result; } int lexstrcmp(const char * s1, const char * s2) { unsigned char c1 = *s1, c2 = *s2; for (;;) { if (c1 == 0) { if (c2 == 0) { return 0; } return -1; } if (c2 == 0) { return 1; } if (c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9') { size_t leadingZeros1 = 0, leadingZeros2 = 0, digitCount1, digitCount2; while (c1 == '0') { ++leadingZeros1; c1 = *++s1; } while (c2 == '0') { ++leadingZeros2; c2 = *++s2; } for (digitCount1 = 0; s1[digitCount1] >= '0' && s1[digitCount1] <= '9'; digitCount1++); for (digitCount2 = 0; s2[digitCount2] >= '0' && s2[digitCount2] <= '9'; digitCount2++); if (digitCount1 < digitCount2) { return -1; } if (digitCount1 > digitCount2) { return 1; } while (c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9') { if (c1 < c2) { return -1; } if (c1 > c2) { return 1; } c1 = *++s1; c2 = *++s2; } if (leadingZeros1 < leadingZeros2) { return -1; } if (leadingZeros1 > leadingZeros2) { return 1; } continue; } if (c1 >= 'A' && c1 <= 'Z') { c1 -= 'A' - 'a'; } if (c2 >= 'A' && c2 <= 'Z') { c2 -= 'A' - 'a'; } if (c1 < c2) { return -1; } if (c1 > c2) { return 1; } c1 = *++s1; c2 = *++s2; } return 0; } char * printHexString(const void * blob, size_t length, char * outString, size_t maxLength) { const unsigned char * blobChars = blob; size_t byteIndex, charIndex = 0; for (byteIndex = 0; byteIndex < length; byteIndex++) { snprintf_safe(outString + charIndex, maxLength - charIndex, "%02X ", blobChars[byteIndex]); charIndex += 3; if (charIndex >= maxLength) { return outString; } } if (byteIndex == 0) { outString[0] = 0; } else { outString[charIndex - 1] = 0; } return outString; } static unsigned int writeDecimalResultReverse(char * outString, const char * resultString, unsigned int resultStringLength, unsigned int maxLength) { if (outString != NULL) { for (unsigned int charIndex = 0; charIndex < maxLength && charIndex < resultStringLength; charIndex++) { outString[charIndex] = resultString[resultStringLength - 1 - charIndex]; } } if (maxLength > 0) { if (resultStringLength >= maxLength) { outString[maxLength - 1] = 0; return maxLength; } outString[resultStringLength] = 0; return resultStringLength; } return 0; } static unsigned int writeU64DecimalStringReverse(char * outBuffer, uint64_t value, unsigned int lengthMax) { unsigned int length = 0; while (value > 0 && length < lengthMax) { outBuffer[length++] = '0' + value % 10; value /= 10; } if (length == 0) { outBuffer[length++] = '0'; } return length; } static unsigned int writeDecimalResult(char * outString, const char * resultBuffer, unsigned int resultLength, unsigned int maxLength) { if (maxLength > 0) { if (resultLength >= maxLength) { memcpy(outString, resultBuffer, maxLength - 1); outString[maxLength - 1] = 0; resultLength = maxLength - 1; } else { memcpy(outString, resultBuffer, resultLength + 1); } } return resultLength; } unsigned int formatDecimalString(double value, char * outString, unsigned int maxLength, unsigned int decimalPrecisionMin, unsigned int decimalPrecisionMax) { if (value != value) { return writeDecimalResult(outString, "nan", 3, maxLength); } if (value < -DBL_MAX) { return writeDecimalResult(outString, "-inf", 4, maxLength); } if (value > DBL_MAX) { return writeDecimalResult(outString, "inf", 3, maxLength); } bool negative = false; if (value < 0) { negative = true; value = -value; } if (value > UINT64_MAX) { value = UINT64_MAX; } if (decimalPrecisionMax > DECIMAL_PRECISION_MAX) { decimalPrecisionMax = DECIMAL_PRECISION_MAX; } if (decimalPrecisionMin > decimalPrecisionMax) { decimalPrecisionMin = decimalPrecisionMax; } uint64_t wholePart = value; double fraction = value - wholePart; uint64_t fractionU64 = fraction * 10000000000000000000ull; bool anyFraction = fractionU64 != 0; char wholeBuffer[24]; unsigned int wholeDigitCount = writeU64DecimalStringReverse(wholeBuffer, wholePart, sizeof(wholeBuffer)); char fractionBuffer[24]; unsigned int fractionDigitCount = 0, fractionDigitSkipCount = 0; if (anyFraction) { fractionDigitCount = writeU64DecimalStringReverse(fractionBuffer, fractionU64, sizeof(fractionBuffer)); while (fractionDigitCount < 19) { fractionBuffer[fractionDigitCount++] = '0'; } while (fractionBuffer[fractionDigitSkipCount] == '0') { fractionDigitSkipCount++; } if (fractionDigitCount - fractionDigitSkipCount > decimalPrecisionMax) { fractionDigitSkipCount = fractionDigitCount - decimalPrecisionMax; } } char resultBuffer[DECIMAL_STRING_MAX]; unsigned int resultLength = 0; if (negative) { resultBuffer[resultLength++] = '-'; } resultLength += writeDecimalResultReverse(resultBuffer + resultLength, wholeBuffer, wholeDigitCount, sizeof(resultBuffer) - resultLength); if (decimalPrecisionMin > 0 || (decimalPrecisionMax > 0 && anyFraction)) { resultBuffer[resultLength++] = '.'; resultLength += writeDecimalResultReverse(resultBuffer + resultLength, fractionBuffer + fractionDigitSkipCount, fractionDigitCount - fractionDigitSkipCount, sizeof(resultBuffer) - resultLength); if (decimalPrecisionMin > fractionDigitCount - fractionDigitSkipCount) { for (unsigned int extraZero = 0; extraZero < decimalPrecisionMin - (fractionDigitCount - fractionDigitSkipCount); extraZero++) { resultBuffer[resultLength++] = '0'; } resultBuffer[resultLength] = 0; } } return writeDecimalResult(outString, resultBuffer, resultLength, maxLength); } enum numberParseResult { NUMBER_PARSE_SUCCESS, NUMBER_PARSE_NO_NUMERALS, NUMBER_PARSE_OVERFLOW }; static enum numberParseResult parsePositiveU64String(uint64_t * outValue, const char * string, unsigned int length, unsigned int * outCharactersRead) { uint64_t value = 0; unsigned int charactersRead = 0; if (length > DECIMAL_PRECISION_MAX) { length = DECIMAL_PRECISION_MAX; } while (charactersRead < length) { if (string[charactersRead] < '0' || string[charactersRead] > '9') { break; } value *= 10; value += string[charactersRead++] - '0'; } *outValue = value; *outCharactersRead = charactersRead; if (charactersRead == 0) { return NUMBER_PARSE_NO_NUMERALS; } if (charactersRead < length && string[charactersRead] >= '0' && string[charactersRead] <= '9') { return NUMBER_PARSE_OVERFLOW; } return NUMBER_PARSE_SUCCESS; } bool parseDecimalString(double * outNumber, const char * string, unsigned int length, unsigned int * outCharactersRead) { if (length == 0) { if (outCharactersRead != NULL) { *outCharactersRead = 0; } return 0.0; } if (length >= 3 && string[0] == 'n' && string[1] == 'a' && string[2] == 'n') { *outNumber = NAN; if (outCharactersRead != NULL) { *outCharactersRead = 3; } return true; } unsigned int charIndex = 0; bool negative = false; if (string[0] == '-') { negative = true; charIndex = 1; } if (charIndex + 3 < length && string[charIndex] == 'i' && string[charIndex + 1] == 'n' && string[charIndex + 2] == 'f') { *outNumber = INFINITY; if (negative) { *outNumber = -*outNumber; } if (outCharactersRead != NULL) { *outCharactersRead = charIndex + 3; } return true; } while (charIndex < length && string[charIndex] == '0') { charIndex++; } unsigned int numeralsRead = 0; uint64_t wholePart = 0; enum numberParseResult parseResult = parsePositiveU64String(&wholePart, string + charIndex, length - charIndex, &numeralsRead); if (parseResult != NUMBER_PARSE_SUCCESS && charIndex == negative) { if (outCharactersRead != NULL) { *outCharactersRead = 0; } return false; } charIndex += numeralsRead; double result = wholePart; if (charIndex < length && string[charIndex] == '.') { charIndex++; uint64_t fractionalPart = 0; enum numberParseResult parseResult = parsePositiveU64String(&fractionalPart, string + charIndex, length - charIndex, &numeralsRead); charIndex += numeralsRead; result += fractionalPart / pow(10, numeralsRead); if (parseResult == NUMBER_PARSE_OVERFLOW) { while (charIndex < length && string[charIndex] >= '0' && string[charIndex] <= '9') { charIndex++; } } } if (charIndex + 1 < length && (string[charIndex] == 'e' || string[charIndex] == 'E') && ((string[charIndex + 1] >= '0' && string[charIndex + 1] <= '9') || (charIndex + 2 < length && (string[charIndex + 1] == '-' || string[charIndex + 1] == '+') && string[charIndex + 2] >= '0' && string[charIndex + 2] <= '9'))) { charIndex++; bool negativeExponent = false; if (string[charIndex] == '-') { negativeExponent = true; charIndex++; } else if (string[charIndex] == '+') { charIndex++; } uint64_t exponentPart = 0; parseResult = parsePositiveU64String(&exponentPart, string + charIndex, length - charIndex, &numeralsRead); charIndex += numeralsRead; if (negativeExponent) { result /= pow(10, exponentPart); } else { result *= pow(10, exponentPart); } } if (negative) { result = -result; } *outNumber = result; if (outCharactersRead != NULL) { *outCharactersRead = charIndex; } return true; } char * createIdentifierFromDisplayString(const char * displayString, unsigned int lengthMax) { unsigned int length = strlen(displayString); if (length > lengthMax) { length = lengthMax; } char * newString = malloc(length + 1); unsigned int newCharIndex = 0; for (unsigned int charIndex = 0; charIndex < length; charIndex++) { if ((displayString[charIndex] >= 'a' && displayString[charIndex] <= 'z') || (displayString[charIndex] >= '0' && displayString[charIndex] <= '9') || displayString[charIndex] == '_') { newString[newCharIndex++] = displayString[charIndex]; } else if (displayString[charIndex] >= 'A' && displayString[charIndex] <= 'Z') { newString[newCharIndex++] = displayString[charIndex] + 'a' - 'A'; } else { if (newCharIndex > 0 && newString[newCharIndex - 1] != '_') { newString[newCharIndex++] = '_'; } } } if (newCharIndex > 0 && newString[newCharIndex - 1] == '_') { newCharIndex--; } newString[newCharIndex] = 0; return newString; } #define UNIQUE_DIGIT_MAX 4 Atom stringToUniqueIdentifier(const char * newIdentifier, unsigned int lengthMax, unsigned int identifierCount, Atom (* getIdentifierAtIndexCallback)(unsigned int index, void * context), void * context) { bool unique = true; for (unsigned int identifierIndex = 0; identifierIndex < identifierCount; identifierIndex++) { if (!strcmp(getIdentifierAtIndexCallback(identifierIndex, context), newIdentifier)) { unique = false; break; } } if (unique) { return Atom_fromString(newIdentifier); } Atom result; unsigned int newIdentifierLength = strlen(newIdentifier); if (newIdentifierLength > lengthMax - (1 + UNIQUE_DIGIT_MAX)) { newIdentifierLength = lengthMax - (1 + UNIQUE_DIGIT_MAX); } unsigned int appendedNumberMax = pow(10, UNIQUE_DIGIT_MAX); unsigned int appendedNumberStart = 1; if (newIdentifierLength > 0) { unsigned int endCharIndex = newIdentifierLength - 1; while (endCharIndex > 0 && newIdentifier[endCharIndex] >= '0' && newIdentifier[endCharIndex] <= '9') { endCharIndex--; } if (newIdentifier[endCharIndex] == '_') { if (newIdentifier[newIdentifierLength - 1] >= '0' && newIdentifier[newIdentifierLength - 1] <= '9') { appendedNumberStart = strtoul(newIdentifier + endCharIndex + 1, NULL, 10); if (appendedNumberStart >= appendedNumberMax) { appendedNumberStart = 1; } } newIdentifierLength = endCharIndex; } } unsigned int length = newIdentifierLength + 1 + UNIQUE_DIGIT_MAX; char * newString = malloc(length + 1); unsigned int appendedNumber = appendedNumberStart; while (!unique && appendedNumber < appendedNumberMax) { snprintf_safe(newString, length + 1, "%.*s_%u", newIdentifierLength, newIdentifier, appendedNumber); unique = true; for (unsigned int identifierIndex = 0; identifierIndex < identifierCount; identifierIndex++) { if (!strcmp(getIdentifierAtIndexCallback(identifierIndex, context), newString)) { unique = false; appendedNumber++; break; } } } if (appendedNumber >= appendedNumberMax && appendedNumberStart > 1) { appendedNumber = 1; while (!unique && appendedNumber < appendedNumberStart) { snprintf_safe(newString, length + 1, "%.*s_%u", newIdentifierLength, newIdentifier, appendedNumber); unique = true; for (unsigned int identifierIndex = 0; identifierIndex < identifierCount; identifierIndex++) { if (!strcmp(getIdentifierAtIndexCallback(identifierIndex, context), newString)) { unique = false; appendedNumber++; break; } } } } if (appendedNumber >= appendedNumberMax) { #ifdef DEBUG fprintf(stderr, "Couldn't create unique identifier from \"%s\" after %u iterations\n", newIdentifier, appendedNumber); #endif abort(); } result = Atom_fromString(newString); free(newString); return result; } char * newDisplayStringWithCopySuffix(const char * string, unsigned int lengthMax, unsigned int compareStringCount, const char * (* getCompareStringAtIndexCallback)(unsigned int index, void * context), void * context) { unsigned int displayStringLength = strlen(string); if (displayStringLength > lengthMax - (6 + UNIQUE_DIGIT_MAX)) { displayStringLength = lengthMax - (6 + UNIQUE_DIGIT_MAX); } unsigned int appendedNumberMax = pow(10, UNIQUE_DIGIT_MAX); unsigned int appendedNumberStart = 2; if (displayStringLength > 0) { unsigned int endCharIndex = displayStringLength - 1; while (endCharIndex > 0 && string[endCharIndex] >= '0' && string[endCharIndex] <= '9') { endCharIndex--; } if (string[endCharIndex] == ' ') { endCharIndex--; } if (endCharIndex > 4 && string[endCharIndex - 4] == ' ' && string[endCharIndex - 3] == 'c' && string[endCharIndex - 2] == 'o' && string[endCharIndex - 1] == 'p' && string[endCharIndex - 0] == 'y') { if (string[displayStringLength - 1] >= '0' && string[displayStringLength - 1] <= '9') { appendedNumberStart = strtoul(string + endCharIndex + 1, NULL, 10); if (appendedNumberStart >= appendedNumberMax) { appendedNumberStart = 2; } } displayStringLength = endCharIndex - 4; } } unsigned int length = displayStringLength + 6 + UNIQUE_DIGIT_MAX; char * newString = malloc(length + 1); snprintf_safe(newString, length + 1, "%.*s copy", displayStringLength, string); if (getCompareStringAtIndexCallback != NULL) { bool unique = true; for (unsigned int compareStringIndex = 0; compareStringIndex < compareStringCount; compareStringIndex++) { if (!strcmp(getCompareStringAtIndexCallback(compareStringIndex, context), newString)) { unique = false; break; } } unsigned int appendedNumber = appendedNumberStart; while (!unique && appendedNumber < appendedNumberMax) { snprintf_safe(newString, length + 1, "%.*s copy %u", displayStringLength, string, appendedNumber); unique = true; for (unsigned int compareStringIndex = 0; compareStringIndex < compareStringCount; compareStringIndex++) { if (!strcmp(getCompareStringAtIndexCallback(compareStringIndex, context), newString)) { unique = false; appendedNumber++; break; } } } if (appendedNumber >= appendedNumberMax && appendedNumberStart > 2) { appendedNumber = 2; while (!unique && appendedNumber < appendedNumberStart) { snprintf_safe(newString, length + 1, "%.*s copy %u", displayStringLength, string, appendedNumber); unique = true; for (unsigned int compareStringIndex = 0; compareStringIndex < compareStringCount; compareStringIndex++) { if (!strcmp(getCompareStringAtIndexCallback(compareStringIndex, context), newString)) { unique = false; appendedNumber++; break; } } } } if (appendedNumber >= appendedNumberMax) { #ifdef DEBUG fprintf(stderr, "Couldn't create unique display string from \"%s\" after %u iterations\n", string, appendedNumber); #endif abort(); } } return newString; } char * newDisplayStringWithNumberSuffix(const char * string, unsigned int lengthMax, unsigned int compareStringCount, const char * (* getCompareStringAtIndexCallback)(unsigned int index, void * context), void * context) { unsigned int displayStringLength = strlen(string); if (displayStringLength > lengthMax - (1 + UNIQUE_DIGIT_MAX)) { displayStringLength = lengthMax - (1 + UNIQUE_DIGIT_MAX); } unsigned int appendedNumberMax = pow(10, UNIQUE_DIGIT_MAX); unsigned int appendedNumberStart = 2; if (displayStringLength > 0) { unsigned int endCharIndex = displayStringLength - 1; while (endCharIndex > 0 && string[endCharIndex] >= '0' && string[endCharIndex] <= '9') { endCharIndex--; } if (string[endCharIndex] == ' ') { endCharIndex--; } } unsigned int length = displayStringLength + 1 + UNIQUE_DIGIT_MAX; char * newString = malloc(length + 1); snprintf_safe(newString, length + 1, "%.*s", displayStringLength, string); if (getCompareStringAtIndexCallback != NULL) { bool unique = true; for (unsigned int compareStringIndex = 0; compareStringIndex < compareStringCount; compareStringIndex++) { if (!strcmp(getCompareStringAtIndexCallback(compareStringIndex, context), newString)) { unique = false; break; } } unsigned int appendedNumber = appendedNumberStart; while (!unique && appendedNumber < appendedNumberMax) { snprintf_safe(newString, length + 1, "%.*s %u", displayStringLength, string, appendedNumber); unique = true; for (unsigned int compareStringIndex = 0; compareStringIndex < compareStringCount; compareStringIndex++) { if (!strcmp(getCompareStringAtIndexCallback(compareStringIndex, context), newString)) { unique = false; appendedNumber++; break; } } } if (appendedNumber >= appendedNumberMax && appendedNumberStart > 2) { appendedNumber = 2; while (!unique && appendedNumber < appendedNumberStart) { snprintf_safe(newString, length + 1, "%.*s %u", displayStringLength, string, appendedNumber); unique = true; for (unsigned int compareStringIndex = 0; compareStringIndex < compareStringCount; compareStringIndex++) { if (!strcmp(getCompareStringAtIndexCallback(compareStringIndex, context), newString)) { unique = false; appendedNumber++; break; } } } } if (appendedNumber >= appendedNumberMax) { #ifdef DEBUG fprintf(stderr, "Couldn't create unique display string from \"%s\" after %u iterations\n", string, appendedNumber); #endif abort(); } } return newString; } void enumerateFilesInDirectory(const char * directoryPath, bool includeInvisible, bool (* callback)(const char * directoryPath, const char * fileName, void * context), void * callbackContext) { DIR * directory = opendir(directoryPath); if (directory != NULL) { struct dirent * fileEntry; while ((fileEntry = readdir(directory)) != NULL) { if (!includeInvisible && fileEntry->d_name[0] == '.') { continue; } if (!callback(directoryPath, fileEntry->d_name, callbackContext)) { break; } } closedir(directory); } }