Debian Codegraph @

src/util/strutl.c

raw
1 /*
2 * This file is part of libbdplus
3 * Copyright (C) 2008-2010 Accident
4 * Copyright (C) 2013 VideoLAN
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library. If not, see
18 * <http://www.gnu.org/licenses/>.
19 */
20
21 #if HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include "strutl.h"
26
27 #include "macro.h"
28
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 char *str_dup(const char *str)
35 {
36 char *dup = NULL;
37
38 if (str) {
39 size_t size = strlen(str) + 1;
40 dup = malloc(size);
41 if (dup) {
42 memcpy(dup, str, size);
43 }
44 }
45 return dup;
46 }
47
48 char *str_printf(const char *fmt, ...)
49 {
50 /* Guess we need no more than 100 bytes. */
51 va_list ap;
52 int len;
53 int size = 100;
54 char *tmp, *str = NULL;
55
56 while (1) {
57
58 tmp = realloc(str, size);
59 if (tmp == NULL) {
60 X_FREE(str);
61 return NULL;
62 }
63 str = tmp;
64
65 /* Try to print in the allocated space. */
66 va_start(ap, fmt);
67 len = vsnprintf(str, size, fmt, ap);
68 va_end(ap);
69
70 /* If that worked, return the string. */
71 if (len > -1 && len < size) {
72 return str;
73 }
74
75 /* Else try again with more space. */
76 if (len > -1) /* glibc 2.1 */
77 size = len+1; /* precisely what is needed */
78 else /* glibc 2.0 */
79 size *= 2; /* twice the old size */
80 }
81 }
82
83 const char *str_next_line(const char *p)
84 {
85 while (*p && *p != '\r' && *p != '\n') {
86 p++;
87 }
88 while (*p && (*p == '\r' || *p == '\n' || *p == ' ')) {
89 p++;
90 }
91
92 return p;
93 }
94
95 const char *str_skip_white(const char *p)
96 {
97 while (*p && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t')) {
98 p++;
99 }
100
101 return p;
102 }
103
104 char *str_print_hex(char *out, const uint8_t *buf, int count)
105 {
106 int zz;
107 for (zz = 0; zz < count; zz++) {
108 sprintf(out + (zz * 2), "%02x", buf[zz]);
109 }
110
111 return out;
112 }