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