1 /*
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 ANDROID_BASE_PARSEINT_H
18 #define ANDROID_BASE_PARSEINT_H
19 
20 #include <errno.h>
21 #include <stdlib.h>
22 
23 #include <limits>
24 
25 namespace android {
26 namespace 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.
31 template <typename T>
32 bool ParseUint(const char* s, T* out,
33                T max = std::numeric_limits<T>::max()) {
34   int base = (s[0] == '0' && s[1] == 'x') ? 16 : 10;
35   errno = 0;
36   char* end;
37   unsigned long long int result = strtoull(s, &end, base);
38   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.
52 template <typename T>
53 bool ParseInt(const char* s, T* out,
54               T min = std::numeric_limits<T>::min(),
55               T max = std::numeric_limits<T>::max()) {
56   int base = (s[0] == '0' && s[1] == 'x') ? 16 : 10;
57   errno = 0;
58   char* end;
59   long long int result = strtoll(s, &end, base);
60   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  // ANDROID_BASE_PARSEINT_H
74