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