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_MEM_C_STRING_H
17 #define ECMASCRIPT_MEM_C_STRING_H
18
19 #include <sstream>
20 #include <string>
21 #include <string_view>
22
23 #include "ecmascript/common.h"
24 #include "ecmascript/mem/caddress_allocator.h"
25
26 namespace panda::ecmascript {
27 class EcmaString;
28 class JSTaggedValue;
29
30 using CString = std::basic_string<char, std::char_traits<char>, CAddressAllocator<char>>;
31 using CStringStream = std::basic_stringstream<char, std::char_traits<char>, CAddressAllocator<char>>;
32
33 // PRINT will skip '\0' in utf16 during conversion of utf8
34 enum StringConvertedUsage { PRINT, LOGICOPERATION };
35
36 int64_t CStringToLL(const CString &str);
37 uint64_t CStringToULL(const CString &str);
38 float CStringToF(const CString &str);
39 double CStringToD(const CString &str);
40
41 CString ConvertToString(const std::string &str);
42 std::string CstringConvertToStdString(const CString &str);
43
44 // '\u0000' is skip according to holdZero
45 CString ConvertToString(const ecmascript::EcmaString *s, StringConvertedUsage usage = StringConvertedUsage::PRINT);
46 CString ConvertToString(ecmascript::JSTaggedValue key);
47
48 template<class T>
FloatToCString(T number)49 std::enable_if_t<std::is_floating_point_v<T>, CString> FloatToCString(T number)
50 {
51 CStringStream strStream;
52 strStream << number;
53 return strStream.str();
54 }
55
56 template<class T>
ToCString(T number)57 std::enable_if_t<std::is_integral_v<T>, CString> ToCString(T number)
58 {
59 if (number == 0) {
60 return CString("0");
61 }
62 bool IsNeg = false;
63 if (number < 0) {
64 number = -number;
65 IsNeg = true;
66 }
67
68 static constexpr uint32_t BUFF_SIZE = std::numeric_limits<T>::digits10 + 3; // 3: Reserved for sign bit and '\0'.
69 char buf[BUFF_SIZE];
70 uint32_t position = BUFF_SIZE - 1;
71 buf[position] = '\0';
72 while (number > 0) {
73 buf[--position] = number % 10 + '0'; // 10 : decimal
74 number /= 10; // 10 : decimal
75 }
76 if (IsNeg) {
77 buf[--position] = '-';
78 }
79 return CString(&buf[position]);
80 }
81 } // namespace panda::ecmascript
82
83 #endif // ECMASCRIPT_MEM_C_STRING_H
84