forked from cleech/open-isns
-
Notifications
You must be signed in to change notification settings - Fork 22
/
parser.c
134 lines (112 loc) · 2.16 KB
/
parser.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
* parser.c - simple line based parser
*
* Copyright (C) 2006, 2007 Olaf Kirch <[email protected]>
*/
#include <stdlib.h>
#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <err.h>
#include <libisns/util.h>
/*
* By default, the parser will recognize any white space
* as "word" separators.
* If you need additional separators, you can put them
* here.
*/
const char * parser_separators = NULL;
const char * parser_punctuation = "=";
char *
parser_get_next_line(FILE *fp)
{
static char buffer[8192];
unsigned int n = 0, count = 0;
int c, continuation = 0;
while (n < sizeof(buffer) - 1) {
c = fgetc(fp);
if (c == EOF)
break;
count++;
if (c == '\r')
continue;
/* Discard all blanks
* following a backslash-newline
*/
if (continuation) {
if (c == ' ' || c == '\t')
continue;
continuation = 0;
}
if (c == '\n') {
if (n && buffer[n-1] == '\\') {
buffer[--n] = '\0';
continuation = 1;
}
while (n && isspace(buffer[n-1]))
buffer[--n] = '\0';
if (!continuation)
break;
buffer[n++] = ' ';
continue;
}
buffer[n++] = c;
}
if (count == 0)
return NULL;
buffer[n] = '\0';
return buffer;
}
static inline int
is_separator(char c)
{
if (isspace(c))
return 1;
return parser_separators && c && strchr(parser_separators, c);
}
static inline int
is_punctuation(char c)
{
return parser_punctuation && c && strchr(parser_punctuation, c);
}
char *
parser_get_next_word(char **sp)
{
static char buffer[512];
char *s = *sp, *p = buffer;
while (is_separator(*s))
++s;
if (*s == '\0')
goto done;
if (is_punctuation(*s)) {
*p++ = *s++;
goto done;
}
while (*s && !is_separator(*s) && !is_punctuation(*s))
*p++ = *s++;
done:
*p++ = '\0';
*sp = s;
return buffer[0]? buffer : NULL;
}
int
parser_split_line(char *line, unsigned int argsmax, char **argv)
{
unsigned int argc = 0;
char *s;
while (argc < argsmax && (s = parser_get_next_word(&line)))
argv[argc++] = strdup(s);
return argc;
}
char *
parser_get_rest_of_line(char **sp)
{
char *s = *sp, *res = NULL;
while (is_separator(*s))
++s;
*sp = "";
if (*s != '\0')
res = s;
return res;
}