xapian-core  2.0.0
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, see
19  * <https://www.gnu.org/licenses/>.
20  */
21 #ifndef XAPIAN_INCLUDED_PARSEINT_H
22 #define XAPIAN_INCLUDED_PARSEINT_H
23 
24 #include "negate_unsigned.h"
25 #include "overflow.h"
26 #include <limits>
27 
28 template<typename T>
29 bool parse_unsigned(const char* p, T& res)
30 {
31  res = 0;
32  do {
33  unsigned char digit = *p - '0';
34  if (digit > 9 ||
35  mul_overflows(res, unsigned(10), res) ||
36  add_overflows(res, digit, res)) {
37  return false;
38  }
39  } while (*++p);
40  return true;
41 }
42 
43 template<typename T>
44 bool parse_signed(const char* p, T& res)
45 {
46  typedef typename std::make_unsigned_t<T> unsigned_type;
47  unsigned_type temp = 0;
48  if (*p == '-' && parse_unsigned(++p, temp) &&
49  // casting the min signed value to unsigned gives us its absolute value.
50  temp <= unsigned_type(std::numeric_limits<T>::min())) {
51  res = negate_unsigned(temp);
52  return true;
53  } else if (parse_unsigned(p, temp) &&
54  temp <= unsigned_type(std::numeric_limits<T>::max())) {
55  res = temp;
56  return true;
57  }
58  return false;
59 }
60 
61 #endif
PositionList * p
Negate unsigned integer, avoiding compiler warnings.
constexpr std::enable_if_t< std::is_unsigned_v< T >, T > negate_unsigned(T value)
Arithmetic operations with overflow checks.
std::enable_if_t< std::is_unsigned_v< T1 > &&std::is_unsigned_v< T2 > &&std::is_unsigned_v< R >, bool > add_overflows(T1 a, T2 b, R &res)
Addition with overflow checking.
Definition: overflow.h:58
std::enable_if_t< std::is_unsigned_v< T1 > &&std::is_unsigned_v< T2 > &&std::is_unsigned_v< R >, bool > mul_overflows(T1 a, T2 b, R &res)
Multiplication with overflow checking.
Definition: overflow.h:188
bool parse_signed(const char *p, T &res)
Definition: parseint.h:44
bool parse_unsigned(const char *p, T &res)
Definition: parseint.h:29