Update for 1.4.18
[xapian.git] / xapian-core / common / parseint.h
blobc94cfdddde0b36982441c7eacca0d5c711369378
1 /** @file
2 * @brief Parse signed and unsigned type from string and check for trailing characters.
3 */
4 /* Copyright (C) 2019 Olly Betts
5 * Copyright (C) 2019 Vaibhav Kansagara
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.
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.
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
21 #ifndef XAPIAN_INCLUDED_PARSEINT_H
22 #define XAPIAN_INCLUDED_PARSEINT_H
24 #include "overflow.h"
25 #include <limits>
27 template<typename T>
28 bool parse_unsigned(const char* p, T& res)
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;
38 } while (*++p);
39 return true;
42 template<typename T>
43 bool parse_signed(const char* p, T& res)
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;
57 return false;
60 #endif