eina_str speedups.
[framework/uifw/eina.git] / src / lib / eina_str.c
1 /*
2  * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2
3  */
4 /* Leave the OpenBSD version below so we can track upstream fixes */
5 /*      $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $        */
6
7 /*
8  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
9  *
10  * Permission to use, copy, modify, and distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22
23 /*
24  * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <limits.h>
35
36 #ifdef HAVE_ICONV
37 # include <errno.h>
38 # include <iconv.h>
39 #endif
40
41 #include "eina_private.h"
42 #include "eina_str.h"
43
44 /*============================================================================*
45  *                                  Local                                     *
46  *============================================================================*/
47
48 /**
49  * @cond LOCAL
50  */
51
52 /*
53  * Internal helper function used by eina_str_has_suffix() and
54  * eina_str_has_extension()
55  */
56 static inline Eina_Bool
57 eina_str_has_suffix_helper(const char *str,
58                            const char *suffix,
59                            int (*cmp)(const char *, const char *))
60 {
61    size_t str_len;
62    size_t suffix_len;
63
64    str_len = strlen(str);
65    suffix_len = eina_strlen_bounded(suffix, str_len);
66    if (suffix_len == (size_t)-1)
67      return EINA_FALSE;
68
69    return cmp(str + str_len - suffix_len, suffix) == 0;
70 }
71
72 static inline char **
73 eina_str_split_full_helper(const char *str, const char *delim, int max_tokens, unsigned int *elements)
74 {
75    char *s, **str_array;
76    const char *src;
77    size_t len, dlen;
78    unsigned int tokens;
79
80    dlen = strlen(delim);
81    if (dlen == 0)
82      {
83         if (elements) *elements = 0;
84         return NULL;
85      }
86
87    tokens = 0;
88    src = str;
89    /* count tokens and check strlen(str) */
90    while (*src != '\0')
91      {
92         const char *d = delim, *d_end = d + dlen;
93         const char *tmp = src;
94         for (; (d < d_end) && (*tmp != '\0'); d++, tmp++)
95           {
96              if (EINA_LIKELY(*d != *tmp))
97                break;
98           }
99         if (EINA_UNLIKELY(d == d_end))
100           {
101              src = tmp;
102              tokens++;
103           }
104         else
105           src++;
106      }
107    len = src - str;
108
109    if ((max_tokens > 0) && (tokens > (unsigned int)max_tokens))
110      tokens = max_tokens;
111
112    str_array = malloc(sizeof(char *) * (tokens + 2));
113    if (!str_array)
114      {
115         if (elements) *elements = 0;
116         return NULL;
117      }
118
119    s = malloc(len + 1);
120    if (!s)
121      {
122         free(str_array);
123         if (elements) *elements = 0;
124         return NULL;
125      }
126
127    /* copy tokens and string */
128    tokens = 0;
129    str_array[0] = s;
130    src = str;
131    while (*src != '\0')
132      {
133         const char *d = delim, *d_end = d + dlen;
134         const char *tmp = src;
135         for (; (d < d_end) && (*tmp != '\0'); d++, tmp++)
136           {
137              if (EINA_LIKELY(*d != *tmp))
138                break;
139           }
140         if (EINA_UNLIKELY(d == d_end))
141           {
142              src = tmp;
143              *s = '\0';
144              s += dlen;
145              tokens++;
146              str_array[tokens] = s;
147           }
148         else
149           {
150              *s = *src;
151              s++;
152              src++;
153           }
154      }
155    *s = '\0';
156    str_array[tokens + 1] = NULL;
157    if (elements) *elements = (tokens + 1);
158    return str_array;
159 }
160
161 /**
162  * @endcond
163  */
164
165 /*============================================================================*
166  *                                 Global                                     *
167  *============================================================================*/
168
169 /*============================================================================*
170  *                                   API                                      *
171  *============================================================================*/
172
173
174 /**
175  * @brief Copy a c-string to another.
176  *
177  * @param dst The destination string.
178  * @param src The source string.
179  * @param siz The size of the destination string.
180  * @return The length of the source string.
181  *
182  * This function copies up to @p siz - 1 characters from the
183  * NUL-terminated string @p src to @p dst, NUL-terminating the result
184  * (unless @p siz is equal to 0). The returned value is the length of
185  * @p src. If the returned value is greater than @p siz, truncation
186  * occured.
187  */
188 EAPI size_t
189 eina_strlcpy(char *dst, const char *src, size_t siz)
190 {
191 #ifdef HAVE_STRLCPY
192    return strlcpy(dst, src, siz);
193 #else
194    char *d = dst;
195    const char *s = src;
196    size_t n = siz;
197
198    /* Copy as many bytes as will fit */
199    if (n != 0)
200      {
201         while (--n != 0)
202           {
203              if ((*d++ = *s++) == '\0')
204                break;
205           }
206      }
207
208    /* Not enough room in dst, add NUL and traverse rest of src */
209    if (n == 0)
210      {
211         if (siz != 0)
212           *d = '\0';                /* NUL-terminate dst */
213         while (*s++)
214           ;
215      }
216
217    return(s - src - 1);        /* count does not include NUL */
218 #endif
219 }
220
221 /**
222  * @brief Append a c-string.
223  *
224  * @param dst The destination string.
225  * @param src The source string.
226  * @param siz The size of the destination string.
227  * @return The length of the source string plus MIN(siz, strlen(initial dst))
228  *
229  * This function appends @p src to @p dst of size @p siz (unlike
230  * strncat, @p siz is the full size of @p dst, not space left).  At
231  * most @p siz - 1 characters will be copied.  Always NUL terminates
232  * (unless @p siz <= strlen(dst)). This function returns strlen(src) +
233  * MIN(siz, strlen(initial dst)). If the returned value is greater or
234  * equal than @p siz, truncation occurred.
235  */
236 EAPI size_t
237 eina_strlcat(char *dst, const char *src, size_t siz)
238 {
239    char *d = dst;
240    const char *s = src;
241    size_t n = siz;
242    size_t dlen;
243
244    /* Find the end of dst and adjust bytes left but don't go past end */
245    while (n-- != 0 && *d != '\0')
246      d++;
247    dlen = d - dst;
248    n = siz - dlen;
249
250    if (n == 0)
251      return(dlen + strlen(s));
252    while (*s != '\0') {
253         if (n != 1) {
254              *d++ = *s;
255              n--;
256         }
257         s++;
258    }
259    *d = '\0';
260
261    return(dlen + (s - src));        /* count does not include NUL */
262 }
263
264 /**
265  * @brief Check if the given string has the given prefix.
266  *
267  * @param str The string to work with.
268  * @param prefix The prefix to check for.
269  * @return #EINA_TRUE if the string has the given prefix, #EINA_FALSE otherwise.
270  *
271  * This function returns #EINA_TRUE if @p str has the prefix
272  * @p prefix, #EINA_FALSE otherwise. If the length of @p prefix is
273  * greater than @p str, #EINA_FALSE is returned.
274  */
275 EAPI Eina_Bool
276 eina_str_has_prefix(const char *str, const char *prefix)
277 {
278    size_t str_len;
279    size_t prefix_len;
280
281    str_len = strlen(str);
282    prefix_len = eina_strlen_bounded(prefix, str_len);
283    if (prefix_len == (size_t)-1)
284      return EINA_FALSE;
285
286    return (strncmp(str, prefix, prefix_len) == 0);
287 }
288
289 /**
290  * @brief Check if the given string has the given suffix.
291  *
292  * @param str The string to work with.
293  * @param suffix The suffix to check for.
294  * @return #EINA_TRUE if the string has the given suffix, #EINA_FALSE otherwise.
295  *
296  * This function returns #EINA_TRUE if @p str has the suffix
297  * @p suffix, #EINA_FALSE otherwise. If the length of @p suffix is
298  * greater than @p str, #EINA_FALSE is returned.
299  */
300 /**
301  * @param str the string to work with
302  * @param suffix the suffix to check for
303  * @return true if str has the given suffix
304  * @brief checks if the string has the given suffix
305  */
306 EAPI Eina_Bool
307 eina_str_has_suffix(const char *str, const char *suffix)
308 {
309    return eina_str_has_suffix_helper(str, suffix, strcmp);
310 }
311
312 /**
313  * @brief Check if the given string has the given suffix.
314  *
315  * @param str The string to work with.
316  * @param ext The  extension to check for.
317  * @return #EINA_TRUE if the string has the given extension, #EINA_FALSE otherwise.
318  *
319  * This function does the same like eina_str_has_suffix(), but with a
320  * case insensitive compare.
321  */
322 EAPI Eina_Bool
323 eina_str_has_extension(const char *str, const char *ext)
324 {
325    return eina_str_has_suffix_helper(str, ext, strcasecmp);
326 }
327
328 /**
329  * @brief Split a string using a delimiter and returns number of elements.
330  *
331  * @param str The string to split.
332  * @param delim The string which specifies the places at which to split the string.
333  * @param max_tokens The maximum number of strings to split string into.
334  * @param elements Where to return the number of elements in returned
335  *        array (not counting the terminating @c NULL). May be @c NULL.
336  * @return A newly-allocated NULL-terminated array of strings.
337  *
338  * This functin splits @p str into a maximum of @p max_tokens pieces,
339  * using the given delimiter @p delim. @p delim is not included in any
340  * of the resulting strings, unless @p max_tokens is reached. If
341  * @p max_tokens is less than @c 1, the string is splitted completely. If
342  * @p max_tokens is reached, the last string in the returned string
343  * array contains the remainder of string. The returned value is a
344  * newly allocated NUL-terminated array of string. To free it, free
345  * the first element of the array and the array itself.
346  *
347  * @see eina_str_split()
348  */
349 EAPI char **
350 eina_str_split_full(const char *str, const char *delim, int max_tokens, unsigned int *elements)
351 {
352    return eina_str_split_full_helper(str, delim, max_tokens, elements);
353 }
354
355
356 /**
357  * @brief Split a string using a delimiter.
358  *
359  * @param str The string to split.
360  * @param delim The string which specifies the places at which to split the string.
361  * @param max_tokens The maximum number of strings to split string into.
362  * @return A newly-allocated NULL-terminated array of strings.
363  *
364  * This functin splits @p str into a maximum of @p max_tokens pieces,
365  * using the given delimiter @p delim. @p delim is not included in any
366  * of the resulting strings, unless @p max_tokens is reached. If
367  * @p max_tokens is less than @c 1, the string is splitted completely. If
368  * @p max_tokens is reached, the last string in the returned string
369  * array contains the remainder of string. The returned value is a
370  * newly allocated NUL-terminated array of string. To free it, free
371  * the first element of the array and the array itself.
372  */
373 EAPI char **
374 eina_str_split(const char *str, const char *delim, int max_tokens)
375 {
376    return eina_str_split_full_helper(str, delim, max_tokens, NULL);
377 }
378
379 /**
380  * @brief Join two strings of known length.
381  *
382  * @param dst The buffer to store the result.
383  * @param size Size (in byte) of the buffer.
384  * @param sep The separator character to use.
385  * @param a First string to use, before @p sep.
386  * @param a_len length of @p a.
387  * @param b Second string to use, after @p sep.
388  * @param b_len length of @p b.
389  * @return The number of characters printed.
390  *
391  * This function joins the strings @p a and @p b (in that order) and
392  * separate them with @p sep. The result is stored in the buffer
393  * @p dst and at most @p size - 1 characters will be written and the
394  * string is NULL-terminated. @p a_len is the length of @p a (not
395  * including '\0') and @p b_len is the length of @p b (not including
396  * '\0'). This function returns the number of characters printed (not
397  * including the trailing '\0' used to end output to strings). Just
398  * like snprintf(), it will not write more than @p size bytes, thus a
399  * returned value of @p size or more means that the output was
400  * truncated.
401  *
402  * @see eina_str_join()
403  * @see eina_str_join_static()
404  */
405 EAPI size_t
406 eina_str_join_len(char *dst, size_t size, char sep, const char *a, size_t a_len, const char *b, size_t b_len)
407 {
408    size_t ret = a_len + b_len + 1;
409    size_t off;
410
411    if (size < 1) return ret;
412
413    if (size <= a_len)
414      {
415         memcpy(dst, a, size - 1);
416         dst[size - 1] = '\0';
417         return ret;
418      }
419
420    memcpy(dst, a, a_len);
421    off = a_len;
422
423    if (size <= off + 1)
424      {
425         dst[size - 1] = '\0';
426         return ret;
427      }
428
429    dst[off] = sep;
430    off++;
431
432    if (size <= off + b_len + 1)
433      {
434         memcpy(dst + off, b, size - off - 1);
435         dst[size - 1] = '\0';
436         return ret;
437      }
438
439    memcpy(dst + off, b, b_len);
440    dst[off + b_len] = '\0';
441    return ret;
442 }
443
444 /**
445  * @brief Use iconv to convert a text string from one encoding to another
446  *
447  * @param enc_from encoding to convert from
448  * @param enc_to   encoding to convert to
449  * @param text     text to convert
450  *
451  */
452 #ifdef HAVE_ICONV
453 EAPI char *
454 eina_str_convert(const char *enc_from, const char *enc_to, const char *text)
455 {
456    iconv_t ic;
457    char *new_txt, *inp, *outp;
458    size_t inb, outb, outlen, tob, outalloc;
459
460    if (!text) return NULL;
461    ic = iconv_open(enc_to, enc_from);
462    if (ic == (iconv_t)(-1)) return NULL;
463    new_txt  = malloc(64);
464    inb      = strlen(text);
465    outb     = 64;
466    inp      = (char*)text;
467    outp     = new_txt;
468    outalloc = 64;
469    outlen   = 0;
470
471    for (;;)
472      {
473         size_t count;
474
475         tob = outb;
476         count = iconv(ic, &inp, &inb, &outp, &outb);
477         outlen += tob - outb;
478         if (count == (size_t)(-1))
479           {
480              if (errno == E2BIG)
481                {
482                   new_txt = realloc(new_txt, outalloc + 64);
483                   outp = new_txt + outlen;
484                   outalloc += 64;
485                   outb += 64;
486                }
487              else if (errno == EILSEQ)
488                {
489                   if (new_txt) free(new_txt);
490                   new_txt = NULL;
491                   break;
492                }
493              else if (errno == EINVAL)
494                {
495                   if (new_txt) free(new_txt);
496                   new_txt = NULL;
497                   break;
498                }
499              else
500                {
501                   if (new_txt) free(new_txt);
502                   new_txt = NULL;
503                   break;
504                }
505           }
506         if (inb == 0)
507           {
508              if (outalloc == outlen) new_txt = realloc(new_txt, outalloc + 1);
509              new_txt[outlen] = 0;
510              break;
511           }
512      }
513    iconv_close(ic);
514    return new_txt;
515 }
516 #else
517 EAPI char *
518 eina_str_convert(const char *enc_from __UNUSED__, const char *enc_to __UNUSED__, const char *text __UNUSED__)
519 {
520    return NULL;
521 }
522 #endif
523
524 /**
525  * @brief Put a \ before and Space( ), \ or ' in a string.
526  *
527  * @param str the string to escape
528  *
529  * A newly allocated string is returned.
530  */
531 EAPI char *
532 eina_str_escape(const char *str)
533 {
534    char *s2, *d;
535    const char *s;
536
537    s2 = malloc((strlen(str) * 2) + 1);
538    if (!s2) return NULL;
539    for (s = str, d = s2; *s != 0; s++, d++)
540      {
541         if ((*s == ' ') || (*s == '\\') || (*s == '\''))
542           {
543              *d = '\\';
544              d++;
545           }
546         *d = *s;
547      }
548    *d = 0;
549    return s2;
550 }