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__)
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 void RE::Init(const string
& pat
, const RE_Options
* options
) {
85 if (options
== NULL
) {
86 options_
= default_options
;
90 error_
= &empty_string
;
94 re_partial_
= Compile(UNANCHORED
);
95 if (re_partial_
!= NULL
) {
96 re_full_
= Compile(ANCHOR_BOTH
);
101 if (re_full_
!= NULL
) (*pcre_free
)(re_full_
);
102 if (re_partial_
!= NULL
) (*pcre_free
)(re_partial_
);
103 if (error_
!= &empty_string
) delete error_
;
112 pcre
* RE::Compile(Anchor anchor
) {
113 // First, convert RE_Options into pcre options
114 int pcre_options
= 0;
115 pcre_options
= options_
.all_options();
117 // Special treatment for anchoring. This is needed because at
118 // runtime pcre only provides an option for anchoring at the
119 // beginning of a string (unless you use offset).
121 // There are three types of anchoring we want:
122 // UNANCHORED Compile the original pattern, and use
123 // a pcre unanchored match.
124 // ANCHOR_START Compile the original pattern, and use
125 // a pcre anchored match.
126 // ANCHOR_BOTH Tack a "\z" to the end of the original pattern
127 // and use a pcre anchored match.
129 const char* compile_error
;
132 if (anchor
!= ANCHOR_BOTH
) {
133 re
= pcre_compile(pattern_
.c_str(), pcre_options
,
134 &compile_error
, &eoffset
, NULL
);
136 // Tack a '\z' at the end of RE. Parenthesize it first so that
137 // the '\z' applies to all top-level alternatives in the regexp.
138 string wrapped
= "(?:"; // A non-counting grouping operator
141 re
= pcre_compile(wrapped
.c_str(), pcre_options
,
142 &compile_error
, &eoffset
, NULL
);
145 if (error_
== &empty_string
) error_
= new string(compile_error
);
150 /***** Matching interfaces *****/
152 bool RE::FullMatch(const StringPiece
& text
,
168 const Arg
& ptr16
) const {
169 const Arg
* args
[kMaxArgs
];
171 if (&ptr1
== &no_arg
) goto done
; args
[n
++] = &ptr1
;
172 if (&ptr2
== &no_arg
) goto done
; args
[n
++] = &ptr2
;
173 if (&ptr3
== &no_arg
) goto done
; args
[n
++] = &ptr3
;
174 if (&ptr4
== &no_arg
) goto done
; args
[n
++] = &ptr4
;
175 if (&ptr5
== &no_arg
) goto done
; args
[n
++] = &ptr5
;
176 if (&ptr6
== &no_arg
) goto done
; args
[n
++] = &ptr6
;
177 if (&ptr7
== &no_arg
) goto done
; args
[n
++] = &ptr7
;
178 if (&ptr8
== &no_arg
) goto done
; args
[n
++] = &ptr8
;
179 if (&ptr9
== &no_arg
) goto done
; args
[n
++] = &ptr9
;
180 if (&ptr10
== &no_arg
) goto done
; args
[n
++] = &ptr10
;
181 if (&ptr11
== &no_arg
) goto done
; args
[n
++] = &ptr11
;
182 if (&ptr12
== &no_arg
) goto done
; args
[n
++] = &ptr12
;
183 if (&ptr13
== &no_arg
) goto done
; args
[n
++] = &ptr13
;
184 if (&ptr14
== &no_arg
) goto done
; args
[n
++] = &ptr14
;
185 if (&ptr15
== &no_arg
) goto done
; args
[n
++] = &ptr15
;
186 if (&ptr16
== &no_arg
) goto done
; args
[n
++] = &ptr16
;
191 return DoMatchImpl(text
, ANCHOR_BOTH
, &consumed
, args
, n
, vec
, kVecSize
);
194 bool RE::PartialMatch(const StringPiece
& text
,
210 const Arg
& ptr16
) const {
211 const Arg
* args
[kMaxArgs
];
213 if (&ptr1
== &no_arg
) goto done
; args
[n
++] = &ptr1
;
214 if (&ptr2
== &no_arg
) goto done
; args
[n
++] = &ptr2
;
215 if (&ptr3
== &no_arg
) goto done
; args
[n
++] = &ptr3
;
216 if (&ptr4
== &no_arg
) goto done
; args
[n
++] = &ptr4
;
217 if (&ptr5
== &no_arg
) goto done
; args
[n
++] = &ptr5
;
218 if (&ptr6
== &no_arg
) goto done
; args
[n
++] = &ptr6
;
219 if (&ptr7
== &no_arg
) goto done
; args
[n
++] = &ptr7
;
220 if (&ptr8
== &no_arg
) goto done
; args
[n
++] = &ptr8
;
221 if (&ptr9
== &no_arg
) goto done
; args
[n
++] = &ptr9
;
222 if (&ptr10
== &no_arg
) goto done
; args
[n
++] = &ptr10
;
223 if (&ptr11
== &no_arg
) goto done
; args
[n
++] = &ptr11
;
224 if (&ptr12
== &no_arg
) goto done
; args
[n
++] = &ptr12
;
225 if (&ptr13
== &no_arg
) goto done
; args
[n
++] = &ptr13
;
226 if (&ptr14
== &no_arg
) goto done
; args
[n
++] = &ptr14
;
227 if (&ptr15
== &no_arg
) goto done
; args
[n
++] = &ptr15
;
228 if (&ptr16
== &no_arg
) goto done
; args
[n
++] = &ptr16
;
233 return DoMatchImpl(text
, UNANCHORED
, &consumed
, args
, n
, vec
, kVecSize
);
236 bool RE::Consume(StringPiece
* input
,
252 const Arg
& ptr16
) const {
253 const Arg
* args
[kMaxArgs
];
255 if (&ptr1
== &no_arg
) goto done
; args
[n
++] = &ptr1
;
256 if (&ptr2
== &no_arg
) goto done
; args
[n
++] = &ptr2
;
257 if (&ptr3
== &no_arg
) goto done
; args
[n
++] = &ptr3
;
258 if (&ptr4
== &no_arg
) goto done
; args
[n
++] = &ptr4
;
259 if (&ptr5
== &no_arg
) goto done
; args
[n
++] = &ptr5
;
260 if (&ptr6
== &no_arg
) goto done
; args
[n
++] = &ptr6
;
261 if (&ptr7
== &no_arg
) goto done
; args
[n
++] = &ptr7
;
262 if (&ptr8
== &no_arg
) goto done
; args
[n
++] = &ptr8
;
263 if (&ptr9
== &no_arg
) goto done
; args
[n
++] = &ptr9
;
264 if (&ptr10
== &no_arg
) goto done
; args
[n
++] = &ptr10
;
265 if (&ptr11
== &no_arg
) goto done
; args
[n
++] = &ptr11
;
266 if (&ptr12
== &no_arg
) goto done
; args
[n
++] = &ptr12
;
267 if (&ptr13
== &no_arg
) goto done
; args
[n
++] = &ptr13
;
268 if (&ptr14
== &no_arg
) goto done
; args
[n
++] = &ptr14
;
269 if (&ptr15
== &no_arg
) goto done
; args
[n
++] = &ptr15
;
270 if (&ptr16
== &no_arg
) goto done
; args
[n
++] = &ptr16
;
275 if (DoMatchImpl(*input
, ANCHOR_START
, &consumed
,
276 args
, n
, vec
, kVecSize
)) {
277 input
->remove_prefix(consumed
);
284 bool RE::FindAndConsume(StringPiece
* input
,
300 const Arg
& ptr16
) const {
301 const Arg
* args
[kMaxArgs
];
303 if (&ptr1
== &no_arg
) goto done
; args
[n
++] = &ptr1
;
304 if (&ptr2
== &no_arg
) goto done
; args
[n
++] = &ptr2
;
305 if (&ptr3
== &no_arg
) goto done
; args
[n
++] = &ptr3
;
306 if (&ptr4
== &no_arg
) goto done
; args
[n
++] = &ptr4
;
307 if (&ptr5
== &no_arg
) goto done
; args
[n
++] = &ptr5
;
308 if (&ptr6
== &no_arg
) goto done
; args
[n
++] = &ptr6
;
309 if (&ptr7
== &no_arg
) goto done
; args
[n
++] = &ptr7
;
310 if (&ptr8
== &no_arg
) goto done
; args
[n
++] = &ptr8
;
311 if (&ptr9
== &no_arg
) goto done
; args
[n
++] = &ptr9
;
312 if (&ptr10
== &no_arg
) goto done
; args
[n
++] = &ptr10
;
313 if (&ptr11
== &no_arg
) goto done
; args
[n
++] = &ptr11
;
314 if (&ptr12
== &no_arg
) goto done
; args
[n
++] = &ptr12
;
315 if (&ptr13
== &no_arg
) goto done
; args
[n
++] = &ptr13
;
316 if (&ptr14
== &no_arg
) goto done
; args
[n
++] = &ptr14
;
317 if (&ptr15
== &no_arg
) goto done
; args
[n
++] = &ptr15
;
318 if (&ptr16
== &no_arg
) goto done
; args
[n
++] = &ptr16
;
323 if (DoMatchImpl(*input
, UNANCHORED
, &consumed
,
324 args
, n
, vec
, kVecSize
)) {
325 input
->remove_prefix(consumed
);
332 bool RE::Replace(const StringPiece
& rewrite
,
335 int matches
= TryMatch(*str
, 0, UNANCHORED
, true, vec
, kVecSize
);
340 if (!Rewrite(&s
, rewrite
, *str
, vec
, matches
))
345 str
->replace(vec
[0], vec
[1] - vec
[0], s
);
349 // Returns PCRE_NEWLINE_CRLF, PCRE_NEWLINE_CR, or PCRE_NEWLINE_LF.
350 // Note that PCRE_NEWLINE_CRLF is defined to be P_N_CR | P_N_LF.
351 // Modified by PH to add PCRE_NEWLINE_ANY and PCRE_NEWLINE_ANYCRLF.
353 static int NewlineMode(int pcre_options
) {
354 // TODO: if we can make it threadsafe, cache this var
355 int newline_mode
= 0;
356 /* if (newline_mode) return newline_mode; */ // do this once it's cached
357 if (pcre_options
& (PCRE_NEWLINE_CRLF
|PCRE_NEWLINE_CR
|PCRE_NEWLINE_LF
|
358 PCRE_NEWLINE_ANY
|PCRE_NEWLINE_ANYCRLF
)) {
359 newline_mode
= (pcre_options
&
360 (PCRE_NEWLINE_CRLF
|PCRE_NEWLINE_CR
|PCRE_NEWLINE_LF
|
361 PCRE_NEWLINE_ANY
|PCRE_NEWLINE_ANYCRLF
));
364 pcre_config(PCRE_CONFIG_NEWLINE
, &newline
);
366 newline_mode
= PCRE_NEWLINE_LF
;
367 else if (newline
== 13)
368 newline_mode
= PCRE_NEWLINE_CR
;
369 else if (newline
== 3338)
370 newline_mode
= PCRE_NEWLINE_CRLF
;
371 else if (newline
== -1)
372 newline_mode
= PCRE_NEWLINE_ANY
;
373 else if (newline
== -2)
374 newline_mode
= PCRE_NEWLINE_ANYCRLF
;
376 assert(NULL
== "Unexpected return value from pcre_config(NEWLINE)");
381 int RE::GlobalReplace(const StringPiece
& rewrite
,
387 bool last_match_was_empty_string
= false;
389 while (start
<= static_cast<int>(str
->length())) {
390 // If the previous match was for the empty string, we shouldn't
391 // just match again: we'll match in the same way and get an
392 // infinite loop. Instead, we do the match in a special way:
393 // anchored -- to force another try at the same position --
394 // and with a flag saying that this time, ignore empty matches.
395 // If this special match returns, that means there's a non-empty
396 // match at this position as well, and we can continue. If not,
397 // we do what perl does, and just advance by one.
398 // Notice that perl prints '@@@' for this;
399 // perl -le '$_ = "aa"; s/b*|aa/@/g; print'
401 if (last_match_was_empty_string
) {
402 matches
= TryMatch(*str
, start
, ANCHOR_START
, false, vec
, kVecSize
);
404 int matchend
= start
+ 1; // advance one character.
405 // If the current char is CR and we're in CRLF mode, skip LF too.
406 // Note it's better to call pcre_fullinfo() than to examine
407 // all_options(), since options_ could have changed bewteen
408 // compile-time and now, but this is simpler and safe enough.
409 // Modified by PH to add ANY and ANYCRLF.
410 if (matchend
< static_cast<int>(str
->length()) &&
411 (*str
)[start
] == '\r' && (*str
)[matchend
] == '\n' &&
412 (NewlineMode(options_
.all_options()) == PCRE_NEWLINE_CRLF
||
413 NewlineMode(options_
.all_options()) == PCRE_NEWLINE_ANY
||
414 NewlineMode(options_
.all_options()) == PCRE_NEWLINE_ANYCRLF
)) {
417 // We also need to advance more than one char if we're in utf8 mode.
419 if (options_
.utf8()) {
420 while (matchend
< static_cast<int>(str
->length()) &&
421 ((*str
)[matchend
] & 0xc0) == 0x80)
425 if (start
< static_cast<int>(str
->length()))
426 out
.append(*str
, start
, matchend
- start
);
428 last_match_was_empty_string
= false;
432 matches
= TryMatch(*str
, start
, UNANCHORED
, true, vec
, kVecSize
);
436 int matchstart
= vec
[0], matchend
= vec
[1];
437 assert(matchstart
>= start
);
438 assert(matchend
>= matchstart
);
439 out
.append(*str
, start
, matchstart
- start
);
440 Rewrite(&out
, rewrite
, *str
, vec
, matches
);
443 last_match_was_empty_string
= (matchstart
== matchend
);
449 if (start
< static_cast<int>(str
->length()))
450 out
.append(*str
, start
, str
->length() - start
);
455 bool RE::Extract(const StringPiece
& rewrite
,
456 const StringPiece
& text
,
459 int matches
= TryMatch(text
, 0, UNANCHORED
, true, vec
, kVecSize
);
463 return Rewrite(out
, rewrite
, text
, vec
, matches
);
466 /*static*/ string
RE::QuoteMeta(const StringPiece
& unquoted
) {
469 // Escape any ascii character not in [A-Za-z_0-9].
471 // Note that it's legal to escape a character even if it has no
472 // special meaning in a regular expression -- so this function does
473 // that. (This also makes it identical to the perl function of the
474 // same name; see `perldoc -f quotemeta`.) The one exception is
475 // escaping NUL: rather than doing backslash + NUL, like perl does,
476 // we do '\0', because pcre itself doesn't take embedded NUL chars.
477 for (int ii
= 0; ii
< unquoted
.size(); ++ii
) {
478 // Note that using 'isalnum' here raises the benchmark time from
480 if (unquoted
[ii
] == '\0') {
482 } else if ((unquoted
[ii
] < 'a' || unquoted
[ii
] > 'z') &&
483 (unquoted
[ii
] < 'A' || unquoted
[ii
] > 'Z') &&
484 (unquoted
[ii
] < '0' || unquoted
[ii
] > '9') &&
485 unquoted
[ii
] != '_' &&
486 // If this is the part of a UTF8 or Latin1 character, we need
487 // to copy this byte without escaping. Experimentally this is
488 // what works correctly with the regexp library.
489 !(unquoted
[ii
] & 128)) {
491 result
+= unquoted
[ii
];
493 result
+= unquoted
[ii
];
500 /***** Actual matching and rewriting code *****/
502 int RE::TryMatch(const StringPiece
& text
,
508 pcre
* re
= (anchor
== ANCHOR_BOTH
) ? re_full_
: re_partial_
;
510 //fprintf(stderr, "Matching against invalid re: %s\n", error_->c_str());
514 pcre_extra extra
= { 0, 0, 0, 0, 0, 0 };
515 if (options_
.match_limit() > 0) {
516 extra
.flags
|= PCRE_EXTRA_MATCH_LIMIT
;
517 extra
.match_limit
= options_
.match_limit();
519 if (options_
.match_limit_recursion() > 0) {
520 extra
.flags
|= PCRE_EXTRA_MATCH_LIMIT_RECURSION
;
521 extra
.match_limit_recursion
= options_
.match_limit_recursion();
525 // Changed by PH as a result of bugzilla #1288
526 int options
= (options_
.all_options() & PCRE_NO_UTF8_CHECK
);
528 if (anchor
!= UNANCHORED
)
529 options
|= PCRE_ANCHORED
;
531 options
|= PCRE_NOTEMPTY
;
533 int rc
= pcre_exec(re
, // The regular expression object
535 (text
.data() == NULL
) ? "" : text
.data(),
543 if (rc
== PCRE_ERROR_NOMATCH
) {
546 //fprintf(stderr, "Unexpected return code: %d when matching '%s'\n",
547 // re, pattern_.c_str());
549 } else if (rc
== 0) {
550 // pcre_exec() returns 0 as a special case when the number of
551 // capturing subpatterns exceeds the size of the vector.
552 // When this happens, there is a match and the output vector
553 // is filled, but we miss out on the positions of the extra subpatterns.
560 bool RE::DoMatchImpl(const StringPiece
& text
,
563 const Arg
* const* args
,
567 assert((1 + n
) * 3 <= vecsize
); // results + PCRE workspace
568 int matches
= TryMatch(text
, 0, anchor
, true, vec
, vecsize
);
569 assert(matches
>= 0); // TryMatch never returns negatives
575 if (n
== 0 || args
== NULL
) {
576 // We are not interested in results
580 if (NumberOfCapturingGroups() < n
) {
581 // RE has fewer capturing groups than number of arg pointers passed in
585 // If we got here, we must have matched the whole pattern.
586 // We do not need (can not do) any more checks on the value of 'matches' here
587 // -- see the comment for TryMatch.
588 for (int i
= 0; i
< n
; i
++) {
589 const int start
= vec
[2*(i
+1)];
590 const int limit
= vec
[2*(i
+1)+1];
591 if (!args
[i
]->Parse(text
.data() + start
, limit
-start
)) {
592 // TODO: Should we indicate what the error was?
600 bool RE::DoMatch(const StringPiece
& text
,
603 const Arg
* const args
[],
606 size_t const vecsize
= (1 + n
) * 3; // results + PCRE workspace
608 int space
[21]; // use stack allocation for small vecsize (common case)
609 int* vec
= vecsize
<= 21 ? space
: new int[vecsize
];
610 bool retval
= DoMatchImpl(text
, anchor
, consumed
, args
, n
, vec
, (int)vecsize
);
611 if (vec
!= space
) delete [] vec
;
615 bool RE::Rewrite(string
*out
, const StringPiece
&rewrite
,
616 const StringPiece
&text
, int *vec
, int veclen
) const {
617 for (const char *s
= rewrite
.data(), *end
= s
+ rewrite
.size();
625 //fprintf(stderr, requested group %d in regexp %.*s\n",
626 // n, rewrite.size(), rewrite.data());
629 int start
= vec
[2 * n
];
631 out
->append(text
.data() + start
, vec
[2 * n
+ 1] - start
);
632 } else if (c
== '\\') {
635 //fprintf(stderr, "invalid rewrite pattern: %.*s\n",
636 // rewrite.size(), rewrite.data());
646 // Return the number of capturing subpatterns, or -1 if the
647 // regexp wasn't valid on construction.
648 int RE::NumberOfCapturingGroups() const {
649 if (re_partial_
== NULL
) return -1;
652 int pcre_retval
= pcre_fullinfo(re_partial_
, // The regular expression object
653 NULL
, // We did not study the pattern
654 PCRE_INFO_CAPTURECOUNT
,
656 assert(pcre_retval
== 0);
660 /***** Parsers for various types *****/
662 bool Arg::parse_null(const char* str
, int n
, void* dest
) {
663 // We fail if somebody asked us to store into a non-NULL void* pointer
664 return (dest
== NULL
);
667 bool Arg::parse_string(const char* str
, int n
, void* dest
) {
668 if (dest
== NULL
) return true;
669 reinterpret_cast<string
*>(dest
)->assign(str
, n
);
673 bool Arg::parse_stringpiece(const char* str
, int n
, void* dest
) {
674 if (dest
== NULL
) return true;
675 reinterpret_cast<StringPiece
*>(dest
)->set(str
, n
);
679 bool Arg::parse_char(const char* str
, int n
, void* dest
) {
680 if (n
!= 1) return false;
681 if (dest
== NULL
) return true;
682 *(reinterpret_cast<char*>(dest
)) = str
[0];
686 bool Arg::parse_uchar(const char* str
, int n
, void* dest
) {
687 if (n
!= 1) return false;
688 if (dest
== NULL
) return true;
689 *(reinterpret_cast<unsigned char*>(dest
)) = str
[0];
693 // Largest number spec that we are willing to parse
694 static const int kMaxNumberLength
= 32;
696 // REQUIRES "buf" must have length at least kMaxNumberLength+1
698 // Copies "str" into "buf" and null-terminates if necessary.
700 // a. "str" if no termination is needed
701 // b. "buf" if the string was copied and null-terminated
702 // c. "" if the input was invalid and has no hope of being parsed
703 static const char* TerminateNumber(char* buf
, const char* str
, int n
) {
704 if ((n
> 0) && isspace(*str
)) {
705 // We are less forgiving than the strtoxxx() routines and do not
706 // allow leading spaces.
710 // See if the character right after the input text may potentially
711 // look like a digit.
712 if (isdigit(str
[n
]) ||
713 ((str
[n
] >= 'a') && (str
[n
] <= 'f')) ||
714 ((str
[n
] >= 'A') && (str
[n
] <= 'F'))) {
715 if (n
> kMaxNumberLength
) return ""; // Input too big to be a valid number
720 // We can parse right out of the supplied string, so return it.
725 bool Arg::parse_long_radix(const char* str
,
729 if (n
== 0) return false;
730 char buf
[kMaxNumberLength
+1];
731 str
= TerminateNumber(buf
, str
, n
);
734 long r
= strtol(str
, &end
, radix
);
735 if (end
!= str
+ n
) return false; // Leftover junk
736 if (errno
) return false;
737 if (dest
== NULL
) return true;
738 *(reinterpret_cast<long*>(dest
)) = r
;
742 bool Arg::parse_ulong_radix(const char* str
,
746 if (n
== 0) return false;
747 char buf
[kMaxNumberLength
+1];
748 str
= TerminateNumber(buf
, str
, n
);
749 if (str
[0] == '-') return false; // strtoul() on a negative number?!
752 unsigned long r
= strtoul(str
, &end
, radix
);
753 if (end
!= str
+ n
) return false; // Leftover junk
754 if (errno
) return false;
755 if (dest
== NULL
) return true;
756 *(reinterpret_cast<unsigned long*>(dest
)) = r
;
760 bool Arg::parse_short_radix(const char* str
,
765 if (!parse_long_radix(str
, n
, &r
, radix
)) return false; // Could not parse
766 if (r
< SHRT_MIN
|| r
> SHRT_MAX
) return false; // Out of range
767 if (dest
== NULL
) return true;
768 *(reinterpret_cast<short*>(dest
)) = static_cast<short>(r
);
772 bool Arg::parse_ushort_radix(const char* str
,
777 if (!parse_ulong_radix(str
, n
, &r
, radix
)) return false; // Could not parse
778 if (r
> USHRT_MAX
) return false; // Out of range
779 if (dest
== NULL
) return true;
780 *(reinterpret_cast<unsigned short*>(dest
)) = static_cast<unsigned short>(r
);
784 bool Arg::parse_int_radix(const char* str
,
789 if (!parse_long_radix(str
, n
, &r
, radix
)) return false; // Could not parse
790 if (r
< INT_MIN
|| r
> INT_MAX
) return false; // Out of range
791 if (dest
== NULL
) return true;
792 *(reinterpret_cast<int*>(dest
)) = r
;
796 bool Arg::parse_uint_radix(const char* str
,
801 if (!parse_ulong_radix(str
, n
, &r
, radix
)) return false; // Could not parse
802 if (r
> UINT_MAX
) return false; // Out of range
803 if (dest
== NULL
) return true;
804 *(reinterpret_cast<unsigned int*>(dest
)) = r
;
808 bool Arg::parse_longlong_radix(const char* str
,
812 #ifndef HAVE_LONG_LONG
815 if (n
== 0) return false;
816 char buf
[kMaxNumberLength
+1];
817 str
= TerminateNumber(buf
, str
, n
);
820 #if defined HAVE_STRTOQ
821 long long r
= strtoq(str
, &end
, radix
);
822 #elif defined HAVE_STRTOLL
823 long long r
= strtoll(str
, &end
, radix
);
824 #elif defined HAVE__STRTOI64
825 long long r
= _strtoi64(str
, &end
, radix
);
826 #elif defined HAVE_STRTOIMAX
827 long long r
= strtoimax(str
, &end
, radix
);
829 #error parse_longlong_radix: cannot convert input to a long-long
831 if (end
!= str
+ n
) return false; // Leftover junk
832 if (errno
) return false;
833 if (dest
== NULL
) return true;
834 *(reinterpret_cast<long long*>(dest
)) = r
;
836 #endif /* HAVE_LONG_LONG */
839 bool Arg::parse_ulonglong_radix(const char* str
,
843 #ifndef HAVE_UNSIGNED_LONG_LONG
846 if (n
== 0) return false;
847 char buf
[kMaxNumberLength
+1];
848 str
= TerminateNumber(buf
, str
, n
);
849 if (str
[0] == '-') return false; // strtoull() on a negative number?!
852 #if defined HAVE_STRTOQ
853 unsigned long long r
= strtouq(str
, &end
, radix
);
854 #elif defined HAVE_STRTOLL
855 unsigned long long r
= strtoull(str
, &end
, radix
);
856 #elif defined HAVE__STRTOI64
857 unsigned long long r
= _strtoui64(str
, &end
, radix
);
858 #elif defined HAVE_STRTOIMAX
859 unsigned long long r
= strtoumax(str
, &end
, radix
);
861 #error parse_ulonglong_radix: cannot convert input to a long-long
863 if (end
!= str
+ n
) return false; // Leftover junk
864 if (errno
) return false;
865 if (dest
== NULL
) return true;
866 *(reinterpret_cast<unsigned long long*>(dest
)) = r
;
868 #endif /* HAVE_UNSIGNED_LONG_LONG */
871 bool Arg::parse_double(const char* str
, int n
, void* dest
) {
872 if (n
== 0) return false;
873 static const int kMaxLength
= 200;
874 char buf
[kMaxLength
];
875 if (n
>= kMaxLength
) return false;
880 double r
= strtod(buf
, &end
);
881 if (end
!= buf
+ n
) return false; // Leftover junk
882 if (errno
) return false;
883 if (dest
== NULL
) return true;
884 *(reinterpret_cast<double*>(dest
)) = r
;
888 bool Arg::parse_float(const char* str
, int n
, void* dest
) {
890 if (!parse_double(str
, n
, &r
)) return false;
891 if (dest
== NULL
) return true;
892 *(reinterpret_cast<float*>(dest
)) = static_cast<float>(r
);
897 #define DEFINE_INTEGER_PARSERS(name) \
898 bool Arg::parse_##name(const char* str, int n, void* dest) { \
899 return parse_##name##_radix(str, n, dest, 10); \
901 bool Arg::parse_##name##_hex(const char* str, int n, void* dest) { \
902 return parse_##name##_radix(str, n, dest, 16); \
904 bool Arg::parse_##name##_octal(const char* str, int n, void* dest) { \
905 return parse_##name##_radix(str, n, dest, 8); \
907 bool Arg::parse_##name##_cradix(const char* str, int n, void* dest) { \
908 return parse_##name##_radix(str, n, dest, 0); \
911 DEFINE_INTEGER_PARSERS(short) /* */
912 DEFINE_INTEGER_PARSERS(ushort
) /* */
913 DEFINE_INTEGER_PARSERS(int) /* Don't use semicolons after these */
914 DEFINE_INTEGER_PARSERS(uint
) /* statements because they can cause */
915 DEFINE_INTEGER_PARSERS(long) /* compiler warnings if the checking */
916 DEFINE_INTEGER_PARSERS(ulong
) /* level is turned up high enough. */
917 DEFINE_INTEGER_PARSERS(longlong
) /* */
918 DEFINE_INTEGER_PARSERS(ulonglong
) /* */
920 #undef DEFINE_INTEGER_PARSERS
922 } // namespace pcrecpp