Mercurial > trustbridge
view common/strhelp.c @ 134:5f830969e4a1
Added missing include.
author | Sascha Wilde <wilde@intevation.de> |
---|---|
date | Mon, 24 Mar 2014 15:17:16 +0100 |
parents | c719d3fdbc15 |
children | 3fb6ddd6b70d |
line wrap: on
line source
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> static void out_of_core(void) { fputs("\nfatal: out of memory\n", stderr); exit(2); } void * xmalloc( size_t n ) { void *p = malloc( n ); if( !p ) out_of_core(); return p; } void * xrealloc( void *a, size_t n ) { void *p = realloc( a, n ); if( !p ) out_of_core(); return p; } char * xstrndup( const char *string, const size_t len ) { char *p = xmalloc( len + 1 ); memcpy( p, string, len ); p[len] = '\0'; return p; } unsigned int strv_length (char **str_array) { unsigned int i = 0; if (!str_array) return 0; while (str_array[i]) ++i; return i; } void strv_append (char ***pArray, const char *string, const size_t len) { unsigned int old_len = 0; if (!*pArray) { *pArray = xmalloc(2 * sizeof(char*)); (*pArray)[0] = xstrndup(string, len); (*pArray)[1] = NULL; return; } old_len = strv_length(*pArray); *pArray = xrealloc(*pArray, sizeof(char**) * (old_len + 2)); (*pArray)[old_len] = xstrndup(string, len); (*pArray)[old_len + 1] = NULL; } void str_append_str(char **pDst, size_t *dst_len, const char *appendage, const size_t len) { if (!appendage) return; if (!(*pDst)) { *pDst = xstrndup(appendage, len); *dst_len = len; } else { size_t new_size = (*dst_len) + len + 1; char *p_old = *pDst; *pDst = xmalloc(new_size); strncpy(*pDst, p_old, *dst_len); strncpy(*pDst + *dst_len, appendage, len); *dst_len = new_size - 1; (*pDst)[*dst_len] = '\0'; free (p_old); } } void strv_free (char **str_array) { if (str_array) { int i; for (i = 0; str_array[i] != NULL; i++) free (str_array[i]); free (str_array); } } bool str_equal (char *s1, char *s2) { size_t l1 = strlen(s1); size_t l2 = strlen(s2); if ((l1 == l2) && (strncmp(s1, s2, l1) == 0)) return true; else return false; } bool str_starts_with (char *s1, char *s2) { if (strncmp(s1, s2, strlen(s2)) == 0) return true; else return false; } void str_trim (char **s) { size_t i; while (isspace(**s)) (*s)++; i = strlen(*s); while (isspace((*s)[--i])) (*s)[i] = '\0'; }