+static inline void procfile_parser(procfile *ff) {
+ // debug(D_PROCFILE, PF_PREFIX ": Parsing file '%s'", ff->filename);
+
+ char *s = ff->data // our current position
+ , *e = &ff->data[ff->len] // the terminating null
+ , *t = ff->data; // the first character of a quoted or a parenthesized string
+
+ // the look up array to find our type of character
+ PF_CHAR_TYPE *separators = ff->separators;
+
+ char quote = 0; // the quote character - only when in quoted string
+
+ size_t
+ l = 0 // counts the number of lines we added
+ , w = 0 // counts the number of words we added
+ , opened = 0; // counts the number of open parenthesis
+
+ ff->lines = pflines_add(ff->lines, w);
+
+ while(likely(s < e)) {
+ // we are not at the end
+ PF_CHAR_TYPE ct = separators[(unsigned char)(*s)];
+
+ // this is faster than a switch()
+ if(likely(ct == PF_CHAR_IS_WORD)) {
+ s++;
+ }
+ else if(likely(ct == PF_CHAR_IS_SEPARATOR)) {
+ if(unlikely(quote || opened)) {
+ // we are inside a quote
+ s++;
+ continue;
+ }
+
+ if(unlikely(s == t)) {
+ // skip all leading white spaces
+ t = ++s;
+ continue;
+ }
+
+ // end of word
+ *s = '\0';
+
+ ff->words = pfwords_add(ff->words, t);
+ ff->lines->lines[l].words++;
+ w++;
+
+ t = ++s;
+ }
+ else if(likely(ct == PF_CHAR_IS_NEWLINE)) {
+ // end of line
+ *s = '\0';
+
+ ff->words = pfwords_add(ff->words, t);
+ ff->lines->lines[l].words++;
+ w++;
+
+ // debug(D_PROCFILE, PF_PREFIX ": ended line %d with %d words", l, ff->lines->lines[l].words);
+
+ ff->lines = pflines_add(ff->lines, w);
+ l++;
+
+ t = ++s;
+ }
+ else if(likely(ct == PF_CHAR_IS_QUOTE)) {
+ if(unlikely(!quote && s == t)) {
+ // quote opened at the beginning
+ quote = *s;
+ t = ++s;
+ }
+ else if(unlikely(quote && quote == *s)) {
+ // quote closed
+ quote = 0;
+
+ *s = '\0';
+ ff->words = pfwords_add(ff->words, t);
+ ff->lines->lines[l].words++;
+ w++;
+
+ t = ++s;
+ }
+ else
+ s++;
+ }
+ else if(likely(ct == PF_CHAR_IS_OPEN)) {
+ if(s == t) {
+ opened++;
+ t = ++s;
+ }
+ else if(opened) {
+ opened++;
+ s++;
+ }
+ else
+ s++;
+ }
+ else if(likely(ct == PF_CHAR_IS_CLOSE)) {
+ if(opened) {
+ opened--;
+
+ if(!opened) {
+ *s = '\0';
+ ff->words = pfwords_add(ff->words, t);
+ ff->lines->lines[l].words++;
+ w++;
+
+ t = ++s;
+ }
+ else
+ s++;
+ }
+ else
+ s++;
+ }
+ else
+ fatal("Internal Error: procfile_readall() does not handle all the cases.");
+ }
+
+ if(likely(s > t && t < e)) {
+ // the last word
+ if(likely(ff->len < ff->size))
+ *s = '\0';
+ else {
+ // we are going to loose the last byte
+ ff->data[ff->size - 1] = '\0';
+ }
+
+ ff->words = pfwords_add(ff->words, t);
+ ff->lines->lines[l].words++;
+ }
+}