/[pcre]/code/trunk/pcrecpp.cc
ViewVC logotype

Contents of /code/trunk/pcrecpp.cc

Parent Directory Parent Directory | Revision Log Revision Log


Revision 91 - (hide annotations) (download)
Sat Feb 24 21:41:34 2007 UTC (7 years, 5 months ago) by nigel
File size: 28657 byte(s)
Load pcre-6.7 into code/trunk.

1 nigel 77 // Copyright (c) 2005, Google Inc.
2     // All rights reserved.
3     //
4     // Redistribution and use in source and binary forms, with or without
5     // modification, are permitted provided that the following conditions are
6     // met:
7     //
8     // * Redistributions of source code must retain the above copyright
9     // notice, this list of conditions and the following disclaimer.
10     // * Redistributions in binary form must reproduce the above
11     // copyright notice, this list of conditions and the following disclaimer
12     // in the documentation and/or other materials provided with the
13     // distribution.
14     // * Neither the name of Google Inc. nor the names of its
15     // contributors may be used to endorse or promote products derived from
16     // this software without specific prior written permission.
17     //
18     // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19     // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20     // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21     // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22     // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23     // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24     // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25     // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26     // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27     // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28     // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29     //
30     // Author: Sanjay Ghemawat
31    
32     #include <stdlib.h>
33     #include <stdio.h>
34     #include <ctype.h>
35     #include <limits.h> /* for SHRT_MIN, USHRT_MAX, etc */
36     #include <assert.h>
37     #include <errno.h>
38     #include <string>
39 nigel 81 #include <algorithm>
40 nigel 77 #include "config.h"
41     // We need this to compile the proper dll on windows/msys. This is copied
42     // from pcre_internal.h. It would probably be better just to include that.
43     #define PCRE_DEFINITION /* Win32 __declspec(export) trigger for .dll */
44     #include "pcre.h"
45     #include "pcre_stringpiece.h"
46     #include "pcrecpp.h"
47    
48    
49     namespace pcrecpp {
50    
51     // Maximum number of args we can set
52     static const int kMaxArgs = 16;
53     static const int kVecSize = (1 + kMaxArgs) * 3; // results + PCRE workspace
54    
55     // Special object that stands-in for no argument
56     Arg no_arg((void*)NULL);
57    
58     // If a regular expression has no error, its error_ field points here
59     static const string empty_string;
60    
61     // If the user doesn't ask for any options, we just use this one
62     static RE_Options default_options;
63    
64     void RE::Init(const char* pat, const RE_Options* options) {
65     pattern_ = pat;
66     if (options == NULL) {
67     options_ = default_options;
68     } else {
69     options_ = *options;
70     }
71     error_ = &empty_string;
72     re_full_ = NULL;
73     re_partial_ = NULL;
74    
75     re_partial_ = Compile(UNANCHORED);
76     if (re_partial_ != NULL) {
77     // Check for complicated patterns. The following change is
78     // conservative in that it may treat some "simple" patterns
79     // as "complex" (e.g., if the vertical bar is in a character
80     // class or is escaped). But it seems good enough.
81     if (strchr(pat, '|') == NULL) {
82     // Simple pattern: we can use position-based checks to perform
83     // fully anchored matches
84     re_full_ = re_partial_;
85     } else {
86     // We need a special pattern for anchored matches
87     re_full_ = Compile(ANCHOR_BOTH);
88     }
89     }
90     }
91    
92     RE::~RE() {
93     if (re_full_ != NULL && re_full_ != re_partial_) (*pcre_free)(re_full_);
94     if (re_partial_ != NULL) (*pcre_free)(re_partial_);
95     if (error_ != &empty_string) delete error_;
96     }
97    
98     pcre* RE::Compile(Anchor anchor) {
99     // First, convert RE_Options into pcre options
100     int pcre_options = 0;
101 nigel 81 pcre_options = options_.all_options();
102 nigel 77
103     // Special treatment for anchoring. This is needed because at
104     // runtime pcre only provides an option for anchoring at the
105     // beginning of a string (unless you use offset).
106     //
107     // There are three types of anchoring we want:
108     // UNANCHORED Compile the original pattern, and use
109     // a pcre unanchored match.
110     // ANCHOR_START Compile the original pattern, and use
111     // a pcre anchored match.
112     // ANCHOR_BOTH Tack a "\z" to the end of the original pattern
113     // and use a pcre anchored match.
114    
115     const char* compile_error;
116     int eoffset;
117     pcre* re;
118     if (anchor != ANCHOR_BOTH) {
119     re = pcre_compile(pattern_.c_str(), pcre_options,
120     &compile_error, &eoffset, NULL);
121     } else {
122     // Tack a '\z' at the end of RE. Parenthesize it first so that
123     // the '\z' applies to all top-level alternatives in the regexp.
124     string wrapped = "(?:"; // A non-counting grouping operator
125     wrapped += pattern_;
126     wrapped += ")\\z";
127     re = pcre_compile(wrapped.c_str(), pcre_options,
128     &compile_error, &eoffset, NULL);
129     }
130     if (re == NULL) {
131     if (error_ == &empty_string) error_ = new string(compile_error);
132     }
133     return re;
134     }
135    
136     /***** Matching interfaces *****/
137    
138     bool RE::FullMatch(const StringPiece& text,
139     const Arg& ptr1,
140     const Arg& ptr2,
141     const Arg& ptr3,
142     const Arg& ptr4,
143     const Arg& ptr5,
144     const Arg& ptr6,
145     const Arg& ptr7,
146     const Arg& ptr8,
147     const Arg& ptr9,
148     const Arg& ptr10,
149     const Arg& ptr11,
150     const Arg& ptr12,
151     const Arg& ptr13,
152     const Arg& ptr14,
153     const Arg& ptr15,
154     const Arg& ptr16) const {
155     const Arg* args[kMaxArgs];
156     int n = 0;
157     if (&ptr1 == &no_arg) goto done; args[n++] = &ptr1;
158     if (&ptr2 == &no_arg) goto done; args[n++] = &ptr2;
159     if (&ptr3 == &no_arg) goto done; args[n++] = &ptr3;
160     if (&ptr4 == &no_arg) goto done; args[n++] = &ptr4;
161     if (&ptr5 == &no_arg) goto done; args[n++] = &ptr5;
162     if (&ptr6 == &no_arg) goto done; args[n++] = &ptr6;
163     if (&ptr7 == &no_arg) goto done; args[n++] = &ptr7;
164     if (&ptr8 == &no_arg) goto done; args[n++] = &ptr8;
165     if (&ptr9 == &no_arg) goto done; args[n++] = &ptr9;
166     if (&ptr10 == &no_arg) goto done; args[n++] = &ptr10;
167     if (&ptr11 == &no_arg) goto done; args[n++] = &ptr11;
168     if (&ptr12 == &no_arg) goto done; args[n++] = &ptr12;
169     if (&ptr13 == &no_arg) goto done; args[n++] = &ptr13;
170     if (&ptr14 == &no_arg) goto done; args[n++] = &ptr14;
171     if (&ptr15 == &no_arg) goto done; args[n++] = &ptr15;
172     if (&ptr16 == &no_arg) goto done; args[n++] = &ptr16;
173     done:
174    
175     int consumed;
176     int vec[kVecSize];
177     return DoMatchImpl(text, ANCHOR_BOTH, &consumed, args, n, vec, kVecSize);
178     }
179    
180     bool RE::PartialMatch(const StringPiece& text,
181     const Arg& ptr1,
182     const Arg& ptr2,
183     const Arg& ptr3,
184     const Arg& ptr4,
185     const Arg& ptr5,
186     const Arg& ptr6,
187     const Arg& ptr7,
188     const Arg& ptr8,
189     const Arg& ptr9,
190     const Arg& ptr10,
191     const Arg& ptr11,
192     const Arg& ptr12,
193     const Arg& ptr13,
194     const Arg& ptr14,
195     const Arg& ptr15,
196     const Arg& ptr16) const {
197     const Arg* args[kMaxArgs];
198     int n = 0;
199     if (&ptr1 == &no_arg) goto done; args[n++] = &ptr1;
200     if (&ptr2 == &no_arg) goto done; args[n++] = &ptr2;
201     if (&ptr3 == &no_arg) goto done; args[n++] = &ptr3;
202     if (&ptr4 == &no_arg) goto done; args[n++] = &ptr4;
203     if (&ptr5 == &no_arg) goto done; args[n++] = &ptr5;
204     if (&ptr6 == &no_arg) goto done; args[n++] = &ptr6;
205     if (&ptr7 == &no_arg) goto done; args[n++] = &ptr7;
206     if (&ptr8 == &no_arg) goto done; args[n++] = &ptr8;
207     if (&ptr9 == &no_arg) goto done; args[n++] = &ptr9;
208     if (&ptr10 == &no_arg) goto done; args[n++] = &ptr10;
209     if (&ptr11 == &no_arg) goto done; args[n++] = &ptr11;
210     if (&ptr12 == &no_arg) goto done; args[n++] = &ptr12;
211     if (&ptr13 == &no_arg) goto done; args[n++] = &ptr13;
212     if (&ptr14 == &no_arg) goto done; args[n++] = &ptr14;
213     if (&ptr15 == &no_arg) goto done; args[n++] = &ptr15;
214     if (&ptr16 == &no_arg) goto done; args[n++] = &ptr16;
215     done:
216    
217     int consumed;
218     int vec[kVecSize];
219     return DoMatchImpl(text, UNANCHORED, &consumed, args, n, vec, kVecSize);
220     }
221    
222     bool RE::Consume(StringPiece* input,
223     const Arg& ptr1,
224     const Arg& ptr2,
225     const Arg& ptr3,
226     const Arg& ptr4,
227     const Arg& ptr5,
228     const Arg& ptr6,
229     const Arg& ptr7,
230     const Arg& ptr8,
231     const Arg& ptr9,
232     const Arg& ptr10,
233     const Arg& ptr11,
234     const Arg& ptr12,
235     const Arg& ptr13,
236     const Arg& ptr14,
237     const Arg& ptr15,
238     const Arg& ptr16) const {
239     const Arg* args[kMaxArgs];
240     int n = 0;
241     if (&ptr1 == &no_arg) goto done; args[n++] = &ptr1;
242     if (&ptr2 == &no_arg) goto done; args[n++] = &ptr2;
243     if (&ptr3 == &no_arg) goto done; args[n++] = &ptr3;
244     if (&ptr4 == &no_arg) goto done; args[n++] = &ptr4;
245     if (&ptr5 == &no_arg) goto done; args[n++] = &ptr5;
246     if (&ptr6 == &no_arg) goto done; args[n++] = &ptr6;
247     if (&ptr7 == &no_arg) goto done; args[n++] = &ptr7;
248     if (&ptr8 == &no_arg) goto done; args[n++] = &ptr8;
249     if (&ptr9 == &no_arg) goto done; args[n++] = &ptr9;
250     if (&ptr10 == &no_arg) goto done; args[n++] = &ptr10;
251     if (&ptr11 == &no_arg) goto done; args[n++] = &ptr11;
252     if (&ptr12 == &no_arg) goto done; args[n++] = &ptr12;
253     if (&ptr13 == &no_arg) goto done; args[n++] = &ptr13;
254     if (&ptr14 == &no_arg) goto done; args[n++] = &ptr14;
255     if (&ptr15 == &no_arg) goto done; args[n++] = &ptr15;
256     if (&ptr16 == &no_arg) goto done; args[n++] = &ptr16;
257     done:
258    
259     int consumed;
260     int vec[kVecSize];
261     if (DoMatchImpl(*input, ANCHOR_START, &consumed,
262     args, n, vec, kVecSize)) {
263     input->remove_prefix(consumed);
264     return true;
265     } else {
266     return false;
267     }
268     }
269    
270     bool RE::FindAndConsume(StringPiece* input,
271     const Arg& ptr1,
272     const Arg& ptr2,
273     const Arg& ptr3,
274     const Arg& ptr4,
275     const Arg& ptr5,
276     const Arg& ptr6,
277     const Arg& ptr7,
278     const Arg& ptr8,
279     const Arg& ptr9,
280     const Arg& ptr10,
281     const Arg& ptr11,
282     const Arg& ptr12,
283     const Arg& ptr13,
284     const Arg& ptr14,
285     const Arg& ptr15,
286     const Arg& ptr16) const {
287     const Arg* args[kMaxArgs];
288     int n = 0;
289     if (&ptr1 == &no_arg) goto done; args[n++] = &ptr1;
290     if (&ptr2 == &no_arg) goto done; args[n++] = &ptr2;
291     if (&ptr3 == &no_arg) goto done; args[n++] = &ptr3;
292     if (&ptr4 == &no_arg) goto done; args[n++] = &ptr4;
293     if (&ptr5 == &no_arg) goto done; args[n++] = &ptr5;
294     if (&ptr6 == &no_arg) goto done; args[n++] = &ptr6;
295     if (&ptr7 == &no_arg) goto done; args[n++] = &ptr7;
296     if (&ptr8 == &no_arg) goto done; args[n++] = &ptr8;
297     if (&ptr9 == &no_arg) goto done; args[n++] = &ptr9;
298     if (&ptr10 == &no_arg) goto done; args[n++] = &ptr10;
299     if (&ptr11 == &no_arg) goto done; args[n++] = &ptr11;
300     if (&ptr12 == &no_arg) goto done; args[n++] = &ptr12;
301     if (&ptr13 == &no_arg) goto done; args[n++] = &ptr13;
302     if (&ptr14 == &no_arg) goto done; args[n++] = &ptr14;
303     if (&ptr15 == &no_arg) goto done; args[n++] = &ptr15;
304     if (&ptr16 == &no_arg) goto done; args[n++] = &ptr16;
305     done:
306    
307     int consumed;
308     int vec[kVecSize];
309     if (DoMatchImpl(*input, UNANCHORED, &consumed,
310     args, n, vec, kVecSize)) {
311     input->remove_prefix(consumed);
312     return true;
313     } else {
314     return false;
315     }
316     }
317    
318     bool RE::Replace(const StringPiece& rewrite,
319     string *str) const {
320     int vec[kVecSize];
321     int matches = TryMatch(*str, 0, UNANCHORED, vec, kVecSize);
322     if (matches == 0)
323     return false;
324    
325     string s;
326     if (!Rewrite(&s, rewrite, *str, vec, matches))
327     return false;
328    
329     assert(vec[0] >= 0);
330     assert(vec[1] >= 0);
331     str->replace(vec[0], vec[1] - vec[0], s);
332     return true;
333     }
334    
335 nigel 91 // Returns PCRE_NEWLINE_CRLF, PCRE_NEWLINE_CR, or PCRE_NEWLINE_LF.
336     // Note that PCRE_NEWLINE_CRLF is defined to be P_N_CR | P_N_LF.
337     static int NewlineMode(int pcre_options) {
338     // TODO: if we can make it threadsafe, cache this var
339     int newline_mode = 0;
340     /* if (newline_mode) return newline_mode; */ // do this once it's cached
341     if (pcre_options & (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF)) {
342     newline_mode = (pcre_options &
343     (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF));
344     } else {
345     int newline;
346     pcre_config(PCRE_CONFIG_NEWLINE, &newline);
347     if (newline == 10)
348     newline_mode = PCRE_NEWLINE_LF;
349     else if (newline == 13)
350     newline_mode = PCRE_NEWLINE_CR;
351     else if (newline == 3338)
352     newline_mode = PCRE_NEWLINE_CRLF;
353     else
354     assert("" == "Unexpected return value from pcre_config(NEWLINE)");
355     }
356     return newline_mode;
357     }
358    
359 nigel 77 int RE::GlobalReplace(const StringPiece& rewrite,
360     string *str) const {
361     int count = 0;
362     int vec[kVecSize];
363     string out;
364     int start = 0;
365     int lastend = -1;
366    
367     for (; start <= static_cast<int>(str->length()); count++) {
368     int matches = TryMatch(*str, start, UNANCHORED, vec, kVecSize);
369     if (matches <= 0)
370     break;
371     int matchstart = vec[0], matchend = vec[1];
372     assert(matchstart >= start);
373     assert(matchend >= matchstart);
374     if (matchstart == matchend && matchstart == lastend) {
375     // advance one character if we matched an empty string at the same
376     // place as the last match occurred
377 nigel 91 matchend = start + 1;
378     // If the current char is CR and we're in CRLF mode, skip LF too.
379     // Note it's better to call pcre_fullinfo() than to examine
380     // all_options(), since options_ could have changed bewteen
381     // compile-time and now, but this is simpler and safe enough.
382     if (start+1 < static_cast<int>(str->length()) &&
383     (*str)[start] == '\r' && (*str)[start+1] == '\n' &&
384     NewlineMode(options_.all_options()) == PCRE_NEWLINE_CRLF) {
385     matchend++;
386     }
387     // We also need to advance more than one char if we're in utf8 mode.
388     #ifdef SUPPORT_UTF8
389     if (options_.utf8()) {
390     while (matchend < static_cast<int>(str->length()) &&
391     ((*str)[matchend] & 0xc0) == 0x80)
392     matchend++;
393     }
394     #endif
395     if (matchend <= static_cast<int>(str->length()))
396     out.append(*str, start, matchend - start);
397     start = matchend;
398 nigel 77 } else {
399     out.append(*str, start, matchstart - start);
400     Rewrite(&out, rewrite, *str, vec, matches);
401     start = matchend;
402     lastend = matchend;
403     count++;
404     }
405     }
406    
407     if (count == 0)
408     return 0;
409    
410     if (start < static_cast<int>(str->length()))
411     out.append(*str, start, str->length() - start);
412     swap(out, *str);
413     return count;
414     }
415    
416     bool RE::Extract(const StringPiece& rewrite,
417     const StringPiece& text,
418     string *out) const {
419     int vec[kVecSize];
420     int matches = TryMatch(text, 0, UNANCHORED, vec, kVecSize);
421     if (matches == 0)
422     return false;
423 nigel 81 out->erase();
424 nigel 77 return Rewrite(out, rewrite, text, vec, matches);
425     }
426    
427     /***** Actual matching and rewriting code *****/
428    
429     int RE::TryMatch(const StringPiece& text,
430     int startpos,
431     Anchor anchor,
432     int *vec,
433     int vecsize) const {
434     pcre* re = (anchor == ANCHOR_BOTH) ? re_full_ : re_partial_;
435     if (re == NULL) {
436     //fprintf(stderr, "Matching against invalid re: %s\n", error_->c_str());
437     return 0;
438     }
439    
440     pcre_extra extra = { 0 };
441     if (options_.match_limit() > 0) {
442 nigel 87 extra.flags |= PCRE_EXTRA_MATCH_LIMIT;
443 nigel 77 extra.match_limit = options_.match_limit();
444     }
445 nigel 87 if (options_.match_limit_recursion() > 0) {
446     extra.flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
447     extra.match_limit_recursion = options_.match_limit_recursion();
448     }
449 nigel 77 int rc = pcre_exec(re, // The regular expression object
450     &extra,
451 nigel 87 (text.data() == NULL) ? "" : text.data(),
452 nigel 77 text.size(),
453     startpos,
454     (anchor == UNANCHORED) ? 0 : PCRE_ANCHORED,
455     vec,
456     vecsize);
457    
458     // Handle errors
459     if (rc == PCRE_ERROR_NOMATCH) {
460     return 0;
461     } else if (rc < 0) {
462     //fprintf(stderr, "Unexpected return code: %d when matching '%s'\n",
463     // re, pattern_.c_str());
464     return 0;
465     } else if (rc == 0) {
466     // pcre_exec() returns 0 as a special case when the number of
467     // capturing subpatterns exceeds the size of the vector.
468     // When this happens, there is a match and the output vector
469     // is filled, but we miss out on the positions of the extra subpatterns.
470     rc = vecsize / 2;
471     }
472    
473     if ((anchor == ANCHOR_BOTH) && (re_full_ == re_partial_)) {
474     // We need an extra check to make sure that the match extended
475     // to the end of the input string
476     assert(vec[0] == 0); // PCRE_ANCHORED forces starting match
477     if (vec[1] != text.size()) return 0; // Did not get ending match
478     }
479    
480     return rc;
481     }
482    
483     bool RE::DoMatchImpl(const StringPiece& text,
484     Anchor anchor,
485     int* consumed,
486     const Arg* const* args,
487     int n,
488     int* vec,
489     int vecsize) const {
490     assert((1 + n) * 3 <= vecsize); // results + PCRE workspace
491     int matches = TryMatch(text, 0, anchor, vec, vecsize);
492     assert(matches >= 0); // TryMatch never returns negatives
493     if (matches == 0)
494     return false;
495    
496     *consumed = vec[1];
497    
498 nigel 87 if (n == 0 || args == NULL) {
499 nigel 77 // We are not interested in results
500     return true;
501     }
502    
503 nigel 87 if (NumberOfCapturingGroups() < n) {
504     // RE has fewer capturing groups than number of arg pointers passed in
505     return false;
506     }
507    
508 nigel 77 // If we got here, we must have matched the whole pattern.
509     // We do not need (can not do) any more checks on the value of 'matches' here
510     // -- see the comment for TryMatch.
511     for (int i = 0; i < n; i++) {
512     const int start = vec[2*(i+1)];
513     const int limit = vec[2*(i+1)+1];
514     if (!args[i]->Parse(text.data() + start, limit-start)) {
515     // TODO: Should we indicate what the error was?
516     return false;
517     }
518     }
519    
520     return true;
521     }
522    
523     bool RE::DoMatch(const StringPiece& text,
524     Anchor anchor,
525     int* consumed,
526     const Arg* const args[],
527     int n) const {
528     assert(n >= 0);
529     size_t const vecsize = (1 + n) * 3; // results + PCRE workspace
530     // (as for kVecSize)
531     int space[21]; // use stack allocation for small vecsize (common case)
532     int* vec = vecsize <= 21 ? space : new int[vecsize];
533     bool retval = DoMatchImpl(text, anchor, consumed, args, n, vec, vecsize);
534     if (vec != space) delete [] vec;
535     return retval;
536     }
537    
538     bool RE::Rewrite(string *out, const StringPiece &rewrite,
539     const StringPiece &text, int *vec, int veclen) const {
540     for (const char *s = rewrite.data(), *end = s + rewrite.size();
541     s < end; s++) {
542     int c = *s;
543     if (c == '\\') {
544     c = *++s;
545     if (isdigit(c)) {
546     int n = (c - '0');
547     if (n >= veclen) {
548     //fprintf(stderr, requested group %d in regexp %.*s\n",
549     // n, rewrite.size(), rewrite.data());
550     return false;
551     }
552     int start = vec[2 * n];
553     if (start >= 0)
554     out->append(text.data() + start, vec[2 * n + 1] - start);
555     } else if (c == '\\') {
556     out->push_back('\\');
557     } else {
558     //fprintf(stderr, "invalid rewrite pattern: %.*s\n",
559     // rewrite.size(), rewrite.data());
560     return false;
561     }
562     } else {
563     out->push_back(c);
564     }
565     }
566     return true;
567     }
568    
569     // Return the number of capturing subpatterns, or -1 if the
570     // regexp wasn't valid on construction.
571 nigel 87 int RE::NumberOfCapturingGroups() const {
572 nigel 77 if (re_partial_ == NULL) return -1;
573    
574     int result;
575     int pcre_retval = pcre_fullinfo(re_partial_, // The regular expression object
576     NULL, // We did not study the pattern
577     PCRE_INFO_CAPTURECOUNT,
578     &result);
579     assert(pcre_retval == 0);
580     return result;
581     }
582    
583     /***** Parsers for various types *****/
584    
585     bool Arg::parse_null(const char* str, int n, void* dest) {
586     // We fail if somebody asked us to store into a non-NULL void* pointer
587     return (dest == NULL);
588     }
589    
590     bool Arg::parse_string(const char* str, int n, void* dest) {
591     reinterpret_cast<string*>(dest)->assign(str, n);
592     return true;
593     }
594    
595     bool Arg::parse_stringpiece(const char* str, int n, void* dest) {
596     reinterpret_cast<StringPiece*>(dest)->set(str, n);
597     return true;
598     }
599    
600     bool Arg::parse_char(const char* str, int n, void* dest) {
601     if (n != 1) return false;
602     *(reinterpret_cast<char*>(dest)) = str[0];
603     return true;
604     }
605    
606     bool Arg::parse_uchar(const char* str, int n, void* dest) {
607     if (n != 1) return false;
608     *(reinterpret_cast<unsigned char*>(dest)) = str[0];
609     return true;
610     }
611    
612     // Largest number spec that we are willing to parse
613     static const int kMaxNumberLength = 32;
614    
615     // REQUIRES "buf" must have length at least kMaxNumberLength+1
616     // REQUIRES "n > 0"
617     // Copies "str" into "buf" and null-terminates if necessary.
618     // Returns one of:
619     // a. "str" if no termination is needed
620     // b. "buf" if the string was copied and null-terminated
621     // c. "" if the input was invalid and has no hope of being parsed
622     static const char* TerminateNumber(char* buf, const char* str, int n) {
623     if ((n > 0) && isspace(*str)) {
624     // We are less forgiving than the strtoxxx() routines and do not
625     // allow leading spaces.
626     return "";
627     }
628    
629     // See if the character right after the input text may potentially
630     // look like a digit.
631     if (isdigit(str[n]) ||
632     ((str[n] >= 'a') && (str[n] <= 'f')) ||
633     ((str[n] >= 'A') && (str[n] <= 'F'))) {
634     if (n > kMaxNumberLength) return ""; // Input too big to be a valid number
635     memcpy(buf, str, n);
636     buf[n] = '\0';
637     return buf;
638     } else {
639     // We can parse right out of the supplied string, so return it.
640     return str;
641     }
642     }
643    
644     bool Arg::parse_long_radix(const char* str,
645     int n,
646     void* dest,
647     int radix) {
648     if (n == 0) return false;
649     char buf[kMaxNumberLength+1];
650     str = TerminateNumber(buf, str, n);
651     char* end;
652     errno = 0;
653     long r = strtol(str, &end, radix);
654     if (end != str + n) return false; // Leftover junk
655     if (errno) return false;
656     *(reinterpret_cast<long*>(dest)) = r;
657     return true;
658     }
659    
660     bool Arg::parse_ulong_radix(const char* str,
661     int n,
662     void* dest,
663     int radix) {
664     if (n == 0) return false;
665     char buf[kMaxNumberLength+1];
666     str = TerminateNumber(buf, str, n);
667 nigel 87 if (str[0] == '-') return false; // strtoul() on a negative number?!
668 nigel 77 char* end;
669     errno = 0;
670     unsigned long r = strtoul(str, &end, radix);
671     if (end != str + n) return false; // Leftover junk
672     if (errno) return false;
673     *(reinterpret_cast<unsigned long*>(dest)) = r;
674     return true;
675     }
676    
677     bool Arg::parse_short_radix(const char* str,
678     int n,
679     void* dest,
680     int radix) {
681     long r;
682     if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
683     if (r < SHRT_MIN || r > SHRT_MAX) return false; // Out of range
684     *(reinterpret_cast<short*>(dest)) = r;
685     return true;
686     }
687    
688     bool Arg::parse_ushort_radix(const char* str,
689     int n,
690     void* dest,
691     int radix) {
692     unsigned long r;
693     if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
694     if (r > USHRT_MAX) return false; // Out of range
695     *(reinterpret_cast<unsigned short*>(dest)) = r;
696     return true;
697     }
698    
699     bool Arg::parse_int_radix(const char* str,
700     int n,
701     void* dest,
702     int radix) {
703     long r;
704     if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
705     if (r < INT_MIN || r > INT_MAX) return false; // Out of range
706     *(reinterpret_cast<int*>(dest)) = r;
707     return true;
708     }
709    
710     bool Arg::parse_uint_radix(const char* str,
711     int n,
712     void* dest,
713     int radix) {
714     unsigned long r;
715     if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
716     if (r > UINT_MAX) return false; // Out of range
717     *(reinterpret_cast<unsigned int*>(dest)) = r;
718     return true;
719     }
720    
721     bool Arg::parse_longlong_radix(const char* str,
722     int n,
723     void* dest,
724     int radix) {
725     #ifndef HAVE_LONG_LONG
726     return false;
727     #else
728     if (n == 0) return false;
729     char buf[kMaxNumberLength+1];
730     str = TerminateNumber(buf, str, n);
731     char* end;
732     errno = 0;
733     #if defined HAVE_STRTOQ
734     long long r = strtoq(str, &end, radix);
735     #elif defined HAVE_STRTOLL
736     long long r = strtoll(str, &end, radix);
737     #else
738     #error parse_longlong_radix: cannot convert input to a long-long
739     #endif
740     if (end != str + n) return false; // Leftover junk
741     if (errno) return false;
742     *(reinterpret_cast<long long*>(dest)) = r;
743     return true;
744     #endif /* HAVE_LONG_LONG */
745     }
746    
747     bool Arg::parse_ulonglong_radix(const char* str,
748     int n,
749     void* dest,
750     int radix) {
751     #ifndef HAVE_UNSIGNED_LONG_LONG
752     return false;
753     #else
754     if (n == 0) return false;
755     char buf[kMaxNumberLength+1];
756     str = TerminateNumber(buf, str, n);
757 nigel 87 if (str[0] == '-') return false; // strtoull() on a negative number?!
758 nigel 77 char* end;
759     errno = 0;
760     #if defined HAVE_STRTOQ
761     unsigned long long r = strtouq(str, &end, radix);
762     #elif defined HAVE_STRTOLL
763     unsigned long long r = strtoull(str, &end, radix);
764     #else
765     #error parse_ulonglong_radix: cannot convert input to a long-long
766     #endif
767     if (end != str + n) return false; // Leftover junk
768     if (errno) return false;
769     *(reinterpret_cast<unsigned long long*>(dest)) = r;
770     return true;
771     #endif /* HAVE_UNSIGNED_LONG_LONG */
772     }
773    
774     bool Arg::parse_double(const char* str, int n, void* dest) {
775     if (n == 0) return false;
776     static const int kMaxLength = 200;
777     char buf[kMaxLength];
778     if (n >= kMaxLength) return false;
779     memcpy(buf, str, n);
780     buf[n] = '\0';
781     errno = 0;
782     char* end;
783     double r = strtod(buf, &end);
784     if (end != buf + n) return false; // Leftover junk
785     if (errno) return false;
786     *(reinterpret_cast<double*>(dest)) = r;
787     return true;
788     }
789    
790     bool Arg::parse_float(const char* str, int n, void* dest) {
791     double r;
792     if (!parse_double(str, n, &r)) return false;
793     *(reinterpret_cast<float*>(dest)) = static_cast<float>(r);
794     return true;
795     }
796    
797    
798     #define DEFINE_INTEGER_PARSERS(name) \
799     bool Arg::parse_##name(const char* str, int n, void* dest) { \
800     return parse_##name##_radix(str, n, dest, 10); \
801     } \
802     bool Arg::parse_##name##_hex(const char* str, int n, void* dest) { \
803     return parse_##name##_radix(str, n, dest, 16); \
804     } \
805     bool Arg::parse_##name##_octal(const char* str, int n, void* dest) { \
806     return parse_##name##_radix(str, n, dest, 8); \
807     } \
808     bool Arg::parse_##name##_cradix(const char* str, int n, void* dest) { \
809     return parse_##name##_radix(str, n, dest, 0); \
810     }
811    
812     DEFINE_INTEGER_PARSERS(short);
813     DEFINE_INTEGER_PARSERS(ushort);
814     DEFINE_INTEGER_PARSERS(int);
815     DEFINE_INTEGER_PARSERS(uint);
816     DEFINE_INTEGER_PARSERS(long);
817     DEFINE_INTEGER_PARSERS(ulong);
818     DEFINE_INTEGER_PARSERS(longlong);
819     DEFINE_INTEGER_PARSERS(ulonglong);
820    
821     #undef DEFINE_INTEGER_PARSERS
822    
823     } // namespace pcrecpp

webmaster@exim.org
ViewVC Help
Powered by ViewVC 1.1.12