xapian-core  1.4.25
parseint.h
Go to the documentation of this file.
1 
4 /* Copyright (C) 2019 Olly Betts
5  * Copyright (C) 2019 Vaibhav Kansagara
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 #ifndef XAPIAN_INCLUDED_PARSEINT_H
22 #define XAPIAN_INCLUDED_PARSEINT_H
23 
24 #include "overflow.h"
25 #include <limits>
26 
27 template<typename T>
28 bool parse_unsigned(const char* p, T& res)
29 {
30  res = 0;
31  do {
32  unsigned char digit = *p - '0';
33  if (digit > 9 ||
34  mul_overflows(res, unsigned(10), res) ||
35  add_overflows(res, digit, res)) {
36  return false;
37  }
38  } while (*++p);
39  return true;
40 }
41 
42 template<typename T>
43 bool parse_signed(const char* p, T& res)
44 {
45  typedef typename std::make_unsigned<T>::type unsigned_type;
46  unsigned_type temp = 0;
47  if (*p == '-' && parse_unsigned(++p, temp) &&
48  // casting the min signed value to unsigned gives us its absolute value.
49  temp <= unsigned_type(std::numeric_limits<T>::min())) {
50  res = -temp;
51  return true;
52  } else if (parse_unsigned(p, temp) &&
53  temp <= unsigned_type(std::numeric_limits<T>::max())) {
54  res = temp;
55  return true;
56  }
57  return false;
58 }
59 
60 #endif
std::enable_if< std::is_unsigned< T1 >::value &&std::is_unsigned< T2 >::value &&std::is_unsigned< R >::value, bool >::type add_overflows(T1 a, T2 b, R &res)
Addition with overflow checking.
Definition: overflow.h:58
Arithmetic operations with overflow checks.
bool parse_signed(const char *p, T &res)
Definition: parseint.h:43
std::enable_if< std::is_unsigned< T1 >::value &&std::is_unsigned< T2 >::value &&std::is_unsigned< R >::value, bool >::type mul_overflows(T1 a, T2 b, R &res)
Multiplication with overflow checking.
Definition: overflow.h:188
bool parse_unsigned(const char *p, T &res)
Definition: parseint.h:28