Skip to content

Commit 9ec832b

Browse files
author
Hood Chatham
authored
Simplify js2python string conversion code a bit (#1679)
1 parent e26463b commit 9ec832b

File tree

1 file changed

+11
-36
lines changed

1 file changed

+11
-36
lines changed

src/core/js2python.c

Lines changed: 11 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,9 @@
99
#include "jsproxy.h"
1010
#include "pyproxy.h"
1111

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
1813
void*
19-
_js2python_get_ptr(PyObject* obj)
14+
PyUnicode_Data(PyObject* obj)
2015
{
2116
return PyUnicode_DATA(obj);
2217
}
@@ -68,46 +63,26 @@ EM_JS_NUM(errcode, js2python_init, (), {
6863
// have Javascript write directly into its buffer. We first need
6964
// to determine if is needs to be a 1-, 2- or 4-byte string, since
7065
// 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));
8369
}
70+
let max_code_point = Math.max(... codepoints);
8471

85-
let result = __js2python_allocate_string(length, max_code_point);
72+
let result = _PyUnicode_New(codepoints.length, max_code_point);
8673
// clang-format off
8774
if (result === 0) {
8875
// clang-format on
8976
return 0;
9077
}
9178

92-
let ptr = __js2python_get_ptr(result);
79+
let ptr = _PyUnicode_Data(result);
9380
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);
10282
} 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);
10784
} 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);
11186
}
11287

11388
return result;

0 commit comments

Comments
 (0)