9f0eae6b8ce0295c4c3698b1371f2ff4195e47f7
[apps/madmutt.git] / lib / str.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #include <stdlib.h>
12 #include <string.h>
13 #include <ctype.h>
14
15 #include <lib-lib/mem.h>
16 #include <lib-lib/str.h>
17
18 #include "str.h"
19
20 void str_adjust (char **p)
21 {
22   if (!p || !*p)
23     return;
24   p_realloc(p, m_strlen(*p) + 1);
25 }
26
27 /* convert all characters in the string to lowercase */
28 char *str_tolower (char *s)
29 {
30   char *p = s;
31
32   while (*p) {
33     *p = tolower ((unsigned char) *p);
34     p++;
35   }
36
37   return (s);
38 }
39
40 /* NULL-pointer aware string comparison functions */
41
42 char *str_substrcpy (char *dest, const char *beg, const char *end,
43                       size_t destlen)
44 {
45   size_t len;
46
47   len = end - beg;
48   if (len > destlen - 1)
49     len = destlen - 1;
50   memcpy (dest, beg, len);
51   dest[len] = 0;
52   return dest;
53 }
54
55 char *str_substrdup(const char *begin, const char *end)
56 {
57     return p_dupstr(begin, (end ? end - begin : strlen(begin)));
58 }
59
60 const char *str_isstr (const char *haystack, const char *needle)
61 {
62   const char *p, *q;
63
64   if (!haystack)
65     return NULL;
66   if (!needle)
67     return (haystack);
68
69   while (*(p = haystack)) {
70     for (q = needle;
71          *p && *q &&
72          tolower ((unsigned char) *p) == tolower ((unsigned char) *q);
73          p++, q++);
74     if (!*q)
75       return (haystack);
76     haystack++;
77   }
78   return NULL;
79 }
80
81 int str_eq (const char* s1, const char* s2) {
82   int l = m_strlen(s1);
83
84   if (l != m_strlen(s2))
85     return (0);
86   return (m_strncmp(s1, s2, l) == 0);
87 }
88
89 void str_skip_trailws (char *s) {
90   char *p;
91
92   for (p = s + m_strlen(s) - 1; p >= s && ISSPACE (*p); p--)
93     *p = 0;
94 }