1/*
2 * Copyright (C) 2017 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 "util/strings/numbers.h"
18
19#ifdef COMPILER_MSVC
20#include <sstream>
21#endif  // COMPILER_MSVC
22
23#include <stdlib.h>
24
25namespace libtextclassifier {
26
27bool ParseInt32(const char *c_str, int32 *value) {
28  char *temp;
29
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  *value = strtol(c_str, &temp, 0);  // NOLINT
40
41  // temp != c_str means that the input string contained at least one digit (see
42  // above).  *temp == '\0' means the input string does not contain any random
43  // chars after the number.
44  return (temp != c_str) && (*temp == '\0');
45}
46
47bool ParseInt64(const char *c_str, int64 *value) {
48  char *temp;
49  *value = strtoll(c_str, &temp, 0);  // NOLINT
50
51  // See comments inside ParseInt32.
52  return (temp != c_str) && (*temp == '\0');
53}
54
55bool ParseDouble(const char *c_str, double *value) {
56  char *temp;
57  *value = strtod(c_str, &temp);
58
59  // See comments inside ParseInt32.
60  return (temp != c_str) && (*temp == '\0');
61}
62
63#ifdef COMPILER_MSVC
64std::string IntToString(int64 input) {
65  std::stringstream stream;
66  stream << input;
67  return stream.str();
68}
69#else
70std::string IntToString(int64 input) {
71  return std::to_string(input);
72}
73#endif  // COMPILER_MSVC
74
75}  // namespace libtextclassifier
76