hotplug2: patches from OpenWRT/svn
[tomato.git] / release / src / router / hotplug2 / parser_utils.c
blob09aa44405f6b34a26dcec43fa79ca0b77d676670
1 /*****************************************************************************\
2 * _ _ _ _ ___ *
3 * | || | ___ | |_ _ __ | | _ _ __ _ |_ ) *
4 * | __ |/ _ \| _|| '_ \| || || |/ _` | / / *
5 * |_||_|\___/ \__|| .__/|_| \_,_|\__, |/___| *
6 * |_| |___/ *
7 \*****************************************************************************/
9 #include <string.h>
10 #include <stdlib.h>
12 #include "mem_utils.h"
13 #include "parser_utils.h"
15 /**
16 * Creates a newly allocated null-terminated string representing line
17 * starting at a given pointer and ending at the closest newline. If
18 * no newline present, returns NULL. TODO, use dup_token
20 * @1 Starting pointer
21 * @2 Pointer where the end position is returned
23 * Returns: Newly allocated string containing the line or NULL
25 char *dup_line(char *start, char **nptr) {
26 char *ptr, *rv;
28 ptr = strchr(start, '\n');
29 if (ptr == NULL)
30 return NULL;
32 rv = xmalloc(ptr - start + 1);
33 memcpy(rv, start, ptr - start);
34 rv[ptr-start] = '\0';
36 if (nptr != NULL)
37 *nptr = ptr + 1;
39 return rv;
42 /**
43 * Returns a token delimited by the given function.
45 * @1 Starting pointer
46 * @2 Pointer where the end position is returned
47 * @3 Function that identifies the delimiter characters
49 * Returns: Newly allocated string containing the token or NULL
51 char *dup_token(char *start, char **nptr, int (*isdelimiter)(int)) {
52 char *ptr, *rv;
54 while (isdelimiter(*start) && *start)
55 start++;
57 ptr = start;
59 while (!isdelimiter(*ptr) && *ptr)
60 ptr++;
62 if (ptr == start)
63 return NULL;
65 rv = xmalloc(ptr - start + 1);
66 memcpy(rv, start, ptr - start);
67 rv[ptr-start] = '\0';
69 if (nptr != NULL) {
70 while (isdelimiter(*ptr))
71 ptr++;
72 *nptr = ptr ;
75 return rv;
78 /**
79 * Returns the last token delimited by the given function.
81 * @1 Starting pointer of the whole string
82 * @2 Starting position
83 * @3 Pointer where the end position is returned
84 * @4 Function that identifies the delimiter characters
86 * Returns: Newly allocated string containing the token or NULL
88 char *dup_token_r(char *start, char *start_string, char **nptr, int (*isdelimiter)(int)) {
89 char *ptr, *rv;
91 if (start <= start_string)
92 return NULL;
94 while (isdelimiter(*start) && (start > start_string))
95 start--;
97 if (start < start_string)
98 start = start_string;
100 ptr = start;
102 while (!isdelimiter(*ptr) && (ptr > start_string))
103 ptr--;
105 if (ptr <= start_string)
106 ptr = start_string;
107 else
108 ptr++;
110 rv = xmalloc(start - ptr + 2);
111 memcpy(rv, ptr, start - ptr + 1);
112 rv[start - ptr + 1] = '\0';
114 if (nptr != NULL) {
115 ptr--;
116 while ((ptr > start_string) && isdelimiter(*ptr))
117 ptr--;
119 if (ptr < start_string)
120 ptr = start_string;
122 *nptr = ptr;
125 return rv;