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 "ecmascript/ecma_string.h"
22#include "ecmascript/js_tagged_value.h"
23
24namespace panda::ecmascript::base {
25constexpr double MIN_RADIX = 2;
26constexpr double MAX_RADIX = 36;
27constexpr double MIN_FRACTION = 0;
28constexpr double MAX_FRACTION = 100;
29
30// Coversion flags
31static constexpr uint32_t NO_FLAGS = 0U;
32static constexpr uint32_t ALLOW_BINARY = 1U << 0U;
33static constexpr uint32_t ALLOW_OCTAL = 1U << 1U;
34static constexpr uint32_t ALLOW_HEX = 1U << 2U;
35static constexpr uint32_t IGNORE_TRAILING = 1U << 3U;
36
37static constexpr char HALFCHAR = '5';
38static constexpr uint32_t MAX_PRECISION = 16;
39static constexpr uint8_t BINARY = 2;
40static constexpr uint8_t OCTAL = 8;
41static constexpr uint8_t DECIMAL = 10;
42static constexpr uint8_t HEXADECIMAL = 16;
43static constexpr double HALF = 0.5;
44static constexpr double EPSILON = std::numeric_limits<double>::epsilon();
45static constexpr int64_t MAX_SAFE_INTEGER = 9007199254740991;
46static constexpr double MAX_VALUE = std::numeric_limits<double>::max();
47static constexpr double MIN_VALUE = std::numeric_limits<double>::min();
48static constexpr double POSITIVE_INFINITY = std::numeric_limits<double>::infinity();
49static constexpr double NAN_VALUE = std::numeric_limits<double>::quiet_NaN();
50static constexpr uint64_t MAX_UINT64_VALUE = std::numeric_limits<uint64_t>::max();
51static constexpr int MAX_INT_VALUE = std::numeric_limits<int>::max();
52
53// Helper defines for double
54static constexpr int DOUBLE_MAX_PRECISION = 17;
55static constexpr int DOUBLE_EXPONENT_BIAS = 0x3FF;
56static constexpr size_t DOUBLE_SIGNIFICAND_SIZE = 52;
57static constexpr uint64_t DOUBLE_SIGN_MASK = 0x8000000000000000ULL;
58static constexpr uint64_t DOUBLE_EXPONENT_MASK = 0x7FFULL << DOUBLE_SIGNIFICAND_SIZE;
59static constexpr uint64_t DOUBLE_SIGNIFICAND_MASK = 0x000FFFFFFFFFFFFFULL;
60static constexpr uint64_t DOUBLE_HIDDEN_BIT = 1ULL << DOUBLE_SIGNIFICAND_SIZE;
61static constexpr int32_t MINUS_ZERO_LOBITS = static_cast<int32_t>(0);
62static constexpr int32_t MINUS_ZERO_HIBITS = static_cast<int32_t>(1) << 31;
63static constexpr int64_t MINUS_ZERO_BITS = (static_cast<uint64_t>(MINUS_ZERO_HIBITS) << 32) | MINUS_ZERO_LOBITS;
64static constexpr size_t INT64_BITS = 64;
65static constexpr size_t INT32_BITS = 32;
66static constexpr size_t INT16_BITS = 16;
67static constexpr size_t INT8_BITS = 8;
68static constexpr size_t JS_DTOA_BUF_SIZE = 128;
69
70// Max number of hexadecimal digits to display an integer
71static constexpr size_t INT64_HEX_DIGITS = INT64_BITS / 4;
72static constexpr size_t INT32_HEX_DIGITS = INT32_BITS / 4;
73static constexpr size_t INT16_HEX_DIGITS = INT16_BITS / 4;
74static constexpr size_t INT8_HEX_DIGITS = INT8_BITS / 4;
75
76static constexpr int EXPONENTBIAS =  DOUBLE_EXPONENT_BIAS + DOUBLE_SIGNIFICAND_SIZE;
77static constexpr int kDENORMAL = -EXPONENTBIAS + 1;
78static constexpr uint64_t kINFINITY = 0x7FF0'0000'0000'0000;
79
80// help defines for random
81static constexpr int RIGHT12 = 12;
82static constexpr int SECONDS_TO_SUBTLE = 1000000;
83static constexpr int RIGHT27 = 27;
84static constexpr int LEFT25 = 25;
85static constexpr uint64_t GET_MULTIPLY = 0x2545F4914F6CDD1D;
86// Exponent bits for double value between [1.0, 2.0)
87static constexpr uint64_t EXPONENTBITS_RANGE_IN_ONE_AND_TWO = 0x3FF0000000000000;
88
89// Special Value for Hole in ElementsKind
90static constexpr uint64_t SPECIAL_HOLE = 0xFFFE000000000001;
91
92// Special Value for Hole in ElementsKind
93static constexpr uint32_t PGO_POLY_INLINE_REP = 0x7FFFFFFF;
94
95//
96static constexpr int MAX_DIGITS = 21;
97static constexpr int MIN_DIGITS = -6;
98
99// NumberFormat type
100static constexpr int VAR_FORMAT = 0;
101static constexpr int FIXED_FORMAT = 1;
102static constexpr int FRAC_FORMAT  = 2;
103static constexpr int FORCE_FORMAT = 4;
104
105// means add the point char to buf
106static constexpr int POINT_INDEX = 3;
107static constexpr int DECIMAL_INDEX = 2;
108
109class NumberHelper {
110public:
111    static inline JSTaggedType GetNaN()
112    {
113        return JSTaggedValue(NAN_VALUE).GetRawData();
114    }
115
116    static inline JSTaggedType GetPositiveInfinity()
117    {
118        return JSTaggedValue(POSITIVE_INFINITY).GetRawData();
119    }
120
121    static bool IsFinite(JSTaggedValue number)
122    {
123        return number.IsInt() || (number.IsDouble() && std::isfinite(number.GetDouble()));
124    }
125    static bool IsNaN(JSTaggedValue number)
126    {
127        return number.IsDouble() && std::isnan(number.GetDouble());
128    }
129
130    static bool inline IsDenormal(uint64_t x)
131    {
132        return (x & kINFINITY) == 0;
133    }
134
135    static int inline Exponent(double x)
136    {
137        uint64_t value =  base::bit_cast<uint64_t>(x);
138        if (IsDenormal(value)) {
139            return kDENORMAL;
140        }
141        int biased = static_cast<int>((value & kINFINITY) >> DOUBLE_SIGNIFICAND_SIZE);
142        return biased - EXPONENTBIAS;
143    }
144
145    static uint64_t inline Significand(double x)
146    {
147        uint64_t value =  base::bit_cast<uint64_t>(x);
148        uint64_t significand = value & DOUBLE_SIGNIFICAND_MASK;
149        if (!IsDenormal(value)) {
150            return significand + DOUBLE_HIDDEN_BIT;
151        } else {
152            return significand;
153        }
154    }
155
156    static bool inline IsSafeIntegerNumber(double d)
157    {
158        double number = TruncateDouble(d);
159        return (number == d) && std::abs(d) <= MAX_SAFE_INTEGER;
160    }
161
162    static JSTaggedValue DoubleToString(JSThread *thread, double number, int radix);
163    static bool IsEmptyString(const uint8_t *start, const uint8_t *end);
164    static JSHandle<EcmaString> IntToEcmaString(const JSThread *thread, int number);
165    static JSHandle<EcmaString> DoubleToEcmaString(const JSThread *thread, double d);
166    static uint32_t ToCharCode(uint32_t number);
167    static JSTaggedValue Int32ToString(JSThread *thread, int32_t number, uint32_t radix);
168    static JSHandle<EcmaString> NumberToString(const JSThread *thread, JSTaggedValue number);
169    static double PUBLIC_API TruncateDouble(double d);
170    static int64_t DoubleToInt64(double d);
171    static bool IsDigitalString(const uint8_t *start, const uint8_t *end);
172    static int StringToInt(const uint8_t *start, const uint8_t *end);
173    static std::pair<bool, JSTaggedNumber> FastStringToNumber(const uint8_t *start,
174        const uint8_t *end, JSTaggedValue string);
175    static double StringToDouble(const uint8_t *start, const uint8_t *end, uint8_t radix, uint32_t flags = NO_FLAGS);
176    static int32_t DoubleToInt(double d, size_t bits);
177    static int32_t PUBLIC_API DoubleInRangeInt32(double d);
178    static JSTaggedValue StringToNumber(EcmaString *string, int32_t radix);
179    static JSTaggedValue StringToDoubleWithRadix(const uint8_t *start, const uint8_t *end, int radix, bool *negative);
180    static CString IntToString(int number);
181    static CString IntegerToString(double number, int radix);
182    static JSTaggedValue PUBLIC_API StringToBigInt(JSThread *thread, JSHandle<JSTaggedValue> strVal);
183    static JSTaggedValue DoubleToExponential(JSThread *thread, double number, int digit);
184    static JSTaggedValue DoubleToASCII(JSThread *thread, double valueNumber, int digits, int flags);
185    static JSTaggedValue DoubleToFixedString(JSThread *thread, double valueNumber, int digits);
186    static JSTaggedValue DoubleToPrecisionString(JSThread *thread, double valueNumber, int digits);
187    static void DoubleToASCIIWithFlag(std::string& buf, double valueNumber, int digits, int flags);
188    static void ToASCIIWithNegative(std::string& tmpbuf, int digitNumber, int n, const std::string& buf);
189    static void ToASCIIWithGreatThanZero(std::string& tmpbuf, int digitNumber, int number, const std::string& buf);
190    static bool StringToInt64(const std::string& str, int64_t& value);
191private:
192    static char Carry(char current, int radix);
193    static double Strtod(const char *str, int exponent, uint8_t radix);
194    static bool GotoNonspace(uint8_t **ptr, const uint8_t *end);
195    static void GetBase(double d, int digits, int *decimalPoint, char *buf, char *bufTmp, int size);
196    static int GetMinmumDigits(double d, int *decimalPoint, char *buf);
197    static int CustomEcvt(double valueNumber, int digits, int *decimalPoint, std::string& buf,
198                          bool isFixed, int *sign);
199    static void CustomFcvt(std::string& buf, int bufSize, double valueNumber, int digits);
200    static int CustomFcvtHelper(std::string& buf, int bufSize, double valueNumber, int digits, int roundingMode);
201    static void GetBaseForRoundingMode(double valueNumber, int digitNumber, int *decimalPoint, std::string& buf,
202                std::string& buf1, int buf1Size, int roundingMode, int *sign);
203    static void CustomEcvtIsFixed(double &valueNumber, int &digits, int *decimalPoint, std::string& buf, int *sign);
204};
205
206// This class is used to generate 0~1 uniform distribution pseudo-random numbers.
207// It uses a 64-bit seed which is current timestamp to generate state value.
208// The value is used in xorshift64* random generator to generate result.
209class RandomGenerator {
210public:
211    static void InitRandom(JSThread *thread);
212    static double NextDouble();
213    static int32_t GenerateIdentityHash();
214    static int32_t Next(int bits);
215
216private:
217    static uint64_t XorShift64(uint64_t *pVal);
218    static double ToDouble(uint64_t state);
219
220private:
221    static thread_local uint64_t randomState_;
222};
223}  // namespace panda::ecmascript::base
224#endif  // ECMASCRIPT_BASE_NUMBER_HELPER_H
225