2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
29 /** \file blender/blenlib/intern/string.c
39 #include "MEM_guardedalloc.h"
41 #include "BLI_dynstr.h"
42 #include "BLI_string.h"
44 #include "BLI_utildefines.h"
47 # pragma GCC diagnostic error "-Wsign-conversion"
50 // #define DEBUG_STRSIZE
53 * Duplicates the first \a len bytes of cstring \a str
54 * into a newly mallocN'd string and returns it. \a str
55 * is assumed to be at least len bytes long.
57 * \param str The string to be duplicated
58 * \param len The number of bytes to duplicate
59 * \retval Returns the duplicated string
61 char *BLI_strdupn(const char *str, const size_t len)
63 char *n = MEM_mallocN(len + 1, "strdup");
71 * Duplicates the cstring \a str into a newly mallocN'd
72 * string and returns it.
74 * \param str The string to be duplicated
75 * \retval Returns the duplicated string
77 char *BLI_strdup(const char *str)
79 return BLI_strdupn(str, strlen(str));
83 * Appends the two strings, and returns new mallocN'ed string
84 * \param str1 first string for copy
85 * \param str2 second string for append
88 char *BLI_strdupcat(const char *__restrict str1, const char *__restrict str2)
90 /* include the NULL terminator of str2 only */
91 const size_t str1_len = strlen(str1);
92 const size_t str2_len = strlen(str2) + 1;
95 str = MEM_mallocN(str1_len + str2_len, "strdupcat");
98 memcpy(s, str1, str1_len); s += str1_len;
99 memcpy(s, str2, str2_len);
105 * Like strncpy but ensures dst is always
108 * \param dst Destination for copy
109 * \param src Source string to copy
110 * \param maxncpy Maximum number of characters to copy (generally
112 * \retval Returns dst
114 char *BLI_strncpy(char *__restrict dst, const char *__restrict src, const size_t maxncpy)
116 size_t srclen = BLI_strnlen(src, maxncpy - 1);
117 BLI_assert(maxncpy != 0);
120 memset(dst, 0xff, sizeof(*dst) * maxncpy);
123 memcpy(dst, src, srclen);
129 * Like strncpy but ensures dst is always
132 * \note This is a duplicate of #BLI_strncpy that returns bytes copied.
133 * And is a drop in replacement for 'snprintf(str, sizeof(str), "%s", arg);'
135 * \param dst Destination for copy
136 * \param src Source string to copy
137 * \param maxncpy Maximum number of characters to copy (generally
139 * \retval The number of bytes copied (The only difference from BLI_strncpy).
141 size_t BLI_strncpy_rlen(char *__restrict dst, const char *__restrict src, const size_t maxncpy)
143 size_t srclen = BLI_strnlen(src, maxncpy - 1);
144 BLI_assert(maxncpy != 0);
147 memset(dst, 0xff, sizeof(*dst) * maxncpy);
150 memcpy(dst, src, srclen);
155 size_t BLI_strcpy_rlen(char *__restrict dst, const char *__restrict src)
157 size_t srclen = strlen(src);
158 memcpy(dst, src, srclen + 1);
163 * Portable replacement for #vsnprintf
165 size_t BLI_vsnprintf(char *__restrict buffer, size_t maxncpy, const char *__restrict format, va_list arg)
169 BLI_assert(buffer != NULL);
170 BLI_assert(maxncpy > 0);
171 BLI_assert(format != NULL);
173 n = (size_t)vsnprintf(buffer, maxncpy, format, arg);
175 if (n != -1 && n < maxncpy) {
179 buffer[maxncpy - 1] = '\0';
186 * Portable replacement for #snprintf
188 size_t BLI_snprintf(char *__restrict dst, size_t maxncpy, const char *__restrict format, ...)
194 memset(dst, 0xff, sizeof(*dst) * maxncpy);
197 va_start(arg, format);
198 n = BLI_vsnprintf(dst, maxncpy, format, arg);
205 * Print formatted string into a newly #MEM_mallocN'd string
208 char *BLI_sprintfN(const char *__restrict format, ...)
214 BLI_assert(format != NULL);
216 va_start(arg, format);
218 ds = BLI_dynstr_new();
219 BLI_dynstr_vappendf(ds, format, arg);
220 n = BLI_dynstr_get_cstring(ds);
229 /* match pythons string escaping, assume double quotes - (")
230 * TODO: should be used to create RNA animation paths.
231 * TODO: support more fancy string escaping. current code is primitive
232 * this basically is an ascii version of PyUnicode_EncodeUnicodeEscape()
233 * which is a useful reference. */
234 size_t BLI_strescape(char *__restrict dst, const char *__restrict src, const size_t maxncpy)
238 BLI_assert(maxncpy != 0);
240 while (len < maxncpy) {
248 /* less common but should also be support */
252 if (len + 1 < maxncpy) {
257 /* not enough space to escape */
278 * Makes a copy of the text within the "" that appear after some text 'blahblah'
279 * i.e. for string 'pose["apples"]' with prefix 'pose[', it should grab "apples"
281 * - str: is the entire string to chop
282 * - prefix: is the part of the string to leave out
284 * Assume that the strings returned must be freed afterwards, and that the inputs will contain
287 * \return the offset and a length so as to avoid doing an allocation.
289 char *BLI_str_quoted_substrN(const char *__restrict str, const char *__restrict prefix)
291 size_t prefixLen = strlen(prefix);
292 const char *startMatch, *endMatch;
294 /* get the starting point (i.e. where prefix starts, and add prefixLen+1 to it to get be after the first " */
295 startMatch = strstr(str, prefix) + prefixLen + 1;
297 /* get the end point (i.e. where the next occurance of " is after the starting point) */
299 endMatch = startMatch;
300 while ((endMatch = strchr(endMatch, '"'))) {
301 if (LIKELY(*(endMatch - 1) != '\\')) {
310 /* return the slice indicated */
311 return BLI_strdupn(startMatch, (size_t)(endMatch - startMatch));
314 return BLI_strdupn("", 0);
318 * string with all instances of substr_old replaced with substr_new,
319 * Returns a copy of the cstring \a str into a newly mallocN'd
322 * \note A rather wasteful string-replacement utility, though this shall do for now...
323 * Feel free to replace this with an even safe + nicer alternative
325 * \param str The string to replace occurrences of substr_old in
326 * \param substr_old The text in the string to find and replace
327 * \param substr_new The text in the string to find and replace
328 * \retval Returns the duplicated string
330 char *BLI_replacestrN(const char *__restrict str, const char *__restrict substr_old, const char *__restrict substr_new)
333 size_t len_old = strlen(substr_old);
336 BLI_assert(substr_old[0] != '\0');
338 /* while we can still find a match for the old substring that we're searching for,
339 * keep dicing and replacing
341 while ((match = strstr(str, substr_old))) {
342 /* the assembly buffer only gets created when we actually need to rebuild the string */
344 ds = BLI_dynstr_new();
346 /* if the match position does not match the current position in the string,
347 * copy the text up to this position and advance the current position in the string
350 /* add the segment of the string from str to match to the buffer, then restore the value at match
352 BLI_dynstr_nappend(ds, str, (match - str));
354 /* now our current position should be set on the start of the match */
358 /* add the replacement text to the accumulation buffer */
359 BLI_dynstr_append(ds, substr_new);
361 /* advance the current position of the string up to the end of the replaced segment */
365 /* finish off and return a new string that has had all occurrences of */
369 /* add what's left of the string to the assembly buffer
370 * - we've been adjusting str to point at the end of the replaced segments
372 BLI_dynstr_append(ds, str);
374 /* convert to new c-string (MEM_malloc'd), and free the buffer */
375 str_new = BLI_dynstr_get_cstring(ds);
381 /* just create a new copy of the entire string - we avoid going through the assembly buffer
382 * for what should be a bit more efficiency...
384 return BLI_strdup(str);
389 * Compare two strings without regard to case.
391 * \retval True if the strings are equal, false otherwise.
393 int BLI_strcaseeq(const char *a, const char *b)
395 return (BLI_strcasecmp(a, b) == 0);
399 * Portable replacement for #strcasestr (not available in MSVC)
401 char *BLI_strcasestr(const char *s, const char *find)
406 if ((c = *find++) != 0) {
411 if ((sc = *s++) == 0)
415 } while (BLI_strncasecmp(s, find, len) != 0);
422 int BLI_strcasecmp(const char *s1, const char *s2)
425 register char c1, c2;
445 int BLI_strncasecmp(const char *s1, const char *s2, size_t len)
448 register char c1, c2;
450 for (i = 0; i < len; i++) {
468 /* compare number on the left size of the string */
469 static int left_number_strcmp(const char *s1, const char *s2, int *tiebreaker)
471 const char *p1 = s1, *p2 = s2;
472 int numdigit, numzero1, numzero2;
474 /* count and skip leading zeros */
475 for (numzero1 = 0; *p1 && (*p1 == '0'); numzero1++)
477 for (numzero2 = 0; *p2 && (*p2 == '0'); numzero2++)
480 /* find number of consecutive digits */
481 for (numdigit = 0; ; numdigit++) {
482 if (isdigit(*(p1 + numdigit)) && isdigit(*(p2 + numdigit)))
484 else if (isdigit(*(p1 + numdigit)))
485 return 1; /* s2 is bigger */
486 else if (isdigit(*(p2 + numdigit)))
487 return -1; /* s1 is bigger */
492 /* same number of digits, compare size of number */
494 int compare = (int)strncmp(p1, p2, (size_t)numdigit);
500 /* use number of leading zeros as tie breaker if still equal */
501 if (*tiebreaker == 0) {
502 if (numzero1 > numzero2)
504 else if (numzero1 < numzero2)
511 /* natural string compare, keeping numbers in order */
512 int BLI_natstrcmp(const char *s1, const char *s2)
514 register int d1 = 0, d2 = 0;
515 register char c1, c2;
518 /* if both chars are numeric, to a left_number_strcmp().
519 * then increase string deltas as long they are
520 * numeric, else do a tolower and char compare */
523 c1 = tolower(s1[d1]);
524 c2 = tolower(s2[d2]);
526 if (isdigit(c1) && isdigit(c2)) {
527 int numcompare = left_number_strcmp(s1 + d1, s2 + d2, &tiebreaker);
533 while (isdigit(s1[d1]))
536 while (isdigit(s2[d2]))
539 c1 = tolower(s1[d1]);
540 c2 = tolower(s2[d2]);
543 /* first check for '.' so "foo.bar" comes before "foo 1.bar" */
544 if (c1 == '.' && c2 != '.')
546 if (c1 != '.' && c2 == '.')
564 /* we might still have a different string because of lower/upper case, in
565 * that case fall back to regular string comparison */
566 return strcmp(s1, s2);
569 void BLI_timestr(double _time, char *str, size_t maxlen)
571 /* format 00:00:00.00 (hr:min:sec) string has to be 12 long */
572 int hr = ( (int) _time) / (60 * 60);
573 int min = (((int) _time) / 60 ) % 60;
574 int sec = ( (int) _time) % 60;
575 int hun = ( (int) (_time * 100.0)) % 100;
578 BLI_snprintf(str, maxlen, "%.2d:%.2d:%.2d.%.2d", hr, min, sec, hun);
581 BLI_snprintf(str, maxlen, "%.2d:%.2d.%.2d", min, sec, hun);
585 /* determine the length of a fixed-size string */
586 size_t BLI_strnlen(const char *s, const size_t maxlen)
590 for (len = 0; len < maxlen; len++, s++) {
597 void BLI_ascii_strtolower(char *str, const size_t len)
601 for (i = 0; (i < len) && str[i]; i++)
602 if (str[i] >= 'A' && str[i] <= 'Z')
606 void BLI_ascii_strtoupper(char *str, const size_t len)
610 for (i = 0; (i < len) && str[i]; i++)
611 if (str[i] >= 'a' && str[i] <= 'z')
616 * Strip trailing zeros from a float, eg:
622 * \return The number of zeto's stripped.
624 int BLI_str_rstrip_float_zero(char *str, const char pad)
626 char *p = strchr(str, '.');
630 p++; /* position at first decimal place */
631 end_p = p + (strlen(p) - 1); /* position at last character */
633 while (end_p != p && *end_p == '0') {
644 * Return index of a string in a string array.
646 * \param str The string to find.
647 * \param str_array Array of strings.
648 * \param str_array_len The length of the array, or -1 for a NULL-terminated array.
649 * \return The index of str in str_array or -1.
651 int BLI_str_index_in_array_n(const char *str, const char **str_array, const int str_array_len)
654 const char **str_iter = str_array;
656 for (index = 0; index < str_array_len; str_iter++, index++) {
657 if (STREQ(str, *str_iter)) {
665 * Return index of a string in a string array.
667 * \param str The string to find.
668 * \param str_array Array of strings, (must be NULL-terminated).
669 * \return The index of str in str_array or -1.
671 int BLI_str_index_in_array(const char *str, const char **str_array)
674 const char **str_iter = str_array;
676 for (index = 0; *str_iter; str_iter++, index++) {
677 if (STREQ(str, *str_iter)) {
685 * Find the first char matching one of the chars in \a delim, from left.
687 * \param str The string to search within.
688 * \param delim The set of delimiters to search for, as unicode values.
689 * \param sep Return value, set to the first delimiter found (or NULL if none found).
690 * \param suf Return value, set to next char after the first delimiter found (or NULL if none found).
691 * \return The length of the prefix (i.e. *sep - str).
693 size_t BLI_str_partition(const char *str, const char delim[], char **sep, char **suf)
695 return BLI_str_partition_ex(str, delim, sep, suf, false);
699 * Find the first char matching one of the chars in \a delim, from right.
701 * \param str The string to search within.
702 * \param delim The set of delimiters to search for, as unicode values.
703 * \param sep Return value, set to the first delimiter found (or NULL if none found).
704 * \param suf Return value, set to next char after the first delimiter found (or NULL if none found).
705 * \return The length of the prefix (i.e. *sep - str).
707 size_t BLI_str_rpartition(const char *str, const char delim[], char **sep, char **suf)
709 return BLI_str_partition_ex(str, delim, sep, suf, true);
713 * Find the first char matching one of the chars in \a delim, either from left or right.
715 * \param str The string to search within.
716 * \param delim The set of delimiters to search for, as unicode values.
717 * \param sep Return value, set to the first delimiter found (or NULL if none found).
718 * \param suf Return value, set to next char after the first delimiter found (or NULL if none found).
719 * \param from_right If %true, search from the right of \a str, else, search from its left.
720 * \return The length of the prefix (i.e. *sep - str).
722 size_t BLI_str_partition_ex(const char *str, const char delim[], char **sep, char **suf, const bool from_right)
725 char *(*func)(const char *str, int c) = from_right ? strrchr : strchr;
729 for (d = delim; *d != '\0'; ++d) {
730 char *tmp = func(str, *d);
732 if (tmp && (from_right ? (*sep < tmp) : (!*sep || *sep > tmp))) {
739 return (size_t)(*sep - str);