1 // Copyright (c) 2010, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Author: Sanjay Ghemawat
39 #include <limits.h> /* for SHRT_MIN, USHRT_MAX, etc */
40 #include <string.h> /* for memcpy */
46 #include "pcrecpp_internal.h"
49 #include "pcre_stringpiece.h"
54 // Maximum number of args we can set
55 static const int kMaxArgs = 16;
56 static const int kVecSize = (1 + kMaxArgs) * 3; // results + PCRE workspace
58 // Special object that stands-in for no argument
59 Arg RE::no_arg((void*)NULL);
61 // This is for ABI compatibility with old versions of pcre (pre-7.6),
62 // which defined a global no_arg variable instead of putting it in the
63 // RE class. This works on GCC >= 3, at least. It definitely works
64 // for ELF, but may not for other object formats (Mach-O, for
65 // instance, does not support aliases.) We could probably have a more
66 // inclusive test if we ever needed it. (Note that not only the
67 // __attribute__ syntax, but also __USER_LABEL_PREFIX__, are
69 #if defined(__GNUC__) && __GNUC__ >= 3 && defined(__ELF__) && !defined(__INTEL_COMPILER)
70 # define ULP_AS_STRING(x) ULP_AS_STRING_INTERNAL(x)
71 # define ULP_AS_STRING_INTERNAL(x) #x
72 # define USER_LABEL_PREFIX_STR ULP_AS_STRING(__USER_LABEL_PREFIX__)
74 __attribute__((alias(USER_LABEL_PREFIX_STR "_ZN7pcrecpp2RE6no_argE")));
77 // If a regular expression has no error, its error_ field points here
78 static const string empty_string;
80 // If the user doesn't ask for any options, we just use this one
81 static RE_Options default_options;
83 // PCRE6.x compatible API
84 void RE::Init(const char *c_pat, const RE_Options* options) {
85 const string cxx_pat(c_pat);
86 Init(cxx_pat, options);
89 void RE::Init(const string& pat, const RE_Options* options) {
91 if (options == NULL) {
92 options_ = default_options;
96 error_ = &empty_string;
100 re_partial_ = Compile(UNANCHORED);
101 if (re_partial_ != NULL) {
102 re_full_ = Compile(ANCHOR_BOTH);
107 if (re_full_ != NULL) (*pcre_free)(re_full_);
108 if (re_partial_ != NULL) (*pcre_free)(re_partial_);
109 if (error_ != &empty_string) delete error_;
118 pcre* RE::Compile(Anchor anchor) {
119 // First, convert RE_Options into pcre options
120 int pcre_options = 0;
121 pcre_options = options_.all_options();
123 // Special treatment for anchoring. This is needed because at
124 // runtime pcre only provides an option for anchoring at the
125 // beginning of a string (unless you use offset).
127 // There are three types of anchoring we want:
128 // UNANCHORED Compile the original pattern, and use
129 // a pcre unanchored match.
130 // ANCHOR_START Compile the original pattern, and use
131 // a pcre anchored match.
132 // ANCHOR_BOTH Tack a "\z" to the end of the original pattern
133 // and use a pcre anchored match.
135 const char* compile_error;
138 if (anchor != ANCHOR_BOTH) {
139 re = pcre_compile(pattern_.c_str(), pcre_options,
140 &compile_error, &eoffset, NULL);
142 // Tack a '\z' at the end of RE. Parenthesize it first so that
143 // the '\z' applies to all top-level alternatives in the regexp.
144 string wrapped = "(?:"; // A non-counting grouping operator
147 re = pcre_compile(wrapped.c_str(), pcre_options,
148 &compile_error, &eoffset, NULL);
151 if (error_ == &empty_string) error_ = new string(compile_error);
156 /***** Matching interfaces *****/
158 bool RE::FullMatch(const StringPiece& text,
174 const Arg& ptr16) const {
175 const Arg* args[kMaxArgs];
177 if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
178 if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
179 if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
180 if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
181 if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
182 if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
183 if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
184 if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
185 if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
186 if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
187 if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
188 if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
189 if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
190 if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
191 if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
192 if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
197 return DoMatchImpl(text, ANCHOR_BOTH, &consumed, args, n, vec, kVecSize);
200 bool RE::PartialMatch(const StringPiece& text,
216 const Arg& ptr16) const {
217 const Arg* args[kMaxArgs];
219 if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
220 if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
221 if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
222 if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
223 if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
224 if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
225 if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
226 if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
227 if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
228 if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
229 if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
230 if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
231 if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
232 if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
233 if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
234 if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
239 return DoMatchImpl(text, UNANCHORED, &consumed, args, n, vec, kVecSize);
242 bool RE::Consume(StringPiece* input,
258 const Arg& ptr16) const {
259 const Arg* args[kMaxArgs];
261 if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
262 if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
263 if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
264 if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
265 if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
266 if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
267 if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
268 if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
269 if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
270 if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
271 if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
272 if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
273 if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
274 if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
275 if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
276 if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
281 if (DoMatchImpl(*input, ANCHOR_START, &consumed,
282 args, n, vec, kVecSize)) {
283 input->remove_prefix(consumed);
290 bool RE::FindAndConsume(StringPiece* input,
306 const Arg& ptr16) const {
307 const Arg* args[kMaxArgs];
309 if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
310 if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
311 if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
312 if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
313 if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
314 if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
315 if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
316 if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
317 if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
318 if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
319 if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
320 if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
321 if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
322 if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
323 if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
324 if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
329 if (DoMatchImpl(*input, UNANCHORED, &consumed,
330 args, n, vec, kVecSize)) {
331 input->remove_prefix(consumed);
338 bool RE::Replace(const StringPiece& rewrite,
341 int matches = TryMatch(*str, 0, UNANCHORED, true, vec, kVecSize);
346 if (!Rewrite(&s, rewrite, *str, vec, matches))
351 str->replace(vec[0], vec[1] - vec[0], s);
355 // Returns PCRE_NEWLINE_CRLF, PCRE_NEWLINE_CR, or PCRE_NEWLINE_LF.
356 // Note that PCRE_NEWLINE_CRLF is defined to be P_N_CR | P_N_LF.
357 // Modified by PH to add PCRE_NEWLINE_ANY and PCRE_NEWLINE_ANYCRLF.
359 static int NewlineMode(int pcre_options) {
360 // TODO: if we can make it threadsafe, cache this var
361 int newline_mode = 0;
362 /* if (newline_mode) return newline_mode; */ // do this once it's cached
363 if (pcre_options & (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|
364 PCRE_NEWLINE_ANY|PCRE_NEWLINE_ANYCRLF)) {
365 newline_mode = (pcre_options &
366 (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|
367 PCRE_NEWLINE_ANY|PCRE_NEWLINE_ANYCRLF));
370 pcre_config(PCRE_CONFIG_NEWLINE, &newline);
372 newline_mode = PCRE_NEWLINE_LF;
373 else if (newline == 13)
374 newline_mode = PCRE_NEWLINE_CR;
375 else if (newline == 3338)
376 newline_mode = PCRE_NEWLINE_CRLF;
377 else if (newline == -1)
378 newline_mode = PCRE_NEWLINE_ANY;
379 else if (newline == -2)
380 newline_mode = PCRE_NEWLINE_ANYCRLF;
382 assert(NULL == "Unexpected return value from pcre_config(NEWLINE)");
387 int RE::GlobalReplace(const StringPiece& rewrite,
393 bool last_match_was_empty_string = false;
395 while (start <= static_cast<int>(str->length())) {
396 // If the previous match was for the empty string, we shouldn't
397 // just match again: we'll match in the same way and get an
398 // infinite loop. Instead, we do the match in a special way:
399 // anchored -- to force another try at the same position --
400 // and with a flag saying that this time, ignore empty matches.
401 // If this special match returns, that means there's a non-empty
402 // match at this position as well, and we can continue. If not,
403 // we do what perl does, and just advance by one.
404 // Notice that perl prints '@@@' for this;
405 // perl -le '$_ = "aa"; s/b*|aa/@/g; print'
407 if (last_match_was_empty_string) {
408 matches = TryMatch(*str, start, ANCHOR_START, false, vec, kVecSize);
410 int matchend = start + 1; // advance one character.
411 // If the current char is CR and we're in CRLF mode, skip LF too.
412 // Note it's better to call pcre_fullinfo() than to examine
413 // all_options(), since options_ could have changed bewteen
414 // compile-time and now, but this is simpler and safe enough.
415 // Modified by PH to add ANY and ANYCRLF.
416 if (matchend < static_cast<int>(str->length()) &&
417 (*str)[start] == '\r' && (*str)[matchend] == '\n' &&
418 (NewlineMode(options_.all_options()) == PCRE_NEWLINE_CRLF ||
419 NewlineMode(options_.all_options()) == PCRE_NEWLINE_ANY ||
420 NewlineMode(options_.all_options()) == PCRE_NEWLINE_ANYCRLF)) {
423 // We also need to advance more than one char if we're in utf8 mode.
425 if (options_.utf8()) {
426 while (matchend < static_cast<int>(str->length()) &&
427 ((*str)[matchend] & 0xc0) == 0x80)
431 if (start < static_cast<int>(str->length()))
432 out.append(*str, start, matchend - start);
434 last_match_was_empty_string = false;
438 matches = TryMatch(*str, start, UNANCHORED, true, vec, kVecSize);
442 int matchstart = vec[0], matchend = vec[1];
443 assert(matchstart >= start);
444 assert(matchend >= matchstart);
445 out.append(*str, start, matchstart - start);
446 Rewrite(&out, rewrite, *str, vec, matches);
449 last_match_was_empty_string = (matchstart == matchend);
455 if (start < static_cast<int>(str->length()))
456 out.append(*str, start, str->length() - start);
461 bool RE::Extract(const StringPiece& rewrite,
462 const StringPiece& text,
465 int matches = TryMatch(text, 0, UNANCHORED, true, vec, kVecSize);
469 return Rewrite(out, rewrite, text, vec, matches);
472 /*static*/ string RE::QuoteMeta(const StringPiece& unquoted) {
475 // Escape any ascii character not in [A-Za-z_0-9].
477 // Note that it's legal to escape a character even if it has no
478 // special meaning in a regular expression -- so this function does
479 // that. (This also makes it identical to the perl function of the
480 // same name; see `perldoc -f quotemeta`.) The one exception is
481 // escaping NUL: rather than doing backslash + NUL, like perl does,
482 // we do '\0', because pcre itself doesn't take embedded NUL chars.
483 for (int ii = 0; ii < unquoted.size(); ++ii) {
484 // Note that using 'isalnum' here raises the benchmark time from
486 if (unquoted[ii] == '\0') {
488 } else if ((unquoted[ii] < 'a' || unquoted[ii] > 'z') &&
489 (unquoted[ii] < 'A' || unquoted[ii] > 'Z') &&
490 (unquoted[ii] < '0' || unquoted[ii] > '9') &&
491 unquoted[ii] != '_' &&
492 // If this is the part of a UTF8 or Latin1 character, we need
493 // to copy this byte without escaping. Experimentally this is
494 // what works correctly with the regexp library.
495 !(unquoted[ii] & 128)) {
497 result += unquoted[ii];
499 result += unquoted[ii];
506 /***** Actual matching and rewriting code *****/
508 int RE::TryMatch(const StringPiece& text,
514 pcre* re = (anchor == ANCHOR_BOTH) ? re_full_ : re_partial_;
516 //fprintf(stderr, "Matching against invalid re: %s\n", error_->c_str());
520 pcre_extra extra = { 0, 0, 0, 0, 0, 0, 0, 0 };
521 if (options_.match_limit() > 0) {
522 extra.flags |= PCRE_EXTRA_MATCH_LIMIT;
523 extra.match_limit = options_.match_limit();
525 if (options_.match_limit_recursion() > 0) {
526 extra.flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
527 extra.match_limit_recursion = options_.match_limit_recursion();
531 // Changed by PH as a result of bugzilla #1288
532 int options = (options_.all_options() & PCRE_NO_UTF8_CHECK);
534 if (anchor != UNANCHORED)
535 options |= PCRE_ANCHORED;
537 options |= PCRE_NOTEMPTY;
539 int rc = pcre_exec(re, // The regular expression object
541 (text.data() == NULL) ? "" : text.data(),
549 if (rc == PCRE_ERROR_NOMATCH) {
552 //fprintf(stderr, "Unexpected return code: %d when matching '%s'\n",
553 // re, pattern_.c_str());
555 } else if (rc == 0) {
556 // pcre_exec() returns 0 as a special case when the number of
557 // capturing subpatterns exceeds the size of the vector.
558 // When this happens, there is a match and the output vector
559 // is filled, but we miss out on the positions of the extra subpatterns.
566 bool RE::DoMatchImpl(const StringPiece& text,
569 const Arg* const* args,
573 assert((1 + n) * 3 <= vecsize); // results + PCRE workspace
574 int matches = TryMatch(text, 0, anchor, true, vec, vecsize);
575 assert(matches >= 0); // TryMatch never returns negatives
581 if (n == 0 || args == NULL) {
582 // We are not interested in results
586 if (NumberOfCapturingGroups() < n) {
587 // RE has fewer capturing groups than number of arg pointers passed in
591 // If we got here, we must have matched the whole pattern.
592 // We do not need (can not do) any more checks on the value of 'matches' here
593 // -- see the comment for TryMatch.
594 for (int i = 0; i < n; i++) {
595 const int start = vec[2*(i+1)];
596 const int limit = vec[2*(i+1)+1];
597 if (!args[i]->Parse(text.data() + start, limit-start)) {
598 // TODO: Should we indicate what the error was?
606 bool RE::DoMatch(const StringPiece& text,
609 const Arg* const args[],
612 size_t const vecsize = (1 + n) * 3; // results + PCRE workspace
614 int space[21]; // use stack allocation for small vecsize (common case)
615 int* vec = vecsize <= 21 ? space : new int[vecsize];
616 bool retval = DoMatchImpl(text, anchor, consumed, args, n, vec, (int)vecsize);
617 if (vec != space) delete [] vec;
621 bool RE::Rewrite(string *out, const StringPiece &rewrite,
622 const StringPiece &text, int *vec, int veclen) const {
623 for (const char *s = rewrite.data(), *end = s + rewrite.size();
631 //fprintf(stderr, requested group %d in regexp %.*s\n",
632 // n, rewrite.size(), rewrite.data());
635 int start = vec[2 * n];
637 out->append(text.data() + start, vec[2 * n + 1] - start);
638 } else if (c == '\\') {
641 //fprintf(stderr, "invalid rewrite pattern: %.*s\n",
642 // rewrite.size(), rewrite.data());
652 // Return the number of capturing subpatterns, or -1 if the
653 // regexp wasn't valid on construction.
654 int RE::NumberOfCapturingGroups() const {
655 if (re_partial_ == NULL) return -1;
658 int pcre_retval = pcre_fullinfo(re_partial_, // The regular expression object
659 NULL, // We did not study the pattern
660 PCRE_INFO_CAPTURECOUNT,
662 assert(pcre_retval == 0);
666 /***** Parsers for various types *****/
668 bool Arg::parse_null(const char* str, int n, void* dest) {
671 // We fail if somebody asked us to store into a non-NULL void* pointer
672 return (dest == NULL);
675 bool Arg::parse_string(const char* str, int n, void* dest) {
676 if (dest == NULL) return true;
677 reinterpret_cast<string*>(dest)->assign(str, n);
681 bool Arg::parse_stringpiece(const char* str, int n, void* dest) {
682 if (dest == NULL) return true;
683 reinterpret_cast<StringPiece*>(dest)->set(str, n);
687 bool Arg::parse_char(const char* str, int n, void* dest) {
688 if (n != 1) return false;
689 if (dest == NULL) return true;
690 *(reinterpret_cast<char*>(dest)) = str[0];
694 bool Arg::parse_uchar(const char* str, int n, void* dest) {
695 if (n != 1) return false;
696 if (dest == NULL) return true;
697 *(reinterpret_cast<unsigned char*>(dest)) = str[0];
701 // Largest number spec that we are willing to parse
702 static const int kMaxNumberLength = 32;
704 // REQUIRES "buf" must have length at least kMaxNumberLength+1
706 // Copies "str" into "buf" and null-terminates if necessary.
708 // a. "str" if no termination is needed
709 // b. "buf" if the string was copied and null-terminated
710 // c. "" if the input was invalid and has no hope of being parsed
711 static const char* TerminateNumber(char* buf, const char* str, int n) {
712 if ((n > 0) && isspace(*str)) {
713 // We are less forgiving than the strtoxxx() routines and do not
714 // allow leading spaces.
718 // See if the character right after the input text may potentially
719 // look like a digit.
720 if (isdigit(str[n]) ||
721 ((str[n] >= 'a') && (str[n] <= 'f')) ||
722 ((str[n] >= 'A') && (str[n] <= 'F'))) {
723 if (n > kMaxNumberLength) return ""; // Input too big to be a valid number
728 // We can parse right out of the supplied string, so return it.
733 bool Arg::parse_long_radix(const char* str,
737 if (n == 0) return false;
738 char buf[kMaxNumberLength+1];
739 str = TerminateNumber(buf, str, n);
742 long r = strtol(str, &end, radix);
743 if (end != str + n) return false; // Leftover junk
744 if (errno) return false;
745 if (dest == NULL) return true;
746 *(reinterpret_cast<long*>(dest)) = r;
750 bool Arg::parse_ulong_radix(const char* str,
754 if (n == 0) return false;
755 char buf[kMaxNumberLength+1];
756 str = TerminateNumber(buf, str, n);
757 if (str[0] == '-') return false; // strtoul() on a negative number?!
760 unsigned long r = strtoul(str, &end, radix);
761 if (end != str + n) return false; // Leftover junk
762 if (errno) return false;
763 if (dest == NULL) return true;
764 *(reinterpret_cast<unsigned long*>(dest)) = r;
768 bool Arg::parse_short_radix(const char* str,
773 if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
774 if (r < SHRT_MIN || r > SHRT_MAX) return false; // Out of range
775 if (dest == NULL) return true;
776 *(reinterpret_cast<short*>(dest)) = static_cast<short>(r);
780 bool Arg::parse_ushort_radix(const char* str,
785 if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
786 if (r > USHRT_MAX) return false; // Out of range
787 if (dest == NULL) return true;
788 *(reinterpret_cast<unsigned short*>(dest)) = static_cast<unsigned short>(r);
792 bool Arg::parse_int_radix(const char* str,
797 if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
798 if (r < INT_MIN || r > INT_MAX) return false; // Out of range
799 if (dest == NULL) return true;
800 *(reinterpret_cast<int*>(dest)) = r;
804 bool Arg::parse_uint_radix(const char* str,
809 if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
810 if (r > UINT_MAX) return false; // Out of range
811 if (dest == NULL) return true;
812 *(reinterpret_cast<unsigned int*>(dest)) = r;
816 bool Arg::parse_longlong_radix(const char* str,
820 #ifndef HAVE_LONG_LONG
823 if (n == 0) return false;
824 char buf[kMaxNumberLength+1];
825 str = TerminateNumber(buf, str, n);
828 #if defined HAVE_STRTOQ
829 long long r = strtoq(str, &end, radix);
830 #elif defined HAVE_STRTOLL
831 long long r = strtoll(str, &end, radix);
832 #elif defined HAVE__STRTOI64
833 long long r = _strtoi64(str, &end, radix);
834 #elif defined HAVE_STRTOIMAX
835 long long r = strtoimax(str, &end, radix);
837 #error parse_longlong_radix: cannot convert input to a long-long
839 if (end != str + n) return false; // Leftover junk
840 if (errno) return false;
841 if (dest == NULL) return true;
842 *(reinterpret_cast<long long*>(dest)) = r;
844 #endif /* HAVE_LONG_LONG */
847 bool Arg::parse_ulonglong_radix(const char* str,
851 #ifndef HAVE_UNSIGNED_LONG_LONG
854 if (n == 0) return false;
855 char buf[kMaxNumberLength+1];
856 str = TerminateNumber(buf, str, n);
857 if (str[0] == '-') return false; // strtoull() on a negative number?!
860 #if defined HAVE_STRTOQ
861 unsigned long long r = strtouq(str, &end, radix);
862 #elif defined HAVE_STRTOLL
863 unsigned long long r = strtoull(str, &end, radix);
864 #elif defined HAVE__STRTOI64
865 unsigned long long r = _strtoui64(str, &end, radix);
866 #elif defined HAVE_STRTOIMAX
867 unsigned long long r = strtoumax(str, &end, radix);
869 #error parse_ulonglong_radix: cannot convert input to a long-long
871 if (end != str + n) return false; // Leftover junk
872 if (errno) return false;
873 if (dest == NULL) return true;
874 *(reinterpret_cast<unsigned long long*>(dest)) = r;
876 #endif /* HAVE_UNSIGNED_LONG_LONG */
879 bool Arg::parse_double(const char* str, int n, void* dest) {
880 if (n == 0) return false;
881 static const int kMaxLength = 200;
882 char buf[kMaxLength];
883 if (n >= kMaxLength) return false;
888 double r = strtod(buf, &end);
889 if (end != buf + n) return false; // Leftover junk
890 if (errno) return false;
891 if (dest == NULL) return true;
892 *(reinterpret_cast<double*>(dest)) = r;
896 bool Arg::parse_float(const char* str, int n, void* dest) {
898 if (!parse_double(str, n, &r)) return false;
899 if (dest == NULL) return true;
900 *(reinterpret_cast<float*>(dest)) = static_cast<float>(r);
905 #define DEFINE_INTEGER_PARSERS(name) \
906 bool Arg::parse_##name(const char* str, int n, void* dest) { \
907 return parse_##name##_radix(str, n, dest, 10); \
909 bool Arg::parse_##name##_hex(const char* str, int n, void* dest) { \
910 return parse_##name##_radix(str, n, dest, 16); \
912 bool Arg::parse_##name##_octal(const char* str, int n, void* dest) { \
913 return parse_##name##_radix(str, n, dest, 8); \
915 bool Arg::parse_##name##_cradix(const char* str, int n, void* dest) { \
916 return parse_##name##_radix(str, n, dest, 0); \
919 DEFINE_INTEGER_PARSERS(short) /* */
920 DEFINE_INTEGER_PARSERS(ushort) /* */
921 DEFINE_INTEGER_PARSERS(int) /* Don't use semicolons after these */
922 DEFINE_INTEGER_PARSERS(uint) /* statements because they can cause */
923 DEFINE_INTEGER_PARSERS(long) /* compiler warnings if the checking */
924 DEFINE_INTEGER_PARSERS(ulong) /* level is turned up high enough. */
925 DEFINE_INTEGER_PARSERS(longlong) /* */
926 DEFINE_INTEGER_PARSERS(ulonglong) /* */
928 #undef DEFINE_INTEGER_PARSERS
930 } // namespace pcrecpp