blob: 0543795e1d4d5f39cf4b1a0508e1cdce6dc9af4d [file] [log] [blame]
Elliott Hughesafe151f2015-09-04 16:26:51 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef BASE_PARSEINT_H
18#define BASE_PARSEINT_H
19
20#include <errno.h>
21#include <stdlib.h>
22
23#include <limits>
24
25namespace android {
26namespace base {
27
28// Parses the unsigned decimal integer in the string 's' and sets 'out' to
29// that value. Optionally allows the caller to define a 'max' beyond which
30// otherwise valid values will be rejected. Returns boolean success.
31template <typename T>
32bool ParseUint(const char* s, T* out,
33 T max = std::numeric_limits<T>::max()) {
Elliott Hughes3ab05862015-11-02 09:01:53 -080034 int base = (s[0] == '0' && s[1] == 'x') ? 16 : 10;
Elliott Hughesafe151f2015-09-04 16:26:51 -070035 errno = 0;
36 char* end;
Elliott Hughes3ab05862015-11-02 09:01:53 -080037 unsigned long long int result = strtoull(s, &end, base);
Elliott Hughesafe151f2015-09-04 16:26:51 -070038 if (errno != 0 || s == end || *end != '\0') {
39 return false;
40 }
41 if (max < result) {
42 return false;
43 }
44 *out = static_cast<T>(result);
45 return true;
46}
47
48// Parses the signed decimal integer in the string 's' and sets 'out' to
49// that value. Optionally allows the caller to define a 'min' and 'max
50// beyond which otherwise valid values will be rejected. Returns boolean
51// success.
52template <typename T>
53bool ParseInt(const char* s, T* out,
54 T min = std::numeric_limits<T>::min(),
55 T max = std::numeric_limits<T>::max()) {
Elliott Hughes3ab05862015-11-02 09:01:53 -080056 int base = (s[0] == '0' && s[1] == 'x') ? 16 : 10;
Elliott Hughesafe151f2015-09-04 16:26:51 -070057 errno = 0;
58 char* end;
Elliott Hughes3ab05862015-11-02 09:01:53 -080059 long long int result = strtoll(s, &end, base);
Elliott Hughesafe151f2015-09-04 16:26:51 -070060 if (errno != 0 || s == end || *end != '\0') {
61 return false;
62 }
63 if (result < min || max < result) {
64 return false;
65 }
66 *out = static_cast<T>(result);
67 return true;
68}
69
70} // namespace base
71} // namespace android
72
73#endif // BASE_PARSEINT_H