• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
6 #define BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <string>
12 #include <vector>
13 
14 #include "base/base_export.h"
15 #include "base/containers/span.h"
16 #include "base/strings/string_piece.h"
17 #include "build/build_config.h"
18 
19 // ----------------------------------------------------------------------------
20 // IMPORTANT MESSAGE FROM YOUR SPONSOR
21 //
22 // Please do not add "convenience" functions for converting strings to integers
23 // that return the value and ignore success/failure. That encourages people to
24 // write code that doesn't properly handle the error conditions.
25 //
26 // DO NOT use these functions in any UI unless it's NOT localized on purpose.
27 // Instead, use base::MessageFormatter for a complex message with numbers
28 // (integer, float, double) embedded or base::Format{Number,Double,Percent} to
29 // just format a single number/percent. Note that some languages use native
30 // digits instead of ASCII digits while others use a group separator or decimal
31 // point different from ',' and '.'. Using these functions in the UI would lead
32 // numbers to be formatted in a non-native way.
33 // ----------------------------------------------------------------------------
34 
35 namespace base {
36 
37 // Number -> string conversions ------------------------------------------------
38 
39 // Ignores locale! see warning above.
40 BASE_EXPORT std::string NumberToString(int value);
41 BASE_EXPORT std::u16string NumberToString16(int value);
42 BASE_EXPORT std::string NumberToString(unsigned int value);
43 BASE_EXPORT std::u16string NumberToString16(unsigned int value);
44 BASE_EXPORT std::string NumberToString(long value);
45 BASE_EXPORT std::u16string NumberToString16(long value);
46 BASE_EXPORT std::string NumberToString(unsigned long value);
47 BASE_EXPORT std::u16string NumberToString16(unsigned long value);
48 BASE_EXPORT std::string NumberToString(long long value);
49 BASE_EXPORT std::u16string NumberToString16(long long value);
50 BASE_EXPORT std::string NumberToString(unsigned long long value);
51 BASE_EXPORT std::u16string NumberToString16(unsigned long long value);
52 BASE_EXPORT std::string NumberToString(double value);
53 BASE_EXPORT std::u16string NumberToString16(double value);
54 
55 // String -> number conversions ------------------------------------------------
56 
57 // Perform a best-effort conversion of the input string to a numeric type,
58 // setting |*output| to the result of the conversion.  Returns true for
59 // "perfect" conversions; returns false in the following cases:
60 //  - Overflow. |*output| will be set to the maximum value supported
61 //    by the data type.
62 //  - Underflow. |*output| will be set to the minimum value supported
63 //    by the data type.
64 //  - Trailing characters in the string after parsing the number.  |*output|
65 //    will be set to the value of the number that was parsed.
66 //  - Leading whitespace in the string before parsing the number. |*output| will
67 //    be set to the value of the number that was parsed.
68 //  - No characters parseable as a number at the beginning of the string.
69 //    |*output| will be set to 0.
70 //  - Empty string.  |*output| will be set to 0.
71 // WARNING: Will write to |output| even when returning false.
72 //          Read the comments above carefully.
73 BASE_EXPORT bool StringToInt(StringPiece input, int* output);
74 BASE_EXPORT bool StringToInt(StringPiece16 input, int* output);
75 
76 BASE_EXPORT bool StringToUint(StringPiece input, unsigned* output);
77 BASE_EXPORT bool StringToUint(StringPiece16 input, unsigned* output);
78 
79 BASE_EXPORT bool StringToInt64(StringPiece input, int64_t* output);
80 BASE_EXPORT bool StringToInt64(StringPiece16 input, int64_t* output);
81 
82 BASE_EXPORT bool StringToUint64(StringPiece input, uint64_t* output);
83 BASE_EXPORT bool StringToUint64(StringPiece16 input, uint64_t* output);
84 
85 BASE_EXPORT bool StringToSizeT(StringPiece input, size_t* output);
86 BASE_EXPORT bool StringToSizeT(StringPiece16 input, size_t* output);
87 
88 // For floating-point conversions, only conversions of input strings in decimal
89 // form are defined to work.  Behavior with strings representing floating-point
90 // numbers in hexadecimal, and strings representing non-finite values (such as
91 // NaN and inf) is undefined.  Otherwise, these behave the same as the integral
92 // variants.  This expects the input string to NOT be specific to the locale.
93 // If your input is locale specific, use ICU to read the number.
94 // WARNING: Will write to |output| even when returning false.
95 //          Read the comments here and above StringToInt() carefully.
96 BASE_EXPORT bool StringToDouble(StringPiece input, double* output);
97 BASE_EXPORT bool StringToDouble(StringPiece16 input, double* output);
98 
99 // Hex encoding ----------------------------------------------------------------
100 
101 // Returns a hex string representation of a binary buffer. The returned hex
102 // string will be in upper case. This function does not check if |size| is
103 // within reasonable limits since it's written with trusted data in mind.  If
104 // you suspect that the data you want to format might be large, the absolute
105 // max size for |size| should be is
106 //   std::numeric_limits<size_t>::max() / 2
107 BASE_EXPORT std::string HexEncode(const void* bytes, size_t size);
108 BASE_EXPORT std::string HexEncode(base::span<const uint8_t> bytes);
109 
110 // Appends a hex representation of `byte`, as two uppercase (by default)
111 // characters, to `output`. This is a useful primitive in larger conversion
112 // routines.
113 inline void AppendHexEncodedByte(uint8_t byte,
114                                  std::string& output,
115                                  bool uppercase = true) {
116   static constexpr char kHexCharsUpper[] = {'0', '1', '2', '3', '4', '5',
117                                             '6', '7', '8', '9', 'A', 'B',
118                                             'C', 'D', 'E', 'F'};
119   static constexpr char kHexCharsLower[] = {'0', '1', '2', '3', '4', '5',
120                                             '6', '7', '8', '9', 'a', 'b',
121                                             'c', 'd', 'e', 'f'};
122   const char* const hex_chars = uppercase ? kHexCharsUpper : kHexCharsLower;
123   output.append({hex_chars[byte >> 4], hex_chars[byte & 0xf]});
124 }
125 
126 // Best effort conversion, see StringToInt above for restrictions.
127 // Will only successful parse hex values that will fit into |output|, i.e.
128 // -0x80000000 < |input| < 0x7FFFFFFF.
129 BASE_EXPORT bool HexStringToInt(StringPiece input, int* output);
130 
131 // Best effort conversion, see StringToInt above for restrictions.
132 // Will only successful parse hex values that will fit into |output|, i.e.
133 // 0x00000000 < |input| < 0xFFFFFFFF.
134 // The string is not required to start with 0x.
135 BASE_EXPORT bool HexStringToUInt(StringPiece input, uint32_t* output);
136 
137 // Best effort conversion, see StringToInt above for restrictions.
138 // Will only successful parse hex values that will fit into |output|, i.e.
139 // -0x8000000000000000 < |input| < 0x7FFFFFFFFFFFFFFF.
140 BASE_EXPORT bool HexStringToInt64(StringPiece input, int64_t* output);
141 
142 // Best effort conversion, see StringToInt above for restrictions.
143 // Will only successful parse hex values that will fit into |output|, i.e.
144 // 0x0000000000000000 < |input| < 0xFFFFFFFFFFFFFFFF.
145 // The string is not required to start with 0x.
146 BASE_EXPORT bool HexStringToUInt64(StringPiece input, uint64_t* output);
147 
148 // Similar to the previous functions, except that output is a vector of bytes.
149 // |*output| will contain as many bytes as were successfully parsed prior to the
150 // error.  There is no overflow, but input.size() must be evenly divisible by 2.
151 // Leading 0x or +/- are not allowed.
152 BASE_EXPORT bool HexStringToBytes(StringPiece input,
153                                   std::vector<uint8_t>* output);
154 
155 // Same as HexStringToBytes, but for an std::string.
156 BASE_EXPORT bool HexStringToString(StringPiece input, std::string* output);
157 
158 // Decodes the hex string |input| into a presized |output|. The output buffer
159 // must be sized exactly to |input.size() / 2| or decoding will fail and no
160 // bytes will be written to |output|. Decoding an empty input is also
161 // considered a failure. When decoding fails due to encountering invalid input
162 // characters, |output| will have been filled with the decoded bytes up until
163 // the failure.
164 BASE_EXPORT bool HexStringToSpan(StringPiece input, base::span<uint8_t> output);
165 
166 }  // namespace base
167 
168 #if BUILDFLAG(IS_WIN)
169 #include "base/strings/string_number_conversions_win.h"
170 #endif
171 
172 #endif  // BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
173