1 /*
2 * Copyright (C) 2018 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 #include "utils/strings/numbers.h"
18
19 #ifdef COMPILER_MSVC
20 #include <sstream>
21 #endif // COMPILER_MSVC
22
23 #include <stdlib.h>
24
25 namespace libtextclassifier3 {
26
27 // This conversion is only valid for numerical base is 10 (radix)
ParseInt32(const char * c_str,int32 * value)28 bool ParseInt32(const char *c_str, int32 *value) {
29 char *temp;
30 // Short version of man strtol:
31 //
32 // strtol parses some optional whitespaces, an optional +/- sign, and next a
33 // succession of digits. If it finds some digits, it sets temp to point to
34 // the first character after that succession of digits and returns the parsed
35 // integer.
36 //
37 // If there were no digits at all, strtol() sets temp to be c_str (the start
38 // address) and returns 0.
39 // Explicitly setting this to base 10 as 0 means the base used is determined
40 // by the format which can cause problems
41 *value = strtol(c_str, &temp, 10); // NOLINT
42
43 // temp != c_str means that the input string contained at least one digit (see
44 // above). *temp == '\0' means the input string does not contain any random
45 // chars after the number.
46 return (temp != c_str) && (*temp == '\0');
47 }
48
49 // This conversion is only valid for numerical base is 10 (radix)
ParseInt64(const char * c_str,int64 * value)50 bool ParseInt64(const char *c_str, int64 *value) {
51 char *temp;
52
53 // Explicitly setting this to base 10 as 0 means the base used is determined
54 // by the format which can cause problems
55 *value = strtoll(c_str, &temp, 10); // NOLINT
56
57 // See comments inside ParseInt32.
58 return (temp != c_str) && (*temp == '\0');
59 }
60
ParseDouble(const char * c_str,double * value)61 bool ParseDouble(const char *c_str, double *value) {
62 char *temp;
63 *value = strtod(c_str, &temp);
64
65 // See comments inside ParseInt32.
66 return (temp != c_str) && (*temp == '\0');
67 }
68
69 #ifdef COMPILER_MSVC
IntToString(int64 input)70 std::string IntToString(int64 input) {
71 std::stringstream stream;
72 stream << input;
73 return stream.str();
74 }
75 #else
IntToString(int64 input)76 std::string IntToString(int64 input) {
77 return std::to_string(input);
78 }
79 #endif // COMPILER_MSVC
80
81 } // namespace libtextclassifier3
82