|
9 | 9 | #include "jsproxy.h" |
10 | 10 | #include "pyproxy.h" |
11 | 11 |
|
12 | | -PyObject* |
13 | | -_js2python_allocate_string(int size, int max_code_point) |
14 | | -{ |
15 | | - return PyUnicode_New(size, max_code_point); |
16 | | -} |
17 | | - |
| 12 | +// PyUnicodeDATA is a macro, we need to access it from Javascript |
18 | 13 | void* |
19 | | -_js2python_get_ptr(PyObject* obj) |
| 14 | +PyUnicode_Data(PyObject* obj) |
20 | 15 | { |
21 | 16 | return PyUnicode_DATA(obj); |
22 | 17 | } |
@@ -68,46 +63,26 @@ EM_JS_NUM(errcode, js2python_init, (), { |
68 | 63 | // have Javascript write directly into its buffer. We first need |
69 | 64 | // to determine if is needs to be a 1-, 2- or 4-byte string, since |
70 | 65 | // Python handles all 3. |
71 | | - let max_code_point = 0; |
72 | | - let length = value.length; |
73 | | - for (let i = 0; i < value.length; i++) { |
74 | | - let code_point = value.codePointAt(i); |
75 | | - max_code_point = Math.max(max_code_point, code_point); |
76 | | - if (code_point > 0xffff) { |
77 | | - // If we have a code point requiring UTF-16 surrogate pairs, the |
78 | | - // number of characters (codePoints) is less than value.length, |
79 | | - // so skip the next charCode and subtract 1 from the length. |
80 | | - i++; |
81 | | - length--; |
82 | | - } |
| 66 | + let codepoints = []; |
| 67 | + for (let c of value) { |
| 68 | + codepoints.push(c.codePointAt(0)); |
83 | 69 | } |
| 70 | + let max_code_point = Math.max(... codepoints); |
84 | 71 |
|
85 | | - let result = __js2python_allocate_string(length, max_code_point); |
| 72 | + let result = _PyUnicode_New(codepoints.length, max_code_point); |
86 | 73 | // clang-format off |
87 | 74 | if (result === 0) { |
88 | 75 | // clang-format on |
89 | 76 | return 0; |
90 | 77 | } |
91 | 78 |
|
92 | | - let ptr = __js2python_get_ptr(result); |
| 79 | + let ptr = _PyUnicode_Data(result); |
93 | 80 | if (max_code_point > 0xffff) { |
94 | | - ptr = ptr / 4; |
95 | | - for (let i = 0, j = 0; j < length; i++, j++) { |
96 | | - let code_point = value.codePointAt(i); |
97 | | - Module.HEAPU32[ptr + j] = code_point; |
98 | | - if (code_point > 0xffff) { |
99 | | - i++; |
100 | | - } |
101 | | - } |
| 81 | + HEAPU32.subarray(ptr / 4, ptr / 4 + codepoints.length).set(codepoints); |
102 | 82 | } else if (max_code_point > 0xff) { |
103 | | - ptr = ptr / 2; |
104 | | - for (let i = 0; i < length; i++) { |
105 | | - Module.HEAPU16[ptr + i] = value.codePointAt(i); |
106 | | - } |
| 83 | + HEAPU16.subarray(ptr / 2, ptr / 2 + codepoints.length).set(codepoints); |
107 | 84 | } else { |
108 | | - for (let i = 0; i < length; i++) { |
109 | | - Module.HEAPU8[ptr + i] = value.codePointAt(i); |
110 | | - } |
| 85 | + HEAPU8.subarray(ptr, ptr + codepoints.length).set(codepoints); |
111 | 86 | } |
112 | 87 |
|
113 | 88 | return result; |
|
0 commit comments