xref: /aosp_15_r20/external/cronet/base/strings/string_number_conversions.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 BASE_EXPORT std::string HexEncode(StringPiece chars);
110 
111 // Appends a hex representation of `byte`, as two uppercase (by default)
112 // characters, to `output`. This is a useful primitive in larger conversion
113 // routines.
114 inline void AppendHexEncodedByte(uint8_t byte,
115                                  std::string& output,
116                                  bool uppercase = true) {
117   static constexpr char kHexCharsUpper[] = {'0', '1', '2', '3', '4', '5',
118                                             '6', '7', '8', '9', 'A', 'B',
119                                             'C', 'D', 'E', 'F'};
120   static constexpr char kHexCharsLower[] = {'0', '1', '2', '3', '4', '5',
121                                             '6', '7', '8', '9', 'a', 'b',
122                                             'c', 'd', 'e', 'f'};
123   const char* const hex_chars = uppercase ? kHexCharsUpper : kHexCharsLower;
124   output.append({hex_chars[byte >> 4], hex_chars[byte & 0xf]});
125 }
126 
127 // Best effort conversion, see StringToInt above for restrictions.
128 // Will only successful parse hex values that will fit into |output|, i.e.
129 // -0x80000000 < |input| < 0x7FFFFFFF.
130 BASE_EXPORT bool HexStringToInt(StringPiece input, int* output);
131 
132 // Best effort conversion, see StringToInt above for restrictions.
133 // Will only successful parse hex values that will fit into |output|, i.e.
134 // 0x00000000 < |input| < 0xFFFFFFFF.
135 // The string is not required to start with 0x.
136 BASE_EXPORT bool HexStringToUInt(StringPiece input, uint32_t* 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 // -0x8000000000000000 < |input| < 0x7FFFFFFFFFFFFFFF.
141 BASE_EXPORT bool HexStringToInt64(StringPiece input, int64_t* output);
142 
143 // Best effort conversion, see StringToInt above for restrictions.
144 // Will only successful parse hex values that will fit into |output|, i.e.
145 // 0x0000000000000000 < |input| < 0xFFFFFFFFFFFFFFFF.
146 // The string is not required to start with 0x.
147 BASE_EXPORT bool HexStringToUInt64(StringPiece input, uint64_t* output);
148 
149 // Similar to the previous functions, except that output is a vector of bytes.
150 // |*output| will contain as many bytes as were successfully parsed prior to the
151 // error.  There is no overflow, but input.size() must be evenly divisible by 2.
152 // Leading 0x or +/- are not allowed.
153 BASE_EXPORT bool HexStringToBytes(StringPiece input,
154                                   std::vector<uint8_t>* output);
155 
156 // Same as HexStringToBytes, but for an std::string.
157 BASE_EXPORT bool HexStringToString(StringPiece input, std::string* output);
158 
159 // Decodes the hex string |input| into a presized |output|. The output buffer
160 // must be sized exactly to |input.size() / 2| or decoding will fail and no
161 // bytes will be written to |output|. Decoding an empty input is also
162 // considered a failure. When decoding fails due to encountering invalid input
163 // characters, |output| will have been filled with the decoded bytes up until
164 // the failure.
165 BASE_EXPORT bool HexStringToSpan(StringPiece input, base::span<uint8_t> output);
166 
167 }  // namespace base
168 
169 #if BUILDFLAG(IS_WIN)
170 #include "base/strings/string_number_conversions_win.h"
171 #endif
172 
173 #endif  // BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
174