changed includes from ../mhl/ to <mhl/...>
[midnight-commander.git] / mhl / mhlstring.h
blob103b3e6c56df3b7c3128c4bc3102133aca0b0951
1 #ifndef __MHL_STRING_H
2 #define __MHL_STRING_H
4 #include <ctype.h>
5 #include <stdarg.h>
6 #include <mhl/mhlmemory.h>
8 #define mhl_str_dup(str) ((str ? strdup(str) : strdup("")))
9 #define mhl_str_ndup(str,len) ((str ? strndup(str,len) : strdup("")))
10 #define mhl_str_len(str) ((str ? strlen(str) : 0))
12 static inline char* mhl_str_trim(char* str)
14 if (!str) return NULL; // NULL string ?! bail out.
16 // find the first non-space
17 char* start; for (start=str; ((*str) && (!isspace(*str))); str++);
19 // only spaces ?
20 if (!(*str)) { *str = 0; return str; }
22 // get the size (cannot be empty - catched above)
23 size_t _sz = strlen(str);
25 // find the proper end
26 char* end;
27 for (end=(str+_sz-1); ((end>str) && (isspace(*end))); end--);
28 end[1] = 0; // terminate, just to be sure
30 // if we have no leading spaces, just trucate
31 if (start==str) { end++; *end = 0; return str; }
34 // if it' only one char, dont need memmove for that
35 if (start==end) { str[0]=*start; str[1]=0; return str; }
37 // by here we have a (non-empty) region between start end end
38 memmove(str,start,(end-start+1));
39 return str;
42 static inline void mhl_str_toupper(char* str)
44 if (str)
45 for (;*str;str++)
46 *str = toupper(*str);
49 #define __STR_CONCAT_MAX 32
50 /* _NEVER_ call this function directly ! */
51 static inline char* __mhl_str_concat_hlp(const char* base, ...)
53 static const char* arg_ptr[__STR_CONCAT_MAX];
54 static size_t arg_sz[__STR_CONCAT_MAX];
55 int count = 0;
56 size_t totalsize = 0;
58 // first pass: scan through the params and count string sizes
59 va_list par;
61 if (base)
63 arg_ptr[0] = base;
64 arg_sz[0] = totalsize = strlen(base);
65 count = 1;
68 va_list args;
69 va_start(args,base);
70 char* a;
71 // note: we use ((char*)(1)) as terminator - NULL is a valid argument !
72 while ((a = va_arg(args, char*))!=(char*)1)
74 // printf("a=%u\n", a);
75 if (a)
77 arg_ptr[count] = a;
78 arg_sz[count] = strlen(a);
79 totalsize += arg_sz[count];
80 count++;
84 if (!count)
85 return mhl_str_dup("");
87 // now as we know how much to copy, allocate the buffer
88 char* buffer = (char*)mhl_mem_alloc_u(totalsize+2);
89 char* current = buffer;
90 int x=0;
91 for (x=0; x<count; x++)
93 memcpy(current, arg_ptr[x], arg_sz[x]);
94 current += arg_sz[x];
97 *current = 0;
98 return buffer;
101 #define mhl_str_concat(...) (__mhl_str_concat_hlp(__VA_ARGS__, (char*)(1)))
103 static inline char* mhl_str_reverse(char* ptr)
105 if (!ptr) return NULL; // missing string
106 if (!(ptr[0] && ptr[1])) return ptr; // empty or 1-ch string
108 size_t _sz = strlen(ptr);
109 char* start = ptr;
110 char* end = ptr+_sz-1;
112 while (start<end)
114 char c = *start;
115 *start = *end;
116 *end = c;
117 start++;
118 end--;
121 return ptr;
124 #endif