• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef ECMASCRIPT_BASE_NUMBER_HELPER_H
17 #define ECMASCRIPT_BASE_NUMBER_HELPER_H
18 
19 #include <cstdint>
20 
21 #include "common_components/objects/string_table/integer_cache.h"
22 #include "ecmascript/ecma_string.h"
23 #include "ecmascript/js_tagged_value.h"
24 
25 namespace panda::ecmascript::base {
26 constexpr double MIN_RADIX = 2;
27 constexpr double MAX_RADIX = 36;
28 constexpr double MIN_FRACTION = 0;
29 constexpr double MAX_FRACTION = 100;
30 
31 // Coversion flags
32 static constexpr uint32_t NO_FLAGS = 0U;
33 static constexpr uint32_t ALLOW_BINARY = 1U << 0U;
34 static constexpr uint32_t ALLOW_OCTAL = 1U << 1U;
35 static constexpr uint32_t ALLOW_HEX = 1U << 2U;
36 static constexpr uint32_t IGNORE_TRAILING = 1U << 3U;
37 
38 static constexpr char HALFCHAR = '5';
39 static constexpr uint32_t MAX_PRECISION = 16;
40 static constexpr uint8_t BINARY = 2;
41 static constexpr uint8_t OCTAL = 8;
42 static constexpr uint8_t DECIMAL = 10;
43 static constexpr uint8_t HEXADECIMAL = 16;
44 static constexpr double HALF = 0.5;
45 static constexpr double EPSILON = std::numeric_limits<double>::epsilon();
46 static constexpr int64_t MAX_SAFE_INTEGER = 9007199254740991;
47 static constexpr double MAX_VALUE = std::numeric_limits<double>::max();
48 static constexpr double MIN_VALUE = std::numeric_limits<double>::min();
49 static constexpr double POSITIVE_INFINITY = std::numeric_limits<double>::infinity();
50 static constexpr double NAN_VALUE = std::numeric_limits<double>::quiet_NaN();
51 static constexpr uint64_t MAX_UINT64_VALUE = std::numeric_limits<uint64_t>::max();
52 static constexpr int MAX_INT_VALUE = std::numeric_limits<int>::max();
53 
54 // Helper defines for double
55 static constexpr int DOUBLE_MAX_PRECISION = 17;
56 static constexpr int DOUBLE_EXPONENT_BIAS = 0x3FF;
57 static constexpr size_t DOUBLE_SIGNIFICAND_SIZE = 52;
58 static constexpr uint64_t DOUBLE_SIGN_MASK = 0x8000000000000000ULL;
59 static constexpr uint64_t DOUBLE_EXPONENT_MASK = 0x7FFULL << DOUBLE_SIGNIFICAND_SIZE;
60 static constexpr uint64_t DOUBLE_SIGNIFICAND_MASK = 0x000FFFFFFFFFFFFFULL;
61 static constexpr uint64_t DOUBLE_HIDDEN_BIT = 1ULL << DOUBLE_SIGNIFICAND_SIZE;
62 static constexpr int32_t MINUS_ZERO_LOBITS = static_cast<int32_t>(0);
63 static constexpr int32_t MINUS_ZERO_HIBITS = static_cast<int32_t>(1) << 31;
64 static constexpr int64_t MINUS_ZERO_BITS = (static_cast<uint64_t>(MINUS_ZERO_HIBITS) << 32) | MINUS_ZERO_LOBITS;
65 static constexpr size_t INT64_BITS = 64;
66 static constexpr size_t INT32_BITS = 32;
67 static constexpr size_t INT16_BITS = 16;
68 static constexpr size_t INT8_BITS = 8;
69 static constexpr size_t JS_DTOA_BUF_SIZE = 128;
70 
71 // Max number of hexadecimal digits to display an integer
72 static constexpr size_t INT64_HEX_DIGITS = INT64_BITS / 4;
73 static constexpr size_t INT32_HEX_DIGITS = INT32_BITS / 4;
74 static constexpr size_t INT16_HEX_DIGITS = INT16_BITS / 4;
75 static constexpr size_t INT8_HEX_DIGITS = INT8_BITS / 4;
76 
77 static constexpr int EXPONENTBIAS =  DOUBLE_EXPONENT_BIAS + DOUBLE_SIGNIFICAND_SIZE;
78 static constexpr int kDENORMAL = -EXPONENTBIAS + 1;
79 static constexpr uint64_t kINFINITY = 0x7FF0'0000'0000'0000;
80 
81 // help defines for random
82 static constexpr int RIGHT12 = 12;
83 static constexpr int SECONDS_TO_SUBTLE = 1000000;
84 static constexpr int RIGHT27 = 27;
85 static constexpr int LEFT25 = 25;
86 static constexpr uint64_t GET_MULTIPLY = 0x2545F4914F6CDD1D;
87 // Exponent bits for double value between [1.0, 2.0)
88 static constexpr uint64_t EXPONENTBITS_RANGE_IN_ONE_AND_TWO = 0x3FF0000000000000;
89 
90 // Special Value for Hole in ElementsKind
91 static constexpr uint64_t SPECIAL_HOLE = 0xFFFE000000000001;
92 
93 // Special Value for Hole in ElementsKind
94 static constexpr uint32_t PGO_POLY_INLINE_REP = 0x7FFFFFFF;
95 
96 //
97 static constexpr int MAX_DIGITS = 21;
98 static constexpr int MIN_DIGITS = -6;
99 
100 // NumberFormat type
101 static constexpr int VAR_FORMAT = 0;
102 static constexpr int FIXED_FORMAT = 1;
103 static constexpr int FRAC_FORMAT  = 2;
104 static constexpr int FORCE_FORMAT = 4;
105 
106 // means add the point char to buf
107 static constexpr int POINT_INDEX = 3;
108 static constexpr int DECIMAL_INDEX = 2;
109 
110 class NumberHelper {
111 public:
112     // double to string buffer offset
113     static constexpr int BUFFER_OFFSET = 8;
114     static constexpr size_t MAX_INTEGER_STRING_LENGTH = 10;
115     static const CString NAN_STR;
116     static const CString ZERO_STR;
117     static const CString MINUS_INFINITY_STR;
118     static const CString INFINITY_STR;
GetNaN()119     static inline JSTaggedType GetNaN()
120     {
121         return JSTaggedValue(NAN_VALUE).GetRawData();
122     }
123 
124     static inline JSTaggedType GetPositiveInfinity()
125     {
126         return JSTaggedValue(POSITIVE_INFINITY).GetRawData();
127     }
128 
129     static bool IsFinite(JSTaggedValue number)
130     {
131         return number.IsInt() || (number.IsDouble() && std::isfinite(number.GetDouble()));
132     }
133     static bool IsNaN(JSTaggedValue number)
134     {
135         return number.IsDouble() && std::isnan(number.GetDouble());
136     }
137 
138     static bool inline IsDenormal(uint64_t x)
139     {
140         return (x & kINFINITY) == 0;
141     }
142 
143     static int inline Exponent(double x)
144     {
145         uint64_t value =  base::bit_cast<uint64_t>(x);
146         if (IsDenormal(value)) {
147             return kDENORMAL;
148         }
149         int biased = static_cast<int>((value & kINFINITY) >> DOUBLE_SIGNIFICAND_SIZE);
150         return biased - EXPONENTBIAS;
151     }
152 
153     static uint64_t inline Significand(double x)
154     {
155         uint64_t value =  base::bit_cast<uint64_t>(x);
156         uint64_t significand = value & DOUBLE_SIGNIFICAND_MASK;
157         if (!IsDenormal(value)) {
158             return significand + DOUBLE_HIDDEN_BIT;
159         } else {
160             return significand;
161         }
162     }
163 
164     static bool inline IsSafeIntegerNumber(double d)
165     {
166         double number = TruncateDouble(d);
167         return (number == d) && std::abs(d) <= MAX_SAFE_INTEGER;
168     }
169 
170     // The result should be less or equal than maxValue, if not, will return false.
171     // Type T only support uint32_t and int32_t, and don't support negative int.
172     template <typename T, typename ElemType>
173     static bool StringToUint(const std::basic_string_view<ElemType> str, T& result, uint64_t maxValue)
174     {
175         static_assert(std::is_same_v<T, uint32_t> || std::is_same_v<T, int32_t>);
176         static_assert(sizeof(ElemType) == sizeof(uint8_t));
177         constexpr T base = 10;
178         if (str.empty() || str.size() > MAX_INTEGER_STRING_LENGTH) {
179             return false;
180         }
181         if (str.size() > 1 && str[0] == '0') {
182             return false;
183         }
184         uint64_t value = 0;
185         for (const uint8_t c : str) {
186             if (c > '9' || c < '0') {
187                 return false;
188             }
189             value = value * base + (c - '0');
190         }
191         if UNLIKELY(value > maxValue) {
192             return false;
193         }
194         result = static_cast<T>(value);
195         return true;
196     }
197 
198     static JSTaggedValue DoubleToString(JSThread *thread, double number, int radix);
199     static bool IsEmptyString(const uint8_t *start, const uint8_t *end);
200     static JSHandle<EcmaString> IntToEcmaString(const JSThread *thread, int number);
201     static CString DoubleToCString(double d);
202     static uint32_t ToCharCode(uint32_t number);
203     static JSTaggedValue Int32ToString(JSThread *thread, int32_t number, uint32_t radix);
204     static JSHandle<EcmaString> NumberToString(const JSThread *thread, JSTaggedValue number);
205     static double PUBLIC_API TruncateDouble(double d);
206     static int64_t DoubleToInt64(double d);
207     static uint64_t DoubleToUInt64(double d);
208     static bool IsDigitalString(const uint8_t *start, const uint8_t *end);
209     static int StringToInt(const uint8_t *start, const uint8_t *end);
210     static std::pair<bool, JSTaggedNumber> FastStringToNumber(const uint8_t *start,
211                                                               const uint8_t *end, common::IntegerCache *cache);
212     static double StringToDouble(const uint8_t *start, const uint8_t *end, uint8_t radix, uint32_t flags = NO_FLAGS);
213     static int32_t DoubleToInt(double d, size_t bits);
214     static int32_t PUBLIC_API DoubleInRangeInt32(double d);
215     static int32_t PUBLIC_API SaturateTruncDoubleToInt32(double d);
216     static JSTaggedValue StringToNumber(JSThread *thread, EcmaString *string, int32_t radix);
217     static JSTaggedValue StringToDoubleWithRadix(const uint8_t *start, const uint8_t *end, int radix, bool *negative);
218     static CString IntToString(int number);
219     template <typename DstType>
AppendIntToString(DstType & str,int number)220     static void AppendIntToString(DstType &str, int number)
221     {
222         return AppendIntToCString(str, number);
223     }
224     static CString IntegerToString(double number, int radix);
225     static JSTaggedValue PUBLIC_API StringToBigInt(JSThread *thread, JSHandle<JSTaggedValue> strVal);
226     static JSTaggedValue DoubleToExponential(JSThread *thread, double number, int digit);
227     static JSTaggedValue DoubleToASCII(JSThread *thread, double valueNumber, int digits, int flags);
228     static JSTaggedValue DoubleToFixedString(JSThread *thread, double valueNumber, int digits);
229     static JSTaggedValue DoubleToPrecisionString(JSThread *thread, double valueNumber, int digits);
230     static void DoubleToASCIIWithFlag(std::string& buf, double valueNumber, int digits, int flags);
231     static void ToASCIIWithNegative(std::string& tmpbuf, int digitNumber, int n, const std::string& buf);
232     static void ToASCIIWithGreatThanZero(std::string& tmpbuf, int digitNumber, int number, const std::string& buf);
233     static bool StringToInt64(const std::string& str, int64_t& value);
234 private:
235     static char Carry(char current, int radix);
236     static double Strtod(const char *str, int exponent, uint8_t radix);
237     static bool GotoNonspace(uint8_t **ptr, const uint8_t *end);
238     static void GetBase(double d, int digits, int *decimalPoint, char *buf, char *bufTmp, int size);
239     static int GetMinmumDigits(double d, int *decimalPoint, char *buf);
240     static int CustomEcvt(double valueNumber, int digits, int *decimalPoint, std::string& buf,
241                           bool isFixed, int *sign);
242     static void CustomFcvt(std::string& buf, int bufSize, double valueNumber, int digits);
243     static int CustomFcvtHelper(std::string& buf, int bufSize, double valueNumber, int digits, int roundingMode);
244     static void GetBaseForRoundingMode(double valueNumber, int digitNumber, int *decimalPoint, std::string& buf,
245                 std::string& buf1, int buf1Size, int roundingMode, int *sign);
246     static void CustomEcvtIsFixed(double &valueNumber, int &digits, int *decimalPoint, std::string& buf, int *sign);
247 };
248 
249 // This class is used to generate 0~1 uniform distribution pseudo-random numbers.
250 // It uses a 64-bit seed which is current timestamp to generate state value.
251 // The value is used in xorshift64* random generator to generate result.
252 class RandomGenerator {
253 public:
254     static void InitRandom(JSThread *thread);
255     static double NextDouble();
256     static int32_t GenerateIdentityHash();
257     static int32_t Next(int bits);
258 
259 private:
260     static uint64_t XorShift64(uint64_t *pVal);
261     static double ToDouble(uint64_t state);
262 
263 private:
264     static thread_local uint64_t randomState_;
265 };
266 }  // namespace panda::ecmascript::base
267 #endif  // ECMASCRIPT_BASE_NUMBER_HELPER_H
268